1 //===- SemaChecking.cpp - Extra Semantic Checking -------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements extra semantic analysis beyond what is enforced
10 //  by the C type system.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/AST/APValue.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/Attr.h"
17 #include "clang/AST/AttrIterator.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclBase.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclarationName.h"
24 #include "clang/AST/EvaluatedExprVisitor.h"
25 #include "clang/AST/Expr.h"
26 #include "clang/AST/ExprCXX.h"
27 #include "clang/AST/ExprObjC.h"
28 #include "clang/AST/ExprOpenMP.h"
29 #include "clang/AST/FormatString.h"
30 #include "clang/AST/NSAPI.h"
31 #include "clang/AST/NonTrivialTypeVisitor.h"
32 #include "clang/AST/OperationKinds.h"
33 #include "clang/AST/RecordLayout.h"
34 #include "clang/AST/Stmt.h"
35 #include "clang/AST/TemplateBase.h"
36 #include "clang/AST/Type.h"
37 #include "clang/AST/TypeLoc.h"
38 #include "clang/AST/UnresolvedSet.h"
39 #include "clang/Basic/AddressSpaces.h"
40 #include "clang/Basic/CharInfo.h"
41 #include "clang/Basic/Diagnostic.h"
42 #include "clang/Basic/IdentifierTable.h"
43 #include "clang/Basic/LLVM.h"
44 #include "clang/Basic/LangOptions.h"
45 #include "clang/Basic/OpenCLOptions.h"
46 #include "clang/Basic/OperatorKinds.h"
47 #include "clang/Basic/PartialDiagnostic.h"
48 #include "clang/Basic/SourceLocation.h"
49 #include "clang/Basic/SourceManager.h"
50 #include "clang/Basic/Specifiers.h"
51 #include "clang/Basic/SyncScope.h"
52 #include "clang/Basic/TargetBuiltins.h"
53 #include "clang/Basic/TargetCXXABI.h"
54 #include "clang/Basic/TargetInfo.h"
55 #include "clang/Basic/TypeTraits.h"
56 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
57 #include "clang/Sema/Initialization.h"
58 #include "clang/Sema/Lookup.h"
59 #include "clang/Sema/Ownership.h"
60 #include "clang/Sema/Scope.h"
61 #include "clang/Sema/ScopeInfo.h"
62 #include "clang/Sema/Sema.h"
63 #include "clang/Sema/SemaInternal.h"
64 #include "llvm/ADT/APFloat.h"
65 #include "llvm/ADT/APInt.h"
66 #include "llvm/ADT/APSInt.h"
67 #include "llvm/ADT/ArrayRef.h"
68 #include "llvm/ADT/DenseMap.h"
69 #include "llvm/ADT/FoldingSet.h"
70 #include "llvm/ADT/None.h"
71 #include "llvm/ADT/Optional.h"
72 #include "llvm/ADT/STLExtras.h"
73 #include "llvm/ADT/SmallBitVector.h"
74 #include "llvm/ADT/SmallPtrSet.h"
75 #include "llvm/ADT/SmallString.h"
76 #include "llvm/ADT/SmallVector.h"
77 #include "llvm/ADT/StringRef.h"
78 #include "llvm/ADT/StringSet.h"
79 #include "llvm/ADT/StringSwitch.h"
80 #include "llvm/ADT/Triple.h"
81 #include "llvm/Support/AtomicOrdering.h"
82 #include "llvm/Support/Casting.h"
83 #include "llvm/Support/Compiler.h"
84 #include "llvm/Support/ConvertUTF.h"
85 #include "llvm/Support/ErrorHandling.h"
86 #include "llvm/Support/Format.h"
87 #include "llvm/Support/Locale.h"
88 #include "llvm/Support/MathExtras.h"
89 #include "llvm/Support/SaveAndRestore.h"
90 #include "llvm/Support/raw_ostream.h"
91 #include <algorithm>
92 #include <bitset>
93 #include <cassert>
94 #include <cctype>
95 #include <cstddef>
96 #include <cstdint>
97 #include <functional>
98 #include <limits>
99 #include <string>
100 #include <tuple>
101 #include <utility>
102 
103 using namespace clang;
104 using namespace sema;
105 
106 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
107                                                     unsigned ByteNo) const {
108   return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
109                                Context.getTargetInfo());
110 }
111 
112 /// Checks that a call expression's argument count is the desired number.
113 /// This is useful when doing custom type-checking.  Returns true on error.
114 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
115   unsigned argCount = call->getNumArgs();
116   if (argCount == desiredArgCount) return false;
117 
118   if (argCount < desiredArgCount)
119     return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args)
120            << 0 /*function call*/ << desiredArgCount << argCount
121            << call->getSourceRange();
122 
123   // Highlight all the excess arguments.
124   SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(),
125                     call->getArg(argCount - 1)->getEndLoc());
126 
127   return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
128     << 0 /*function call*/ << desiredArgCount << argCount
129     << call->getArg(1)->getSourceRange();
130 }
131 
132 /// Check that the first argument to __builtin_annotation is an integer
133 /// and the second argument is a non-wide string literal.
134 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
135   if (checkArgCount(S, TheCall, 2))
136     return true;
137 
138   // First argument should be an integer.
139   Expr *ValArg = TheCall->getArg(0);
140   QualType Ty = ValArg->getType();
141   if (!Ty->isIntegerType()) {
142     S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
143         << ValArg->getSourceRange();
144     return true;
145   }
146 
147   // Second argument should be a constant string.
148   Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
149   StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
150   if (!Literal || !Literal->isAscii()) {
151     S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
152         << StrArg->getSourceRange();
153     return true;
154   }
155 
156   TheCall->setType(Ty);
157   return false;
158 }
159 
160 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
161   // We need at least one argument.
162   if (TheCall->getNumArgs() < 1) {
163     S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
164         << 0 << 1 << TheCall->getNumArgs()
165         << TheCall->getCallee()->getSourceRange();
166     return true;
167   }
168 
169   // All arguments should be wide string literals.
170   for (Expr *Arg : TheCall->arguments()) {
171     auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
172     if (!Literal || !Literal->isWide()) {
173       S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
174           << Arg->getSourceRange();
175       return true;
176     }
177   }
178 
179   return false;
180 }
181 
182 /// Check that the argument to __builtin_addressof is a glvalue, and set the
183 /// result type to the corresponding pointer type.
184 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
185   if (checkArgCount(S, TheCall, 1))
186     return true;
187 
188   ExprResult Arg(TheCall->getArg(0));
189   QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
190   if (ResultType.isNull())
191     return true;
192 
193   TheCall->setArg(0, Arg.get());
194   TheCall->setType(ResultType);
195   return false;
196 }
197 
198 /// Check the number of arguments and set the result type to
199 /// the argument type.
200 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
201   if (checkArgCount(S, TheCall, 1))
202     return true;
203 
204   TheCall->setType(TheCall->getArg(0)->getType());
205   return false;
206 }
207 
208 /// Check that the value argument for __builtin_is_aligned(value, alignment) and
209 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
210 /// type (but not a function pointer) and that the alignment is a power-of-two.
211 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
212   if (checkArgCount(S, TheCall, 2))
213     return true;
214 
215   clang::Expr *Source = TheCall->getArg(0);
216   bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
217 
218   auto IsValidIntegerType = [](QualType Ty) {
219     return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
220   };
221   QualType SrcTy = Source->getType();
222   // We should also be able to use it with arrays (but not functions!).
223   if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
224     SrcTy = S.Context.getDecayedType(SrcTy);
225   }
226   if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
227       SrcTy->isFunctionPointerType()) {
228     // FIXME: this is not quite the right error message since we don't allow
229     // floating point types, or member pointers.
230     S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand)
231         << SrcTy;
232     return true;
233   }
234 
235   clang::Expr *AlignOp = TheCall->getArg(1);
236   if (!IsValidIntegerType(AlignOp->getType())) {
237     S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int)
238         << AlignOp->getType();
239     return true;
240   }
241   Expr::EvalResult AlignResult;
242   unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1;
243   // We can't check validity of alignment if it is value dependent.
244   if (!AlignOp->isValueDependent() &&
245       AlignOp->EvaluateAsInt(AlignResult, S.Context,
246                              Expr::SE_AllowSideEffects)) {
247     llvm::APSInt AlignValue = AlignResult.Val.getInt();
248     llvm::APSInt MaxValue(
249         llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits));
250     if (AlignValue < 1) {
251       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1;
252       return true;
253     }
254     if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) {
255       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big)
256           << toString(MaxValue, 10);
257       return true;
258     }
259     if (!AlignValue.isPowerOf2()) {
260       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two);
261       return true;
262     }
263     if (AlignValue == 1) {
264       S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless)
265           << IsBooleanAlignBuiltin;
266     }
267   }
268 
269   ExprResult SrcArg = S.PerformCopyInitialization(
270       InitializedEntity::InitializeParameter(S.Context, SrcTy, false),
271       SourceLocation(), Source);
272   if (SrcArg.isInvalid())
273     return true;
274   TheCall->setArg(0, SrcArg.get());
275   ExprResult AlignArg =
276       S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
277                                       S.Context, AlignOp->getType(), false),
278                                   SourceLocation(), AlignOp);
279   if (AlignArg.isInvalid())
280     return true;
281   TheCall->setArg(1, AlignArg.get());
282   // For align_up/align_down, the return type is the same as the (potentially
283   // decayed) argument type including qualifiers. For is_aligned(), the result
284   // is always bool.
285   TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
286   return false;
287 }
288 
289 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall,
290                                 unsigned BuiltinID) {
291   if (checkArgCount(S, TheCall, 3))
292     return true;
293 
294   // First two arguments should be integers.
295   for (unsigned I = 0; I < 2; ++I) {
296     ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I));
297     if (Arg.isInvalid()) return true;
298     TheCall->setArg(I, Arg.get());
299 
300     QualType Ty = Arg.get()->getType();
301     if (!Ty->isIntegerType()) {
302       S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
303           << Ty << Arg.get()->getSourceRange();
304       return true;
305     }
306   }
307 
308   // Third argument should be a pointer to a non-const integer.
309   // IRGen correctly handles volatile, restrict, and address spaces, and
310   // the other qualifiers aren't possible.
311   {
312     ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(2));
313     if (Arg.isInvalid()) return true;
314     TheCall->setArg(2, Arg.get());
315 
316     QualType Ty = Arg.get()->getType();
317     const auto *PtrTy = Ty->getAs<PointerType>();
318     if (!PtrTy ||
319         !PtrTy->getPointeeType()->isIntegerType() ||
320         PtrTy->getPointeeType().isConstQualified()) {
321       S.Diag(Arg.get()->getBeginLoc(),
322              diag::err_overflow_builtin_must_be_ptr_int)
323         << Ty << Arg.get()->getSourceRange();
324       return true;
325     }
326   }
327 
328   // Disallow signed ExtIntType args larger than 128 bits to mul function until
329   // we improve backend support.
330   if (BuiltinID == Builtin::BI__builtin_mul_overflow) {
331     for (unsigned I = 0; I < 3; ++I) {
332       const auto Arg = TheCall->getArg(I);
333       // Third argument will be a pointer.
334       auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType();
335       if (Ty->isExtIntType() && Ty->isSignedIntegerType() &&
336           S.getASTContext().getIntWidth(Ty) > 128)
337         return S.Diag(Arg->getBeginLoc(),
338                       diag::err_overflow_builtin_ext_int_max_size)
339                << 128;
340     }
341   }
342 
343   return false;
344 }
345 
346 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
347   if (checkArgCount(S, BuiltinCall, 2))
348     return true;
349 
350   SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
351   Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
352   Expr *Call = BuiltinCall->getArg(0);
353   Expr *Chain = BuiltinCall->getArg(1);
354 
355   if (Call->getStmtClass() != Stmt::CallExprClass) {
356     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
357         << Call->getSourceRange();
358     return true;
359   }
360 
361   auto CE = cast<CallExpr>(Call);
362   if (CE->getCallee()->getType()->isBlockPointerType()) {
363     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
364         << Call->getSourceRange();
365     return true;
366   }
367 
368   const Decl *TargetDecl = CE->getCalleeDecl();
369   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
370     if (FD->getBuiltinID()) {
371       S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
372           << Call->getSourceRange();
373       return true;
374     }
375 
376   if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
377     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
378         << Call->getSourceRange();
379     return true;
380   }
381 
382   ExprResult ChainResult = S.UsualUnaryConversions(Chain);
383   if (ChainResult.isInvalid())
384     return true;
385   if (!ChainResult.get()->getType()->isPointerType()) {
386     S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
387         << Chain->getSourceRange();
388     return true;
389   }
390 
391   QualType ReturnTy = CE->getCallReturnType(S.Context);
392   QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
393   QualType BuiltinTy = S.Context.getFunctionType(
394       ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
395   QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
396 
397   Builtin =
398       S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
399 
400   BuiltinCall->setType(CE->getType());
401   BuiltinCall->setValueKind(CE->getValueKind());
402   BuiltinCall->setObjectKind(CE->getObjectKind());
403   BuiltinCall->setCallee(Builtin);
404   BuiltinCall->setArg(1, ChainResult.get());
405 
406   return false;
407 }
408 
409 namespace {
410 
411 class EstimateSizeFormatHandler
412     : public analyze_format_string::FormatStringHandler {
413   size_t Size;
414 
415 public:
416   EstimateSizeFormatHandler(StringRef Format)
417       : Size(std::min(Format.find(0), Format.size()) +
418              1 /* null byte always written by sprintf */) {}
419 
420   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
421                              const char *, unsigned SpecifierLen) override {
422 
423     const size_t FieldWidth = computeFieldWidth(FS);
424     const size_t Precision = computePrecision(FS);
425 
426     // The actual format.
427     switch (FS.getConversionSpecifier().getKind()) {
428     // Just a char.
429     case analyze_format_string::ConversionSpecifier::cArg:
430     case analyze_format_string::ConversionSpecifier::CArg:
431       Size += std::max(FieldWidth, (size_t)1);
432       break;
433     // Just an integer.
434     case analyze_format_string::ConversionSpecifier::dArg:
435     case analyze_format_string::ConversionSpecifier::DArg:
436     case analyze_format_string::ConversionSpecifier::iArg:
437     case analyze_format_string::ConversionSpecifier::oArg:
438     case analyze_format_string::ConversionSpecifier::OArg:
439     case analyze_format_string::ConversionSpecifier::uArg:
440     case analyze_format_string::ConversionSpecifier::UArg:
441     case analyze_format_string::ConversionSpecifier::xArg:
442     case analyze_format_string::ConversionSpecifier::XArg:
443       Size += std::max(FieldWidth, Precision);
444       break;
445 
446     // %g style conversion switches between %f or %e style dynamically.
447     // %f always takes less space, so default to it.
448     case analyze_format_string::ConversionSpecifier::gArg:
449     case analyze_format_string::ConversionSpecifier::GArg:
450 
451     // Floating point number in the form '[+]ddd.ddd'.
452     case analyze_format_string::ConversionSpecifier::fArg:
453     case analyze_format_string::ConversionSpecifier::FArg:
454       Size += std::max(FieldWidth, 1 /* integer part */ +
455                                        (Precision ? 1 + Precision
456                                                   : 0) /* period + decimal */);
457       break;
458 
459     // Floating point number in the form '[-]d.ddde[+-]dd'.
460     case analyze_format_string::ConversionSpecifier::eArg:
461     case analyze_format_string::ConversionSpecifier::EArg:
462       Size +=
463           std::max(FieldWidth,
464                    1 /* integer part */ +
465                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
466                        1 /* e or E letter */ + 2 /* exponent */);
467       break;
468 
469     // Floating point number in the form '[-]0xh.hhhhp±dd'.
470     case analyze_format_string::ConversionSpecifier::aArg:
471     case analyze_format_string::ConversionSpecifier::AArg:
472       Size +=
473           std::max(FieldWidth,
474                    2 /* 0x */ + 1 /* integer part */ +
475                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
476                        1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
477       break;
478 
479     // Just a string.
480     case analyze_format_string::ConversionSpecifier::sArg:
481     case analyze_format_string::ConversionSpecifier::SArg:
482       Size += FieldWidth;
483       break;
484 
485     // Just a pointer in the form '0xddd'.
486     case analyze_format_string::ConversionSpecifier::pArg:
487       Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
488       break;
489 
490     // A plain percent.
491     case analyze_format_string::ConversionSpecifier::PercentArg:
492       Size += 1;
493       break;
494 
495     default:
496       break;
497     }
498 
499     Size += FS.hasPlusPrefix() || FS.hasSpacePrefix();
500 
501     if (FS.hasAlternativeForm()) {
502       switch (FS.getConversionSpecifier().getKind()) {
503       default:
504         break;
505       // Force a leading '0'.
506       case analyze_format_string::ConversionSpecifier::oArg:
507         Size += 1;
508         break;
509       // Force a leading '0x'.
510       case analyze_format_string::ConversionSpecifier::xArg:
511       case analyze_format_string::ConversionSpecifier::XArg:
512         Size += 2;
513         break;
514       // Force a period '.' before decimal, even if precision is 0.
515       case analyze_format_string::ConversionSpecifier::aArg:
516       case analyze_format_string::ConversionSpecifier::AArg:
517       case analyze_format_string::ConversionSpecifier::eArg:
518       case analyze_format_string::ConversionSpecifier::EArg:
519       case analyze_format_string::ConversionSpecifier::fArg:
520       case analyze_format_string::ConversionSpecifier::FArg:
521       case analyze_format_string::ConversionSpecifier::gArg:
522       case analyze_format_string::ConversionSpecifier::GArg:
523         Size += (Precision ? 0 : 1);
524         break;
525       }
526     }
527     assert(SpecifierLen <= Size && "no underflow");
528     Size -= SpecifierLen;
529     return true;
530   }
531 
532   size_t getSizeLowerBound() const { return Size; }
533 
534 private:
535   static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
536     const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
537     size_t FieldWidth = 0;
538     if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant)
539       FieldWidth = FW.getConstantAmount();
540     return FieldWidth;
541   }
542 
543   static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
544     const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
545     size_t Precision = 0;
546 
547     // See man 3 printf for default precision value based on the specifier.
548     switch (FW.getHowSpecified()) {
549     case analyze_format_string::OptionalAmount::NotSpecified:
550       switch (FS.getConversionSpecifier().getKind()) {
551       default:
552         break;
553       case analyze_format_string::ConversionSpecifier::dArg: // %d
554       case analyze_format_string::ConversionSpecifier::DArg: // %D
555       case analyze_format_string::ConversionSpecifier::iArg: // %i
556         Precision = 1;
557         break;
558       case analyze_format_string::ConversionSpecifier::oArg: // %d
559       case analyze_format_string::ConversionSpecifier::OArg: // %D
560       case analyze_format_string::ConversionSpecifier::uArg: // %d
561       case analyze_format_string::ConversionSpecifier::UArg: // %D
562       case analyze_format_string::ConversionSpecifier::xArg: // %d
563       case analyze_format_string::ConversionSpecifier::XArg: // %D
564         Precision = 1;
565         break;
566       case analyze_format_string::ConversionSpecifier::fArg: // %f
567       case analyze_format_string::ConversionSpecifier::FArg: // %F
568       case analyze_format_string::ConversionSpecifier::eArg: // %e
569       case analyze_format_string::ConversionSpecifier::EArg: // %E
570       case analyze_format_string::ConversionSpecifier::gArg: // %g
571       case analyze_format_string::ConversionSpecifier::GArg: // %G
572         Precision = 6;
573         break;
574       case analyze_format_string::ConversionSpecifier::pArg: // %d
575         Precision = 1;
576         break;
577       }
578       break;
579     case analyze_format_string::OptionalAmount::Constant:
580       Precision = FW.getConstantAmount();
581       break;
582     default:
583       break;
584     }
585     return Precision;
586   }
587 };
588 
589 } // namespace
590 
591 /// Check a call to BuiltinID for buffer overflows. If BuiltinID is a
592 /// __builtin_*_chk function, then use the object size argument specified in the
593 /// source. Otherwise, infer the object size using __builtin_object_size.
594 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
595                                                CallExpr *TheCall) {
596   // FIXME: There are some more useful checks we could be doing here:
597   //  - Evaluate strlen of strcpy arguments, use as object size.
598 
599   if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
600       isConstantEvaluated())
601     return;
602 
603   unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true);
604   if (!BuiltinID)
605     return;
606 
607   const TargetInfo &TI = getASTContext().getTargetInfo();
608   unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
609 
610   unsigned DiagID = 0;
611   bool IsChkVariant = false;
612   Optional<llvm::APSInt> UsedSize;
613   unsigned SizeIndex, ObjectIndex;
614   switch (BuiltinID) {
615   default:
616     return;
617   case Builtin::BIsprintf:
618   case Builtin::BI__builtin___sprintf_chk: {
619     size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
620     auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
621 
622     if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) {
623 
624       if (!Format->isAscii() && !Format->isUTF8())
625         return;
626 
627       StringRef FormatStrRef = Format->getString();
628       EstimateSizeFormatHandler H(FormatStrRef);
629       const char *FormatBytes = FormatStrRef.data();
630       const ConstantArrayType *T =
631           Context.getAsConstantArrayType(Format->getType());
632       assert(T && "String literal not of constant array type!");
633       size_t TypeSize = T->getSize().getZExtValue();
634 
635       // In case there's a null byte somewhere.
636       size_t StrLen =
637           std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
638       if (!analyze_format_string::ParsePrintfString(
639               H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
640               Context.getTargetInfo(), false)) {
641         DiagID = diag::warn_fortify_source_format_overflow;
642         UsedSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
643                        .extOrTrunc(SizeTypeWidth);
644         if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
645           IsChkVariant = true;
646           ObjectIndex = 2;
647         } else {
648           IsChkVariant = false;
649           ObjectIndex = 0;
650         }
651         break;
652       }
653     }
654     return;
655   }
656   case Builtin::BI__builtin___memcpy_chk:
657   case Builtin::BI__builtin___memmove_chk:
658   case Builtin::BI__builtin___memset_chk:
659   case Builtin::BI__builtin___strlcat_chk:
660   case Builtin::BI__builtin___strlcpy_chk:
661   case Builtin::BI__builtin___strncat_chk:
662   case Builtin::BI__builtin___strncpy_chk:
663   case Builtin::BI__builtin___stpncpy_chk:
664   case Builtin::BI__builtin___memccpy_chk:
665   case Builtin::BI__builtin___mempcpy_chk: {
666     DiagID = diag::warn_builtin_chk_overflow;
667     IsChkVariant = true;
668     SizeIndex = TheCall->getNumArgs() - 2;
669     ObjectIndex = TheCall->getNumArgs() - 1;
670     break;
671   }
672 
673   case Builtin::BI__builtin___snprintf_chk:
674   case Builtin::BI__builtin___vsnprintf_chk: {
675     DiagID = diag::warn_builtin_chk_overflow;
676     IsChkVariant = true;
677     SizeIndex = 1;
678     ObjectIndex = 3;
679     break;
680   }
681 
682   case Builtin::BIstrncat:
683   case Builtin::BI__builtin_strncat:
684   case Builtin::BIstrncpy:
685   case Builtin::BI__builtin_strncpy:
686   case Builtin::BIstpncpy:
687   case Builtin::BI__builtin_stpncpy: {
688     // Whether these functions overflow depends on the runtime strlen of the
689     // string, not just the buffer size, so emitting the "always overflow"
690     // diagnostic isn't quite right. We should still diagnose passing a buffer
691     // size larger than the destination buffer though; this is a runtime abort
692     // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
693     DiagID = diag::warn_fortify_source_size_mismatch;
694     SizeIndex = TheCall->getNumArgs() - 1;
695     ObjectIndex = 0;
696     break;
697   }
698 
699   case Builtin::BImemcpy:
700   case Builtin::BI__builtin_memcpy:
701   case Builtin::BImemmove:
702   case Builtin::BI__builtin_memmove:
703   case Builtin::BImemset:
704   case Builtin::BI__builtin_memset:
705   case Builtin::BImempcpy:
706   case Builtin::BI__builtin_mempcpy: {
707     DiagID = diag::warn_fortify_source_overflow;
708     SizeIndex = TheCall->getNumArgs() - 1;
709     ObjectIndex = 0;
710     break;
711   }
712   case Builtin::BIsnprintf:
713   case Builtin::BI__builtin_snprintf:
714   case Builtin::BIvsnprintf:
715   case Builtin::BI__builtin_vsnprintf: {
716     DiagID = diag::warn_fortify_source_size_mismatch;
717     SizeIndex = 1;
718     ObjectIndex = 0;
719     break;
720   }
721   }
722 
723   llvm::APSInt ObjectSize;
724   // For __builtin___*_chk, the object size is explicitly provided by the caller
725   // (usually using __builtin_object_size). Use that value to check this call.
726   if (IsChkVariant) {
727     Expr::EvalResult Result;
728     Expr *SizeArg = TheCall->getArg(ObjectIndex);
729     if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
730       return;
731     ObjectSize = Result.Val.getInt();
732 
733   // Otherwise, try to evaluate an imaginary call to __builtin_object_size.
734   } else {
735     // If the parameter has a pass_object_size attribute, then we should use its
736     // (potentially) more strict checking mode. Otherwise, conservatively assume
737     // type 0.
738     int BOSType = 0;
739     if (const auto *POS =
740             FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>())
741       BOSType = POS->getType();
742 
743     Expr *ObjArg = TheCall->getArg(ObjectIndex);
744     uint64_t Result;
745     if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
746       return;
747     // Get the object size in the target's size_t width.
748     ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
749   }
750 
751   // Evaluate the number of bytes of the object that this call will use.
752   if (!UsedSize) {
753     Expr::EvalResult Result;
754     Expr *UsedSizeArg = TheCall->getArg(SizeIndex);
755     if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext()))
756       return;
757     UsedSize = Result.Val.getInt().extOrTrunc(SizeTypeWidth);
758   }
759 
760   if (UsedSize.getValue().ule(ObjectSize))
761     return;
762 
763   StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
764   // Skim off the details of whichever builtin was called to produce a better
765   // diagnostic, as it's unlikley that the user wrote the __builtin explicitly.
766   if (IsChkVariant) {
767     FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
768     FunctionName = FunctionName.drop_back(std::strlen("_chk"));
769   } else if (FunctionName.startswith("__builtin_")) {
770     FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
771   }
772 
773   DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
774                       PDiag(DiagID)
775                           << FunctionName << toString(ObjectSize, /*Radix=*/10)
776                           << toString(UsedSize.getValue(), /*Radix=*/10));
777 }
778 
779 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
780                                      Scope::ScopeFlags NeededScopeFlags,
781                                      unsigned DiagID) {
782   // Scopes aren't available during instantiation. Fortunately, builtin
783   // functions cannot be template args so they cannot be formed through template
784   // instantiation. Therefore checking once during the parse is sufficient.
785   if (SemaRef.inTemplateInstantiation())
786     return false;
787 
788   Scope *S = SemaRef.getCurScope();
789   while (S && !S->isSEHExceptScope())
790     S = S->getParent();
791   if (!S || !(S->getFlags() & NeededScopeFlags)) {
792     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
793     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
794         << DRE->getDecl()->getIdentifier();
795     return true;
796   }
797 
798   return false;
799 }
800 
801 static inline bool isBlockPointer(Expr *Arg) {
802   return Arg->getType()->isBlockPointerType();
803 }
804 
805 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
806 /// void*, which is a requirement of device side enqueue.
807 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
808   const BlockPointerType *BPT =
809       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
810   ArrayRef<QualType> Params =
811       BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes();
812   unsigned ArgCounter = 0;
813   bool IllegalParams = false;
814   // Iterate through the block parameters until either one is found that is not
815   // a local void*, or the block is valid.
816   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
817        I != E; ++I, ++ArgCounter) {
818     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
819         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
820             LangAS::opencl_local) {
821       // Get the location of the error. If a block literal has been passed
822       // (BlockExpr) then we can point straight to the offending argument,
823       // else we just point to the variable reference.
824       SourceLocation ErrorLoc;
825       if (isa<BlockExpr>(BlockArg)) {
826         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
827         ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
828       } else if (isa<DeclRefExpr>(BlockArg)) {
829         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
830       }
831       S.Diag(ErrorLoc,
832              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
833       IllegalParams = true;
834     }
835   }
836 
837   return IllegalParams;
838 }
839 
840 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
841   if (!S.getOpenCLOptions().isSupported("cl_khr_subgroups", S.getLangOpts())) {
842     S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
843         << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
844     return true;
845   }
846   return false;
847 }
848 
849 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
850   if (checkArgCount(S, TheCall, 2))
851     return true;
852 
853   if (checkOpenCLSubgroupExt(S, TheCall))
854     return true;
855 
856   // First argument is an ndrange_t type.
857   Expr *NDRangeArg = TheCall->getArg(0);
858   if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
859     S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
860         << TheCall->getDirectCallee() << "'ndrange_t'";
861     return true;
862   }
863 
864   Expr *BlockArg = TheCall->getArg(1);
865   if (!isBlockPointer(BlockArg)) {
866     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
867         << TheCall->getDirectCallee() << "block";
868     return true;
869   }
870   return checkOpenCLBlockArgs(S, BlockArg);
871 }
872 
873 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
874 /// get_kernel_work_group_size
875 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
876 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
877   if (checkArgCount(S, TheCall, 1))
878     return true;
879 
880   Expr *BlockArg = TheCall->getArg(0);
881   if (!isBlockPointer(BlockArg)) {
882     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
883         << TheCall->getDirectCallee() << "block";
884     return true;
885   }
886   return checkOpenCLBlockArgs(S, BlockArg);
887 }
888 
889 /// Diagnose integer type and any valid implicit conversion to it.
890 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
891                                       const QualType &IntType);
892 
893 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
894                                             unsigned Start, unsigned End) {
895   bool IllegalParams = false;
896   for (unsigned I = Start; I <= End; ++I)
897     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
898                                               S.Context.getSizeType());
899   return IllegalParams;
900 }
901 
902 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
903 /// 'local void*' parameter of passed block.
904 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
905                                            Expr *BlockArg,
906                                            unsigned NumNonVarArgs) {
907   const BlockPointerType *BPT =
908       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
909   unsigned NumBlockParams =
910       BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams();
911   unsigned TotalNumArgs = TheCall->getNumArgs();
912 
913   // For each argument passed to the block, a corresponding uint needs to
914   // be passed to describe the size of the local memory.
915   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
916     S.Diag(TheCall->getBeginLoc(),
917            diag::err_opencl_enqueue_kernel_local_size_args);
918     return true;
919   }
920 
921   // Check that the sizes of the local memory are specified by integers.
922   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
923                                          TotalNumArgs - 1);
924 }
925 
926 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
927 /// overload formats specified in Table 6.13.17.1.
928 /// int enqueue_kernel(queue_t queue,
929 ///                    kernel_enqueue_flags_t flags,
930 ///                    const ndrange_t ndrange,
931 ///                    void (^block)(void))
932 /// int enqueue_kernel(queue_t queue,
933 ///                    kernel_enqueue_flags_t flags,
934 ///                    const ndrange_t ndrange,
935 ///                    uint num_events_in_wait_list,
936 ///                    clk_event_t *event_wait_list,
937 ///                    clk_event_t *event_ret,
938 ///                    void (^block)(void))
939 /// int enqueue_kernel(queue_t queue,
940 ///                    kernel_enqueue_flags_t flags,
941 ///                    const ndrange_t ndrange,
942 ///                    void (^block)(local void*, ...),
943 ///                    uint size0, ...)
944 /// int enqueue_kernel(queue_t queue,
945 ///                    kernel_enqueue_flags_t flags,
946 ///                    const ndrange_t ndrange,
947 ///                    uint num_events_in_wait_list,
948 ///                    clk_event_t *event_wait_list,
949 ///                    clk_event_t *event_ret,
950 ///                    void (^block)(local void*, ...),
951 ///                    uint size0, ...)
952 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
953   unsigned NumArgs = TheCall->getNumArgs();
954 
955   if (NumArgs < 4) {
956     S.Diag(TheCall->getBeginLoc(),
957            diag::err_typecheck_call_too_few_args_at_least)
958         << 0 << 4 << NumArgs;
959     return true;
960   }
961 
962   Expr *Arg0 = TheCall->getArg(0);
963   Expr *Arg1 = TheCall->getArg(1);
964   Expr *Arg2 = TheCall->getArg(2);
965   Expr *Arg3 = TheCall->getArg(3);
966 
967   // First argument always needs to be a queue_t type.
968   if (!Arg0->getType()->isQueueT()) {
969     S.Diag(TheCall->getArg(0)->getBeginLoc(),
970            diag::err_opencl_builtin_expected_type)
971         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
972     return true;
973   }
974 
975   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
976   if (!Arg1->getType()->isIntegerType()) {
977     S.Diag(TheCall->getArg(1)->getBeginLoc(),
978            diag::err_opencl_builtin_expected_type)
979         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
980     return true;
981   }
982 
983   // Third argument is always an ndrange_t type.
984   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
985     S.Diag(TheCall->getArg(2)->getBeginLoc(),
986            diag::err_opencl_builtin_expected_type)
987         << TheCall->getDirectCallee() << "'ndrange_t'";
988     return true;
989   }
990 
991   // With four arguments, there is only one form that the function could be
992   // called in: no events and no variable arguments.
993   if (NumArgs == 4) {
994     // check that the last argument is the right block type.
995     if (!isBlockPointer(Arg3)) {
996       S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
997           << TheCall->getDirectCallee() << "block";
998       return true;
999     }
1000     // we have a block type, check the prototype
1001     const BlockPointerType *BPT =
1002         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
1003     if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) {
1004       S.Diag(Arg3->getBeginLoc(),
1005              diag::err_opencl_enqueue_kernel_blocks_no_args);
1006       return true;
1007     }
1008     return false;
1009   }
1010   // we can have block + varargs.
1011   if (isBlockPointer(Arg3))
1012     return (checkOpenCLBlockArgs(S, Arg3) ||
1013             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
1014   // last two cases with either exactly 7 args or 7 args and varargs.
1015   if (NumArgs >= 7) {
1016     // check common block argument.
1017     Expr *Arg6 = TheCall->getArg(6);
1018     if (!isBlockPointer(Arg6)) {
1019       S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1020           << TheCall->getDirectCallee() << "block";
1021       return true;
1022     }
1023     if (checkOpenCLBlockArgs(S, Arg6))
1024       return true;
1025 
1026     // Forth argument has to be any integer type.
1027     if (!Arg3->getType()->isIntegerType()) {
1028       S.Diag(TheCall->getArg(3)->getBeginLoc(),
1029              diag::err_opencl_builtin_expected_type)
1030           << TheCall->getDirectCallee() << "integer";
1031       return true;
1032     }
1033     // check remaining common arguments.
1034     Expr *Arg4 = TheCall->getArg(4);
1035     Expr *Arg5 = TheCall->getArg(5);
1036 
1037     // Fifth argument is always passed as a pointer to clk_event_t.
1038     if (!Arg4->isNullPointerConstant(S.Context,
1039                                      Expr::NPC_ValueDependentIsNotNull) &&
1040         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
1041       S.Diag(TheCall->getArg(4)->getBeginLoc(),
1042              diag::err_opencl_builtin_expected_type)
1043           << TheCall->getDirectCallee()
1044           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1045       return true;
1046     }
1047 
1048     // Sixth argument is always passed as a pointer to clk_event_t.
1049     if (!Arg5->isNullPointerConstant(S.Context,
1050                                      Expr::NPC_ValueDependentIsNotNull) &&
1051         !(Arg5->getType()->isPointerType() &&
1052           Arg5->getType()->getPointeeType()->isClkEventT())) {
1053       S.Diag(TheCall->getArg(5)->getBeginLoc(),
1054              diag::err_opencl_builtin_expected_type)
1055           << TheCall->getDirectCallee()
1056           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1057       return true;
1058     }
1059 
1060     if (NumArgs == 7)
1061       return false;
1062 
1063     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
1064   }
1065 
1066   // None of the specific case has been detected, give generic error
1067   S.Diag(TheCall->getBeginLoc(),
1068          diag::err_opencl_enqueue_kernel_incorrect_args);
1069   return true;
1070 }
1071 
1072 /// Returns OpenCL access qual.
1073 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
1074     return D->getAttr<OpenCLAccessAttr>();
1075 }
1076 
1077 /// Returns true if pipe element type is different from the pointer.
1078 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
1079   const Expr *Arg0 = Call->getArg(0);
1080   // First argument type should always be pipe.
1081   if (!Arg0->getType()->isPipeType()) {
1082     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1083         << Call->getDirectCallee() << Arg0->getSourceRange();
1084     return true;
1085   }
1086   OpenCLAccessAttr *AccessQual =
1087       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
1088   // Validates the access qualifier is compatible with the call.
1089   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
1090   // read_only and write_only, and assumed to be read_only if no qualifier is
1091   // specified.
1092   switch (Call->getDirectCallee()->getBuiltinID()) {
1093   case Builtin::BIread_pipe:
1094   case Builtin::BIreserve_read_pipe:
1095   case Builtin::BIcommit_read_pipe:
1096   case Builtin::BIwork_group_reserve_read_pipe:
1097   case Builtin::BIsub_group_reserve_read_pipe:
1098   case Builtin::BIwork_group_commit_read_pipe:
1099   case Builtin::BIsub_group_commit_read_pipe:
1100     if (!(!AccessQual || AccessQual->isReadOnly())) {
1101       S.Diag(Arg0->getBeginLoc(),
1102              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1103           << "read_only" << Arg0->getSourceRange();
1104       return true;
1105     }
1106     break;
1107   case Builtin::BIwrite_pipe:
1108   case Builtin::BIreserve_write_pipe:
1109   case Builtin::BIcommit_write_pipe:
1110   case Builtin::BIwork_group_reserve_write_pipe:
1111   case Builtin::BIsub_group_reserve_write_pipe:
1112   case Builtin::BIwork_group_commit_write_pipe:
1113   case Builtin::BIsub_group_commit_write_pipe:
1114     if (!(AccessQual && AccessQual->isWriteOnly())) {
1115       S.Diag(Arg0->getBeginLoc(),
1116              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1117           << "write_only" << Arg0->getSourceRange();
1118       return true;
1119     }
1120     break;
1121   default:
1122     break;
1123   }
1124   return false;
1125 }
1126 
1127 /// Returns true if pipe element type is different from the pointer.
1128 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
1129   const Expr *Arg0 = Call->getArg(0);
1130   const Expr *ArgIdx = Call->getArg(Idx);
1131   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
1132   const QualType EltTy = PipeTy->getElementType();
1133   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
1134   // The Idx argument should be a pointer and the type of the pointer and
1135   // the type of pipe element should also be the same.
1136   if (!ArgTy ||
1137       !S.Context.hasSameType(
1138           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
1139     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1140         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
1141         << ArgIdx->getType() << ArgIdx->getSourceRange();
1142     return true;
1143   }
1144   return false;
1145 }
1146 
1147 // Performs semantic analysis for the read/write_pipe call.
1148 // \param S Reference to the semantic analyzer.
1149 // \param Call A pointer to the builtin call.
1150 // \return True if a semantic error has been found, false otherwise.
1151 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
1152   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
1153   // functions have two forms.
1154   switch (Call->getNumArgs()) {
1155   case 2:
1156     if (checkOpenCLPipeArg(S, Call))
1157       return true;
1158     // The call with 2 arguments should be
1159     // read/write_pipe(pipe T, T*).
1160     // Check packet type T.
1161     if (checkOpenCLPipePacketType(S, Call, 1))
1162       return true;
1163     break;
1164 
1165   case 4: {
1166     if (checkOpenCLPipeArg(S, Call))
1167       return true;
1168     // The call with 4 arguments should be
1169     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
1170     // Check reserve_id_t.
1171     if (!Call->getArg(1)->getType()->isReserveIDT()) {
1172       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1173           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1174           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1175       return true;
1176     }
1177 
1178     // Check the index.
1179     const Expr *Arg2 = Call->getArg(2);
1180     if (!Arg2->getType()->isIntegerType() &&
1181         !Arg2->getType()->isUnsignedIntegerType()) {
1182       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1183           << Call->getDirectCallee() << S.Context.UnsignedIntTy
1184           << Arg2->getType() << Arg2->getSourceRange();
1185       return true;
1186     }
1187 
1188     // Check packet type T.
1189     if (checkOpenCLPipePacketType(S, Call, 3))
1190       return true;
1191   } break;
1192   default:
1193     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
1194         << Call->getDirectCallee() << Call->getSourceRange();
1195     return true;
1196   }
1197 
1198   return false;
1199 }
1200 
1201 // Performs a semantic analysis on the {work_group_/sub_group_
1202 //        /_}reserve_{read/write}_pipe
1203 // \param S Reference to the semantic analyzer.
1204 // \param Call The call to the builtin function to be analyzed.
1205 // \return True if a semantic error was found, false otherwise.
1206 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
1207   if (checkArgCount(S, Call, 2))
1208     return true;
1209 
1210   if (checkOpenCLPipeArg(S, Call))
1211     return true;
1212 
1213   // Check the reserve size.
1214   if (!Call->getArg(1)->getType()->isIntegerType() &&
1215       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
1216     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1217         << Call->getDirectCallee() << S.Context.UnsignedIntTy
1218         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1219     return true;
1220   }
1221 
1222   // Since return type of reserve_read/write_pipe built-in function is
1223   // reserve_id_t, which is not defined in the builtin def file , we used int
1224   // as return type and need to override the return type of these functions.
1225   Call->setType(S.Context.OCLReserveIDTy);
1226 
1227   return false;
1228 }
1229 
1230 // Performs a semantic analysis on {work_group_/sub_group_
1231 //        /_}commit_{read/write}_pipe
1232 // \param S Reference to the semantic analyzer.
1233 // \param Call The call to the builtin function to be analyzed.
1234 // \return True if a semantic error was found, false otherwise.
1235 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
1236   if (checkArgCount(S, Call, 2))
1237     return true;
1238 
1239   if (checkOpenCLPipeArg(S, Call))
1240     return true;
1241 
1242   // Check reserve_id_t.
1243   if (!Call->getArg(1)->getType()->isReserveIDT()) {
1244     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1245         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1246         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1247     return true;
1248   }
1249 
1250   return false;
1251 }
1252 
1253 // Performs a semantic analysis on the call to built-in Pipe
1254 //        Query Functions.
1255 // \param S Reference to the semantic analyzer.
1256 // \param Call The call to the builtin function to be analyzed.
1257 // \return True if a semantic error was found, false otherwise.
1258 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
1259   if (checkArgCount(S, Call, 1))
1260     return true;
1261 
1262   if (!Call->getArg(0)->getType()->isPipeType()) {
1263     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1264         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
1265     return true;
1266   }
1267 
1268   return false;
1269 }
1270 
1271 // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
1272 // Performs semantic analysis for the to_global/local/private call.
1273 // \param S Reference to the semantic analyzer.
1274 // \param BuiltinID ID of the builtin function.
1275 // \param Call A pointer to the builtin call.
1276 // \return True if a semantic error has been found, false otherwise.
1277 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
1278                                     CallExpr *Call) {
1279   if (checkArgCount(S, Call, 1))
1280     return true;
1281 
1282   auto RT = Call->getArg(0)->getType();
1283   if (!RT->isPointerType() || RT->getPointeeType()
1284       .getAddressSpace() == LangAS::opencl_constant) {
1285     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
1286         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
1287     return true;
1288   }
1289 
1290   if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
1291     S.Diag(Call->getArg(0)->getBeginLoc(),
1292            diag::warn_opencl_generic_address_space_arg)
1293         << Call->getDirectCallee()->getNameInfo().getAsString()
1294         << Call->getArg(0)->getSourceRange();
1295   }
1296 
1297   RT = RT->getPointeeType();
1298   auto Qual = RT.getQualifiers();
1299   switch (BuiltinID) {
1300   case Builtin::BIto_global:
1301     Qual.setAddressSpace(LangAS::opencl_global);
1302     break;
1303   case Builtin::BIto_local:
1304     Qual.setAddressSpace(LangAS::opencl_local);
1305     break;
1306   case Builtin::BIto_private:
1307     Qual.setAddressSpace(LangAS::opencl_private);
1308     break;
1309   default:
1310     llvm_unreachable("Invalid builtin function");
1311   }
1312   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
1313       RT.getUnqualifiedType(), Qual)));
1314 
1315   return false;
1316 }
1317 
1318 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
1319   if (checkArgCount(S, TheCall, 1))
1320     return ExprError();
1321 
1322   // Compute __builtin_launder's parameter type from the argument.
1323   // The parameter type is:
1324   //  * The type of the argument if it's not an array or function type,
1325   //  Otherwise,
1326   //  * The decayed argument type.
1327   QualType ParamTy = [&]() {
1328     QualType ArgTy = TheCall->getArg(0)->getType();
1329     if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1330       return S.Context.getPointerType(Ty->getElementType());
1331     if (ArgTy->isFunctionType()) {
1332       return S.Context.getPointerType(ArgTy);
1333     }
1334     return ArgTy;
1335   }();
1336 
1337   TheCall->setType(ParamTy);
1338 
1339   auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
1340     if (!ParamTy->isPointerType())
1341       return 0;
1342     if (ParamTy->isFunctionPointerType())
1343       return 1;
1344     if (ParamTy->isVoidPointerType())
1345       return 2;
1346     return llvm::Optional<unsigned>{};
1347   }();
1348   if (DiagSelect.hasValue()) {
1349     S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1350         << DiagSelect.getValue() << TheCall->getSourceRange();
1351     return ExprError();
1352   }
1353 
1354   // We either have an incomplete class type, or we have a class template
1355   // whose instantiation has not been forced. Example:
1356   //
1357   //   template <class T> struct Foo { T value; };
1358   //   Foo<int> *p = nullptr;
1359   //   auto *d = __builtin_launder(p);
1360   if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1361                             diag::err_incomplete_type))
1362     return ExprError();
1363 
1364   assert(ParamTy->getPointeeType()->isObjectType() &&
1365          "Unhandled non-object pointer case");
1366 
1367   InitializedEntity Entity =
1368       InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
1369   ExprResult Arg =
1370       S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1371   if (Arg.isInvalid())
1372     return ExprError();
1373   TheCall->setArg(0, Arg.get());
1374 
1375   return TheCall;
1376 }
1377 
1378 // Emit an error and return true if the current architecture is not in the list
1379 // of supported architectures.
1380 static bool
1381 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1382                           ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
1383   llvm::Triple::ArchType CurArch =
1384       S.getASTContext().getTargetInfo().getTriple().getArch();
1385   if (llvm::is_contained(SupportedArchs, CurArch))
1386     return false;
1387   S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1388       << TheCall->getSourceRange();
1389   return true;
1390 }
1391 
1392 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
1393                                  SourceLocation CallSiteLoc);
1394 
1395 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
1396                                       CallExpr *TheCall) {
1397   switch (TI.getTriple().getArch()) {
1398   default:
1399     // Some builtins don't require additional checking, so just consider these
1400     // acceptable.
1401     return false;
1402   case llvm::Triple::arm:
1403   case llvm::Triple::armeb:
1404   case llvm::Triple::thumb:
1405   case llvm::Triple::thumbeb:
1406     return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
1407   case llvm::Triple::aarch64:
1408   case llvm::Triple::aarch64_32:
1409   case llvm::Triple::aarch64_be:
1410     return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
1411   case llvm::Triple::bpfeb:
1412   case llvm::Triple::bpfel:
1413     return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
1414   case llvm::Triple::hexagon:
1415     return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
1416   case llvm::Triple::mips:
1417   case llvm::Triple::mipsel:
1418   case llvm::Triple::mips64:
1419   case llvm::Triple::mips64el:
1420     return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
1421   case llvm::Triple::systemz:
1422     return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
1423   case llvm::Triple::x86:
1424   case llvm::Triple::x86_64:
1425     return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall);
1426   case llvm::Triple::ppc:
1427   case llvm::Triple::ppcle:
1428   case llvm::Triple::ppc64:
1429   case llvm::Triple::ppc64le:
1430     return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
1431   case llvm::Triple::amdgcn:
1432     return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
1433   case llvm::Triple::riscv32:
1434   case llvm::Triple::riscv64:
1435     return CheckRISCVBuiltinFunctionCall(TI, BuiltinID, TheCall);
1436   }
1437 }
1438 
1439 ExprResult
1440 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
1441                                CallExpr *TheCall) {
1442   ExprResult TheCallResult(TheCall);
1443 
1444   // Find out if any arguments are required to be integer constant expressions.
1445   unsigned ICEArguments = 0;
1446   ASTContext::GetBuiltinTypeError Error;
1447   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
1448   if (Error != ASTContext::GE_None)
1449     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
1450 
1451   // If any arguments are required to be ICE's, check and diagnose.
1452   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
1453     // Skip arguments not required to be ICE's.
1454     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
1455 
1456     llvm::APSInt Result;
1457     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
1458       return true;
1459     ICEArguments &= ~(1 << ArgNo);
1460   }
1461 
1462   switch (BuiltinID) {
1463   case Builtin::BI__builtin___CFStringMakeConstantString:
1464     assert(TheCall->getNumArgs() == 1 &&
1465            "Wrong # arguments to builtin CFStringMakeConstantString");
1466     if (CheckObjCString(TheCall->getArg(0)))
1467       return ExprError();
1468     break;
1469   case Builtin::BI__builtin_ms_va_start:
1470   case Builtin::BI__builtin_stdarg_start:
1471   case Builtin::BI__builtin_va_start:
1472     if (SemaBuiltinVAStart(BuiltinID, TheCall))
1473       return ExprError();
1474     break;
1475   case Builtin::BI__va_start: {
1476     switch (Context.getTargetInfo().getTriple().getArch()) {
1477     case llvm::Triple::aarch64:
1478     case llvm::Triple::arm:
1479     case llvm::Triple::thumb:
1480       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
1481         return ExprError();
1482       break;
1483     default:
1484       if (SemaBuiltinVAStart(BuiltinID, TheCall))
1485         return ExprError();
1486       break;
1487     }
1488     break;
1489   }
1490 
1491   // The acquire, release, and no fence variants are ARM and AArch64 only.
1492   case Builtin::BI_interlockedbittestandset_acq:
1493   case Builtin::BI_interlockedbittestandset_rel:
1494   case Builtin::BI_interlockedbittestandset_nf:
1495   case Builtin::BI_interlockedbittestandreset_acq:
1496   case Builtin::BI_interlockedbittestandreset_rel:
1497   case Builtin::BI_interlockedbittestandreset_nf:
1498     if (CheckBuiltinTargetSupport(
1499             *this, BuiltinID, TheCall,
1500             {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
1501       return ExprError();
1502     break;
1503 
1504   // The 64-bit bittest variants are x64, ARM, and AArch64 only.
1505   case Builtin::BI_bittest64:
1506   case Builtin::BI_bittestandcomplement64:
1507   case Builtin::BI_bittestandreset64:
1508   case Builtin::BI_bittestandset64:
1509   case Builtin::BI_interlockedbittestandreset64:
1510   case Builtin::BI_interlockedbittestandset64:
1511     if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
1512                                   {llvm::Triple::x86_64, llvm::Triple::arm,
1513                                    llvm::Triple::thumb, llvm::Triple::aarch64}))
1514       return ExprError();
1515     break;
1516 
1517   case Builtin::BI__builtin_isgreater:
1518   case Builtin::BI__builtin_isgreaterequal:
1519   case Builtin::BI__builtin_isless:
1520   case Builtin::BI__builtin_islessequal:
1521   case Builtin::BI__builtin_islessgreater:
1522   case Builtin::BI__builtin_isunordered:
1523     if (SemaBuiltinUnorderedCompare(TheCall))
1524       return ExprError();
1525     break;
1526   case Builtin::BI__builtin_fpclassify:
1527     if (SemaBuiltinFPClassification(TheCall, 6))
1528       return ExprError();
1529     break;
1530   case Builtin::BI__builtin_isfinite:
1531   case Builtin::BI__builtin_isinf:
1532   case Builtin::BI__builtin_isinf_sign:
1533   case Builtin::BI__builtin_isnan:
1534   case Builtin::BI__builtin_isnormal:
1535   case Builtin::BI__builtin_signbit:
1536   case Builtin::BI__builtin_signbitf:
1537   case Builtin::BI__builtin_signbitl:
1538     if (SemaBuiltinFPClassification(TheCall, 1))
1539       return ExprError();
1540     break;
1541   case Builtin::BI__builtin_shufflevector:
1542     return SemaBuiltinShuffleVector(TheCall);
1543     // TheCall will be freed by the smart pointer here, but that's fine, since
1544     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1545   case Builtin::BI__builtin_prefetch:
1546     if (SemaBuiltinPrefetch(TheCall))
1547       return ExprError();
1548     break;
1549   case Builtin::BI__builtin_alloca_with_align:
1550     if (SemaBuiltinAllocaWithAlign(TheCall))
1551       return ExprError();
1552     LLVM_FALLTHROUGH;
1553   case Builtin::BI__builtin_alloca:
1554     Diag(TheCall->getBeginLoc(), diag::warn_alloca)
1555         << TheCall->getDirectCallee();
1556     break;
1557   case Builtin::BI__arithmetic_fence:
1558     if (SemaBuiltinArithmeticFence(TheCall))
1559       return ExprError();
1560     break;
1561   case Builtin::BI__assume:
1562   case Builtin::BI__builtin_assume:
1563     if (SemaBuiltinAssume(TheCall))
1564       return ExprError();
1565     break;
1566   case Builtin::BI__builtin_assume_aligned:
1567     if (SemaBuiltinAssumeAligned(TheCall))
1568       return ExprError();
1569     break;
1570   case Builtin::BI__builtin_dynamic_object_size:
1571   case Builtin::BI__builtin_object_size:
1572     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1573       return ExprError();
1574     break;
1575   case Builtin::BI__builtin_longjmp:
1576     if (SemaBuiltinLongjmp(TheCall))
1577       return ExprError();
1578     break;
1579   case Builtin::BI__builtin_setjmp:
1580     if (SemaBuiltinSetjmp(TheCall))
1581       return ExprError();
1582     break;
1583   case Builtin::BI__builtin_classify_type:
1584     if (checkArgCount(*this, TheCall, 1)) return true;
1585     TheCall->setType(Context.IntTy);
1586     break;
1587   case Builtin::BI__builtin_complex:
1588     if (SemaBuiltinComplex(TheCall))
1589       return ExprError();
1590     break;
1591   case Builtin::BI__builtin_constant_p: {
1592     if (checkArgCount(*this, TheCall, 1)) return true;
1593     ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
1594     if (Arg.isInvalid()) return true;
1595     TheCall->setArg(0, Arg.get());
1596     TheCall->setType(Context.IntTy);
1597     break;
1598   }
1599   case Builtin::BI__builtin_launder:
1600     return SemaBuiltinLaunder(*this, TheCall);
1601   case Builtin::BI__sync_fetch_and_add:
1602   case Builtin::BI__sync_fetch_and_add_1:
1603   case Builtin::BI__sync_fetch_and_add_2:
1604   case Builtin::BI__sync_fetch_and_add_4:
1605   case Builtin::BI__sync_fetch_and_add_8:
1606   case Builtin::BI__sync_fetch_and_add_16:
1607   case Builtin::BI__sync_fetch_and_sub:
1608   case Builtin::BI__sync_fetch_and_sub_1:
1609   case Builtin::BI__sync_fetch_and_sub_2:
1610   case Builtin::BI__sync_fetch_and_sub_4:
1611   case Builtin::BI__sync_fetch_and_sub_8:
1612   case Builtin::BI__sync_fetch_and_sub_16:
1613   case Builtin::BI__sync_fetch_and_or:
1614   case Builtin::BI__sync_fetch_and_or_1:
1615   case Builtin::BI__sync_fetch_and_or_2:
1616   case Builtin::BI__sync_fetch_and_or_4:
1617   case Builtin::BI__sync_fetch_and_or_8:
1618   case Builtin::BI__sync_fetch_and_or_16:
1619   case Builtin::BI__sync_fetch_and_and:
1620   case Builtin::BI__sync_fetch_and_and_1:
1621   case Builtin::BI__sync_fetch_and_and_2:
1622   case Builtin::BI__sync_fetch_and_and_4:
1623   case Builtin::BI__sync_fetch_and_and_8:
1624   case Builtin::BI__sync_fetch_and_and_16:
1625   case Builtin::BI__sync_fetch_and_xor:
1626   case Builtin::BI__sync_fetch_and_xor_1:
1627   case Builtin::BI__sync_fetch_and_xor_2:
1628   case Builtin::BI__sync_fetch_and_xor_4:
1629   case Builtin::BI__sync_fetch_and_xor_8:
1630   case Builtin::BI__sync_fetch_and_xor_16:
1631   case Builtin::BI__sync_fetch_and_nand:
1632   case Builtin::BI__sync_fetch_and_nand_1:
1633   case Builtin::BI__sync_fetch_and_nand_2:
1634   case Builtin::BI__sync_fetch_and_nand_4:
1635   case Builtin::BI__sync_fetch_and_nand_8:
1636   case Builtin::BI__sync_fetch_and_nand_16:
1637   case Builtin::BI__sync_add_and_fetch:
1638   case Builtin::BI__sync_add_and_fetch_1:
1639   case Builtin::BI__sync_add_and_fetch_2:
1640   case Builtin::BI__sync_add_and_fetch_4:
1641   case Builtin::BI__sync_add_and_fetch_8:
1642   case Builtin::BI__sync_add_and_fetch_16:
1643   case Builtin::BI__sync_sub_and_fetch:
1644   case Builtin::BI__sync_sub_and_fetch_1:
1645   case Builtin::BI__sync_sub_and_fetch_2:
1646   case Builtin::BI__sync_sub_and_fetch_4:
1647   case Builtin::BI__sync_sub_and_fetch_8:
1648   case Builtin::BI__sync_sub_and_fetch_16:
1649   case Builtin::BI__sync_and_and_fetch:
1650   case Builtin::BI__sync_and_and_fetch_1:
1651   case Builtin::BI__sync_and_and_fetch_2:
1652   case Builtin::BI__sync_and_and_fetch_4:
1653   case Builtin::BI__sync_and_and_fetch_8:
1654   case Builtin::BI__sync_and_and_fetch_16:
1655   case Builtin::BI__sync_or_and_fetch:
1656   case Builtin::BI__sync_or_and_fetch_1:
1657   case Builtin::BI__sync_or_and_fetch_2:
1658   case Builtin::BI__sync_or_and_fetch_4:
1659   case Builtin::BI__sync_or_and_fetch_8:
1660   case Builtin::BI__sync_or_and_fetch_16:
1661   case Builtin::BI__sync_xor_and_fetch:
1662   case Builtin::BI__sync_xor_and_fetch_1:
1663   case Builtin::BI__sync_xor_and_fetch_2:
1664   case Builtin::BI__sync_xor_and_fetch_4:
1665   case Builtin::BI__sync_xor_and_fetch_8:
1666   case Builtin::BI__sync_xor_and_fetch_16:
1667   case Builtin::BI__sync_nand_and_fetch:
1668   case Builtin::BI__sync_nand_and_fetch_1:
1669   case Builtin::BI__sync_nand_and_fetch_2:
1670   case Builtin::BI__sync_nand_and_fetch_4:
1671   case Builtin::BI__sync_nand_and_fetch_8:
1672   case Builtin::BI__sync_nand_and_fetch_16:
1673   case Builtin::BI__sync_val_compare_and_swap:
1674   case Builtin::BI__sync_val_compare_and_swap_1:
1675   case Builtin::BI__sync_val_compare_and_swap_2:
1676   case Builtin::BI__sync_val_compare_and_swap_4:
1677   case Builtin::BI__sync_val_compare_and_swap_8:
1678   case Builtin::BI__sync_val_compare_and_swap_16:
1679   case Builtin::BI__sync_bool_compare_and_swap:
1680   case Builtin::BI__sync_bool_compare_and_swap_1:
1681   case Builtin::BI__sync_bool_compare_and_swap_2:
1682   case Builtin::BI__sync_bool_compare_and_swap_4:
1683   case Builtin::BI__sync_bool_compare_and_swap_8:
1684   case Builtin::BI__sync_bool_compare_and_swap_16:
1685   case Builtin::BI__sync_lock_test_and_set:
1686   case Builtin::BI__sync_lock_test_and_set_1:
1687   case Builtin::BI__sync_lock_test_and_set_2:
1688   case Builtin::BI__sync_lock_test_and_set_4:
1689   case Builtin::BI__sync_lock_test_and_set_8:
1690   case Builtin::BI__sync_lock_test_and_set_16:
1691   case Builtin::BI__sync_lock_release:
1692   case Builtin::BI__sync_lock_release_1:
1693   case Builtin::BI__sync_lock_release_2:
1694   case Builtin::BI__sync_lock_release_4:
1695   case Builtin::BI__sync_lock_release_8:
1696   case Builtin::BI__sync_lock_release_16:
1697   case Builtin::BI__sync_swap:
1698   case Builtin::BI__sync_swap_1:
1699   case Builtin::BI__sync_swap_2:
1700   case Builtin::BI__sync_swap_4:
1701   case Builtin::BI__sync_swap_8:
1702   case Builtin::BI__sync_swap_16:
1703     return SemaBuiltinAtomicOverloaded(TheCallResult);
1704   case Builtin::BI__sync_synchronize:
1705     Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1706         << TheCall->getCallee()->getSourceRange();
1707     break;
1708   case Builtin::BI__builtin_nontemporal_load:
1709   case Builtin::BI__builtin_nontemporal_store:
1710     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1711   case Builtin::BI__builtin_memcpy_inline: {
1712     clang::Expr *SizeOp = TheCall->getArg(2);
1713     // We warn about copying to or from `nullptr` pointers when `size` is
1714     // greater than 0. When `size` is value dependent we cannot evaluate its
1715     // value so we bail out.
1716     if (SizeOp->isValueDependent())
1717       break;
1718     if (!SizeOp->EvaluateKnownConstInt(Context).isNullValue()) {
1719       CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
1720       CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
1721     }
1722     break;
1723   }
1724 #define BUILTIN(ID, TYPE, ATTRS)
1725 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1726   case Builtin::BI##ID: \
1727     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1728 #include "clang/Basic/Builtins.def"
1729   case Builtin::BI__annotation:
1730     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1731       return ExprError();
1732     break;
1733   case Builtin::BI__builtin_annotation:
1734     if (SemaBuiltinAnnotation(*this, TheCall))
1735       return ExprError();
1736     break;
1737   case Builtin::BI__builtin_addressof:
1738     if (SemaBuiltinAddressof(*this, TheCall))
1739       return ExprError();
1740     break;
1741   case Builtin::BI__builtin_is_aligned:
1742   case Builtin::BI__builtin_align_up:
1743   case Builtin::BI__builtin_align_down:
1744     if (SemaBuiltinAlignment(*this, TheCall, BuiltinID))
1745       return ExprError();
1746     break;
1747   case Builtin::BI__builtin_add_overflow:
1748   case Builtin::BI__builtin_sub_overflow:
1749   case Builtin::BI__builtin_mul_overflow:
1750     if (SemaBuiltinOverflow(*this, TheCall, BuiltinID))
1751       return ExprError();
1752     break;
1753   case Builtin::BI__builtin_operator_new:
1754   case Builtin::BI__builtin_operator_delete: {
1755     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1756     ExprResult Res =
1757         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1758     if (Res.isInvalid())
1759       CorrectDelayedTyposInExpr(TheCallResult.get());
1760     return Res;
1761   }
1762   case Builtin::BI__builtin_dump_struct: {
1763     // We first want to ensure we are called with 2 arguments
1764     if (checkArgCount(*this, TheCall, 2))
1765       return ExprError();
1766     // Ensure that the first argument is of type 'struct XX *'
1767     const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1768     const QualType PtrArgType = PtrArg->getType();
1769     if (!PtrArgType->isPointerType() ||
1770         !PtrArgType->getPointeeType()->isRecordType()) {
1771       Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1772           << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1773           << "structure pointer";
1774       return ExprError();
1775     }
1776 
1777     // Ensure that the second argument is of type 'FunctionType'
1778     const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1779     const QualType FnPtrArgType = FnPtrArg->getType();
1780     if (!FnPtrArgType->isPointerType()) {
1781       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1782           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1783           << FnPtrArgType << "'int (*)(const char *, ...)'";
1784       return ExprError();
1785     }
1786 
1787     const auto *FuncType =
1788         FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1789 
1790     if (!FuncType) {
1791       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1792           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1793           << FnPtrArgType << "'int (*)(const char *, ...)'";
1794       return ExprError();
1795     }
1796 
1797     if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1798       if (!FT->getNumParams()) {
1799         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1800             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1801             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1802         return ExprError();
1803       }
1804       QualType PT = FT->getParamType(0);
1805       if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1806           !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1807           !PT->getPointeeType().isConstQualified()) {
1808         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1809             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1810             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1811         return ExprError();
1812       }
1813     }
1814 
1815     TheCall->setType(Context.IntTy);
1816     break;
1817   }
1818   case Builtin::BI__builtin_expect_with_probability: {
1819     // We first want to ensure we are called with 3 arguments
1820     if (checkArgCount(*this, TheCall, 3))
1821       return ExprError();
1822     // then check probability is constant float in range [0.0, 1.0]
1823     const Expr *ProbArg = TheCall->getArg(2);
1824     SmallVector<PartialDiagnosticAt, 8> Notes;
1825     Expr::EvalResult Eval;
1826     Eval.Diag = &Notes;
1827     if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
1828         !Eval.Val.isFloat()) {
1829       Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
1830           << ProbArg->getSourceRange();
1831       for (const PartialDiagnosticAt &PDiag : Notes)
1832         Diag(PDiag.first, PDiag.second);
1833       return ExprError();
1834     }
1835     llvm::APFloat Probability = Eval.Val.getFloat();
1836     bool LoseInfo = false;
1837     Probability.convert(llvm::APFloat::IEEEdouble(),
1838                         llvm::RoundingMode::Dynamic, &LoseInfo);
1839     if (!(Probability >= llvm::APFloat(0.0) &&
1840           Probability <= llvm::APFloat(1.0))) {
1841       Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
1842           << ProbArg->getSourceRange();
1843       return ExprError();
1844     }
1845     break;
1846   }
1847   case Builtin::BI__builtin_preserve_access_index:
1848     if (SemaBuiltinPreserveAI(*this, TheCall))
1849       return ExprError();
1850     break;
1851   case Builtin::BI__builtin_call_with_static_chain:
1852     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1853       return ExprError();
1854     break;
1855   case Builtin::BI__exception_code:
1856   case Builtin::BI_exception_code:
1857     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1858                                  diag::err_seh___except_block))
1859       return ExprError();
1860     break;
1861   case Builtin::BI__exception_info:
1862   case Builtin::BI_exception_info:
1863     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1864                                  diag::err_seh___except_filter))
1865       return ExprError();
1866     break;
1867   case Builtin::BI__GetExceptionInfo:
1868     if (checkArgCount(*this, TheCall, 1))
1869       return ExprError();
1870 
1871     if (CheckCXXThrowOperand(
1872             TheCall->getBeginLoc(),
1873             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1874             TheCall))
1875       return ExprError();
1876 
1877     TheCall->setType(Context.VoidPtrTy);
1878     break;
1879   // OpenCL v2.0, s6.13.16 - Pipe functions
1880   case Builtin::BIread_pipe:
1881   case Builtin::BIwrite_pipe:
1882     // Since those two functions are declared with var args, we need a semantic
1883     // check for the argument.
1884     if (SemaBuiltinRWPipe(*this, TheCall))
1885       return ExprError();
1886     break;
1887   case Builtin::BIreserve_read_pipe:
1888   case Builtin::BIreserve_write_pipe:
1889   case Builtin::BIwork_group_reserve_read_pipe:
1890   case Builtin::BIwork_group_reserve_write_pipe:
1891     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1892       return ExprError();
1893     break;
1894   case Builtin::BIsub_group_reserve_read_pipe:
1895   case Builtin::BIsub_group_reserve_write_pipe:
1896     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1897         SemaBuiltinReserveRWPipe(*this, TheCall))
1898       return ExprError();
1899     break;
1900   case Builtin::BIcommit_read_pipe:
1901   case Builtin::BIcommit_write_pipe:
1902   case Builtin::BIwork_group_commit_read_pipe:
1903   case Builtin::BIwork_group_commit_write_pipe:
1904     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1905       return ExprError();
1906     break;
1907   case Builtin::BIsub_group_commit_read_pipe:
1908   case Builtin::BIsub_group_commit_write_pipe:
1909     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1910         SemaBuiltinCommitRWPipe(*this, TheCall))
1911       return ExprError();
1912     break;
1913   case Builtin::BIget_pipe_num_packets:
1914   case Builtin::BIget_pipe_max_packets:
1915     if (SemaBuiltinPipePackets(*this, TheCall))
1916       return ExprError();
1917     break;
1918   case Builtin::BIto_global:
1919   case Builtin::BIto_local:
1920   case Builtin::BIto_private:
1921     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1922       return ExprError();
1923     break;
1924   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1925   case Builtin::BIenqueue_kernel:
1926     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1927       return ExprError();
1928     break;
1929   case Builtin::BIget_kernel_work_group_size:
1930   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1931     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1932       return ExprError();
1933     break;
1934   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1935   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1936     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1937       return ExprError();
1938     break;
1939   case Builtin::BI__builtin_os_log_format:
1940     Cleanup.setExprNeedsCleanups(true);
1941     LLVM_FALLTHROUGH;
1942   case Builtin::BI__builtin_os_log_format_buffer_size:
1943     if (SemaBuiltinOSLogFormat(TheCall))
1944       return ExprError();
1945     break;
1946   case Builtin::BI__builtin_frame_address:
1947   case Builtin::BI__builtin_return_address: {
1948     if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
1949       return ExprError();
1950 
1951     // -Wframe-address warning if non-zero passed to builtin
1952     // return/frame address.
1953     Expr::EvalResult Result;
1954     if (!TheCall->getArg(0)->isValueDependent() &&
1955         TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
1956         Result.Val.getInt() != 0)
1957       Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
1958           << ((BuiltinID == Builtin::BI__builtin_return_address)
1959                   ? "__builtin_return_address"
1960                   : "__builtin_frame_address")
1961           << TheCall->getSourceRange();
1962     break;
1963   }
1964 
1965   case Builtin::BI__builtin_matrix_transpose:
1966     return SemaBuiltinMatrixTranspose(TheCall, TheCallResult);
1967 
1968   case Builtin::BI__builtin_matrix_column_major_load:
1969     return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
1970 
1971   case Builtin::BI__builtin_matrix_column_major_store:
1972     return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
1973 
1974   case Builtin::BI__builtin_get_device_side_mangled_name: {
1975     auto Check = [](CallExpr *TheCall) {
1976       if (TheCall->getNumArgs() != 1)
1977         return false;
1978       auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());
1979       if (!DRE)
1980         return false;
1981       auto *D = DRE->getDecl();
1982       if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D))
1983         return false;
1984       return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
1985              D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
1986     };
1987     if (!Check(TheCall)) {
1988       Diag(TheCall->getBeginLoc(),
1989            diag::err_hip_invalid_args_builtin_mangled_name);
1990       return ExprError();
1991     }
1992   }
1993   }
1994 
1995   // Since the target specific builtins for each arch overlap, only check those
1996   // of the arch we are compiling for.
1997   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1998     if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
1999       assert(Context.getAuxTargetInfo() &&
2000              "Aux Target Builtin, but not an aux target?");
2001 
2002       if (CheckTSBuiltinFunctionCall(
2003               *Context.getAuxTargetInfo(),
2004               Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
2005         return ExprError();
2006     } else {
2007       if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
2008                                      TheCall))
2009         return ExprError();
2010     }
2011   }
2012 
2013   return TheCallResult;
2014 }
2015 
2016 // Get the valid immediate range for the specified NEON type code.
2017 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
2018   NeonTypeFlags Type(t);
2019   int IsQuad = ForceQuad ? true : Type.isQuad();
2020   switch (Type.getEltType()) {
2021   case NeonTypeFlags::Int8:
2022   case NeonTypeFlags::Poly8:
2023     return shift ? 7 : (8 << IsQuad) - 1;
2024   case NeonTypeFlags::Int16:
2025   case NeonTypeFlags::Poly16:
2026     return shift ? 15 : (4 << IsQuad) - 1;
2027   case NeonTypeFlags::Int32:
2028     return shift ? 31 : (2 << IsQuad) - 1;
2029   case NeonTypeFlags::Int64:
2030   case NeonTypeFlags::Poly64:
2031     return shift ? 63 : (1 << IsQuad) - 1;
2032   case NeonTypeFlags::Poly128:
2033     return shift ? 127 : (1 << IsQuad) - 1;
2034   case NeonTypeFlags::Float16:
2035     assert(!shift && "cannot shift float types!");
2036     return (4 << IsQuad) - 1;
2037   case NeonTypeFlags::Float32:
2038     assert(!shift && "cannot shift float types!");
2039     return (2 << IsQuad) - 1;
2040   case NeonTypeFlags::Float64:
2041     assert(!shift && "cannot shift float types!");
2042     return (1 << IsQuad) - 1;
2043   case NeonTypeFlags::BFloat16:
2044     assert(!shift && "cannot shift float types!");
2045     return (4 << IsQuad) - 1;
2046   }
2047   llvm_unreachable("Invalid NeonTypeFlag!");
2048 }
2049 
2050 /// getNeonEltType - Return the QualType corresponding to the elements of
2051 /// the vector type specified by the NeonTypeFlags.  This is used to check
2052 /// the pointer arguments for Neon load/store intrinsics.
2053 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
2054                                bool IsPolyUnsigned, bool IsInt64Long) {
2055   switch (Flags.getEltType()) {
2056   case NeonTypeFlags::Int8:
2057     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
2058   case NeonTypeFlags::Int16:
2059     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
2060   case NeonTypeFlags::Int32:
2061     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
2062   case NeonTypeFlags::Int64:
2063     if (IsInt64Long)
2064       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
2065     else
2066       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
2067                                 : Context.LongLongTy;
2068   case NeonTypeFlags::Poly8:
2069     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
2070   case NeonTypeFlags::Poly16:
2071     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
2072   case NeonTypeFlags::Poly64:
2073     if (IsInt64Long)
2074       return Context.UnsignedLongTy;
2075     else
2076       return Context.UnsignedLongLongTy;
2077   case NeonTypeFlags::Poly128:
2078     break;
2079   case NeonTypeFlags::Float16:
2080     return Context.HalfTy;
2081   case NeonTypeFlags::Float32:
2082     return Context.FloatTy;
2083   case NeonTypeFlags::Float64:
2084     return Context.DoubleTy;
2085   case NeonTypeFlags::BFloat16:
2086     return Context.BFloat16Ty;
2087   }
2088   llvm_unreachable("Invalid NeonTypeFlag!");
2089 }
2090 
2091 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2092   // Range check SVE intrinsics that take immediate values.
2093   SmallVector<std::tuple<int,int,int>, 3> ImmChecks;
2094 
2095   switch (BuiltinID) {
2096   default:
2097     return false;
2098 #define GET_SVE_IMMEDIATE_CHECK
2099 #include "clang/Basic/arm_sve_sema_rangechecks.inc"
2100 #undef GET_SVE_IMMEDIATE_CHECK
2101   }
2102 
2103   // Perform all the immediate checks for this builtin call.
2104   bool HasError = false;
2105   for (auto &I : ImmChecks) {
2106     int ArgNum, CheckTy, ElementSizeInBits;
2107     std::tie(ArgNum, CheckTy, ElementSizeInBits) = I;
2108 
2109     typedef bool(*OptionSetCheckFnTy)(int64_t Value);
2110 
2111     // Function that checks whether the operand (ArgNum) is an immediate
2112     // that is one of the predefined values.
2113     auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm,
2114                                    int ErrDiag) -> bool {
2115       // We can't check the value of a dependent argument.
2116       Expr *Arg = TheCall->getArg(ArgNum);
2117       if (Arg->isTypeDependent() || Arg->isValueDependent())
2118         return false;
2119 
2120       // Check constant-ness first.
2121       llvm::APSInt Imm;
2122       if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm))
2123         return true;
2124 
2125       if (!CheckImm(Imm.getSExtValue()))
2126         return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange();
2127       return false;
2128     };
2129 
2130     switch ((SVETypeFlags::ImmCheckType)CheckTy) {
2131     case SVETypeFlags::ImmCheck0_31:
2132       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31))
2133         HasError = true;
2134       break;
2135     case SVETypeFlags::ImmCheck0_13:
2136       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13))
2137         HasError = true;
2138       break;
2139     case SVETypeFlags::ImmCheck1_16:
2140       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16))
2141         HasError = true;
2142       break;
2143     case SVETypeFlags::ImmCheck0_7:
2144       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7))
2145         HasError = true;
2146       break;
2147     case SVETypeFlags::ImmCheckExtract:
2148       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2149                                       (2048 / ElementSizeInBits) - 1))
2150         HasError = true;
2151       break;
2152     case SVETypeFlags::ImmCheckShiftRight:
2153       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits))
2154         HasError = true;
2155       break;
2156     case SVETypeFlags::ImmCheckShiftRightNarrow:
2157       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1,
2158                                       ElementSizeInBits / 2))
2159         HasError = true;
2160       break;
2161     case SVETypeFlags::ImmCheckShiftLeft:
2162       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2163                                       ElementSizeInBits - 1))
2164         HasError = true;
2165       break;
2166     case SVETypeFlags::ImmCheckLaneIndex:
2167       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2168                                       (128 / (1 * ElementSizeInBits)) - 1))
2169         HasError = true;
2170       break;
2171     case SVETypeFlags::ImmCheckLaneIndexCompRotate:
2172       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2173                                       (128 / (2 * ElementSizeInBits)) - 1))
2174         HasError = true;
2175       break;
2176     case SVETypeFlags::ImmCheckLaneIndexDot:
2177       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2178                                       (128 / (4 * ElementSizeInBits)) - 1))
2179         HasError = true;
2180       break;
2181     case SVETypeFlags::ImmCheckComplexRot90_270:
2182       if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; },
2183                               diag::err_rotation_argument_to_cadd))
2184         HasError = true;
2185       break;
2186     case SVETypeFlags::ImmCheckComplexRotAll90:
2187       if (CheckImmediateInSet(
2188               [](int64_t V) {
2189                 return V == 0 || V == 90 || V == 180 || V == 270;
2190               },
2191               diag::err_rotation_argument_to_cmla))
2192         HasError = true;
2193       break;
2194     case SVETypeFlags::ImmCheck0_1:
2195       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1))
2196         HasError = true;
2197       break;
2198     case SVETypeFlags::ImmCheck0_2:
2199       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2))
2200         HasError = true;
2201       break;
2202     case SVETypeFlags::ImmCheck0_3:
2203       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3))
2204         HasError = true;
2205       break;
2206     }
2207   }
2208 
2209   return HasError;
2210 }
2211 
2212 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI,
2213                                         unsigned BuiltinID, CallExpr *TheCall) {
2214   llvm::APSInt Result;
2215   uint64_t mask = 0;
2216   unsigned TV = 0;
2217   int PtrArgNum = -1;
2218   bool HasConstPtr = false;
2219   switch (BuiltinID) {
2220 #define GET_NEON_OVERLOAD_CHECK
2221 #include "clang/Basic/arm_neon.inc"
2222 #include "clang/Basic/arm_fp16.inc"
2223 #undef GET_NEON_OVERLOAD_CHECK
2224   }
2225 
2226   // For NEON intrinsics which are overloaded on vector element type, validate
2227   // the immediate which specifies which variant to emit.
2228   unsigned ImmArg = TheCall->getNumArgs()-1;
2229   if (mask) {
2230     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
2231       return true;
2232 
2233     TV = Result.getLimitedValue(64);
2234     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
2235       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
2236              << TheCall->getArg(ImmArg)->getSourceRange();
2237   }
2238 
2239   if (PtrArgNum >= 0) {
2240     // Check that pointer arguments have the specified type.
2241     Expr *Arg = TheCall->getArg(PtrArgNum);
2242     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
2243       Arg = ICE->getSubExpr();
2244     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
2245     QualType RHSTy = RHS.get()->getType();
2246 
2247     llvm::Triple::ArchType Arch = TI.getTriple().getArch();
2248     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
2249                           Arch == llvm::Triple::aarch64_32 ||
2250                           Arch == llvm::Triple::aarch64_be;
2251     bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong;
2252     QualType EltTy =
2253         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
2254     if (HasConstPtr)
2255       EltTy = EltTy.withConst();
2256     QualType LHSTy = Context.getPointerType(EltTy);
2257     AssignConvertType ConvTy;
2258     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
2259     if (RHS.isInvalid())
2260       return true;
2261     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
2262                                  RHS.get(), AA_Assigning))
2263       return true;
2264   }
2265 
2266   // For NEON intrinsics which take an immediate value as part of the
2267   // instruction, range check them here.
2268   unsigned i = 0, l = 0, u = 0;
2269   switch (BuiltinID) {
2270   default:
2271     return false;
2272   #define GET_NEON_IMMEDIATE_CHECK
2273   #include "clang/Basic/arm_neon.inc"
2274   #include "clang/Basic/arm_fp16.inc"
2275   #undef GET_NEON_IMMEDIATE_CHECK
2276   }
2277 
2278   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2279 }
2280 
2281 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2282   switch (BuiltinID) {
2283   default:
2284     return false;
2285   #include "clang/Basic/arm_mve_builtin_sema.inc"
2286   }
2287 }
2288 
2289 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2290                                        CallExpr *TheCall) {
2291   bool Err = false;
2292   switch (BuiltinID) {
2293   default:
2294     return false;
2295 #include "clang/Basic/arm_cde_builtin_sema.inc"
2296   }
2297 
2298   if (Err)
2299     return true;
2300 
2301   return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true);
2302 }
2303 
2304 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI,
2305                                         const Expr *CoprocArg, bool WantCDE) {
2306   if (isConstantEvaluated())
2307     return false;
2308 
2309   // We can't check the value of a dependent argument.
2310   if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent())
2311     return false;
2312 
2313   llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context);
2314   int64_t CoprocNo = CoprocNoAP.getExtValue();
2315   assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative");
2316 
2317   uint32_t CDECoprocMask = TI.getARMCDECoprocMask();
2318   bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo));
2319 
2320   if (IsCDECoproc != WantCDE)
2321     return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc)
2322            << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange();
2323 
2324   return false;
2325 }
2326 
2327 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
2328                                         unsigned MaxWidth) {
2329   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
2330           BuiltinID == ARM::BI__builtin_arm_ldaex ||
2331           BuiltinID == ARM::BI__builtin_arm_strex ||
2332           BuiltinID == ARM::BI__builtin_arm_stlex ||
2333           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2334           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2335           BuiltinID == AArch64::BI__builtin_arm_strex ||
2336           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
2337          "unexpected ARM builtin");
2338   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
2339                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
2340                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2341                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
2342 
2343   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2344 
2345   // Ensure that we have the proper number of arguments.
2346   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
2347     return true;
2348 
2349   // Inspect the pointer argument of the atomic builtin.  This should always be
2350   // a pointer type, whose element is an integral scalar or pointer type.
2351   // Because it is a pointer type, we don't have to worry about any implicit
2352   // casts here.
2353   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
2354   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
2355   if (PointerArgRes.isInvalid())
2356     return true;
2357   PointerArg = PointerArgRes.get();
2358 
2359   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2360   if (!pointerType) {
2361     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
2362         << PointerArg->getType() << PointerArg->getSourceRange();
2363     return true;
2364   }
2365 
2366   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
2367   // task is to insert the appropriate casts into the AST. First work out just
2368   // what the appropriate type is.
2369   QualType ValType = pointerType->getPointeeType();
2370   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
2371   if (IsLdrex)
2372     AddrType.addConst();
2373 
2374   // Issue a warning if the cast is dodgy.
2375   CastKind CastNeeded = CK_NoOp;
2376   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
2377     CastNeeded = CK_BitCast;
2378     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
2379         << PointerArg->getType() << Context.getPointerType(AddrType)
2380         << AA_Passing << PointerArg->getSourceRange();
2381   }
2382 
2383   // Finally, do the cast and replace the argument with the corrected version.
2384   AddrType = Context.getPointerType(AddrType);
2385   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
2386   if (PointerArgRes.isInvalid())
2387     return true;
2388   PointerArg = PointerArgRes.get();
2389 
2390   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
2391 
2392   // In general, we allow ints, floats and pointers to be loaded and stored.
2393   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2394       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
2395     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
2396         << PointerArg->getType() << PointerArg->getSourceRange();
2397     return true;
2398   }
2399 
2400   // But ARM doesn't have instructions to deal with 128-bit versions.
2401   if (Context.getTypeSize(ValType) > MaxWidth) {
2402     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
2403     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
2404         << PointerArg->getType() << PointerArg->getSourceRange();
2405     return true;
2406   }
2407 
2408   switch (ValType.getObjCLifetime()) {
2409   case Qualifiers::OCL_None:
2410   case Qualifiers::OCL_ExplicitNone:
2411     // okay
2412     break;
2413 
2414   case Qualifiers::OCL_Weak:
2415   case Qualifiers::OCL_Strong:
2416   case Qualifiers::OCL_Autoreleasing:
2417     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
2418         << ValType << PointerArg->getSourceRange();
2419     return true;
2420   }
2421 
2422   if (IsLdrex) {
2423     TheCall->setType(ValType);
2424     return false;
2425   }
2426 
2427   // Initialize the argument to be stored.
2428   ExprResult ValArg = TheCall->getArg(0);
2429   InitializedEntity Entity = InitializedEntity::InitializeParameter(
2430       Context, ValType, /*consume*/ false);
2431   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2432   if (ValArg.isInvalid())
2433     return true;
2434   TheCall->setArg(0, ValArg.get());
2435 
2436   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
2437   // but the custom checker bypasses all default analysis.
2438   TheCall->setType(Context.IntTy);
2439   return false;
2440 }
2441 
2442 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2443                                        CallExpr *TheCall) {
2444   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
2445       BuiltinID == ARM::BI__builtin_arm_ldaex ||
2446       BuiltinID == ARM::BI__builtin_arm_strex ||
2447       BuiltinID == ARM::BI__builtin_arm_stlex) {
2448     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
2449   }
2450 
2451   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
2452     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2453       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
2454   }
2455 
2456   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2457       BuiltinID == ARM::BI__builtin_arm_wsr64)
2458     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
2459 
2460   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
2461       BuiltinID == ARM::BI__builtin_arm_rsrp ||
2462       BuiltinID == ARM::BI__builtin_arm_wsr ||
2463       BuiltinID == ARM::BI__builtin_arm_wsrp)
2464     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2465 
2466   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2467     return true;
2468   if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
2469     return true;
2470   if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall))
2471     return true;
2472 
2473   // For intrinsics which take an immediate value as part of the instruction,
2474   // range check them here.
2475   // FIXME: VFP Intrinsics should error if VFP not present.
2476   switch (BuiltinID) {
2477   default: return false;
2478   case ARM::BI__builtin_arm_ssat:
2479     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
2480   case ARM::BI__builtin_arm_usat:
2481     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
2482   case ARM::BI__builtin_arm_ssat16:
2483     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
2484   case ARM::BI__builtin_arm_usat16:
2485     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2486   case ARM::BI__builtin_arm_vcvtr_f:
2487   case ARM::BI__builtin_arm_vcvtr_d:
2488     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
2489   case ARM::BI__builtin_arm_dmb:
2490   case ARM::BI__builtin_arm_dsb:
2491   case ARM::BI__builtin_arm_isb:
2492   case ARM::BI__builtin_arm_dbg:
2493     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
2494   case ARM::BI__builtin_arm_cdp:
2495   case ARM::BI__builtin_arm_cdp2:
2496   case ARM::BI__builtin_arm_mcr:
2497   case ARM::BI__builtin_arm_mcr2:
2498   case ARM::BI__builtin_arm_mrc:
2499   case ARM::BI__builtin_arm_mrc2:
2500   case ARM::BI__builtin_arm_mcrr:
2501   case ARM::BI__builtin_arm_mcrr2:
2502   case ARM::BI__builtin_arm_mrrc:
2503   case ARM::BI__builtin_arm_mrrc2:
2504   case ARM::BI__builtin_arm_ldc:
2505   case ARM::BI__builtin_arm_ldcl:
2506   case ARM::BI__builtin_arm_ldc2:
2507   case ARM::BI__builtin_arm_ldc2l:
2508   case ARM::BI__builtin_arm_stc:
2509   case ARM::BI__builtin_arm_stcl:
2510   case ARM::BI__builtin_arm_stc2:
2511   case ARM::BI__builtin_arm_stc2l:
2512     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) ||
2513            CheckARMCoprocessorImmediate(TI, TheCall->getArg(0),
2514                                         /*WantCDE*/ false);
2515   }
2516 }
2517 
2518 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI,
2519                                            unsigned BuiltinID,
2520                                            CallExpr *TheCall) {
2521   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2522       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2523       BuiltinID == AArch64::BI__builtin_arm_strex ||
2524       BuiltinID == AArch64::BI__builtin_arm_stlex) {
2525     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
2526   }
2527 
2528   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
2529     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2530       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
2531       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
2532       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
2533   }
2534 
2535   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2536       BuiltinID == AArch64::BI__builtin_arm_wsr64)
2537     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2538 
2539   // Memory Tagging Extensions (MTE) Intrinsics
2540   if (BuiltinID == AArch64::BI__builtin_arm_irg ||
2541       BuiltinID == AArch64::BI__builtin_arm_addg ||
2542       BuiltinID == AArch64::BI__builtin_arm_gmi ||
2543       BuiltinID == AArch64::BI__builtin_arm_ldg ||
2544       BuiltinID == AArch64::BI__builtin_arm_stg ||
2545       BuiltinID == AArch64::BI__builtin_arm_subp) {
2546     return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
2547   }
2548 
2549   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
2550       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2551       BuiltinID == AArch64::BI__builtin_arm_wsr ||
2552       BuiltinID == AArch64::BI__builtin_arm_wsrp)
2553     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2554 
2555   // Only check the valid encoding range. Any constant in this range would be
2556   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
2557   // an exception for incorrect registers. This matches MSVC behavior.
2558   if (BuiltinID == AArch64::BI_ReadStatusReg ||
2559       BuiltinID == AArch64::BI_WriteStatusReg)
2560     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
2561 
2562   if (BuiltinID == AArch64::BI__getReg)
2563     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
2564 
2565   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2566     return true;
2567 
2568   if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall))
2569     return true;
2570 
2571   // For intrinsics which take an immediate value as part of the instruction,
2572   // range check them here.
2573   unsigned i = 0, l = 0, u = 0;
2574   switch (BuiltinID) {
2575   default: return false;
2576   case AArch64::BI__builtin_arm_dmb:
2577   case AArch64::BI__builtin_arm_dsb:
2578   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
2579   case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
2580   }
2581 
2582   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2583 }
2584 
2585 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) {
2586   if (Arg->getType()->getAsPlaceholderType())
2587     return false;
2588 
2589   // The first argument needs to be a record field access.
2590   // If it is an array element access, we delay decision
2591   // to BPF backend to check whether the access is a
2592   // field access or not.
2593   return (Arg->IgnoreParens()->getObjectKind() == OK_BitField ||
2594           dyn_cast<MemberExpr>(Arg->IgnoreParens()) ||
2595           dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens()));
2596 }
2597 
2598 static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S,
2599                             QualType VectorTy, QualType EltTy) {
2600   QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType();
2601   if (!Context.hasSameType(VectorEltTy, EltTy)) {
2602     S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types)
2603         << Call->getSourceRange() << VectorEltTy << EltTy;
2604     return false;
2605   }
2606   return true;
2607 }
2608 
2609 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) {
2610   QualType ArgType = Arg->getType();
2611   if (ArgType->getAsPlaceholderType())
2612     return false;
2613 
2614   // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type
2615   // format:
2616   //   1. __builtin_preserve_type_info(*(<type> *)0, flag);
2617   //   2. <type> var;
2618   //      __builtin_preserve_type_info(var, flag);
2619   if (!dyn_cast<DeclRefExpr>(Arg->IgnoreParens()) &&
2620       !dyn_cast<UnaryOperator>(Arg->IgnoreParens()))
2621     return false;
2622 
2623   // Typedef type.
2624   if (ArgType->getAs<TypedefType>())
2625     return true;
2626 
2627   // Record type or Enum type.
2628   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2629   if (const auto *RT = Ty->getAs<RecordType>()) {
2630     if (!RT->getDecl()->getDeclName().isEmpty())
2631       return true;
2632   } else if (const auto *ET = Ty->getAs<EnumType>()) {
2633     if (!ET->getDecl()->getDeclName().isEmpty())
2634       return true;
2635   }
2636 
2637   return false;
2638 }
2639 
2640 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) {
2641   QualType ArgType = Arg->getType();
2642   if (ArgType->getAsPlaceholderType())
2643     return false;
2644 
2645   // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type
2646   // format:
2647   //   __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>,
2648   //                                 flag);
2649   const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens());
2650   if (!UO)
2651     return false;
2652 
2653   const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr());
2654   if (!CE)
2655     return false;
2656   if (CE->getCastKind() != CK_IntegralToPointer &&
2657       CE->getCastKind() != CK_NullToPointer)
2658     return false;
2659 
2660   // The integer must be from an EnumConstantDecl.
2661   const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr());
2662   if (!DR)
2663     return false;
2664 
2665   const EnumConstantDecl *Enumerator =
2666       dyn_cast<EnumConstantDecl>(DR->getDecl());
2667   if (!Enumerator)
2668     return false;
2669 
2670   // The type must be EnumType.
2671   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2672   const auto *ET = Ty->getAs<EnumType>();
2673   if (!ET)
2674     return false;
2675 
2676   // The enum value must be supported.
2677   for (auto *EDI : ET->getDecl()->enumerators()) {
2678     if (EDI == Enumerator)
2679       return true;
2680   }
2681 
2682   return false;
2683 }
2684 
2685 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
2686                                        CallExpr *TheCall) {
2687   assert((BuiltinID == BPF::BI__builtin_preserve_field_info ||
2688           BuiltinID == BPF::BI__builtin_btf_type_id ||
2689           BuiltinID == BPF::BI__builtin_preserve_type_info ||
2690           BuiltinID == BPF::BI__builtin_preserve_enum_value) &&
2691          "unexpected BPF builtin");
2692 
2693   if (checkArgCount(*this, TheCall, 2))
2694     return true;
2695 
2696   // The second argument needs to be a constant int
2697   Expr *Arg = TheCall->getArg(1);
2698   Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context);
2699   diag::kind kind;
2700   if (!Value) {
2701     if (BuiltinID == BPF::BI__builtin_preserve_field_info)
2702       kind = diag::err_preserve_field_info_not_const;
2703     else if (BuiltinID == BPF::BI__builtin_btf_type_id)
2704       kind = diag::err_btf_type_id_not_const;
2705     else if (BuiltinID == BPF::BI__builtin_preserve_type_info)
2706       kind = diag::err_preserve_type_info_not_const;
2707     else
2708       kind = diag::err_preserve_enum_value_not_const;
2709     Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange();
2710     return true;
2711   }
2712 
2713   // The first argument
2714   Arg = TheCall->getArg(0);
2715   bool InvalidArg = false;
2716   bool ReturnUnsignedInt = true;
2717   if (BuiltinID == BPF::BI__builtin_preserve_field_info) {
2718     if (!isValidBPFPreserveFieldInfoArg(Arg)) {
2719       InvalidArg = true;
2720       kind = diag::err_preserve_field_info_not_field;
2721     }
2722   } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) {
2723     if (!isValidBPFPreserveTypeInfoArg(Arg)) {
2724       InvalidArg = true;
2725       kind = diag::err_preserve_type_info_invalid;
2726     }
2727   } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) {
2728     if (!isValidBPFPreserveEnumValueArg(Arg)) {
2729       InvalidArg = true;
2730       kind = diag::err_preserve_enum_value_invalid;
2731     }
2732     ReturnUnsignedInt = false;
2733   } else if (BuiltinID == BPF::BI__builtin_btf_type_id) {
2734     ReturnUnsignedInt = false;
2735   }
2736 
2737   if (InvalidArg) {
2738     Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange();
2739     return true;
2740   }
2741 
2742   if (ReturnUnsignedInt)
2743     TheCall->setType(Context.UnsignedIntTy);
2744   else
2745     TheCall->setType(Context.UnsignedLongTy);
2746   return false;
2747 }
2748 
2749 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2750   struct ArgInfo {
2751     uint8_t OpNum;
2752     bool IsSigned;
2753     uint8_t BitWidth;
2754     uint8_t Align;
2755   };
2756   struct BuiltinInfo {
2757     unsigned BuiltinID;
2758     ArgInfo Infos[2];
2759   };
2760 
2761   static BuiltinInfo Infos[] = {
2762     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
2763     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
2764     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
2765     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  1 }} },
2766     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
2767     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
2768     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
2769     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
2770     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
2771     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
2772     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
2773 
2774     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
2775     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
2776     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
2777     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
2778     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
2779     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
2780     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
2781     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
2782     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
2783     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
2784     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
2785 
2786     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
2787     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
2788     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
2789     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
2790     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
2791     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
2792     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
2793     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
2794     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
2795     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
2796     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
2797     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
2798     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
2799     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
2800     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
2801     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
2802     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
2803     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
2804     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
2805     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
2806     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
2807     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
2808     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
2809     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
2810     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
2811     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
2812     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
2813     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
2814     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
2815     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
2816     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
2817     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
2818     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
2819     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
2820     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
2821     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
2822     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
2823     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
2824     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
2825     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
2826     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
2827     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
2828     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
2829     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
2830     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
2831     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
2832     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
2833     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
2834     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
2835     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
2836     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
2837     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
2838                                                       {{ 1, false, 6,  0 }} },
2839     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
2840     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
2841     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
2842     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
2843     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
2844     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
2845     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
2846                                                       {{ 1, false, 5,  0 }} },
2847     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
2848     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
2849     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
2850     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
2851     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
2852     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
2853                                                        { 2, false, 5,  0 }} },
2854     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
2855                                                        { 2, false, 6,  0 }} },
2856     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
2857                                                        { 3, false, 5,  0 }} },
2858     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
2859                                                        { 3, false, 6,  0 }} },
2860     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
2861     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
2862     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
2863     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
2864     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
2865     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
2866     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
2867     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
2868     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
2869     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
2870     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
2871     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
2872     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
2873     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
2874     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
2875     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
2876                                                       {{ 2, false, 4,  0 },
2877                                                        { 3, false, 5,  0 }} },
2878     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
2879                                                       {{ 2, false, 4,  0 },
2880                                                        { 3, false, 5,  0 }} },
2881     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
2882                                                       {{ 2, false, 4,  0 },
2883                                                        { 3, false, 5,  0 }} },
2884     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
2885                                                       {{ 2, false, 4,  0 },
2886                                                        { 3, false, 5,  0 }} },
2887     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
2888     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
2889     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
2890     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
2891     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
2892     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
2893     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
2894     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
2895     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
2896     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
2897     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
2898                                                        { 2, false, 5,  0 }} },
2899     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
2900                                                        { 2, false, 6,  0 }} },
2901     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
2902     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
2903     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
2904     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
2905     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
2906     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
2907     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
2908     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
2909     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
2910                                                       {{ 1, false, 4,  0 }} },
2911     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
2912     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
2913                                                       {{ 1, false, 4,  0 }} },
2914     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
2915     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
2916     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
2917     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
2918     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
2919     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
2920     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
2921     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
2922     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
2923     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
2924     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
2925     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
2926     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
2927     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
2928     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
2929     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
2930     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
2931     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
2932     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
2933     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
2934                                                       {{ 3, false, 1,  0 }} },
2935     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
2936     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
2937     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
2938     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
2939                                                       {{ 3, false, 1,  0 }} },
2940     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
2941     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
2942     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
2943     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
2944                                                       {{ 3, false, 1,  0 }} },
2945   };
2946 
2947   // Use a dynamically initialized static to sort the table exactly once on
2948   // first run.
2949   static const bool SortOnce =
2950       (llvm::sort(Infos,
2951                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
2952                    return LHS.BuiltinID < RHS.BuiltinID;
2953                  }),
2954        true);
2955   (void)SortOnce;
2956 
2957   const BuiltinInfo *F = llvm::partition_point(
2958       Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
2959   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
2960     return false;
2961 
2962   bool Error = false;
2963 
2964   for (const ArgInfo &A : F->Infos) {
2965     // Ignore empty ArgInfo elements.
2966     if (A.BitWidth == 0)
2967       continue;
2968 
2969     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
2970     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
2971     if (!A.Align) {
2972       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
2973     } else {
2974       unsigned M = 1 << A.Align;
2975       Min *= M;
2976       Max *= M;
2977       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
2978                SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
2979     }
2980   }
2981   return Error;
2982 }
2983 
2984 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
2985                                            CallExpr *TheCall) {
2986   return CheckHexagonBuiltinArgument(BuiltinID, TheCall);
2987 }
2988 
2989 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI,
2990                                         unsigned BuiltinID, CallExpr *TheCall) {
2991   return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) ||
2992          CheckMipsBuiltinArgument(BuiltinID, TheCall);
2993 }
2994 
2995 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
2996                                CallExpr *TheCall) {
2997 
2998   if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
2999       BuiltinID <= Mips::BI__builtin_mips_lwx) {
3000     if (!TI.hasFeature("dsp"))
3001       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
3002   }
3003 
3004   if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
3005       BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
3006     if (!TI.hasFeature("dspr2"))
3007       return Diag(TheCall->getBeginLoc(),
3008                   diag::err_mips_builtin_requires_dspr2);
3009   }
3010 
3011   if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
3012       BuiltinID <= Mips::BI__builtin_msa_xori_b) {
3013     if (!TI.hasFeature("msa"))
3014       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
3015   }
3016 
3017   return false;
3018 }
3019 
3020 // CheckMipsBuiltinArgument - Checks the constant value passed to the
3021 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
3022 // ordering for DSP is unspecified. MSA is ordered by the data format used
3023 // by the underlying instruction i.e., df/m, df/n and then by size.
3024 //
3025 // FIXME: The size tests here should instead be tablegen'd along with the
3026 //        definitions from include/clang/Basic/BuiltinsMips.def.
3027 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
3028 //        be too.
3029 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
3030   unsigned i = 0, l = 0, u = 0, m = 0;
3031   switch (BuiltinID) {
3032   default: return false;
3033   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
3034   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
3035   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
3036   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
3037   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
3038   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
3039   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
3040   // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
3041   // df/m field.
3042   // These intrinsics take an unsigned 3 bit immediate.
3043   case Mips::BI__builtin_msa_bclri_b:
3044   case Mips::BI__builtin_msa_bnegi_b:
3045   case Mips::BI__builtin_msa_bseti_b:
3046   case Mips::BI__builtin_msa_sat_s_b:
3047   case Mips::BI__builtin_msa_sat_u_b:
3048   case Mips::BI__builtin_msa_slli_b:
3049   case Mips::BI__builtin_msa_srai_b:
3050   case Mips::BI__builtin_msa_srari_b:
3051   case Mips::BI__builtin_msa_srli_b:
3052   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
3053   case Mips::BI__builtin_msa_binsli_b:
3054   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
3055   // These intrinsics take an unsigned 4 bit immediate.
3056   case Mips::BI__builtin_msa_bclri_h:
3057   case Mips::BI__builtin_msa_bnegi_h:
3058   case Mips::BI__builtin_msa_bseti_h:
3059   case Mips::BI__builtin_msa_sat_s_h:
3060   case Mips::BI__builtin_msa_sat_u_h:
3061   case Mips::BI__builtin_msa_slli_h:
3062   case Mips::BI__builtin_msa_srai_h:
3063   case Mips::BI__builtin_msa_srari_h:
3064   case Mips::BI__builtin_msa_srli_h:
3065   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
3066   case Mips::BI__builtin_msa_binsli_h:
3067   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
3068   // These intrinsics take an unsigned 5 bit immediate.
3069   // The first block of intrinsics actually have an unsigned 5 bit field,
3070   // not a df/n field.
3071   case Mips::BI__builtin_msa_cfcmsa:
3072   case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
3073   case Mips::BI__builtin_msa_clei_u_b:
3074   case Mips::BI__builtin_msa_clei_u_h:
3075   case Mips::BI__builtin_msa_clei_u_w:
3076   case Mips::BI__builtin_msa_clei_u_d:
3077   case Mips::BI__builtin_msa_clti_u_b:
3078   case Mips::BI__builtin_msa_clti_u_h:
3079   case Mips::BI__builtin_msa_clti_u_w:
3080   case Mips::BI__builtin_msa_clti_u_d:
3081   case Mips::BI__builtin_msa_maxi_u_b:
3082   case Mips::BI__builtin_msa_maxi_u_h:
3083   case Mips::BI__builtin_msa_maxi_u_w:
3084   case Mips::BI__builtin_msa_maxi_u_d:
3085   case Mips::BI__builtin_msa_mini_u_b:
3086   case Mips::BI__builtin_msa_mini_u_h:
3087   case Mips::BI__builtin_msa_mini_u_w:
3088   case Mips::BI__builtin_msa_mini_u_d:
3089   case Mips::BI__builtin_msa_addvi_b:
3090   case Mips::BI__builtin_msa_addvi_h:
3091   case Mips::BI__builtin_msa_addvi_w:
3092   case Mips::BI__builtin_msa_addvi_d:
3093   case Mips::BI__builtin_msa_bclri_w:
3094   case Mips::BI__builtin_msa_bnegi_w:
3095   case Mips::BI__builtin_msa_bseti_w:
3096   case Mips::BI__builtin_msa_sat_s_w:
3097   case Mips::BI__builtin_msa_sat_u_w:
3098   case Mips::BI__builtin_msa_slli_w:
3099   case Mips::BI__builtin_msa_srai_w:
3100   case Mips::BI__builtin_msa_srari_w:
3101   case Mips::BI__builtin_msa_srli_w:
3102   case Mips::BI__builtin_msa_srlri_w:
3103   case Mips::BI__builtin_msa_subvi_b:
3104   case Mips::BI__builtin_msa_subvi_h:
3105   case Mips::BI__builtin_msa_subvi_w:
3106   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
3107   case Mips::BI__builtin_msa_binsli_w:
3108   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
3109   // These intrinsics take an unsigned 6 bit immediate.
3110   case Mips::BI__builtin_msa_bclri_d:
3111   case Mips::BI__builtin_msa_bnegi_d:
3112   case Mips::BI__builtin_msa_bseti_d:
3113   case Mips::BI__builtin_msa_sat_s_d:
3114   case Mips::BI__builtin_msa_sat_u_d:
3115   case Mips::BI__builtin_msa_slli_d:
3116   case Mips::BI__builtin_msa_srai_d:
3117   case Mips::BI__builtin_msa_srari_d:
3118   case Mips::BI__builtin_msa_srli_d:
3119   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
3120   case Mips::BI__builtin_msa_binsli_d:
3121   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
3122   // These intrinsics take a signed 5 bit immediate.
3123   case Mips::BI__builtin_msa_ceqi_b:
3124   case Mips::BI__builtin_msa_ceqi_h:
3125   case Mips::BI__builtin_msa_ceqi_w:
3126   case Mips::BI__builtin_msa_ceqi_d:
3127   case Mips::BI__builtin_msa_clti_s_b:
3128   case Mips::BI__builtin_msa_clti_s_h:
3129   case Mips::BI__builtin_msa_clti_s_w:
3130   case Mips::BI__builtin_msa_clti_s_d:
3131   case Mips::BI__builtin_msa_clei_s_b:
3132   case Mips::BI__builtin_msa_clei_s_h:
3133   case Mips::BI__builtin_msa_clei_s_w:
3134   case Mips::BI__builtin_msa_clei_s_d:
3135   case Mips::BI__builtin_msa_maxi_s_b:
3136   case Mips::BI__builtin_msa_maxi_s_h:
3137   case Mips::BI__builtin_msa_maxi_s_w:
3138   case Mips::BI__builtin_msa_maxi_s_d:
3139   case Mips::BI__builtin_msa_mini_s_b:
3140   case Mips::BI__builtin_msa_mini_s_h:
3141   case Mips::BI__builtin_msa_mini_s_w:
3142   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
3143   // These intrinsics take an unsigned 8 bit immediate.
3144   case Mips::BI__builtin_msa_andi_b:
3145   case Mips::BI__builtin_msa_nori_b:
3146   case Mips::BI__builtin_msa_ori_b:
3147   case Mips::BI__builtin_msa_shf_b:
3148   case Mips::BI__builtin_msa_shf_h:
3149   case Mips::BI__builtin_msa_shf_w:
3150   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
3151   case Mips::BI__builtin_msa_bseli_b:
3152   case Mips::BI__builtin_msa_bmnzi_b:
3153   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
3154   // df/n format
3155   // These intrinsics take an unsigned 4 bit immediate.
3156   case Mips::BI__builtin_msa_copy_s_b:
3157   case Mips::BI__builtin_msa_copy_u_b:
3158   case Mips::BI__builtin_msa_insve_b:
3159   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
3160   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
3161   // These intrinsics take an unsigned 3 bit immediate.
3162   case Mips::BI__builtin_msa_copy_s_h:
3163   case Mips::BI__builtin_msa_copy_u_h:
3164   case Mips::BI__builtin_msa_insve_h:
3165   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
3166   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3167   // These intrinsics take an unsigned 2 bit immediate.
3168   case Mips::BI__builtin_msa_copy_s_w:
3169   case Mips::BI__builtin_msa_copy_u_w:
3170   case Mips::BI__builtin_msa_insve_w:
3171   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
3172   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3173   // These intrinsics take an unsigned 1 bit immediate.
3174   case Mips::BI__builtin_msa_copy_s_d:
3175   case Mips::BI__builtin_msa_copy_u_d:
3176   case Mips::BI__builtin_msa_insve_d:
3177   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
3178   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3179   // Memory offsets and immediate loads.
3180   // These intrinsics take a signed 10 bit immediate.
3181   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
3182   case Mips::BI__builtin_msa_ldi_h:
3183   case Mips::BI__builtin_msa_ldi_w:
3184   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
3185   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3186   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3187   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3188   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3189   case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break;
3190   case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break;
3191   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3192   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3193   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3194   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
3195   case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break;
3196   case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break;
3197   }
3198 
3199   if (!m)
3200     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3201 
3202   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3203          SemaBuiltinConstantArgMultiple(TheCall, i, m);
3204 }
3205 
3206 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str,
3207 /// advancing the pointer over the consumed characters. The decoded type is
3208 /// returned. If the decoded type represents a constant integer with a
3209 /// constraint on its value then Mask is set to that value. The type descriptors
3210 /// used in Str are specific to PPC MMA builtins and are documented in the file
3211 /// defining the PPC builtins.
3212 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str,
3213                                         unsigned &Mask) {
3214   bool RequireICE = false;
3215   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3216   switch (*Str++) {
3217   case 'V':
3218     return Context.getVectorType(Context.UnsignedCharTy, 16,
3219                                  VectorType::VectorKind::AltiVecVector);
3220   case 'i': {
3221     char *End;
3222     unsigned size = strtoul(Str, &End, 10);
3223     assert(End != Str && "Missing constant parameter constraint");
3224     Str = End;
3225     Mask = size;
3226     return Context.IntTy;
3227   }
3228   case 'W': {
3229     char *End;
3230     unsigned size = strtoul(Str, &End, 10);
3231     assert(End != Str && "Missing PowerPC MMA type size");
3232     Str = End;
3233     QualType Type;
3234     switch (size) {
3235   #define PPC_VECTOR_TYPE(typeName, Id, size) \
3236     case size: Type = Context.Id##Ty; break;
3237   #include "clang/Basic/PPCTypes.def"
3238     default: llvm_unreachable("Invalid PowerPC MMA vector type");
3239     }
3240     bool CheckVectorArgs = false;
3241     while (!CheckVectorArgs) {
3242       switch (*Str++) {
3243       case '*':
3244         Type = Context.getPointerType(Type);
3245         break;
3246       case 'C':
3247         Type = Type.withConst();
3248         break;
3249       default:
3250         CheckVectorArgs = true;
3251         --Str;
3252         break;
3253       }
3254     }
3255     return Type;
3256   }
3257   default:
3258     return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true);
3259   }
3260 }
3261 
3262 static bool isPPC_64Builtin(unsigned BuiltinID) {
3263   // These builtins only work on PPC 64bit targets.
3264   switch (BuiltinID) {
3265   case PPC::BI__builtin_divde:
3266   case PPC::BI__builtin_divdeu:
3267   case PPC::BI__builtin_bpermd:
3268   case PPC::BI__builtin_ppc_ldarx:
3269   case PPC::BI__builtin_ppc_stdcx:
3270   case PPC::BI__builtin_ppc_tdw:
3271   case PPC::BI__builtin_ppc_trapd:
3272   case PPC::BI__builtin_ppc_cmpeqb:
3273   case PPC::BI__builtin_ppc_setb:
3274   case PPC::BI__builtin_ppc_mulhd:
3275   case PPC::BI__builtin_ppc_mulhdu:
3276   case PPC::BI__builtin_ppc_maddhd:
3277   case PPC::BI__builtin_ppc_maddhdu:
3278   case PPC::BI__builtin_ppc_maddld:
3279   case PPC::BI__builtin_ppc_load8r:
3280   case PPC::BI__builtin_ppc_store8r:
3281   case PPC::BI__builtin_ppc_insert_exp:
3282   case PPC::BI__builtin_ppc_extract_sig:
3283     return true;
3284   }
3285   return false;
3286 }
3287 
3288 static bool SemaFeatureCheck(Sema &S, CallExpr *TheCall,
3289                              StringRef FeatureToCheck, unsigned DiagID,
3290                              StringRef DiagArg = "") {
3291   if (S.Context.getTargetInfo().hasFeature(FeatureToCheck))
3292     return false;
3293 
3294   if (DiagArg.empty())
3295     S.Diag(TheCall->getBeginLoc(), DiagID) << TheCall->getSourceRange();
3296   else
3297     S.Diag(TheCall->getBeginLoc(), DiagID)
3298         << DiagArg << TheCall->getSourceRange();
3299 
3300   return true;
3301 }
3302 
3303 /// Returns true if the argument consists of one contiguous run of 1s with any
3304 /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB, so
3305 /// 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not,
3306 /// since all 1s are not contiguous.
3307 bool Sema::SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
3308   llvm::APSInt Result;
3309   // We can't check the value of a dependent argument.
3310   Expr *Arg = TheCall->getArg(ArgNum);
3311   if (Arg->isTypeDependent() || Arg->isValueDependent())
3312     return false;
3313 
3314   // Check constant-ness first.
3315   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3316     return true;
3317 
3318   // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
3319   if (Result.isShiftedMask() || (~Result).isShiftedMask())
3320     return false;
3321 
3322   return Diag(TheCall->getBeginLoc(),
3323               diag::err_argument_not_contiguous_bit_field)
3324          << ArgNum << Arg->getSourceRange();
3325 }
3326 
3327 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3328                                        CallExpr *TheCall) {
3329   unsigned i = 0, l = 0, u = 0;
3330   bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64;
3331   llvm::APSInt Result;
3332 
3333   if (isPPC_64Builtin(BuiltinID) && !IsTarget64Bit)
3334     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3335            << TheCall->getSourceRange();
3336 
3337   switch (BuiltinID) {
3338   default: return false;
3339   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3340   case PPC::BI__builtin_altivec_crypto_vshasigmad:
3341     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3342            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3343   case PPC::BI__builtin_altivec_dss:
3344     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
3345   case PPC::BI__builtin_tbegin:
3346   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
3347   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
3348   case PPC::BI__builtin_tabortwc:
3349   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
3350   case PPC::BI__builtin_tabortwci:
3351   case PPC::BI__builtin_tabortdci:
3352     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3353            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
3354   case PPC::BI__builtin_altivec_dst:
3355   case PPC::BI__builtin_altivec_dstt:
3356   case PPC::BI__builtin_altivec_dstst:
3357   case PPC::BI__builtin_altivec_dststt:
3358     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
3359   case PPC::BI__builtin_vsx_xxpermdi:
3360   case PPC::BI__builtin_vsx_xxsldwi:
3361     return SemaBuiltinVSX(TheCall);
3362   case PPC::BI__builtin_divwe:
3363   case PPC::BI__builtin_divweu:
3364   case PPC::BI__builtin_divde:
3365   case PPC::BI__builtin_divdeu:
3366     return SemaFeatureCheck(*this, TheCall, "extdiv",
3367                             diag::err_ppc_builtin_only_on_arch, "7");
3368   case PPC::BI__builtin_bpermd:
3369     return SemaFeatureCheck(*this, TheCall, "bpermd",
3370                             diag::err_ppc_builtin_only_on_arch, "7");
3371   case PPC::BI__builtin_unpack_vector_int128:
3372     return SemaFeatureCheck(*this, TheCall, "vsx",
3373                             diag::err_ppc_builtin_only_on_arch, "7") ||
3374            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3375   case PPC::BI__builtin_pack_vector_int128:
3376     return SemaFeatureCheck(*this, TheCall, "vsx",
3377                             diag::err_ppc_builtin_only_on_arch, "7");
3378   case PPC::BI__builtin_altivec_vgnb:
3379      return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7);
3380   case PPC::BI__builtin_altivec_vec_replace_elt:
3381   case PPC::BI__builtin_altivec_vec_replace_unaligned: {
3382     QualType VecTy = TheCall->getArg(0)->getType();
3383     QualType EltTy = TheCall->getArg(1)->getType();
3384     unsigned Width = Context.getIntWidth(EltTy);
3385     return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) ||
3386            !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy);
3387   }
3388   case PPC::BI__builtin_vsx_xxeval:
3389      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255);
3390   case PPC::BI__builtin_altivec_vsldbi:
3391      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3392   case PPC::BI__builtin_altivec_vsrdbi:
3393      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3394   case PPC::BI__builtin_vsx_xxpermx:
3395      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7);
3396   case PPC::BI__builtin_ppc_tw:
3397   case PPC::BI__builtin_ppc_tdw:
3398     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
3399   case PPC::BI__builtin_ppc_cmpeqb:
3400   case PPC::BI__builtin_ppc_setb:
3401   case PPC::BI__builtin_ppc_maddhd:
3402   case PPC::BI__builtin_ppc_maddhdu:
3403   case PPC::BI__builtin_ppc_maddld:
3404     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3405                             diag::err_ppc_builtin_only_on_arch, "9");
3406   case PPC::BI__builtin_ppc_cmprb:
3407     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3408                             diag::err_ppc_builtin_only_on_arch, "9") ||
3409            SemaBuiltinConstantArgRange(TheCall, 0, 0, 1);
3410   // For __rlwnm, __rlwimi and __rldimi, the last parameter mask must
3411   // be a constant that represents a contiguous bit field.
3412   case PPC::BI__builtin_ppc_rlwnm:
3413     return SemaBuiltinConstantArg(TheCall, 1, Result) ||
3414            SemaValueIsRunOfOnes(TheCall, 2);
3415   case PPC::BI__builtin_ppc_rlwimi:
3416   case PPC::BI__builtin_ppc_rldimi:
3417     return SemaBuiltinConstantArg(TheCall, 2, Result) ||
3418            SemaValueIsRunOfOnes(TheCall, 3);
3419   case PPC::BI__builtin_ppc_extract_exp:
3420   case PPC::BI__builtin_ppc_extract_sig:
3421   case PPC::BI__builtin_ppc_insert_exp:
3422     return SemaFeatureCheck(*this, TheCall, "power9-vector",
3423                             diag::err_ppc_builtin_only_on_arch, "9");
3424   case PPC::BI__builtin_ppc_mtfsb0:
3425   case PPC::BI__builtin_ppc_mtfsb1:
3426     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
3427   case PPC::BI__builtin_ppc_mtfsf:
3428     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 255);
3429   case PPC::BI__builtin_ppc_mtfsfi:
3430     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) ||
3431            SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
3432   case PPC::BI__builtin_ppc_alignx:
3433     return SemaBuiltinConstantArgPower2(TheCall, 0);
3434   case PPC::BI__builtin_ppc_rdlam:
3435     return SemaValueIsRunOfOnes(TheCall, 2);
3436   case PPC::BI__builtin_ppc_icbt:
3437   case PPC::BI__builtin_ppc_sthcx:
3438   case PPC::BI__builtin_ppc_stbcx:
3439   case PPC::BI__builtin_ppc_lharx:
3440   case PPC::BI__builtin_ppc_lbarx:
3441     return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions",
3442                             diag::err_ppc_builtin_only_on_arch, "8");
3443 #define CUSTOM_BUILTIN(Name, Intr, Types, Acc) \
3444   case PPC::BI__builtin_##Name: \
3445     return SemaBuiltinPPCMMACall(TheCall, Types);
3446 #include "clang/Basic/BuiltinsPPC.def"
3447   }
3448   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3449 }
3450 
3451 // Check if the given type is a non-pointer PPC MMA type. This function is used
3452 // in Sema to prevent invalid uses of restricted PPC MMA types.
3453 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) {
3454   if (Type->isPointerType() || Type->isArrayType())
3455     return false;
3456 
3457   QualType CoreType = Type.getCanonicalType().getUnqualifiedType();
3458 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty
3459   if (false
3460 #include "clang/Basic/PPCTypes.def"
3461      ) {
3462     Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type);
3463     return true;
3464   }
3465   return false;
3466 }
3467 
3468 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID,
3469                                           CallExpr *TheCall) {
3470   // position of memory order and scope arguments in the builtin
3471   unsigned OrderIndex, ScopeIndex;
3472   switch (BuiltinID) {
3473   case AMDGPU::BI__builtin_amdgcn_atomic_inc32:
3474   case AMDGPU::BI__builtin_amdgcn_atomic_inc64:
3475   case AMDGPU::BI__builtin_amdgcn_atomic_dec32:
3476   case AMDGPU::BI__builtin_amdgcn_atomic_dec64:
3477     OrderIndex = 2;
3478     ScopeIndex = 3;
3479     break;
3480   case AMDGPU::BI__builtin_amdgcn_fence:
3481     OrderIndex = 0;
3482     ScopeIndex = 1;
3483     break;
3484   default:
3485     return false;
3486   }
3487 
3488   ExprResult Arg = TheCall->getArg(OrderIndex);
3489   auto ArgExpr = Arg.get();
3490   Expr::EvalResult ArgResult;
3491 
3492   if (!ArgExpr->EvaluateAsInt(ArgResult, Context))
3493     return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int)
3494            << ArgExpr->getType();
3495   auto Ord = ArgResult.Val.getInt().getZExtValue();
3496 
3497   // Check valididty of memory ordering as per C11 / C++11's memody model.
3498   // Only fence needs check. Atomic dec/inc allow all memory orders.
3499   if (!llvm::isValidAtomicOrderingCABI(Ord))
3500     return Diag(ArgExpr->getBeginLoc(),
3501                 diag::warn_atomic_op_has_invalid_memory_order)
3502            << ArgExpr->getSourceRange();
3503   switch (static_cast<llvm::AtomicOrderingCABI>(Ord)) {
3504   case llvm::AtomicOrderingCABI::relaxed:
3505   case llvm::AtomicOrderingCABI::consume:
3506     if (BuiltinID == AMDGPU::BI__builtin_amdgcn_fence)
3507       return Diag(ArgExpr->getBeginLoc(),
3508                   diag::warn_atomic_op_has_invalid_memory_order)
3509              << ArgExpr->getSourceRange();
3510     break;
3511   case llvm::AtomicOrderingCABI::acquire:
3512   case llvm::AtomicOrderingCABI::release:
3513   case llvm::AtomicOrderingCABI::acq_rel:
3514   case llvm::AtomicOrderingCABI::seq_cst:
3515     break;
3516   }
3517 
3518   Arg = TheCall->getArg(ScopeIndex);
3519   ArgExpr = Arg.get();
3520   Expr::EvalResult ArgResult1;
3521   // Check that sync scope is a constant literal
3522   if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context))
3523     return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal)
3524            << ArgExpr->getType();
3525 
3526   return false;
3527 }
3528 
3529 bool Sema::CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum) {
3530   llvm::APSInt Result;
3531 
3532   // We can't check the value of a dependent argument.
3533   Expr *Arg = TheCall->getArg(ArgNum);
3534   if (Arg->isTypeDependent() || Arg->isValueDependent())
3535     return false;
3536 
3537   // Check constant-ness first.
3538   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3539     return true;
3540 
3541   int64_t Val = Result.getSExtValue();
3542   if ((Val >= 0 && Val <= 3) || (Val >= 5 && Val <= 7))
3543     return false;
3544 
3545   return Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_invalid_lmul)
3546          << Arg->getSourceRange();
3547 }
3548 
3549 bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI,
3550                                          unsigned BuiltinID,
3551                                          CallExpr *TheCall) {
3552   // CodeGenFunction can also detect this, but this gives a better error
3553   // message.
3554   bool FeatureMissing = false;
3555   SmallVector<StringRef> ReqFeatures;
3556   StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID);
3557   Features.split(ReqFeatures, ',');
3558 
3559   // Check if each required feature is included
3560   for (StringRef F : ReqFeatures) {
3561     if (TI.hasFeature(F))
3562       continue;
3563 
3564     // If the feature is 64bit, alter the string so it will print better in
3565     // the diagnostic.
3566     if (F == "64bit")
3567       F = "RV64";
3568 
3569     // Convert features like "zbr" and "experimental-zbr" to "Zbr".
3570     F.consume_front("experimental-");
3571     std::string FeatureStr = F.str();
3572     FeatureStr[0] = std::toupper(FeatureStr[0]);
3573 
3574     // Error message
3575     FeatureMissing = true;
3576     Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_requires_extension)
3577         << TheCall->getSourceRange() << StringRef(FeatureStr);
3578   }
3579 
3580   if (FeatureMissing)
3581     return true;
3582 
3583   switch (BuiltinID) {
3584   case RISCV::BI__builtin_rvv_vsetvli:
3585     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3) ||
3586            CheckRISCVLMUL(TheCall, 2);
3587   case RISCV::BI__builtin_rvv_vsetvlimax:
3588     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3) ||
3589            CheckRISCVLMUL(TheCall, 1);
3590   case RISCV::BI__builtin_rvv_vget_v_i8m2_i8m1:
3591   case RISCV::BI__builtin_rvv_vget_v_i16m2_i16m1:
3592   case RISCV::BI__builtin_rvv_vget_v_i32m2_i32m1:
3593   case RISCV::BI__builtin_rvv_vget_v_i64m2_i64m1:
3594   case RISCV::BI__builtin_rvv_vget_v_f32m2_f32m1:
3595   case RISCV::BI__builtin_rvv_vget_v_f64m2_f64m1:
3596   case RISCV::BI__builtin_rvv_vget_v_u8m2_u8m1:
3597   case RISCV::BI__builtin_rvv_vget_v_u16m2_u16m1:
3598   case RISCV::BI__builtin_rvv_vget_v_u32m2_u32m1:
3599   case RISCV::BI__builtin_rvv_vget_v_u64m2_u64m1:
3600   case RISCV::BI__builtin_rvv_vget_v_i8m4_i8m2:
3601   case RISCV::BI__builtin_rvv_vget_v_i16m4_i16m2:
3602   case RISCV::BI__builtin_rvv_vget_v_i32m4_i32m2:
3603   case RISCV::BI__builtin_rvv_vget_v_i64m4_i64m2:
3604   case RISCV::BI__builtin_rvv_vget_v_f32m4_f32m2:
3605   case RISCV::BI__builtin_rvv_vget_v_f64m4_f64m2:
3606   case RISCV::BI__builtin_rvv_vget_v_u8m4_u8m2:
3607   case RISCV::BI__builtin_rvv_vget_v_u16m4_u16m2:
3608   case RISCV::BI__builtin_rvv_vget_v_u32m4_u32m2:
3609   case RISCV::BI__builtin_rvv_vget_v_u64m4_u64m2:
3610   case RISCV::BI__builtin_rvv_vget_v_i8m8_i8m4:
3611   case RISCV::BI__builtin_rvv_vget_v_i16m8_i16m4:
3612   case RISCV::BI__builtin_rvv_vget_v_i32m8_i32m4:
3613   case RISCV::BI__builtin_rvv_vget_v_i64m8_i64m4:
3614   case RISCV::BI__builtin_rvv_vget_v_f32m8_f32m4:
3615   case RISCV::BI__builtin_rvv_vget_v_f64m8_f64m4:
3616   case RISCV::BI__builtin_rvv_vget_v_u8m8_u8m4:
3617   case RISCV::BI__builtin_rvv_vget_v_u16m8_u16m4:
3618   case RISCV::BI__builtin_rvv_vget_v_u32m8_u32m4:
3619   case RISCV::BI__builtin_rvv_vget_v_u64m8_u64m4:
3620     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3621   case RISCV::BI__builtin_rvv_vget_v_i8m4_i8m1:
3622   case RISCV::BI__builtin_rvv_vget_v_i16m4_i16m1:
3623   case RISCV::BI__builtin_rvv_vget_v_i32m4_i32m1:
3624   case RISCV::BI__builtin_rvv_vget_v_i64m4_i64m1:
3625   case RISCV::BI__builtin_rvv_vget_v_f32m4_f32m1:
3626   case RISCV::BI__builtin_rvv_vget_v_f64m4_f64m1:
3627   case RISCV::BI__builtin_rvv_vget_v_u8m4_u8m1:
3628   case RISCV::BI__builtin_rvv_vget_v_u16m4_u16m1:
3629   case RISCV::BI__builtin_rvv_vget_v_u32m4_u32m1:
3630   case RISCV::BI__builtin_rvv_vget_v_u64m4_u64m1:
3631   case RISCV::BI__builtin_rvv_vget_v_i8m8_i8m2:
3632   case RISCV::BI__builtin_rvv_vget_v_i16m8_i16m2:
3633   case RISCV::BI__builtin_rvv_vget_v_i32m8_i32m2:
3634   case RISCV::BI__builtin_rvv_vget_v_i64m8_i64m2:
3635   case RISCV::BI__builtin_rvv_vget_v_f32m8_f32m2:
3636   case RISCV::BI__builtin_rvv_vget_v_f64m8_f64m2:
3637   case RISCV::BI__builtin_rvv_vget_v_u8m8_u8m2:
3638   case RISCV::BI__builtin_rvv_vget_v_u16m8_u16m2:
3639   case RISCV::BI__builtin_rvv_vget_v_u32m8_u32m2:
3640   case RISCV::BI__builtin_rvv_vget_v_u64m8_u64m2:
3641     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
3642   case RISCV::BI__builtin_rvv_vget_v_i8m8_i8m1:
3643   case RISCV::BI__builtin_rvv_vget_v_i16m8_i16m1:
3644   case RISCV::BI__builtin_rvv_vget_v_i32m8_i32m1:
3645   case RISCV::BI__builtin_rvv_vget_v_i64m8_i64m1:
3646   case RISCV::BI__builtin_rvv_vget_v_f32m8_f32m1:
3647   case RISCV::BI__builtin_rvv_vget_v_f64m8_f64m1:
3648   case RISCV::BI__builtin_rvv_vget_v_u8m8_u8m1:
3649   case RISCV::BI__builtin_rvv_vget_v_u16m8_u16m1:
3650   case RISCV::BI__builtin_rvv_vget_v_u32m8_u32m1:
3651   case RISCV::BI__builtin_rvv_vget_v_u64m8_u64m1:
3652     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 7);
3653   case RISCV::BI__builtin_rvv_vset_v_i8m1_i8m2:
3654   case RISCV::BI__builtin_rvv_vset_v_i16m1_i16m2:
3655   case RISCV::BI__builtin_rvv_vset_v_i32m1_i32m2:
3656   case RISCV::BI__builtin_rvv_vset_v_i64m1_i64m2:
3657   case RISCV::BI__builtin_rvv_vset_v_f32m1_f32m2:
3658   case RISCV::BI__builtin_rvv_vset_v_f64m1_f64m2:
3659   case RISCV::BI__builtin_rvv_vset_v_u8m1_u8m2:
3660   case RISCV::BI__builtin_rvv_vset_v_u16m1_u16m2:
3661   case RISCV::BI__builtin_rvv_vset_v_u32m1_u32m2:
3662   case RISCV::BI__builtin_rvv_vset_v_u64m1_u64m2:
3663   case RISCV::BI__builtin_rvv_vset_v_i8m2_i8m4:
3664   case RISCV::BI__builtin_rvv_vset_v_i16m2_i16m4:
3665   case RISCV::BI__builtin_rvv_vset_v_i32m2_i32m4:
3666   case RISCV::BI__builtin_rvv_vset_v_i64m2_i64m4:
3667   case RISCV::BI__builtin_rvv_vset_v_f32m2_f32m4:
3668   case RISCV::BI__builtin_rvv_vset_v_f64m2_f64m4:
3669   case RISCV::BI__builtin_rvv_vset_v_u8m2_u8m4:
3670   case RISCV::BI__builtin_rvv_vset_v_u16m2_u16m4:
3671   case RISCV::BI__builtin_rvv_vset_v_u32m2_u32m4:
3672   case RISCV::BI__builtin_rvv_vset_v_u64m2_u64m4:
3673   case RISCV::BI__builtin_rvv_vset_v_i8m4_i8m8:
3674   case RISCV::BI__builtin_rvv_vset_v_i16m4_i16m8:
3675   case RISCV::BI__builtin_rvv_vset_v_i32m4_i32m8:
3676   case RISCV::BI__builtin_rvv_vset_v_i64m4_i64m8:
3677   case RISCV::BI__builtin_rvv_vset_v_f32m4_f32m8:
3678   case RISCV::BI__builtin_rvv_vset_v_f64m4_f64m8:
3679   case RISCV::BI__builtin_rvv_vset_v_u8m4_u8m8:
3680   case RISCV::BI__builtin_rvv_vset_v_u16m4_u16m8:
3681   case RISCV::BI__builtin_rvv_vset_v_u32m4_u32m8:
3682   case RISCV::BI__builtin_rvv_vset_v_u64m4_u64m8:
3683     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3684   case RISCV::BI__builtin_rvv_vset_v_i8m1_i8m4:
3685   case RISCV::BI__builtin_rvv_vset_v_i16m1_i16m4:
3686   case RISCV::BI__builtin_rvv_vset_v_i32m1_i32m4:
3687   case RISCV::BI__builtin_rvv_vset_v_i64m1_i64m4:
3688   case RISCV::BI__builtin_rvv_vset_v_f32m1_f32m4:
3689   case RISCV::BI__builtin_rvv_vset_v_f64m1_f64m4:
3690   case RISCV::BI__builtin_rvv_vset_v_u8m1_u8m4:
3691   case RISCV::BI__builtin_rvv_vset_v_u16m1_u16m4:
3692   case RISCV::BI__builtin_rvv_vset_v_u32m1_u32m4:
3693   case RISCV::BI__builtin_rvv_vset_v_u64m1_u64m4:
3694   case RISCV::BI__builtin_rvv_vset_v_i8m2_i8m8:
3695   case RISCV::BI__builtin_rvv_vset_v_i16m2_i16m8:
3696   case RISCV::BI__builtin_rvv_vset_v_i32m2_i32m8:
3697   case RISCV::BI__builtin_rvv_vset_v_i64m2_i64m8:
3698   case RISCV::BI__builtin_rvv_vset_v_f32m2_f32m8:
3699   case RISCV::BI__builtin_rvv_vset_v_f64m2_f64m8:
3700   case RISCV::BI__builtin_rvv_vset_v_u8m2_u8m8:
3701   case RISCV::BI__builtin_rvv_vset_v_u16m2_u16m8:
3702   case RISCV::BI__builtin_rvv_vset_v_u32m2_u32m8:
3703   case RISCV::BI__builtin_rvv_vset_v_u64m2_u64m8:
3704     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
3705   case RISCV::BI__builtin_rvv_vset_v_i8m1_i8m8:
3706   case RISCV::BI__builtin_rvv_vset_v_i16m1_i16m8:
3707   case RISCV::BI__builtin_rvv_vset_v_i32m1_i32m8:
3708   case RISCV::BI__builtin_rvv_vset_v_i64m1_i64m8:
3709   case RISCV::BI__builtin_rvv_vset_v_f32m1_f32m8:
3710   case RISCV::BI__builtin_rvv_vset_v_f64m1_f64m8:
3711   case RISCV::BI__builtin_rvv_vset_v_u8m1_u8m8:
3712   case RISCV::BI__builtin_rvv_vset_v_u16m1_u16m8:
3713   case RISCV::BI__builtin_rvv_vset_v_u32m1_u32m8:
3714   case RISCV::BI__builtin_rvv_vset_v_u64m1_u64m8:
3715     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 7);
3716   }
3717 
3718   return false;
3719 }
3720 
3721 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3722                                            CallExpr *TheCall) {
3723   if (BuiltinID == SystemZ::BI__builtin_tabort) {
3724     Expr *Arg = TheCall->getArg(0);
3725     if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context))
3726       if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256)
3727         return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
3728                << Arg->getSourceRange();
3729   }
3730 
3731   // For intrinsics which take an immediate value as part of the instruction,
3732   // range check them here.
3733   unsigned i = 0, l = 0, u = 0;
3734   switch (BuiltinID) {
3735   default: return false;
3736   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3737   case SystemZ::BI__builtin_s390_verimb:
3738   case SystemZ::BI__builtin_s390_verimh:
3739   case SystemZ::BI__builtin_s390_verimf:
3740   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
3741   case SystemZ::BI__builtin_s390_vfaeb:
3742   case SystemZ::BI__builtin_s390_vfaeh:
3743   case SystemZ::BI__builtin_s390_vfaef:
3744   case SystemZ::BI__builtin_s390_vfaebs:
3745   case SystemZ::BI__builtin_s390_vfaehs:
3746   case SystemZ::BI__builtin_s390_vfaefs:
3747   case SystemZ::BI__builtin_s390_vfaezb:
3748   case SystemZ::BI__builtin_s390_vfaezh:
3749   case SystemZ::BI__builtin_s390_vfaezf:
3750   case SystemZ::BI__builtin_s390_vfaezbs:
3751   case SystemZ::BI__builtin_s390_vfaezhs:
3752   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
3753   case SystemZ::BI__builtin_s390_vfisb:
3754   case SystemZ::BI__builtin_s390_vfidb:
3755     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3756            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3757   case SystemZ::BI__builtin_s390_vftcisb:
3758   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3759   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3760   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3761   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3762   case SystemZ::BI__builtin_s390_vstrcb:
3763   case SystemZ::BI__builtin_s390_vstrch:
3764   case SystemZ::BI__builtin_s390_vstrcf:
3765   case SystemZ::BI__builtin_s390_vstrczb:
3766   case SystemZ::BI__builtin_s390_vstrczh:
3767   case SystemZ::BI__builtin_s390_vstrczf:
3768   case SystemZ::BI__builtin_s390_vstrcbs:
3769   case SystemZ::BI__builtin_s390_vstrchs:
3770   case SystemZ::BI__builtin_s390_vstrcfs:
3771   case SystemZ::BI__builtin_s390_vstrczbs:
3772   case SystemZ::BI__builtin_s390_vstrczhs:
3773   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
3774   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3775   case SystemZ::BI__builtin_s390_vfminsb:
3776   case SystemZ::BI__builtin_s390_vfmaxsb:
3777   case SystemZ::BI__builtin_s390_vfmindb:
3778   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
3779   case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
3780   case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
3781   }
3782   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3783 }
3784 
3785 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3786 /// This checks that the target supports __builtin_cpu_supports and
3787 /// that the string argument is constant and valid.
3788 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI,
3789                                    CallExpr *TheCall) {
3790   Expr *Arg = TheCall->getArg(0);
3791 
3792   // Check if the argument is a string literal.
3793   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3794     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3795            << Arg->getSourceRange();
3796 
3797   // Check the contents of the string.
3798   StringRef Feature =
3799       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3800   if (!TI.validateCpuSupports(Feature))
3801     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
3802            << Arg->getSourceRange();
3803   return false;
3804 }
3805 
3806 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3807 /// This checks that the target supports __builtin_cpu_is and
3808 /// that the string argument is constant and valid.
3809 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) {
3810   Expr *Arg = TheCall->getArg(0);
3811 
3812   // Check if the argument is a string literal.
3813   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3814     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3815            << Arg->getSourceRange();
3816 
3817   // Check the contents of the string.
3818   StringRef Feature =
3819       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3820   if (!TI.validateCpuIs(Feature))
3821     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
3822            << Arg->getSourceRange();
3823   return false;
3824 }
3825 
3826 // Check if the rounding mode is legal.
3827 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3828   // Indicates if this instruction has rounding control or just SAE.
3829   bool HasRC = false;
3830 
3831   unsigned ArgNum = 0;
3832   switch (BuiltinID) {
3833   default:
3834     return false;
3835   case X86::BI__builtin_ia32_vcvttsd2si32:
3836   case X86::BI__builtin_ia32_vcvttsd2si64:
3837   case X86::BI__builtin_ia32_vcvttsd2usi32:
3838   case X86::BI__builtin_ia32_vcvttsd2usi64:
3839   case X86::BI__builtin_ia32_vcvttss2si32:
3840   case X86::BI__builtin_ia32_vcvttss2si64:
3841   case X86::BI__builtin_ia32_vcvttss2usi32:
3842   case X86::BI__builtin_ia32_vcvttss2usi64:
3843     ArgNum = 1;
3844     break;
3845   case X86::BI__builtin_ia32_maxpd512:
3846   case X86::BI__builtin_ia32_maxps512:
3847   case X86::BI__builtin_ia32_minpd512:
3848   case X86::BI__builtin_ia32_minps512:
3849     ArgNum = 2;
3850     break;
3851   case X86::BI__builtin_ia32_cvtps2pd512_mask:
3852   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
3853   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
3854   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
3855   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
3856   case X86::BI__builtin_ia32_cvttps2dq512_mask:
3857   case X86::BI__builtin_ia32_cvttps2qq512_mask:
3858   case X86::BI__builtin_ia32_cvttps2udq512_mask:
3859   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
3860   case X86::BI__builtin_ia32_exp2pd_mask:
3861   case X86::BI__builtin_ia32_exp2ps_mask:
3862   case X86::BI__builtin_ia32_getexppd512_mask:
3863   case X86::BI__builtin_ia32_getexpps512_mask:
3864   case X86::BI__builtin_ia32_rcp28pd_mask:
3865   case X86::BI__builtin_ia32_rcp28ps_mask:
3866   case X86::BI__builtin_ia32_rsqrt28pd_mask:
3867   case X86::BI__builtin_ia32_rsqrt28ps_mask:
3868   case X86::BI__builtin_ia32_vcomisd:
3869   case X86::BI__builtin_ia32_vcomiss:
3870   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
3871     ArgNum = 3;
3872     break;
3873   case X86::BI__builtin_ia32_cmppd512_mask:
3874   case X86::BI__builtin_ia32_cmpps512_mask:
3875   case X86::BI__builtin_ia32_cmpsd_mask:
3876   case X86::BI__builtin_ia32_cmpss_mask:
3877   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
3878   case X86::BI__builtin_ia32_getexpsd128_round_mask:
3879   case X86::BI__builtin_ia32_getexpss128_round_mask:
3880   case X86::BI__builtin_ia32_getmantpd512_mask:
3881   case X86::BI__builtin_ia32_getmantps512_mask:
3882   case X86::BI__builtin_ia32_maxsd_round_mask:
3883   case X86::BI__builtin_ia32_maxss_round_mask:
3884   case X86::BI__builtin_ia32_minsd_round_mask:
3885   case X86::BI__builtin_ia32_minss_round_mask:
3886   case X86::BI__builtin_ia32_rcp28sd_round_mask:
3887   case X86::BI__builtin_ia32_rcp28ss_round_mask:
3888   case X86::BI__builtin_ia32_reducepd512_mask:
3889   case X86::BI__builtin_ia32_reduceps512_mask:
3890   case X86::BI__builtin_ia32_rndscalepd_mask:
3891   case X86::BI__builtin_ia32_rndscaleps_mask:
3892   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
3893   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
3894     ArgNum = 4;
3895     break;
3896   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3897   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3898   case X86::BI__builtin_ia32_fixupimmps512_mask:
3899   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3900   case X86::BI__builtin_ia32_fixupimmsd_mask:
3901   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3902   case X86::BI__builtin_ia32_fixupimmss_mask:
3903   case X86::BI__builtin_ia32_fixupimmss_maskz:
3904   case X86::BI__builtin_ia32_getmantsd_round_mask:
3905   case X86::BI__builtin_ia32_getmantss_round_mask:
3906   case X86::BI__builtin_ia32_rangepd512_mask:
3907   case X86::BI__builtin_ia32_rangeps512_mask:
3908   case X86::BI__builtin_ia32_rangesd128_round_mask:
3909   case X86::BI__builtin_ia32_rangess128_round_mask:
3910   case X86::BI__builtin_ia32_reducesd_mask:
3911   case X86::BI__builtin_ia32_reducess_mask:
3912   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3913   case X86::BI__builtin_ia32_rndscaless_round_mask:
3914     ArgNum = 5;
3915     break;
3916   case X86::BI__builtin_ia32_vcvtsd2si64:
3917   case X86::BI__builtin_ia32_vcvtsd2si32:
3918   case X86::BI__builtin_ia32_vcvtsd2usi32:
3919   case X86::BI__builtin_ia32_vcvtsd2usi64:
3920   case X86::BI__builtin_ia32_vcvtss2si32:
3921   case X86::BI__builtin_ia32_vcvtss2si64:
3922   case X86::BI__builtin_ia32_vcvtss2usi32:
3923   case X86::BI__builtin_ia32_vcvtss2usi64:
3924   case X86::BI__builtin_ia32_sqrtpd512:
3925   case X86::BI__builtin_ia32_sqrtps512:
3926     ArgNum = 1;
3927     HasRC = true;
3928     break;
3929   case X86::BI__builtin_ia32_addpd512:
3930   case X86::BI__builtin_ia32_addps512:
3931   case X86::BI__builtin_ia32_divpd512:
3932   case X86::BI__builtin_ia32_divps512:
3933   case X86::BI__builtin_ia32_mulpd512:
3934   case X86::BI__builtin_ia32_mulps512:
3935   case X86::BI__builtin_ia32_subpd512:
3936   case X86::BI__builtin_ia32_subps512:
3937   case X86::BI__builtin_ia32_cvtsi2sd64:
3938   case X86::BI__builtin_ia32_cvtsi2ss32:
3939   case X86::BI__builtin_ia32_cvtsi2ss64:
3940   case X86::BI__builtin_ia32_cvtusi2sd64:
3941   case X86::BI__builtin_ia32_cvtusi2ss32:
3942   case X86::BI__builtin_ia32_cvtusi2ss64:
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_cvtpd2ps512_mask:
3949   case X86::BI__builtin_ia32_cvtpd2dq512_mask:
3950   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
3951   case X86::BI__builtin_ia32_cvtpd2udq512_mask:
3952   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
3953   case X86::BI__builtin_ia32_cvtps2dq512_mask:
3954   case X86::BI__builtin_ia32_cvtps2qq512_mask:
3955   case X86::BI__builtin_ia32_cvtps2udq512_mask:
3956   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
3957   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
3958   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
3959   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
3960   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
3961     ArgNum = 3;
3962     HasRC = true;
3963     break;
3964   case X86::BI__builtin_ia32_addss_round_mask:
3965   case X86::BI__builtin_ia32_addsd_round_mask:
3966   case X86::BI__builtin_ia32_divss_round_mask:
3967   case X86::BI__builtin_ia32_divsd_round_mask:
3968   case X86::BI__builtin_ia32_mulss_round_mask:
3969   case X86::BI__builtin_ia32_mulsd_round_mask:
3970   case X86::BI__builtin_ia32_subss_round_mask:
3971   case X86::BI__builtin_ia32_subsd_round_mask:
3972   case X86::BI__builtin_ia32_scalefpd512_mask:
3973   case X86::BI__builtin_ia32_scalefps512_mask:
3974   case X86::BI__builtin_ia32_scalefsd_round_mask:
3975   case X86::BI__builtin_ia32_scalefss_round_mask:
3976   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
3977   case X86::BI__builtin_ia32_sqrtsd_round_mask:
3978   case X86::BI__builtin_ia32_sqrtss_round_mask:
3979   case X86::BI__builtin_ia32_vfmaddsd3_mask:
3980   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
3981   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
3982   case X86::BI__builtin_ia32_vfmaddss3_mask:
3983   case X86::BI__builtin_ia32_vfmaddss3_maskz:
3984   case X86::BI__builtin_ia32_vfmaddss3_mask3:
3985   case X86::BI__builtin_ia32_vfmaddpd512_mask:
3986   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
3987   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
3988   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
3989   case X86::BI__builtin_ia32_vfmaddps512_mask:
3990   case X86::BI__builtin_ia32_vfmaddps512_maskz:
3991   case X86::BI__builtin_ia32_vfmaddps512_mask3:
3992   case X86::BI__builtin_ia32_vfmsubps512_mask3:
3993   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
3994   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
3995   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
3996   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
3997   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
3998   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
3999   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
4000   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
4001     ArgNum = 4;
4002     HasRC = true;
4003     break;
4004   }
4005 
4006   llvm::APSInt Result;
4007 
4008   // We can't check the value of a dependent argument.
4009   Expr *Arg = TheCall->getArg(ArgNum);
4010   if (Arg->isTypeDependent() || Arg->isValueDependent())
4011     return false;
4012 
4013   // Check constant-ness first.
4014   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4015     return true;
4016 
4017   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
4018   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
4019   // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
4020   // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
4021   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
4022       Result == 8/*ROUND_NO_EXC*/ ||
4023       (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
4024       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
4025     return false;
4026 
4027   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
4028          << Arg->getSourceRange();
4029 }
4030 
4031 // Check if the gather/scatter scale is legal.
4032 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
4033                                              CallExpr *TheCall) {
4034   unsigned ArgNum = 0;
4035   switch (BuiltinID) {
4036   default:
4037     return false;
4038   case X86::BI__builtin_ia32_gatherpfdpd:
4039   case X86::BI__builtin_ia32_gatherpfdps:
4040   case X86::BI__builtin_ia32_gatherpfqpd:
4041   case X86::BI__builtin_ia32_gatherpfqps:
4042   case X86::BI__builtin_ia32_scatterpfdpd:
4043   case X86::BI__builtin_ia32_scatterpfdps:
4044   case X86::BI__builtin_ia32_scatterpfqpd:
4045   case X86::BI__builtin_ia32_scatterpfqps:
4046     ArgNum = 3;
4047     break;
4048   case X86::BI__builtin_ia32_gatherd_pd:
4049   case X86::BI__builtin_ia32_gatherd_pd256:
4050   case X86::BI__builtin_ia32_gatherq_pd:
4051   case X86::BI__builtin_ia32_gatherq_pd256:
4052   case X86::BI__builtin_ia32_gatherd_ps:
4053   case X86::BI__builtin_ia32_gatherd_ps256:
4054   case X86::BI__builtin_ia32_gatherq_ps:
4055   case X86::BI__builtin_ia32_gatherq_ps256:
4056   case X86::BI__builtin_ia32_gatherd_q:
4057   case X86::BI__builtin_ia32_gatherd_q256:
4058   case X86::BI__builtin_ia32_gatherq_q:
4059   case X86::BI__builtin_ia32_gatherq_q256:
4060   case X86::BI__builtin_ia32_gatherd_d:
4061   case X86::BI__builtin_ia32_gatherd_d256:
4062   case X86::BI__builtin_ia32_gatherq_d:
4063   case X86::BI__builtin_ia32_gatherq_d256:
4064   case X86::BI__builtin_ia32_gather3div2df:
4065   case X86::BI__builtin_ia32_gather3div2di:
4066   case X86::BI__builtin_ia32_gather3div4df:
4067   case X86::BI__builtin_ia32_gather3div4di:
4068   case X86::BI__builtin_ia32_gather3div4sf:
4069   case X86::BI__builtin_ia32_gather3div4si:
4070   case X86::BI__builtin_ia32_gather3div8sf:
4071   case X86::BI__builtin_ia32_gather3div8si:
4072   case X86::BI__builtin_ia32_gather3siv2df:
4073   case X86::BI__builtin_ia32_gather3siv2di:
4074   case X86::BI__builtin_ia32_gather3siv4df:
4075   case X86::BI__builtin_ia32_gather3siv4di:
4076   case X86::BI__builtin_ia32_gather3siv4sf:
4077   case X86::BI__builtin_ia32_gather3siv4si:
4078   case X86::BI__builtin_ia32_gather3siv8sf:
4079   case X86::BI__builtin_ia32_gather3siv8si:
4080   case X86::BI__builtin_ia32_gathersiv8df:
4081   case X86::BI__builtin_ia32_gathersiv16sf:
4082   case X86::BI__builtin_ia32_gatherdiv8df:
4083   case X86::BI__builtin_ia32_gatherdiv16sf:
4084   case X86::BI__builtin_ia32_gathersiv8di:
4085   case X86::BI__builtin_ia32_gathersiv16si:
4086   case X86::BI__builtin_ia32_gatherdiv8di:
4087   case X86::BI__builtin_ia32_gatherdiv16si:
4088   case X86::BI__builtin_ia32_scatterdiv2df:
4089   case X86::BI__builtin_ia32_scatterdiv2di:
4090   case X86::BI__builtin_ia32_scatterdiv4df:
4091   case X86::BI__builtin_ia32_scatterdiv4di:
4092   case X86::BI__builtin_ia32_scatterdiv4sf:
4093   case X86::BI__builtin_ia32_scatterdiv4si:
4094   case X86::BI__builtin_ia32_scatterdiv8sf:
4095   case X86::BI__builtin_ia32_scatterdiv8si:
4096   case X86::BI__builtin_ia32_scattersiv2df:
4097   case X86::BI__builtin_ia32_scattersiv2di:
4098   case X86::BI__builtin_ia32_scattersiv4df:
4099   case X86::BI__builtin_ia32_scattersiv4di:
4100   case X86::BI__builtin_ia32_scattersiv4sf:
4101   case X86::BI__builtin_ia32_scattersiv4si:
4102   case X86::BI__builtin_ia32_scattersiv8sf:
4103   case X86::BI__builtin_ia32_scattersiv8si:
4104   case X86::BI__builtin_ia32_scattersiv8df:
4105   case X86::BI__builtin_ia32_scattersiv16sf:
4106   case X86::BI__builtin_ia32_scatterdiv8df:
4107   case X86::BI__builtin_ia32_scatterdiv16sf:
4108   case X86::BI__builtin_ia32_scattersiv8di:
4109   case X86::BI__builtin_ia32_scattersiv16si:
4110   case X86::BI__builtin_ia32_scatterdiv8di:
4111   case X86::BI__builtin_ia32_scatterdiv16si:
4112     ArgNum = 4;
4113     break;
4114   }
4115 
4116   llvm::APSInt Result;
4117 
4118   // We can't check the value of a dependent argument.
4119   Expr *Arg = TheCall->getArg(ArgNum);
4120   if (Arg->isTypeDependent() || Arg->isValueDependent())
4121     return false;
4122 
4123   // Check constant-ness first.
4124   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4125     return true;
4126 
4127   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
4128     return false;
4129 
4130   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
4131          << Arg->getSourceRange();
4132 }
4133 
4134 enum { TileRegLow = 0, TileRegHigh = 7 };
4135 
4136 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
4137                                              ArrayRef<int> ArgNums) {
4138   for (int ArgNum : ArgNums) {
4139     if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh))
4140       return true;
4141   }
4142   return false;
4143 }
4144 
4145 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall,
4146                                         ArrayRef<int> ArgNums) {
4147   // Because the max number of tile register is TileRegHigh + 1, so here we use
4148   // each bit to represent the usage of them in bitset.
4149   std::bitset<TileRegHigh + 1> ArgValues;
4150   for (int ArgNum : ArgNums) {
4151     Expr *Arg = TheCall->getArg(ArgNum);
4152     if (Arg->isTypeDependent() || Arg->isValueDependent())
4153       continue;
4154 
4155     llvm::APSInt Result;
4156     if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4157       return true;
4158     int ArgExtValue = Result.getExtValue();
4159     assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) &&
4160            "Incorrect tile register num.");
4161     if (ArgValues.test(ArgExtValue))
4162       return Diag(TheCall->getBeginLoc(),
4163                   diag::err_x86_builtin_tile_arg_duplicate)
4164              << TheCall->getArg(ArgNum)->getSourceRange();
4165     ArgValues.set(ArgExtValue);
4166   }
4167   return false;
4168 }
4169 
4170 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
4171                                                 ArrayRef<int> ArgNums) {
4172   return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) ||
4173          CheckX86BuiltinTileDuplicate(TheCall, ArgNums);
4174 }
4175 
4176 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) {
4177   switch (BuiltinID) {
4178   default:
4179     return false;
4180   case X86::BI__builtin_ia32_tileloadd64:
4181   case X86::BI__builtin_ia32_tileloaddt164:
4182   case X86::BI__builtin_ia32_tilestored64:
4183   case X86::BI__builtin_ia32_tilezero:
4184     return CheckX86BuiltinTileArgumentsRange(TheCall, 0);
4185   case X86::BI__builtin_ia32_tdpbssd:
4186   case X86::BI__builtin_ia32_tdpbsud:
4187   case X86::BI__builtin_ia32_tdpbusd:
4188   case X86::BI__builtin_ia32_tdpbuud:
4189   case X86::BI__builtin_ia32_tdpbf16ps:
4190     return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2});
4191   }
4192 }
4193 static bool isX86_32Builtin(unsigned BuiltinID) {
4194   // These builtins only work on x86-32 targets.
4195   switch (BuiltinID) {
4196   case X86::BI__builtin_ia32_readeflags_u32:
4197   case X86::BI__builtin_ia32_writeeflags_u32:
4198     return true;
4199   }
4200 
4201   return false;
4202 }
4203 
4204 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
4205                                        CallExpr *TheCall) {
4206   if (BuiltinID == X86::BI__builtin_cpu_supports)
4207     return SemaBuiltinCpuSupports(*this, TI, TheCall);
4208 
4209   if (BuiltinID == X86::BI__builtin_cpu_is)
4210     return SemaBuiltinCpuIs(*this, TI, TheCall);
4211 
4212   // Check for 32-bit only builtins on a 64-bit target.
4213   const llvm::Triple &TT = TI.getTriple();
4214   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
4215     return Diag(TheCall->getCallee()->getBeginLoc(),
4216                 diag::err_32_bit_builtin_64_bit_tgt);
4217 
4218   // If the intrinsic has rounding or SAE make sure its valid.
4219   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
4220     return true;
4221 
4222   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
4223   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
4224     return true;
4225 
4226   // If the intrinsic has a tile arguments, make sure they are valid.
4227   if (CheckX86BuiltinTileArguments(BuiltinID, TheCall))
4228     return true;
4229 
4230   // For intrinsics which take an immediate value as part of the instruction,
4231   // range check them here.
4232   int i = 0, l = 0, u = 0;
4233   switch (BuiltinID) {
4234   default:
4235     return false;
4236   case X86::BI__builtin_ia32_vec_ext_v2si:
4237   case X86::BI__builtin_ia32_vec_ext_v2di:
4238   case X86::BI__builtin_ia32_vextractf128_pd256:
4239   case X86::BI__builtin_ia32_vextractf128_ps256:
4240   case X86::BI__builtin_ia32_vextractf128_si256:
4241   case X86::BI__builtin_ia32_extract128i256:
4242   case X86::BI__builtin_ia32_extractf64x4_mask:
4243   case X86::BI__builtin_ia32_extracti64x4_mask:
4244   case X86::BI__builtin_ia32_extractf32x8_mask:
4245   case X86::BI__builtin_ia32_extracti32x8_mask:
4246   case X86::BI__builtin_ia32_extractf64x2_256_mask:
4247   case X86::BI__builtin_ia32_extracti64x2_256_mask:
4248   case X86::BI__builtin_ia32_extractf32x4_256_mask:
4249   case X86::BI__builtin_ia32_extracti32x4_256_mask:
4250     i = 1; l = 0; u = 1;
4251     break;
4252   case X86::BI__builtin_ia32_vec_set_v2di:
4253   case X86::BI__builtin_ia32_vinsertf128_pd256:
4254   case X86::BI__builtin_ia32_vinsertf128_ps256:
4255   case X86::BI__builtin_ia32_vinsertf128_si256:
4256   case X86::BI__builtin_ia32_insert128i256:
4257   case X86::BI__builtin_ia32_insertf32x8:
4258   case X86::BI__builtin_ia32_inserti32x8:
4259   case X86::BI__builtin_ia32_insertf64x4:
4260   case X86::BI__builtin_ia32_inserti64x4:
4261   case X86::BI__builtin_ia32_insertf64x2_256:
4262   case X86::BI__builtin_ia32_inserti64x2_256:
4263   case X86::BI__builtin_ia32_insertf32x4_256:
4264   case X86::BI__builtin_ia32_inserti32x4_256:
4265     i = 2; l = 0; u = 1;
4266     break;
4267   case X86::BI__builtin_ia32_vpermilpd:
4268   case X86::BI__builtin_ia32_vec_ext_v4hi:
4269   case X86::BI__builtin_ia32_vec_ext_v4si:
4270   case X86::BI__builtin_ia32_vec_ext_v4sf:
4271   case X86::BI__builtin_ia32_vec_ext_v4di:
4272   case X86::BI__builtin_ia32_extractf32x4_mask:
4273   case X86::BI__builtin_ia32_extracti32x4_mask:
4274   case X86::BI__builtin_ia32_extractf64x2_512_mask:
4275   case X86::BI__builtin_ia32_extracti64x2_512_mask:
4276     i = 1; l = 0; u = 3;
4277     break;
4278   case X86::BI_mm_prefetch:
4279   case X86::BI__builtin_ia32_vec_ext_v8hi:
4280   case X86::BI__builtin_ia32_vec_ext_v8si:
4281     i = 1; l = 0; u = 7;
4282     break;
4283   case X86::BI__builtin_ia32_sha1rnds4:
4284   case X86::BI__builtin_ia32_blendpd:
4285   case X86::BI__builtin_ia32_shufpd:
4286   case X86::BI__builtin_ia32_vec_set_v4hi:
4287   case X86::BI__builtin_ia32_vec_set_v4si:
4288   case X86::BI__builtin_ia32_vec_set_v4di:
4289   case X86::BI__builtin_ia32_shuf_f32x4_256:
4290   case X86::BI__builtin_ia32_shuf_f64x2_256:
4291   case X86::BI__builtin_ia32_shuf_i32x4_256:
4292   case X86::BI__builtin_ia32_shuf_i64x2_256:
4293   case X86::BI__builtin_ia32_insertf64x2_512:
4294   case X86::BI__builtin_ia32_inserti64x2_512:
4295   case X86::BI__builtin_ia32_insertf32x4:
4296   case X86::BI__builtin_ia32_inserti32x4:
4297     i = 2; l = 0; u = 3;
4298     break;
4299   case X86::BI__builtin_ia32_vpermil2pd:
4300   case X86::BI__builtin_ia32_vpermil2pd256:
4301   case X86::BI__builtin_ia32_vpermil2ps:
4302   case X86::BI__builtin_ia32_vpermil2ps256:
4303     i = 3; l = 0; u = 3;
4304     break;
4305   case X86::BI__builtin_ia32_cmpb128_mask:
4306   case X86::BI__builtin_ia32_cmpw128_mask:
4307   case X86::BI__builtin_ia32_cmpd128_mask:
4308   case X86::BI__builtin_ia32_cmpq128_mask:
4309   case X86::BI__builtin_ia32_cmpb256_mask:
4310   case X86::BI__builtin_ia32_cmpw256_mask:
4311   case X86::BI__builtin_ia32_cmpd256_mask:
4312   case X86::BI__builtin_ia32_cmpq256_mask:
4313   case X86::BI__builtin_ia32_cmpb512_mask:
4314   case X86::BI__builtin_ia32_cmpw512_mask:
4315   case X86::BI__builtin_ia32_cmpd512_mask:
4316   case X86::BI__builtin_ia32_cmpq512_mask:
4317   case X86::BI__builtin_ia32_ucmpb128_mask:
4318   case X86::BI__builtin_ia32_ucmpw128_mask:
4319   case X86::BI__builtin_ia32_ucmpd128_mask:
4320   case X86::BI__builtin_ia32_ucmpq128_mask:
4321   case X86::BI__builtin_ia32_ucmpb256_mask:
4322   case X86::BI__builtin_ia32_ucmpw256_mask:
4323   case X86::BI__builtin_ia32_ucmpd256_mask:
4324   case X86::BI__builtin_ia32_ucmpq256_mask:
4325   case X86::BI__builtin_ia32_ucmpb512_mask:
4326   case X86::BI__builtin_ia32_ucmpw512_mask:
4327   case X86::BI__builtin_ia32_ucmpd512_mask:
4328   case X86::BI__builtin_ia32_ucmpq512_mask:
4329   case X86::BI__builtin_ia32_vpcomub:
4330   case X86::BI__builtin_ia32_vpcomuw:
4331   case X86::BI__builtin_ia32_vpcomud:
4332   case X86::BI__builtin_ia32_vpcomuq:
4333   case X86::BI__builtin_ia32_vpcomb:
4334   case X86::BI__builtin_ia32_vpcomw:
4335   case X86::BI__builtin_ia32_vpcomd:
4336   case X86::BI__builtin_ia32_vpcomq:
4337   case X86::BI__builtin_ia32_vec_set_v8hi:
4338   case X86::BI__builtin_ia32_vec_set_v8si:
4339     i = 2; l = 0; u = 7;
4340     break;
4341   case X86::BI__builtin_ia32_vpermilpd256:
4342   case X86::BI__builtin_ia32_roundps:
4343   case X86::BI__builtin_ia32_roundpd:
4344   case X86::BI__builtin_ia32_roundps256:
4345   case X86::BI__builtin_ia32_roundpd256:
4346   case X86::BI__builtin_ia32_getmantpd128_mask:
4347   case X86::BI__builtin_ia32_getmantpd256_mask:
4348   case X86::BI__builtin_ia32_getmantps128_mask:
4349   case X86::BI__builtin_ia32_getmantps256_mask:
4350   case X86::BI__builtin_ia32_getmantpd512_mask:
4351   case X86::BI__builtin_ia32_getmantps512_mask:
4352   case X86::BI__builtin_ia32_vec_ext_v16qi:
4353   case X86::BI__builtin_ia32_vec_ext_v16hi:
4354     i = 1; l = 0; u = 15;
4355     break;
4356   case X86::BI__builtin_ia32_pblendd128:
4357   case X86::BI__builtin_ia32_blendps:
4358   case X86::BI__builtin_ia32_blendpd256:
4359   case X86::BI__builtin_ia32_shufpd256:
4360   case X86::BI__builtin_ia32_roundss:
4361   case X86::BI__builtin_ia32_roundsd:
4362   case X86::BI__builtin_ia32_rangepd128_mask:
4363   case X86::BI__builtin_ia32_rangepd256_mask:
4364   case X86::BI__builtin_ia32_rangepd512_mask:
4365   case X86::BI__builtin_ia32_rangeps128_mask:
4366   case X86::BI__builtin_ia32_rangeps256_mask:
4367   case X86::BI__builtin_ia32_rangeps512_mask:
4368   case X86::BI__builtin_ia32_getmantsd_round_mask:
4369   case X86::BI__builtin_ia32_getmantss_round_mask:
4370   case X86::BI__builtin_ia32_vec_set_v16qi:
4371   case X86::BI__builtin_ia32_vec_set_v16hi:
4372     i = 2; l = 0; u = 15;
4373     break;
4374   case X86::BI__builtin_ia32_vec_ext_v32qi:
4375     i = 1; l = 0; u = 31;
4376     break;
4377   case X86::BI__builtin_ia32_cmpps:
4378   case X86::BI__builtin_ia32_cmpss:
4379   case X86::BI__builtin_ia32_cmppd:
4380   case X86::BI__builtin_ia32_cmpsd:
4381   case X86::BI__builtin_ia32_cmpps256:
4382   case X86::BI__builtin_ia32_cmppd256:
4383   case X86::BI__builtin_ia32_cmpps128_mask:
4384   case X86::BI__builtin_ia32_cmppd128_mask:
4385   case X86::BI__builtin_ia32_cmpps256_mask:
4386   case X86::BI__builtin_ia32_cmppd256_mask:
4387   case X86::BI__builtin_ia32_cmpps512_mask:
4388   case X86::BI__builtin_ia32_cmppd512_mask:
4389   case X86::BI__builtin_ia32_cmpsd_mask:
4390   case X86::BI__builtin_ia32_cmpss_mask:
4391   case X86::BI__builtin_ia32_vec_set_v32qi:
4392     i = 2; l = 0; u = 31;
4393     break;
4394   case X86::BI__builtin_ia32_permdf256:
4395   case X86::BI__builtin_ia32_permdi256:
4396   case X86::BI__builtin_ia32_permdf512:
4397   case X86::BI__builtin_ia32_permdi512:
4398   case X86::BI__builtin_ia32_vpermilps:
4399   case X86::BI__builtin_ia32_vpermilps256:
4400   case X86::BI__builtin_ia32_vpermilpd512:
4401   case X86::BI__builtin_ia32_vpermilps512:
4402   case X86::BI__builtin_ia32_pshufd:
4403   case X86::BI__builtin_ia32_pshufd256:
4404   case X86::BI__builtin_ia32_pshufd512:
4405   case X86::BI__builtin_ia32_pshufhw:
4406   case X86::BI__builtin_ia32_pshufhw256:
4407   case X86::BI__builtin_ia32_pshufhw512:
4408   case X86::BI__builtin_ia32_pshuflw:
4409   case X86::BI__builtin_ia32_pshuflw256:
4410   case X86::BI__builtin_ia32_pshuflw512:
4411   case X86::BI__builtin_ia32_vcvtps2ph:
4412   case X86::BI__builtin_ia32_vcvtps2ph_mask:
4413   case X86::BI__builtin_ia32_vcvtps2ph256:
4414   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
4415   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
4416   case X86::BI__builtin_ia32_rndscaleps_128_mask:
4417   case X86::BI__builtin_ia32_rndscalepd_128_mask:
4418   case X86::BI__builtin_ia32_rndscaleps_256_mask:
4419   case X86::BI__builtin_ia32_rndscalepd_256_mask:
4420   case X86::BI__builtin_ia32_rndscaleps_mask:
4421   case X86::BI__builtin_ia32_rndscalepd_mask:
4422   case X86::BI__builtin_ia32_reducepd128_mask:
4423   case X86::BI__builtin_ia32_reducepd256_mask:
4424   case X86::BI__builtin_ia32_reducepd512_mask:
4425   case X86::BI__builtin_ia32_reduceps128_mask:
4426   case X86::BI__builtin_ia32_reduceps256_mask:
4427   case X86::BI__builtin_ia32_reduceps512_mask:
4428   case X86::BI__builtin_ia32_prold512:
4429   case X86::BI__builtin_ia32_prolq512:
4430   case X86::BI__builtin_ia32_prold128:
4431   case X86::BI__builtin_ia32_prold256:
4432   case X86::BI__builtin_ia32_prolq128:
4433   case X86::BI__builtin_ia32_prolq256:
4434   case X86::BI__builtin_ia32_prord512:
4435   case X86::BI__builtin_ia32_prorq512:
4436   case X86::BI__builtin_ia32_prord128:
4437   case X86::BI__builtin_ia32_prord256:
4438   case X86::BI__builtin_ia32_prorq128:
4439   case X86::BI__builtin_ia32_prorq256:
4440   case X86::BI__builtin_ia32_fpclasspd128_mask:
4441   case X86::BI__builtin_ia32_fpclasspd256_mask:
4442   case X86::BI__builtin_ia32_fpclassps128_mask:
4443   case X86::BI__builtin_ia32_fpclassps256_mask:
4444   case X86::BI__builtin_ia32_fpclassps512_mask:
4445   case X86::BI__builtin_ia32_fpclasspd512_mask:
4446   case X86::BI__builtin_ia32_fpclasssd_mask:
4447   case X86::BI__builtin_ia32_fpclassss_mask:
4448   case X86::BI__builtin_ia32_pslldqi128_byteshift:
4449   case X86::BI__builtin_ia32_pslldqi256_byteshift:
4450   case X86::BI__builtin_ia32_pslldqi512_byteshift:
4451   case X86::BI__builtin_ia32_psrldqi128_byteshift:
4452   case X86::BI__builtin_ia32_psrldqi256_byteshift:
4453   case X86::BI__builtin_ia32_psrldqi512_byteshift:
4454   case X86::BI__builtin_ia32_kshiftliqi:
4455   case X86::BI__builtin_ia32_kshiftlihi:
4456   case X86::BI__builtin_ia32_kshiftlisi:
4457   case X86::BI__builtin_ia32_kshiftlidi:
4458   case X86::BI__builtin_ia32_kshiftriqi:
4459   case X86::BI__builtin_ia32_kshiftrihi:
4460   case X86::BI__builtin_ia32_kshiftrisi:
4461   case X86::BI__builtin_ia32_kshiftridi:
4462     i = 1; l = 0; u = 255;
4463     break;
4464   case X86::BI__builtin_ia32_vperm2f128_pd256:
4465   case X86::BI__builtin_ia32_vperm2f128_ps256:
4466   case X86::BI__builtin_ia32_vperm2f128_si256:
4467   case X86::BI__builtin_ia32_permti256:
4468   case X86::BI__builtin_ia32_pblendw128:
4469   case X86::BI__builtin_ia32_pblendw256:
4470   case X86::BI__builtin_ia32_blendps256:
4471   case X86::BI__builtin_ia32_pblendd256:
4472   case X86::BI__builtin_ia32_palignr128:
4473   case X86::BI__builtin_ia32_palignr256:
4474   case X86::BI__builtin_ia32_palignr512:
4475   case X86::BI__builtin_ia32_alignq512:
4476   case X86::BI__builtin_ia32_alignd512:
4477   case X86::BI__builtin_ia32_alignd128:
4478   case X86::BI__builtin_ia32_alignd256:
4479   case X86::BI__builtin_ia32_alignq128:
4480   case X86::BI__builtin_ia32_alignq256:
4481   case X86::BI__builtin_ia32_vcomisd:
4482   case X86::BI__builtin_ia32_vcomiss:
4483   case X86::BI__builtin_ia32_shuf_f32x4:
4484   case X86::BI__builtin_ia32_shuf_f64x2:
4485   case X86::BI__builtin_ia32_shuf_i32x4:
4486   case X86::BI__builtin_ia32_shuf_i64x2:
4487   case X86::BI__builtin_ia32_shufpd512:
4488   case X86::BI__builtin_ia32_shufps:
4489   case X86::BI__builtin_ia32_shufps256:
4490   case X86::BI__builtin_ia32_shufps512:
4491   case X86::BI__builtin_ia32_dbpsadbw128:
4492   case X86::BI__builtin_ia32_dbpsadbw256:
4493   case X86::BI__builtin_ia32_dbpsadbw512:
4494   case X86::BI__builtin_ia32_vpshldd128:
4495   case X86::BI__builtin_ia32_vpshldd256:
4496   case X86::BI__builtin_ia32_vpshldd512:
4497   case X86::BI__builtin_ia32_vpshldq128:
4498   case X86::BI__builtin_ia32_vpshldq256:
4499   case X86::BI__builtin_ia32_vpshldq512:
4500   case X86::BI__builtin_ia32_vpshldw128:
4501   case X86::BI__builtin_ia32_vpshldw256:
4502   case X86::BI__builtin_ia32_vpshldw512:
4503   case X86::BI__builtin_ia32_vpshrdd128:
4504   case X86::BI__builtin_ia32_vpshrdd256:
4505   case X86::BI__builtin_ia32_vpshrdd512:
4506   case X86::BI__builtin_ia32_vpshrdq128:
4507   case X86::BI__builtin_ia32_vpshrdq256:
4508   case X86::BI__builtin_ia32_vpshrdq512:
4509   case X86::BI__builtin_ia32_vpshrdw128:
4510   case X86::BI__builtin_ia32_vpshrdw256:
4511   case X86::BI__builtin_ia32_vpshrdw512:
4512     i = 2; l = 0; u = 255;
4513     break;
4514   case X86::BI__builtin_ia32_fixupimmpd512_mask:
4515   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
4516   case X86::BI__builtin_ia32_fixupimmps512_mask:
4517   case X86::BI__builtin_ia32_fixupimmps512_maskz:
4518   case X86::BI__builtin_ia32_fixupimmsd_mask:
4519   case X86::BI__builtin_ia32_fixupimmsd_maskz:
4520   case X86::BI__builtin_ia32_fixupimmss_mask:
4521   case X86::BI__builtin_ia32_fixupimmss_maskz:
4522   case X86::BI__builtin_ia32_fixupimmpd128_mask:
4523   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
4524   case X86::BI__builtin_ia32_fixupimmpd256_mask:
4525   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
4526   case X86::BI__builtin_ia32_fixupimmps128_mask:
4527   case X86::BI__builtin_ia32_fixupimmps128_maskz:
4528   case X86::BI__builtin_ia32_fixupimmps256_mask:
4529   case X86::BI__builtin_ia32_fixupimmps256_maskz:
4530   case X86::BI__builtin_ia32_pternlogd512_mask:
4531   case X86::BI__builtin_ia32_pternlogd512_maskz:
4532   case X86::BI__builtin_ia32_pternlogq512_mask:
4533   case X86::BI__builtin_ia32_pternlogq512_maskz:
4534   case X86::BI__builtin_ia32_pternlogd128_mask:
4535   case X86::BI__builtin_ia32_pternlogd128_maskz:
4536   case X86::BI__builtin_ia32_pternlogd256_mask:
4537   case X86::BI__builtin_ia32_pternlogd256_maskz:
4538   case X86::BI__builtin_ia32_pternlogq128_mask:
4539   case X86::BI__builtin_ia32_pternlogq128_maskz:
4540   case X86::BI__builtin_ia32_pternlogq256_mask:
4541   case X86::BI__builtin_ia32_pternlogq256_maskz:
4542     i = 3; l = 0; u = 255;
4543     break;
4544   case X86::BI__builtin_ia32_gatherpfdpd:
4545   case X86::BI__builtin_ia32_gatherpfdps:
4546   case X86::BI__builtin_ia32_gatherpfqpd:
4547   case X86::BI__builtin_ia32_gatherpfqps:
4548   case X86::BI__builtin_ia32_scatterpfdpd:
4549   case X86::BI__builtin_ia32_scatterpfdps:
4550   case X86::BI__builtin_ia32_scatterpfqpd:
4551   case X86::BI__builtin_ia32_scatterpfqps:
4552     i = 4; l = 2; u = 3;
4553     break;
4554   case X86::BI__builtin_ia32_reducesd_mask:
4555   case X86::BI__builtin_ia32_reducess_mask:
4556   case X86::BI__builtin_ia32_rndscalesd_round_mask:
4557   case X86::BI__builtin_ia32_rndscaless_round_mask:
4558     i = 4; l = 0; u = 255;
4559     break;
4560   }
4561 
4562   // Note that we don't force a hard error on the range check here, allowing
4563   // template-generated or macro-generated dead code to potentially have out-of-
4564   // range values. These need to code generate, but don't need to necessarily
4565   // make any sense. We use a warning that defaults to an error.
4566   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
4567 }
4568 
4569 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
4570 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
4571 /// Returns true when the format fits the function and the FormatStringInfo has
4572 /// been populated.
4573 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
4574                                FormatStringInfo *FSI) {
4575   FSI->HasVAListArg = Format->getFirstArg() == 0;
4576   FSI->FormatIdx = Format->getFormatIdx() - 1;
4577   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
4578 
4579   // The way the format attribute works in GCC, the implicit this argument
4580   // of member functions is counted. However, it doesn't appear in our own
4581   // lists, so decrement format_idx in that case.
4582   if (IsCXXMember) {
4583     if(FSI->FormatIdx == 0)
4584       return false;
4585     --FSI->FormatIdx;
4586     if (FSI->FirstDataArg != 0)
4587       --FSI->FirstDataArg;
4588   }
4589   return true;
4590 }
4591 
4592 /// Checks if a the given expression evaluates to null.
4593 ///
4594 /// Returns true if the value evaluates to null.
4595 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4596   // If the expression has non-null type, it doesn't evaluate to null.
4597   if (auto nullability
4598         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
4599     if (*nullability == NullabilityKind::NonNull)
4600       return false;
4601   }
4602 
4603   // As a special case, transparent unions initialized with zero are
4604   // considered null for the purposes of the nonnull attribute.
4605   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
4606     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
4607       if (const CompoundLiteralExpr *CLE =
4608           dyn_cast<CompoundLiteralExpr>(Expr))
4609         if (const InitListExpr *ILE =
4610             dyn_cast<InitListExpr>(CLE->getInitializer()))
4611           Expr = ILE->getInit(0);
4612   }
4613 
4614   bool Result;
4615   return (!Expr->isValueDependent() &&
4616           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
4617           !Result);
4618 }
4619 
4620 static void CheckNonNullArgument(Sema &S,
4621                                  const Expr *ArgExpr,
4622                                  SourceLocation CallSiteLoc) {
4623   if (CheckNonNullExpr(S, ArgExpr))
4624     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
4625                           S.PDiag(diag::warn_null_arg)
4626                               << ArgExpr->getSourceRange());
4627 }
4628 
4629 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
4630   FormatStringInfo FSI;
4631   if ((GetFormatStringType(Format) == FST_NSString) &&
4632       getFormatStringInfo(Format, false, &FSI)) {
4633     Idx = FSI.FormatIdx;
4634     return true;
4635   }
4636   return false;
4637 }
4638 
4639 /// Diagnose use of %s directive in an NSString which is being passed
4640 /// as formatting string to formatting method.
4641 static void
4642 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
4643                                         const NamedDecl *FDecl,
4644                                         Expr **Args,
4645                                         unsigned NumArgs) {
4646   unsigned Idx = 0;
4647   bool Format = false;
4648   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
4649   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
4650     Idx = 2;
4651     Format = true;
4652   }
4653   else
4654     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4655       if (S.GetFormatNSStringIdx(I, Idx)) {
4656         Format = true;
4657         break;
4658       }
4659     }
4660   if (!Format || NumArgs <= Idx)
4661     return;
4662   const Expr *FormatExpr = Args[Idx];
4663   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
4664     FormatExpr = CSCE->getSubExpr();
4665   const StringLiteral *FormatString;
4666   if (const ObjCStringLiteral *OSL =
4667       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
4668     FormatString = OSL->getString();
4669   else
4670     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
4671   if (!FormatString)
4672     return;
4673   if (S.FormatStringHasSArg(FormatString)) {
4674     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
4675       << "%s" << 1 << 1;
4676     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
4677       << FDecl->getDeclName();
4678   }
4679 }
4680 
4681 /// Determine whether the given type has a non-null nullability annotation.
4682 static bool isNonNullType(ASTContext &ctx, QualType type) {
4683   if (auto nullability = type->getNullability(ctx))
4684     return *nullability == NullabilityKind::NonNull;
4685 
4686   return false;
4687 }
4688 
4689 static void CheckNonNullArguments(Sema &S,
4690                                   const NamedDecl *FDecl,
4691                                   const FunctionProtoType *Proto,
4692                                   ArrayRef<const Expr *> Args,
4693                                   SourceLocation CallSiteLoc) {
4694   assert((FDecl || Proto) && "Need a function declaration or prototype");
4695 
4696   // Already checked by by constant evaluator.
4697   if (S.isConstantEvaluated())
4698     return;
4699   // Check the attributes attached to the method/function itself.
4700   llvm::SmallBitVector NonNullArgs;
4701   if (FDecl) {
4702     // Handle the nonnull attribute on the function/method declaration itself.
4703     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4704       if (!NonNull->args_size()) {
4705         // Easy case: all pointer arguments are nonnull.
4706         for (const auto *Arg : Args)
4707           if (S.isValidPointerAttrType(Arg->getType()))
4708             CheckNonNullArgument(S, Arg, CallSiteLoc);
4709         return;
4710       }
4711 
4712       for (const ParamIdx &Idx : NonNull->args()) {
4713         unsigned IdxAST = Idx.getASTIndex();
4714         if (IdxAST >= Args.size())
4715           continue;
4716         if (NonNullArgs.empty())
4717           NonNullArgs.resize(Args.size());
4718         NonNullArgs.set(IdxAST);
4719       }
4720     }
4721   }
4722 
4723   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4724     // Handle the nonnull attribute on the parameters of the
4725     // function/method.
4726     ArrayRef<ParmVarDecl*> parms;
4727     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4728       parms = FD->parameters();
4729     else
4730       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4731 
4732     unsigned ParamIndex = 0;
4733     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4734          I != E; ++I, ++ParamIndex) {
4735       const ParmVarDecl *PVD = *I;
4736       if (PVD->hasAttr<NonNullAttr>() ||
4737           isNonNullType(S.Context, PVD->getType())) {
4738         if (NonNullArgs.empty())
4739           NonNullArgs.resize(Args.size());
4740 
4741         NonNullArgs.set(ParamIndex);
4742       }
4743     }
4744   } else {
4745     // If we have a non-function, non-method declaration but no
4746     // function prototype, try to dig out the function prototype.
4747     if (!Proto) {
4748       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4749         QualType type = VD->getType().getNonReferenceType();
4750         if (auto pointerType = type->getAs<PointerType>())
4751           type = pointerType->getPointeeType();
4752         else if (auto blockType = type->getAs<BlockPointerType>())
4753           type = blockType->getPointeeType();
4754         // FIXME: data member pointers?
4755 
4756         // Dig out the function prototype, if there is one.
4757         Proto = type->getAs<FunctionProtoType>();
4758       }
4759     }
4760 
4761     // Fill in non-null argument information from the nullability
4762     // information on the parameter types (if we have them).
4763     if (Proto) {
4764       unsigned Index = 0;
4765       for (auto paramType : Proto->getParamTypes()) {
4766         if (isNonNullType(S.Context, paramType)) {
4767           if (NonNullArgs.empty())
4768             NonNullArgs.resize(Args.size());
4769 
4770           NonNullArgs.set(Index);
4771         }
4772 
4773         ++Index;
4774       }
4775     }
4776   }
4777 
4778   // Check for non-null arguments.
4779   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4780        ArgIndex != ArgIndexEnd; ++ArgIndex) {
4781     if (NonNullArgs[ArgIndex])
4782       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
4783   }
4784 }
4785 
4786 /// Warn if a pointer or reference argument passed to a function points to an
4787 /// object that is less aligned than the parameter. This can happen when
4788 /// creating a typedef with a lower alignment than the original type and then
4789 /// calling functions defined in terms of the original type.
4790 void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
4791                              StringRef ParamName, QualType ArgTy,
4792                              QualType ParamTy) {
4793 
4794   // If a function accepts a pointer or reference type
4795   if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
4796     return;
4797 
4798   // If the parameter is a pointer type, get the pointee type for the
4799   // argument too. If the parameter is a reference type, don't try to get
4800   // the pointee type for the argument.
4801   if (ParamTy->isPointerType())
4802     ArgTy = ArgTy->getPointeeType();
4803 
4804   // Remove reference or pointer
4805   ParamTy = ParamTy->getPointeeType();
4806 
4807   // Find expected alignment, and the actual alignment of the passed object.
4808   // getTypeAlignInChars requires complete types
4809   if (ArgTy.isNull() || ParamTy->isIncompleteType() ||
4810       ArgTy->isIncompleteType() || ParamTy->isUndeducedType() ||
4811       ArgTy->isUndeducedType())
4812     return;
4813 
4814   CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
4815   CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
4816 
4817   // If the argument is less aligned than the parameter, there is a
4818   // potential alignment issue.
4819   if (ArgAlign < ParamAlign)
4820     Diag(Loc, diag::warn_param_mismatched_alignment)
4821         << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
4822         << ParamName << FDecl;
4823 }
4824 
4825 /// Handles the checks for format strings, non-POD arguments to vararg
4826 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
4827 /// attributes.
4828 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
4829                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
4830                      bool IsMemberFunction, SourceLocation Loc,
4831                      SourceRange Range, VariadicCallType CallType) {
4832   // FIXME: We should check as much as we can in the template definition.
4833   if (CurContext->isDependentContext())
4834     return;
4835 
4836   // Printf and scanf checking.
4837   llvm::SmallBitVector CheckedVarArgs;
4838   if (FDecl) {
4839     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4840       // Only create vector if there are format attributes.
4841       CheckedVarArgs.resize(Args.size());
4842 
4843       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4844                            CheckedVarArgs);
4845     }
4846   }
4847 
4848   // Refuse POD arguments that weren't caught by the format string
4849   // checks above.
4850   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4851   if (CallType != VariadicDoesNotApply &&
4852       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4853     unsigned NumParams = Proto ? Proto->getNumParams()
4854                        : FDecl && isa<FunctionDecl>(FDecl)
4855                            ? cast<FunctionDecl>(FDecl)->getNumParams()
4856                        : FDecl && isa<ObjCMethodDecl>(FDecl)
4857                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
4858                        : 0;
4859 
4860     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4861       // Args[ArgIdx] can be null in malformed code.
4862       if (const Expr *Arg = Args[ArgIdx]) {
4863         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4864           checkVariadicArgument(Arg, CallType);
4865       }
4866     }
4867   }
4868 
4869   if (FDecl || Proto) {
4870     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4871 
4872     // Type safety checking.
4873     if (FDecl) {
4874       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4875         CheckArgumentWithTypeTag(I, Args, Loc);
4876     }
4877   }
4878 
4879   // Check that passed arguments match the alignment of original arguments.
4880   // Try to get the missing prototype from the declaration.
4881   if (!Proto && FDecl) {
4882     const auto *FT = FDecl->getFunctionType();
4883     if (isa_and_nonnull<FunctionProtoType>(FT))
4884       Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
4885   }
4886   if (Proto) {
4887     // For variadic functions, we may have more args than parameters.
4888     // For some K&R functions, we may have less args than parameters.
4889     const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
4890     for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
4891       // Args[ArgIdx] can be null in malformed code.
4892       if (const Expr *Arg = Args[ArgIdx]) {
4893         if (Arg->containsErrors())
4894           continue;
4895 
4896         QualType ParamTy = Proto->getParamType(ArgIdx);
4897         QualType ArgTy = Arg->getType();
4898         CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
4899                           ArgTy, ParamTy);
4900       }
4901     }
4902   }
4903 
4904   if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
4905     auto *AA = FDecl->getAttr<AllocAlignAttr>();
4906     const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
4907     if (!Arg->isValueDependent()) {
4908       Expr::EvalResult Align;
4909       if (Arg->EvaluateAsInt(Align, Context)) {
4910         const llvm::APSInt &I = Align.Val.getInt();
4911         if (!I.isPowerOf2())
4912           Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
4913               << Arg->getSourceRange();
4914 
4915         if (I > Sema::MaximumAlignment)
4916           Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
4917               << Arg->getSourceRange() << Sema::MaximumAlignment;
4918       }
4919     }
4920   }
4921 
4922   if (FD)
4923     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4924 }
4925 
4926 /// CheckConstructorCall - Check a constructor call for correctness and safety
4927 /// properties not enforced by the C type system.
4928 void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
4929                                 ArrayRef<const Expr *> Args,
4930                                 const FunctionProtoType *Proto,
4931                                 SourceLocation Loc) {
4932   VariadicCallType CallType =
4933       Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4934 
4935   auto *Ctor = cast<CXXConstructorDecl>(FDecl);
4936   CheckArgAlignment(Loc, FDecl, "'this'", Context.getPointerType(ThisType),
4937                     Context.getPointerType(Ctor->getThisObjectType()));
4938 
4939   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4940             Loc, SourceRange(), CallType);
4941 }
4942 
4943 /// CheckFunctionCall - Check a direct function call for various correctness
4944 /// and safety properties not strictly enforced by the C type system.
4945 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
4946                              const FunctionProtoType *Proto) {
4947   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4948                               isa<CXXMethodDecl>(FDecl);
4949   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4950                           IsMemberOperatorCall;
4951   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4952                                                   TheCall->getCallee());
4953   Expr** Args = TheCall->getArgs();
4954   unsigned NumArgs = TheCall->getNumArgs();
4955 
4956   Expr *ImplicitThis = nullptr;
4957   if (IsMemberOperatorCall) {
4958     // If this is a call to a member operator, hide the first argument
4959     // from checkCall.
4960     // FIXME: Our choice of AST representation here is less than ideal.
4961     ImplicitThis = Args[0];
4962     ++Args;
4963     --NumArgs;
4964   } else if (IsMemberFunction)
4965     ImplicitThis =
4966         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4967 
4968   if (ImplicitThis) {
4969     // ImplicitThis may or may not be a pointer, depending on whether . or -> is
4970     // used.
4971     QualType ThisType = ImplicitThis->getType();
4972     if (!ThisType->isPointerType()) {
4973       assert(!ThisType->isReferenceType());
4974       ThisType = Context.getPointerType(ThisType);
4975     }
4976 
4977     QualType ThisTypeFromDecl =
4978         Context.getPointerType(cast<CXXMethodDecl>(FDecl)->getThisObjectType());
4979 
4980     CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
4981                       ThisTypeFromDecl);
4982   }
4983 
4984   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
4985             IsMemberFunction, TheCall->getRParenLoc(),
4986             TheCall->getCallee()->getSourceRange(), CallType);
4987 
4988   IdentifierInfo *FnInfo = FDecl->getIdentifier();
4989   // None of the checks below are needed for functions that don't have
4990   // simple names (e.g., C++ conversion functions).
4991   if (!FnInfo)
4992     return false;
4993 
4994   CheckTCBEnforcement(TheCall, FDecl);
4995 
4996   CheckAbsoluteValueFunction(TheCall, FDecl);
4997   CheckMaxUnsignedZero(TheCall, FDecl);
4998 
4999   if (getLangOpts().ObjC)
5000     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
5001 
5002   unsigned CMId = FDecl->getMemoryFunctionKind();
5003 
5004   // Handle memory setting and copying functions.
5005   switch (CMId) {
5006   case 0:
5007     return false;
5008   case Builtin::BIstrlcpy: // fallthrough
5009   case Builtin::BIstrlcat:
5010     CheckStrlcpycatArguments(TheCall, FnInfo);
5011     break;
5012   case Builtin::BIstrncat:
5013     CheckStrncatArguments(TheCall, FnInfo);
5014     break;
5015   case Builtin::BIfree:
5016     CheckFreeArguments(TheCall);
5017     break;
5018   default:
5019     CheckMemaccessArguments(TheCall, CMId, FnInfo);
5020   }
5021 
5022   return false;
5023 }
5024 
5025 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
5026                                ArrayRef<const Expr *> Args) {
5027   VariadicCallType CallType =
5028       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
5029 
5030   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
5031             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
5032             CallType);
5033 
5034   return false;
5035 }
5036 
5037 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
5038                             const FunctionProtoType *Proto) {
5039   QualType Ty;
5040   if (const auto *V = dyn_cast<VarDecl>(NDecl))
5041     Ty = V->getType().getNonReferenceType();
5042   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
5043     Ty = F->getType().getNonReferenceType();
5044   else
5045     return false;
5046 
5047   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
5048       !Ty->isFunctionProtoType())
5049     return false;
5050 
5051   VariadicCallType CallType;
5052   if (!Proto || !Proto->isVariadic()) {
5053     CallType = VariadicDoesNotApply;
5054   } else if (Ty->isBlockPointerType()) {
5055     CallType = VariadicBlock;
5056   } else { // Ty->isFunctionPointerType()
5057     CallType = VariadicFunction;
5058   }
5059 
5060   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
5061             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5062             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
5063             TheCall->getCallee()->getSourceRange(), CallType);
5064 
5065   return false;
5066 }
5067 
5068 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
5069 /// such as function pointers returned from functions.
5070 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
5071   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
5072                                                   TheCall->getCallee());
5073   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
5074             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5075             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
5076             TheCall->getCallee()->getSourceRange(), CallType);
5077 
5078   return false;
5079 }
5080 
5081 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
5082   if (!llvm::isValidAtomicOrderingCABI(Ordering))
5083     return false;
5084 
5085   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
5086   switch (Op) {
5087   case AtomicExpr::AO__c11_atomic_init:
5088   case AtomicExpr::AO__opencl_atomic_init:
5089     llvm_unreachable("There is no ordering argument for an init");
5090 
5091   case AtomicExpr::AO__c11_atomic_load:
5092   case AtomicExpr::AO__opencl_atomic_load:
5093   case AtomicExpr::AO__atomic_load_n:
5094   case AtomicExpr::AO__atomic_load:
5095     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
5096            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5097 
5098   case AtomicExpr::AO__c11_atomic_store:
5099   case AtomicExpr::AO__opencl_atomic_store:
5100   case AtomicExpr::AO__atomic_store:
5101   case AtomicExpr::AO__atomic_store_n:
5102     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
5103            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
5104            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5105 
5106   default:
5107     return true;
5108   }
5109 }
5110 
5111 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
5112                                          AtomicExpr::AtomicOp Op) {
5113   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
5114   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5115   MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
5116   return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
5117                          DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
5118                          Op);
5119 }
5120 
5121 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
5122                                  SourceLocation RParenLoc, MultiExprArg Args,
5123                                  AtomicExpr::AtomicOp Op,
5124                                  AtomicArgumentOrder ArgOrder) {
5125   // All the non-OpenCL operations take one of the following forms.
5126   // The OpenCL operations take the __c11 forms with one extra argument for
5127   // synchronization scope.
5128   enum {
5129     // C    __c11_atomic_init(A *, C)
5130     Init,
5131 
5132     // C    __c11_atomic_load(A *, int)
5133     Load,
5134 
5135     // void __atomic_load(A *, CP, int)
5136     LoadCopy,
5137 
5138     // void __atomic_store(A *, CP, int)
5139     Copy,
5140 
5141     // C    __c11_atomic_add(A *, M, int)
5142     Arithmetic,
5143 
5144     // C    __atomic_exchange_n(A *, CP, int)
5145     Xchg,
5146 
5147     // void __atomic_exchange(A *, C *, CP, int)
5148     GNUXchg,
5149 
5150     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
5151     C11CmpXchg,
5152 
5153     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
5154     GNUCmpXchg
5155   } Form = Init;
5156 
5157   const unsigned NumForm = GNUCmpXchg + 1;
5158   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
5159   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
5160   // where:
5161   //   C is an appropriate type,
5162   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
5163   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
5164   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
5165   //   the int parameters are for orderings.
5166 
5167   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
5168       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
5169       "need to update code for modified forms");
5170   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
5171                     AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
5172                         AtomicExpr::AO__atomic_load,
5173                 "need to update code for modified C11 atomics");
5174   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
5175                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
5176   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
5177                Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
5178                IsOpenCL;
5179   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
5180              Op == AtomicExpr::AO__atomic_store_n ||
5181              Op == AtomicExpr::AO__atomic_exchange_n ||
5182              Op == AtomicExpr::AO__atomic_compare_exchange_n;
5183   bool IsAddSub = false;
5184 
5185   switch (Op) {
5186   case AtomicExpr::AO__c11_atomic_init:
5187   case AtomicExpr::AO__opencl_atomic_init:
5188     Form = Init;
5189     break;
5190 
5191   case AtomicExpr::AO__c11_atomic_load:
5192   case AtomicExpr::AO__opencl_atomic_load:
5193   case AtomicExpr::AO__atomic_load_n:
5194     Form = Load;
5195     break;
5196 
5197   case AtomicExpr::AO__atomic_load:
5198     Form = LoadCopy;
5199     break;
5200 
5201   case AtomicExpr::AO__c11_atomic_store:
5202   case AtomicExpr::AO__opencl_atomic_store:
5203   case AtomicExpr::AO__atomic_store:
5204   case AtomicExpr::AO__atomic_store_n:
5205     Form = Copy;
5206     break;
5207 
5208   case AtomicExpr::AO__c11_atomic_fetch_add:
5209   case AtomicExpr::AO__c11_atomic_fetch_sub:
5210   case AtomicExpr::AO__opencl_atomic_fetch_add:
5211   case AtomicExpr::AO__opencl_atomic_fetch_sub:
5212   case AtomicExpr::AO__atomic_fetch_add:
5213   case AtomicExpr::AO__atomic_fetch_sub:
5214   case AtomicExpr::AO__atomic_add_fetch:
5215   case AtomicExpr::AO__atomic_sub_fetch:
5216     IsAddSub = true;
5217     Form = Arithmetic;
5218     break;
5219   case AtomicExpr::AO__c11_atomic_fetch_and:
5220   case AtomicExpr::AO__c11_atomic_fetch_or:
5221   case AtomicExpr::AO__c11_atomic_fetch_xor:
5222   case AtomicExpr::AO__opencl_atomic_fetch_and:
5223   case AtomicExpr::AO__opencl_atomic_fetch_or:
5224   case AtomicExpr::AO__opencl_atomic_fetch_xor:
5225   case AtomicExpr::AO__atomic_fetch_and:
5226   case AtomicExpr::AO__atomic_fetch_or:
5227   case AtomicExpr::AO__atomic_fetch_xor:
5228   case AtomicExpr::AO__atomic_fetch_nand:
5229   case AtomicExpr::AO__atomic_and_fetch:
5230   case AtomicExpr::AO__atomic_or_fetch:
5231   case AtomicExpr::AO__atomic_xor_fetch:
5232   case AtomicExpr::AO__atomic_nand_fetch:
5233     Form = Arithmetic;
5234     break;
5235   case AtomicExpr::AO__c11_atomic_fetch_min:
5236   case AtomicExpr::AO__c11_atomic_fetch_max:
5237   case AtomicExpr::AO__opencl_atomic_fetch_min:
5238   case AtomicExpr::AO__opencl_atomic_fetch_max:
5239   case AtomicExpr::AO__atomic_min_fetch:
5240   case AtomicExpr::AO__atomic_max_fetch:
5241   case AtomicExpr::AO__atomic_fetch_min:
5242   case AtomicExpr::AO__atomic_fetch_max:
5243     Form = Arithmetic;
5244     break;
5245 
5246   case AtomicExpr::AO__c11_atomic_exchange:
5247   case AtomicExpr::AO__opencl_atomic_exchange:
5248   case AtomicExpr::AO__atomic_exchange_n:
5249     Form = Xchg;
5250     break;
5251 
5252   case AtomicExpr::AO__atomic_exchange:
5253     Form = GNUXchg;
5254     break;
5255 
5256   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
5257   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
5258   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
5259   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
5260     Form = C11CmpXchg;
5261     break;
5262 
5263   case AtomicExpr::AO__atomic_compare_exchange:
5264   case AtomicExpr::AO__atomic_compare_exchange_n:
5265     Form = GNUCmpXchg;
5266     break;
5267   }
5268 
5269   unsigned AdjustedNumArgs = NumArgs[Form];
5270   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
5271     ++AdjustedNumArgs;
5272   // Check we have the right number of arguments.
5273   if (Args.size() < AdjustedNumArgs) {
5274     Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
5275         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5276         << ExprRange;
5277     return ExprError();
5278   } else if (Args.size() > AdjustedNumArgs) {
5279     Diag(Args[AdjustedNumArgs]->getBeginLoc(),
5280          diag::err_typecheck_call_too_many_args)
5281         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5282         << ExprRange;
5283     return ExprError();
5284   }
5285 
5286   // Inspect the first argument of the atomic operation.
5287   Expr *Ptr = Args[0];
5288   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
5289   if (ConvertedPtr.isInvalid())
5290     return ExprError();
5291 
5292   Ptr = ConvertedPtr.get();
5293   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
5294   if (!pointerType) {
5295     Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
5296         << Ptr->getType() << Ptr->getSourceRange();
5297     return ExprError();
5298   }
5299 
5300   // For a __c11 builtin, this should be a pointer to an _Atomic type.
5301   QualType AtomTy = pointerType->getPointeeType(); // 'A'
5302   QualType ValType = AtomTy; // 'C'
5303   if (IsC11) {
5304     if (!AtomTy->isAtomicType()) {
5305       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
5306           << Ptr->getType() << Ptr->getSourceRange();
5307       return ExprError();
5308     }
5309     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
5310         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
5311       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
5312           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
5313           << Ptr->getSourceRange();
5314       return ExprError();
5315     }
5316     ValType = AtomTy->castAs<AtomicType>()->getValueType();
5317   } else if (Form != Load && Form != LoadCopy) {
5318     if (ValType.isConstQualified()) {
5319       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
5320           << Ptr->getType() << Ptr->getSourceRange();
5321       return ExprError();
5322     }
5323   }
5324 
5325   // For an arithmetic operation, the implied arithmetic must be well-formed.
5326   if (Form == Arithmetic) {
5327     // gcc does not enforce these rules for GNU atomics, but we do so for
5328     // sanity.
5329     auto IsAllowedValueType = [&](QualType ValType) {
5330       if (ValType->isIntegerType())
5331         return true;
5332       if (ValType->isPointerType())
5333         return true;
5334       if (!ValType->isFloatingType())
5335         return false;
5336       // LLVM Parser does not allow atomicrmw with x86_fp80 type.
5337       if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
5338           &Context.getTargetInfo().getLongDoubleFormat() ==
5339               &llvm::APFloat::x87DoubleExtended())
5340         return false;
5341       return true;
5342     };
5343     if (IsAddSub && !IsAllowedValueType(ValType)) {
5344       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_ptr_or_fp)
5345           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5346       return ExprError();
5347     }
5348     if (!IsAddSub && !ValType->isIntegerType()) {
5349       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
5350           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5351       return ExprError();
5352     }
5353     if (IsC11 && ValType->isPointerType() &&
5354         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
5355                             diag::err_incomplete_type)) {
5356       return ExprError();
5357     }
5358   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
5359     // For __atomic_*_n operations, the value type must be a scalar integral or
5360     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
5361     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
5362         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5363     return ExprError();
5364   }
5365 
5366   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
5367       !AtomTy->isScalarType()) {
5368     // For GNU atomics, require a trivially-copyable type. This is not part of
5369     // the GNU atomics specification, but we enforce it for sanity.
5370     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
5371         << Ptr->getType() << Ptr->getSourceRange();
5372     return ExprError();
5373   }
5374 
5375   switch (ValType.getObjCLifetime()) {
5376   case Qualifiers::OCL_None:
5377   case Qualifiers::OCL_ExplicitNone:
5378     // okay
5379     break;
5380 
5381   case Qualifiers::OCL_Weak:
5382   case Qualifiers::OCL_Strong:
5383   case Qualifiers::OCL_Autoreleasing:
5384     // FIXME: Can this happen? By this point, ValType should be known
5385     // to be trivially copyable.
5386     Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
5387         << ValType << Ptr->getSourceRange();
5388     return ExprError();
5389   }
5390 
5391   // All atomic operations have an overload which takes a pointer to a volatile
5392   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
5393   // into the result or the other operands. Similarly atomic_load takes a
5394   // pointer to a const 'A'.
5395   ValType.removeLocalVolatile();
5396   ValType.removeLocalConst();
5397   QualType ResultType = ValType;
5398   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
5399       Form == Init)
5400     ResultType = Context.VoidTy;
5401   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
5402     ResultType = Context.BoolTy;
5403 
5404   // The type of a parameter passed 'by value'. In the GNU atomics, such
5405   // arguments are actually passed as pointers.
5406   QualType ByValType = ValType; // 'CP'
5407   bool IsPassedByAddress = false;
5408   if (!IsC11 && !IsN) {
5409     ByValType = Ptr->getType();
5410     IsPassedByAddress = true;
5411   }
5412 
5413   SmallVector<Expr *, 5> APIOrderedArgs;
5414   if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
5415     APIOrderedArgs.push_back(Args[0]);
5416     switch (Form) {
5417     case Init:
5418     case Load:
5419       APIOrderedArgs.push_back(Args[1]); // Val1/Order
5420       break;
5421     case LoadCopy:
5422     case Copy:
5423     case Arithmetic:
5424     case Xchg:
5425       APIOrderedArgs.push_back(Args[2]); // Val1
5426       APIOrderedArgs.push_back(Args[1]); // Order
5427       break;
5428     case GNUXchg:
5429       APIOrderedArgs.push_back(Args[2]); // Val1
5430       APIOrderedArgs.push_back(Args[3]); // Val2
5431       APIOrderedArgs.push_back(Args[1]); // Order
5432       break;
5433     case C11CmpXchg:
5434       APIOrderedArgs.push_back(Args[2]); // Val1
5435       APIOrderedArgs.push_back(Args[4]); // Val2
5436       APIOrderedArgs.push_back(Args[1]); // Order
5437       APIOrderedArgs.push_back(Args[3]); // OrderFail
5438       break;
5439     case GNUCmpXchg:
5440       APIOrderedArgs.push_back(Args[2]); // Val1
5441       APIOrderedArgs.push_back(Args[4]); // Val2
5442       APIOrderedArgs.push_back(Args[5]); // Weak
5443       APIOrderedArgs.push_back(Args[1]); // Order
5444       APIOrderedArgs.push_back(Args[3]); // OrderFail
5445       break;
5446     }
5447   } else
5448     APIOrderedArgs.append(Args.begin(), Args.end());
5449 
5450   // The first argument's non-CV pointer type is used to deduce the type of
5451   // subsequent arguments, except for:
5452   //  - weak flag (always converted to bool)
5453   //  - memory order (always converted to int)
5454   //  - scope  (always converted to int)
5455   for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
5456     QualType Ty;
5457     if (i < NumVals[Form] + 1) {
5458       switch (i) {
5459       case 0:
5460         // The first argument is always a pointer. It has a fixed type.
5461         // It is always dereferenced, a nullptr is undefined.
5462         CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5463         // Nothing else to do: we already know all we want about this pointer.
5464         continue;
5465       case 1:
5466         // The second argument is the non-atomic operand. For arithmetic, this
5467         // is always passed by value, and for a compare_exchange it is always
5468         // passed by address. For the rest, GNU uses by-address and C11 uses
5469         // by-value.
5470         assert(Form != Load);
5471         if (Form == Arithmetic && ValType->isPointerType())
5472           Ty = Context.getPointerDiffType();
5473         else if (Form == Init || Form == Arithmetic)
5474           Ty = ValType;
5475         else if (Form == Copy || Form == Xchg) {
5476           if (IsPassedByAddress) {
5477             // The value pointer is always dereferenced, a nullptr is undefined.
5478             CheckNonNullArgument(*this, APIOrderedArgs[i],
5479                                  ExprRange.getBegin());
5480           }
5481           Ty = ByValType;
5482         } else {
5483           Expr *ValArg = APIOrderedArgs[i];
5484           // The value pointer is always dereferenced, a nullptr is undefined.
5485           CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
5486           LangAS AS = LangAS::Default;
5487           // Keep address space of non-atomic pointer type.
5488           if (const PointerType *PtrTy =
5489                   ValArg->getType()->getAs<PointerType>()) {
5490             AS = PtrTy->getPointeeType().getAddressSpace();
5491           }
5492           Ty = Context.getPointerType(
5493               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
5494         }
5495         break;
5496       case 2:
5497         // The third argument to compare_exchange / GNU exchange is the desired
5498         // value, either by-value (for the C11 and *_n variant) or as a pointer.
5499         if (IsPassedByAddress)
5500           CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5501         Ty = ByValType;
5502         break;
5503       case 3:
5504         // The fourth argument to GNU compare_exchange is a 'weak' flag.
5505         Ty = Context.BoolTy;
5506         break;
5507       }
5508     } else {
5509       // The order(s) and scope are always converted to int.
5510       Ty = Context.IntTy;
5511     }
5512 
5513     InitializedEntity Entity =
5514         InitializedEntity::InitializeParameter(Context, Ty, false);
5515     ExprResult Arg = APIOrderedArgs[i];
5516     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5517     if (Arg.isInvalid())
5518       return true;
5519     APIOrderedArgs[i] = Arg.get();
5520   }
5521 
5522   // Permute the arguments into a 'consistent' order.
5523   SmallVector<Expr*, 5> SubExprs;
5524   SubExprs.push_back(Ptr);
5525   switch (Form) {
5526   case Init:
5527     // Note, AtomicExpr::getVal1() has a special case for this atomic.
5528     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5529     break;
5530   case Load:
5531     SubExprs.push_back(APIOrderedArgs[1]); // Order
5532     break;
5533   case LoadCopy:
5534   case Copy:
5535   case Arithmetic:
5536   case Xchg:
5537     SubExprs.push_back(APIOrderedArgs[2]); // Order
5538     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5539     break;
5540   case GNUXchg:
5541     // Note, AtomicExpr::getVal2() has a special case for this atomic.
5542     SubExprs.push_back(APIOrderedArgs[3]); // Order
5543     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5544     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5545     break;
5546   case C11CmpXchg:
5547     SubExprs.push_back(APIOrderedArgs[3]); // Order
5548     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5549     SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
5550     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5551     break;
5552   case GNUCmpXchg:
5553     SubExprs.push_back(APIOrderedArgs[4]); // Order
5554     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5555     SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
5556     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5557     SubExprs.push_back(APIOrderedArgs[3]); // Weak
5558     break;
5559   }
5560 
5561   if (SubExprs.size() >= 2 && Form != Init) {
5562     if (Optional<llvm::APSInt> Result =
5563             SubExprs[1]->getIntegerConstantExpr(Context))
5564       if (!isValidOrderingForOp(Result->getSExtValue(), Op))
5565         Diag(SubExprs[1]->getBeginLoc(),
5566              diag::warn_atomic_op_has_invalid_memory_order)
5567             << SubExprs[1]->getSourceRange();
5568   }
5569 
5570   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
5571     auto *Scope = Args[Args.size() - 1];
5572     if (Optional<llvm::APSInt> Result =
5573             Scope->getIntegerConstantExpr(Context)) {
5574       if (!ScopeModel->isValid(Result->getZExtValue()))
5575         Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
5576             << Scope->getSourceRange();
5577     }
5578     SubExprs.push_back(Scope);
5579   }
5580 
5581   AtomicExpr *AE = new (Context)
5582       AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
5583 
5584   if ((Op == AtomicExpr::AO__c11_atomic_load ||
5585        Op == AtomicExpr::AO__c11_atomic_store ||
5586        Op == AtomicExpr::AO__opencl_atomic_load ||
5587        Op == AtomicExpr::AO__opencl_atomic_store ) &&
5588       Context.AtomicUsesUnsupportedLibcall(AE))
5589     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
5590         << ((Op == AtomicExpr::AO__c11_atomic_load ||
5591              Op == AtomicExpr::AO__opencl_atomic_load)
5592                 ? 0
5593                 : 1);
5594 
5595   if (ValType->isExtIntType()) {
5596     Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_ext_int_prohibit);
5597     return ExprError();
5598   }
5599 
5600   return AE;
5601 }
5602 
5603 /// checkBuiltinArgument - Given a call to a builtin function, perform
5604 /// normal type-checking on the given argument, updating the call in
5605 /// place.  This is useful when a builtin function requires custom
5606 /// type-checking for some of its arguments but not necessarily all of
5607 /// them.
5608 ///
5609 /// Returns true on error.
5610 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
5611   FunctionDecl *Fn = E->getDirectCallee();
5612   assert(Fn && "builtin call without direct callee!");
5613 
5614   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
5615   InitializedEntity Entity =
5616     InitializedEntity::InitializeParameter(S.Context, Param);
5617 
5618   ExprResult Arg = E->getArg(0);
5619   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
5620   if (Arg.isInvalid())
5621     return true;
5622 
5623   E->setArg(ArgIndex, Arg.get());
5624   return false;
5625 }
5626 
5627 /// We have a call to a function like __sync_fetch_and_add, which is an
5628 /// overloaded function based on the pointer type of its first argument.
5629 /// The main BuildCallExpr routines have already promoted the types of
5630 /// arguments because all of these calls are prototyped as void(...).
5631 ///
5632 /// This function goes through and does final semantic checking for these
5633 /// builtins, as well as generating any warnings.
5634 ExprResult
5635 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
5636   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
5637   Expr *Callee = TheCall->getCallee();
5638   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
5639   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5640 
5641   // Ensure that we have at least one argument to do type inference from.
5642   if (TheCall->getNumArgs() < 1) {
5643     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5644         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
5645     return ExprError();
5646   }
5647 
5648   // Inspect the first argument of the atomic builtin.  This should always be
5649   // a pointer type, whose element is an integral scalar or pointer type.
5650   // Because it is a pointer type, we don't have to worry about any implicit
5651   // casts here.
5652   // FIXME: We don't allow floating point scalars as input.
5653   Expr *FirstArg = TheCall->getArg(0);
5654   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
5655   if (FirstArgResult.isInvalid())
5656     return ExprError();
5657   FirstArg = FirstArgResult.get();
5658   TheCall->setArg(0, FirstArg);
5659 
5660   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5661   if (!pointerType) {
5662     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
5663         << FirstArg->getType() << FirstArg->getSourceRange();
5664     return ExprError();
5665   }
5666 
5667   QualType ValType = pointerType->getPointeeType();
5668   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5669       !ValType->isBlockPointerType()) {
5670     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
5671         << FirstArg->getType() << FirstArg->getSourceRange();
5672     return ExprError();
5673   }
5674 
5675   if (ValType.isConstQualified()) {
5676     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
5677         << FirstArg->getType() << FirstArg->getSourceRange();
5678     return ExprError();
5679   }
5680 
5681   switch (ValType.getObjCLifetime()) {
5682   case Qualifiers::OCL_None:
5683   case Qualifiers::OCL_ExplicitNone:
5684     // okay
5685     break;
5686 
5687   case Qualifiers::OCL_Weak:
5688   case Qualifiers::OCL_Strong:
5689   case Qualifiers::OCL_Autoreleasing:
5690     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
5691         << ValType << FirstArg->getSourceRange();
5692     return ExprError();
5693   }
5694 
5695   // Strip any qualifiers off ValType.
5696   ValType = ValType.getUnqualifiedType();
5697 
5698   // The majority of builtins return a value, but a few have special return
5699   // types, so allow them to override appropriately below.
5700   QualType ResultType = ValType;
5701 
5702   // We need to figure out which concrete builtin this maps onto.  For example,
5703   // __sync_fetch_and_add with a 2 byte object turns into
5704   // __sync_fetch_and_add_2.
5705 #define BUILTIN_ROW(x) \
5706   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5707     Builtin::BI##x##_8, Builtin::BI##x##_16 }
5708 
5709   static const unsigned BuiltinIndices[][5] = {
5710     BUILTIN_ROW(__sync_fetch_and_add),
5711     BUILTIN_ROW(__sync_fetch_and_sub),
5712     BUILTIN_ROW(__sync_fetch_and_or),
5713     BUILTIN_ROW(__sync_fetch_and_and),
5714     BUILTIN_ROW(__sync_fetch_and_xor),
5715     BUILTIN_ROW(__sync_fetch_and_nand),
5716 
5717     BUILTIN_ROW(__sync_add_and_fetch),
5718     BUILTIN_ROW(__sync_sub_and_fetch),
5719     BUILTIN_ROW(__sync_and_and_fetch),
5720     BUILTIN_ROW(__sync_or_and_fetch),
5721     BUILTIN_ROW(__sync_xor_and_fetch),
5722     BUILTIN_ROW(__sync_nand_and_fetch),
5723 
5724     BUILTIN_ROW(__sync_val_compare_and_swap),
5725     BUILTIN_ROW(__sync_bool_compare_and_swap),
5726     BUILTIN_ROW(__sync_lock_test_and_set),
5727     BUILTIN_ROW(__sync_lock_release),
5728     BUILTIN_ROW(__sync_swap)
5729   };
5730 #undef BUILTIN_ROW
5731 
5732   // Determine the index of the size.
5733   unsigned SizeIndex;
5734   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
5735   case 1: SizeIndex = 0; break;
5736   case 2: SizeIndex = 1; break;
5737   case 4: SizeIndex = 2; break;
5738   case 8: SizeIndex = 3; break;
5739   case 16: SizeIndex = 4; break;
5740   default:
5741     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
5742         << FirstArg->getType() << FirstArg->getSourceRange();
5743     return ExprError();
5744   }
5745 
5746   // Each of these builtins has one pointer argument, followed by some number of
5747   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5748   // that we ignore.  Find out which row of BuiltinIndices to read from as well
5749   // as the number of fixed args.
5750   unsigned BuiltinID = FDecl->getBuiltinID();
5751   unsigned BuiltinIndex, NumFixed = 1;
5752   bool WarnAboutSemanticsChange = false;
5753   switch (BuiltinID) {
5754   default: llvm_unreachable("Unknown overloaded atomic builtin!");
5755   case Builtin::BI__sync_fetch_and_add:
5756   case Builtin::BI__sync_fetch_and_add_1:
5757   case Builtin::BI__sync_fetch_and_add_2:
5758   case Builtin::BI__sync_fetch_and_add_4:
5759   case Builtin::BI__sync_fetch_and_add_8:
5760   case Builtin::BI__sync_fetch_and_add_16:
5761     BuiltinIndex = 0;
5762     break;
5763 
5764   case Builtin::BI__sync_fetch_and_sub:
5765   case Builtin::BI__sync_fetch_and_sub_1:
5766   case Builtin::BI__sync_fetch_and_sub_2:
5767   case Builtin::BI__sync_fetch_and_sub_4:
5768   case Builtin::BI__sync_fetch_and_sub_8:
5769   case Builtin::BI__sync_fetch_and_sub_16:
5770     BuiltinIndex = 1;
5771     break;
5772 
5773   case Builtin::BI__sync_fetch_and_or:
5774   case Builtin::BI__sync_fetch_and_or_1:
5775   case Builtin::BI__sync_fetch_and_or_2:
5776   case Builtin::BI__sync_fetch_and_or_4:
5777   case Builtin::BI__sync_fetch_and_or_8:
5778   case Builtin::BI__sync_fetch_and_or_16:
5779     BuiltinIndex = 2;
5780     break;
5781 
5782   case Builtin::BI__sync_fetch_and_and:
5783   case Builtin::BI__sync_fetch_and_and_1:
5784   case Builtin::BI__sync_fetch_and_and_2:
5785   case Builtin::BI__sync_fetch_and_and_4:
5786   case Builtin::BI__sync_fetch_and_and_8:
5787   case Builtin::BI__sync_fetch_and_and_16:
5788     BuiltinIndex = 3;
5789     break;
5790 
5791   case Builtin::BI__sync_fetch_and_xor:
5792   case Builtin::BI__sync_fetch_and_xor_1:
5793   case Builtin::BI__sync_fetch_and_xor_2:
5794   case Builtin::BI__sync_fetch_and_xor_4:
5795   case Builtin::BI__sync_fetch_and_xor_8:
5796   case Builtin::BI__sync_fetch_and_xor_16:
5797     BuiltinIndex = 4;
5798     break;
5799 
5800   case Builtin::BI__sync_fetch_and_nand:
5801   case Builtin::BI__sync_fetch_and_nand_1:
5802   case Builtin::BI__sync_fetch_and_nand_2:
5803   case Builtin::BI__sync_fetch_and_nand_4:
5804   case Builtin::BI__sync_fetch_and_nand_8:
5805   case Builtin::BI__sync_fetch_and_nand_16:
5806     BuiltinIndex = 5;
5807     WarnAboutSemanticsChange = true;
5808     break;
5809 
5810   case Builtin::BI__sync_add_and_fetch:
5811   case Builtin::BI__sync_add_and_fetch_1:
5812   case Builtin::BI__sync_add_and_fetch_2:
5813   case Builtin::BI__sync_add_and_fetch_4:
5814   case Builtin::BI__sync_add_and_fetch_8:
5815   case Builtin::BI__sync_add_and_fetch_16:
5816     BuiltinIndex = 6;
5817     break;
5818 
5819   case Builtin::BI__sync_sub_and_fetch:
5820   case Builtin::BI__sync_sub_and_fetch_1:
5821   case Builtin::BI__sync_sub_and_fetch_2:
5822   case Builtin::BI__sync_sub_and_fetch_4:
5823   case Builtin::BI__sync_sub_and_fetch_8:
5824   case Builtin::BI__sync_sub_and_fetch_16:
5825     BuiltinIndex = 7;
5826     break;
5827 
5828   case Builtin::BI__sync_and_and_fetch:
5829   case Builtin::BI__sync_and_and_fetch_1:
5830   case Builtin::BI__sync_and_and_fetch_2:
5831   case Builtin::BI__sync_and_and_fetch_4:
5832   case Builtin::BI__sync_and_and_fetch_8:
5833   case Builtin::BI__sync_and_and_fetch_16:
5834     BuiltinIndex = 8;
5835     break;
5836 
5837   case Builtin::BI__sync_or_and_fetch:
5838   case Builtin::BI__sync_or_and_fetch_1:
5839   case Builtin::BI__sync_or_and_fetch_2:
5840   case Builtin::BI__sync_or_and_fetch_4:
5841   case Builtin::BI__sync_or_and_fetch_8:
5842   case Builtin::BI__sync_or_and_fetch_16:
5843     BuiltinIndex = 9;
5844     break;
5845 
5846   case Builtin::BI__sync_xor_and_fetch:
5847   case Builtin::BI__sync_xor_and_fetch_1:
5848   case Builtin::BI__sync_xor_and_fetch_2:
5849   case Builtin::BI__sync_xor_and_fetch_4:
5850   case Builtin::BI__sync_xor_and_fetch_8:
5851   case Builtin::BI__sync_xor_and_fetch_16:
5852     BuiltinIndex = 10;
5853     break;
5854 
5855   case Builtin::BI__sync_nand_and_fetch:
5856   case Builtin::BI__sync_nand_and_fetch_1:
5857   case Builtin::BI__sync_nand_and_fetch_2:
5858   case Builtin::BI__sync_nand_and_fetch_4:
5859   case Builtin::BI__sync_nand_and_fetch_8:
5860   case Builtin::BI__sync_nand_and_fetch_16:
5861     BuiltinIndex = 11;
5862     WarnAboutSemanticsChange = true;
5863     break;
5864 
5865   case Builtin::BI__sync_val_compare_and_swap:
5866   case Builtin::BI__sync_val_compare_and_swap_1:
5867   case Builtin::BI__sync_val_compare_and_swap_2:
5868   case Builtin::BI__sync_val_compare_and_swap_4:
5869   case Builtin::BI__sync_val_compare_and_swap_8:
5870   case Builtin::BI__sync_val_compare_and_swap_16:
5871     BuiltinIndex = 12;
5872     NumFixed = 2;
5873     break;
5874 
5875   case Builtin::BI__sync_bool_compare_and_swap:
5876   case Builtin::BI__sync_bool_compare_and_swap_1:
5877   case Builtin::BI__sync_bool_compare_and_swap_2:
5878   case Builtin::BI__sync_bool_compare_and_swap_4:
5879   case Builtin::BI__sync_bool_compare_and_swap_8:
5880   case Builtin::BI__sync_bool_compare_and_swap_16:
5881     BuiltinIndex = 13;
5882     NumFixed = 2;
5883     ResultType = Context.BoolTy;
5884     break;
5885 
5886   case Builtin::BI__sync_lock_test_and_set:
5887   case Builtin::BI__sync_lock_test_and_set_1:
5888   case Builtin::BI__sync_lock_test_and_set_2:
5889   case Builtin::BI__sync_lock_test_and_set_4:
5890   case Builtin::BI__sync_lock_test_and_set_8:
5891   case Builtin::BI__sync_lock_test_and_set_16:
5892     BuiltinIndex = 14;
5893     break;
5894 
5895   case Builtin::BI__sync_lock_release:
5896   case Builtin::BI__sync_lock_release_1:
5897   case Builtin::BI__sync_lock_release_2:
5898   case Builtin::BI__sync_lock_release_4:
5899   case Builtin::BI__sync_lock_release_8:
5900   case Builtin::BI__sync_lock_release_16:
5901     BuiltinIndex = 15;
5902     NumFixed = 0;
5903     ResultType = Context.VoidTy;
5904     break;
5905 
5906   case Builtin::BI__sync_swap:
5907   case Builtin::BI__sync_swap_1:
5908   case Builtin::BI__sync_swap_2:
5909   case Builtin::BI__sync_swap_4:
5910   case Builtin::BI__sync_swap_8:
5911   case Builtin::BI__sync_swap_16:
5912     BuiltinIndex = 16;
5913     break;
5914   }
5915 
5916   // Now that we know how many fixed arguments we expect, first check that we
5917   // have at least that many.
5918   if (TheCall->getNumArgs() < 1+NumFixed) {
5919     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5920         << 0 << 1 + NumFixed << TheCall->getNumArgs()
5921         << Callee->getSourceRange();
5922     return ExprError();
5923   }
5924 
5925   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5926       << Callee->getSourceRange();
5927 
5928   if (WarnAboutSemanticsChange) {
5929     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
5930         << Callee->getSourceRange();
5931   }
5932 
5933   // Get the decl for the concrete builtin from this, we can tell what the
5934   // concrete integer type we should convert to is.
5935   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5936   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
5937   FunctionDecl *NewBuiltinDecl;
5938   if (NewBuiltinID == BuiltinID)
5939     NewBuiltinDecl = FDecl;
5940   else {
5941     // Perform builtin lookup to avoid redeclaring it.
5942     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
5943     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5944     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5945     assert(Res.getFoundDecl());
5946     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
5947     if (!NewBuiltinDecl)
5948       return ExprError();
5949   }
5950 
5951   // The first argument --- the pointer --- has a fixed type; we
5952   // deduce the types of the rest of the arguments accordingly.  Walk
5953   // the remaining arguments, converting them to the deduced value type.
5954   for (unsigned i = 0; i != NumFixed; ++i) {
5955     ExprResult Arg = TheCall->getArg(i+1);
5956 
5957     // GCC does an implicit conversion to the pointer or integer ValType.  This
5958     // can fail in some cases (1i -> int**), check for this error case now.
5959     // Initialize the argument.
5960     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5961                                                    ValType, /*consume*/ false);
5962     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5963     if (Arg.isInvalid())
5964       return ExprError();
5965 
5966     // Okay, we have something that *can* be converted to the right type.  Check
5967     // to see if there is a potentially weird extension going on here.  This can
5968     // happen when you do an atomic operation on something like an char* and
5969     // pass in 42.  The 42 gets converted to char.  This is even more strange
5970     // for things like 45.123 -> char, etc.
5971     // FIXME: Do this check.
5972     TheCall->setArg(i+1, Arg.get());
5973   }
5974 
5975   // Create a new DeclRefExpr to refer to the new decl.
5976   DeclRefExpr *NewDRE = DeclRefExpr::Create(
5977       Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
5978       /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
5979       DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
5980 
5981   // Set the callee in the CallExpr.
5982   // FIXME: This loses syntactic information.
5983   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5984   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5985                                               CK_BuiltinFnToFnPtr);
5986   TheCall->setCallee(PromotedCall.get());
5987 
5988   // Change the result type of the call to match the original value type. This
5989   // is arbitrary, but the codegen for these builtins ins design to handle it
5990   // gracefully.
5991   TheCall->setType(ResultType);
5992 
5993   // Prohibit use of _ExtInt with atomic builtins.
5994   // The arguments would have already been converted to the first argument's
5995   // type, so only need to check the first argument.
5996   const auto *ExtIntValType = ValType->getAs<ExtIntType>();
5997   if (ExtIntValType && !llvm::isPowerOf2_64(ExtIntValType->getNumBits())) {
5998     Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
5999     return ExprError();
6000   }
6001 
6002   return TheCallResult;
6003 }
6004 
6005 /// SemaBuiltinNontemporalOverloaded - We have a call to
6006 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
6007 /// overloaded function based on the pointer type of its last argument.
6008 ///
6009 /// This function goes through and does final semantic checking for these
6010 /// builtins.
6011 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
6012   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
6013   DeclRefExpr *DRE =
6014       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6015   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6016   unsigned BuiltinID = FDecl->getBuiltinID();
6017   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
6018           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
6019          "Unexpected nontemporal load/store builtin!");
6020   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
6021   unsigned numArgs = isStore ? 2 : 1;
6022 
6023   // Ensure that we have the proper number of arguments.
6024   if (checkArgCount(*this, TheCall, numArgs))
6025     return ExprError();
6026 
6027   // Inspect the last argument of the nontemporal builtin.  This should always
6028   // be a pointer type, from which we imply the type of the memory access.
6029   // Because it is a pointer type, we don't have to worry about any implicit
6030   // casts here.
6031   Expr *PointerArg = TheCall->getArg(numArgs - 1);
6032   ExprResult PointerArgResult =
6033       DefaultFunctionArrayLvalueConversion(PointerArg);
6034 
6035   if (PointerArgResult.isInvalid())
6036     return ExprError();
6037   PointerArg = PointerArgResult.get();
6038   TheCall->setArg(numArgs - 1, PointerArg);
6039 
6040   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
6041   if (!pointerType) {
6042     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
6043         << PointerArg->getType() << PointerArg->getSourceRange();
6044     return ExprError();
6045   }
6046 
6047   QualType ValType = pointerType->getPointeeType();
6048 
6049   // Strip any qualifiers off ValType.
6050   ValType = ValType.getUnqualifiedType();
6051   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
6052       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
6053       !ValType->isVectorType()) {
6054     Diag(DRE->getBeginLoc(),
6055          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
6056         << PointerArg->getType() << PointerArg->getSourceRange();
6057     return ExprError();
6058   }
6059 
6060   if (!isStore) {
6061     TheCall->setType(ValType);
6062     return TheCallResult;
6063   }
6064 
6065   ExprResult ValArg = TheCall->getArg(0);
6066   InitializedEntity Entity = InitializedEntity::InitializeParameter(
6067       Context, ValType, /*consume*/ false);
6068   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
6069   if (ValArg.isInvalid())
6070     return ExprError();
6071 
6072   TheCall->setArg(0, ValArg.get());
6073   TheCall->setType(Context.VoidTy);
6074   return TheCallResult;
6075 }
6076 
6077 /// CheckObjCString - Checks that the argument to the builtin
6078 /// CFString constructor is correct
6079 /// Note: It might also make sense to do the UTF-16 conversion here (would
6080 /// simplify the backend).
6081 bool Sema::CheckObjCString(Expr *Arg) {
6082   Arg = Arg->IgnoreParenCasts();
6083   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
6084 
6085   if (!Literal || !Literal->isAscii()) {
6086     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
6087         << Arg->getSourceRange();
6088     return true;
6089   }
6090 
6091   if (Literal->containsNonAsciiOrNull()) {
6092     StringRef String = Literal->getString();
6093     unsigned NumBytes = String.size();
6094     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
6095     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
6096     llvm::UTF16 *ToPtr = &ToBuf[0];
6097 
6098     llvm::ConversionResult Result =
6099         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
6100                                  ToPtr + NumBytes, llvm::strictConversion);
6101     // Check for conversion failure.
6102     if (Result != llvm::conversionOK)
6103       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
6104           << Arg->getSourceRange();
6105   }
6106   return false;
6107 }
6108 
6109 /// CheckObjCString - Checks that the format string argument to the os_log()
6110 /// and os_trace() functions is correct, and converts it to const char *.
6111 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
6112   Arg = Arg->IgnoreParenCasts();
6113   auto *Literal = dyn_cast<StringLiteral>(Arg);
6114   if (!Literal) {
6115     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
6116       Literal = ObjcLiteral->getString();
6117     }
6118   }
6119 
6120   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
6121     return ExprError(
6122         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
6123         << Arg->getSourceRange());
6124   }
6125 
6126   ExprResult Result(Literal);
6127   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
6128   InitializedEntity Entity =
6129       InitializedEntity::InitializeParameter(Context, ResultTy, false);
6130   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
6131   return Result;
6132 }
6133 
6134 /// Check that the user is calling the appropriate va_start builtin for the
6135 /// target and calling convention.
6136 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
6137   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
6138   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
6139   bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
6140                     TT.getArch() == llvm::Triple::aarch64_32);
6141   bool IsWindows = TT.isOSWindows();
6142   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
6143   if (IsX64 || IsAArch64) {
6144     CallingConv CC = CC_C;
6145     if (const FunctionDecl *FD = S.getCurFunctionDecl())
6146       CC = FD->getType()->castAs<FunctionType>()->getCallConv();
6147     if (IsMSVAStart) {
6148       // Don't allow this in System V ABI functions.
6149       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
6150         return S.Diag(Fn->getBeginLoc(),
6151                       diag::err_ms_va_start_used_in_sysv_function);
6152     } else {
6153       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
6154       // On x64 Windows, don't allow this in System V ABI functions.
6155       // (Yes, that means there's no corresponding way to support variadic
6156       // System V ABI functions on Windows.)
6157       if ((IsWindows && CC == CC_X86_64SysV) ||
6158           (!IsWindows && CC == CC_Win64))
6159         return S.Diag(Fn->getBeginLoc(),
6160                       diag::err_va_start_used_in_wrong_abi_function)
6161                << !IsWindows;
6162     }
6163     return false;
6164   }
6165 
6166   if (IsMSVAStart)
6167     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
6168   return false;
6169 }
6170 
6171 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
6172                                              ParmVarDecl **LastParam = nullptr) {
6173   // Determine whether the current function, block, or obj-c method is variadic
6174   // and get its parameter list.
6175   bool IsVariadic = false;
6176   ArrayRef<ParmVarDecl *> Params;
6177   DeclContext *Caller = S.CurContext;
6178   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
6179     IsVariadic = Block->isVariadic();
6180     Params = Block->parameters();
6181   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
6182     IsVariadic = FD->isVariadic();
6183     Params = FD->parameters();
6184   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
6185     IsVariadic = MD->isVariadic();
6186     // FIXME: This isn't correct for methods (results in bogus warning).
6187     Params = MD->parameters();
6188   } else if (isa<CapturedDecl>(Caller)) {
6189     // We don't support va_start in a CapturedDecl.
6190     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
6191     return true;
6192   } else {
6193     // This must be some other declcontext that parses exprs.
6194     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
6195     return true;
6196   }
6197 
6198   if (!IsVariadic) {
6199     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
6200     return true;
6201   }
6202 
6203   if (LastParam)
6204     *LastParam = Params.empty() ? nullptr : Params.back();
6205 
6206   return false;
6207 }
6208 
6209 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
6210 /// for validity.  Emit an error and return true on failure; return false
6211 /// on success.
6212 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
6213   Expr *Fn = TheCall->getCallee();
6214 
6215   if (checkVAStartABI(*this, BuiltinID, Fn))
6216     return true;
6217 
6218   if (checkArgCount(*this, TheCall, 2))
6219     return true;
6220 
6221   // Type-check the first argument normally.
6222   if (checkBuiltinArgument(*this, TheCall, 0))
6223     return true;
6224 
6225   // Check that the current function is variadic, and get its last parameter.
6226   ParmVarDecl *LastParam;
6227   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
6228     return true;
6229 
6230   // Verify that the second argument to the builtin is the last argument of the
6231   // current function or method.
6232   bool SecondArgIsLastNamedArgument = false;
6233   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
6234 
6235   // These are valid if SecondArgIsLastNamedArgument is false after the next
6236   // block.
6237   QualType Type;
6238   SourceLocation ParamLoc;
6239   bool IsCRegister = false;
6240 
6241   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
6242     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
6243       SecondArgIsLastNamedArgument = PV == LastParam;
6244 
6245       Type = PV->getType();
6246       ParamLoc = PV->getLocation();
6247       IsCRegister =
6248           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
6249     }
6250   }
6251 
6252   if (!SecondArgIsLastNamedArgument)
6253     Diag(TheCall->getArg(1)->getBeginLoc(),
6254          diag::warn_second_arg_of_va_start_not_last_named_param);
6255   else if (IsCRegister || Type->isReferenceType() ||
6256            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
6257              // Promotable integers are UB, but enumerations need a bit of
6258              // extra checking to see what their promotable type actually is.
6259              if (!Type->isPromotableIntegerType())
6260                return false;
6261              if (!Type->isEnumeralType())
6262                return true;
6263              const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
6264              return !(ED &&
6265                       Context.typesAreCompatible(ED->getPromotionType(), Type));
6266            }()) {
6267     unsigned Reason = 0;
6268     if (Type->isReferenceType())  Reason = 1;
6269     else if (IsCRegister)         Reason = 2;
6270     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
6271     Diag(ParamLoc, diag::note_parameter_type) << Type;
6272   }
6273 
6274   TheCall->setType(Context.VoidTy);
6275   return false;
6276 }
6277 
6278 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
6279   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
6280   //                 const char *named_addr);
6281 
6282   Expr *Func = Call->getCallee();
6283 
6284   if (Call->getNumArgs() < 3)
6285     return Diag(Call->getEndLoc(),
6286                 diag::err_typecheck_call_too_few_args_at_least)
6287            << 0 /*function call*/ << 3 << Call->getNumArgs();
6288 
6289   // Type-check the first argument normally.
6290   if (checkBuiltinArgument(*this, Call, 0))
6291     return true;
6292 
6293   // Check that the current function is variadic.
6294   if (checkVAStartIsInVariadicFunction(*this, Func))
6295     return true;
6296 
6297   // __va_start on Windows does not validate the parameter qualifiers
6298 
6299   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
6300   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
6301 
6302   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
6303   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
6304 
6305   const QualType &ConstCharPtrTy =
6306       Context.getPointerType(Context.CharTy.withConst());
6307   if (!Arg1Ty->isPointerType() ||
6308       Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
6309     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6310         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
6311         << 0                                      /* qualifier difference */
6312         << 3                                      /* parameter mismatch */
6313         << 2 << Arg1->getType() << ConstCharPtrTy;
6314 
6315   const QualType SizeTy = Context.getSizeType();
6316   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
6317     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6318         << Arg2->getType() << SizeTy << 1 /* different class */
6319         << 0                              /* qualifier difference */
6320         << 3                              /* parameter mismatch */
6321         << 3 << Arg2->getType() << SizeTy;
6322 
6323   return false;
6324 }
6325 
6326 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
6327 /// friends.  This is declared to take (...), so we have to check everything.
6328 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
6329   if (checkArgCount(*this, TheCall, 2))
6330     return true;
6331 
6332   ExprResult OrigArg0 = TheCall->getArg(0);
6333   ExprResult OrigArg1 = TheCall->getArg(1);
6334 
6335   // Do standard promotions between the two arguments, returning their common
6336   // type.
6337   QualType Res = UsualArithmeticConversions(
6338       OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
6339   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
6340     return true;
6341 
6342   // Make sure any conversions are pushed back into the call; this is
6343   // type safe since unordered compare builtins are declared as "_Bool
6344   // foo(...)".
6345   TheCall->setArg(0, OrigArg0.get());
6346   TheCall->setArg(1, OrigArg1.get());
6347 
6348   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
6349     return false;
6350 
6351   // If the common type isn't a real floating type, then the arguments were
6352   // invalid for this operation.
6353   if (Res.isNull() || !Res->isRealFloatingType())
6354     return Diag(OrigArg0.get()->getBeginLoc(),
6355                 diag::err_typecheck_call_invalid_ordered_compare)
6356            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
6357            << SourceRange(OrigArg0.get()->getBeginLoc(),
6358                           OrigArg1.get()->getEndLoc());
6359 
6360   return false;
6361 }
6362 
6363 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
6364 /// __builtin_isnan and friends.  This is declared to take (...), so we have
6365 /// to check everything. We expect the last argument to be a floating point
6366 /// value.
6367 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
6368   if (checkArgCount(*this, TheCall, NumArgs))
6369     return true;
6370 
6371   // __builtin_fpclassify is the only case where NumArgs != 1, so we can count
6372   // on all preceding parameters just being int.  Try all of those.
6373   for (unsigned i = 0; i < NumArgs - 1; ++i) {
6374     Expr *Arg = TheCall->getArg(i);
6375 
6376     if (Arg->isTypeDependent())
6377       return false;
6378 
6379     ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);
6380 
6381     if (Res.isInvalid())
6382       return true;
6383     TheCall->setArg(i, Res.get());
6384   }
6385 
6386   Expr *OrigArg = TheCall->getArg(NumArgs-1);
6387 
6388   if (OrigArg->isTypeDependent())
6389     return false;
6390 
6391   // Usual Unary Conversions will convert half to float, which we want for
6392   // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
6393   // type how it is, but do normal L->Rvalue conversions.
6394   if (Context.getTargetInfo().useFP16ConversionIntrinsics())
6395     OrigArg = UsualUnaryConversions(OrigArg).get();
6396   else
6397     OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
6398   TheCall->setArg(NumArgs - 1, OrigArg);
6399 
6400   // This operation requires a non-_Complex floating-point number.
6401   if (!OrigArg->getType()->isRealFloatingType())
6402     return Diag(OrigArg->getBeginLoc(),
6403                 diag::err_typecheck_call_invalid_unary_fp)
6404            << OrigArg->getType() << OrigArg->getSourceRange();
6405 
6406   return false;
6407 }
6408 
6409 /// Perform semantic analysis for a call to __builtin_complex.
6410 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) {
6411   if (checkArgCount(*this, TheCall, 2))
6412     return true;
6413 
6414   bool Dependent = false;
6415   for (unsigned I = 0; I != 2; ++I) {
6416     Expr *Arg = TheCall->getArg(I);
6417     QualType T = Arg->getType();
6418     if (T->isDependentType()) {
6419       Dependent = true;
6420       continue;
6421     }
6422 
6423     // Despite supporting _Complex int, GCC requires a real floating point type
6424     // for the operands of __builtin_complex.
6425     if (!T->isRealFloatingType()) {
6426       return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
6427              << Arg->getType() << Arg->getSourceRange();
6428     }
6429 
6430     ExprResult Converted = DefaultLvalueConversion(Arg);
6431     if (Converted.isInvalid())
6432       return true;
6433     TheCall->setArg(I, Converted.get());
6434   }
6435 
6436   if (Dependent) {
6437     TheCall->setType(Context.DependentTy);
6438     return false;
6439   }
6440 
6441   Expr *Real = TheCall->getArg(0);
6442   Expr *Imag = TheCall->getArg(1);
6443   if (!Context.hasSameType(Real->getType(), Imag->getType())) {
6444     return Diag(Real->getBeginLoc(),
6445                 diag::err_typecheck_call_different_arg_types)
6446            << Real->getType() << Imag->getType()
6447            << Real->getSourceRange() << Imag->getSourceRange();
6448   }
6449 
6450   // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers;
6451   // don't allow this builtin to form those types either.
6452   // FIXME: Should we allow these types?
6453   if (Real->getType()->isFloat16Type())
6454     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6455            << "_Float16";
6456   if (Real->getType()->isHalfType())
6457     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6458            << "half";
6459 
6460   TheCall->setType(Context.getComplexType(Real->getType()));
6461   return false;
6462 }
6463 
6464 // Customized Sema Checking for VSX builtins that have the following signature:
6465 // vector [...] builtinName(vector [...], vector [...], const int);
6466 // Which takes the same type of vectors (any legal vector type) for the first
6467 // two arguments and takes compile time constant for the third argument.
6468 // Example builtins are :
6469 // vector double vec_xxpermdi(vector double, vector double, int);
6470 // vector short vec_xxsldwi(vector short, vector short, int);
6471 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
6472   unsigned ExpectedNumArgs = 3;
6473   if (checkArgCount(*this, TheCall, ExpectedNumArgs))
6474     return true;
6475 
6476   // Check the third argument is a compile time constant
6477   if (!TheCall->getArg(2)->isIntegerConstantExpr(Context))
6478     return Diag(TheCall->getBeginLoc(),
6479                 diag::err_vsx_builtin_nonconstant_argument)
6480            << 3 /* argument index */ << TheCall->getDirectCallee()
6481            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
6482                           TheCall->getArg(2)->getEndLoc());
6483 
6484   QualType Arg1Ty = TheCall->getArg(0)->getType();
6485   QualType Arg2Ty = TheCall->getArg(1)->getType();
6486 
6487   // Check the type of argument 1 and argument 2 are vectors.
6488   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
6489   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
6490       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
6491     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
6492            << TheCall->getDirectCallee()
6493            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6494                           TheCall->getArg(1)->getEndLoc());
6495   }
6496 
6497   // Check the first two arguments are the same type.
6498   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
6499     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
6500            << TheCall->getDirectCallee()
6501            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6502                           TheCall->getArg(1)->getEndLoc());
6503   }
6504 
6505   // When default clang type checking is turned off and the customized type
6506   // checking is used, the returning type of the function must be explicitly
6507   // set. Otherwise it is _Bool by default.
6508   TheCall->setType(Arg1Ty);
6509 
6510   return false;
6511 }
6512 
6513 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
6514 // This is declared to take (...), so we have to check everything.
6515 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
6516   if (TheCall->getNumArgs() < 2)
6517     return ExprError(Diag(TheCall->getEndLoc(),
6518                           diag::err_typecheck_call_too_few_args_at_least)
6519                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
6520                      << TheCall->getSourceRange());
6521 
6522   // Determine which of the following types of shufflevector we're checking:
6523   // 1) unary, vector mask: (lhs, mask)
6524   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
6525   QualType resType = TheCall->getArg(0)->getType();
6526   unsigned numElements = 0;
6527 
6528   if (!TheCall->getArg(0)->isTypeDependent() &&
6529       !TheCall->getArg(1)->isTypeDependent()) {
6530     QualType LHSType = TheCall->getArg(0)->getType();
6531     QualType RHSType = TheCall->getArg(1)->getType();
6532 
6533     if (!LHSType->isVectorType() || !RHSType->isVectorType())
6534       return ExprError(
6535           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
6536           << TheCall->getDirectCallee()
6537           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6538                          TheCall->getArg(1)->getEndLoc()));
6539 
6540     numElements = LHSType->castAs<VectorType>()->getNumElements();
6541     unsigned numResElements = TheCall->getNumArgs() - 2;
6542 
6543     // Check to see if we have a call with 2 vector arguments, the unary shuffle
6544     // with mask.  If so, verify that RHS is an integer vector type with the
6545     // same number of elts as lhs.
6546     if (TheCall->getNumArgs() == 2) {
6547       if (!RHSType->hasIntegerRepresentation() ||
6548           RHSType->castAs<VectorType>()->getNumElements() != numElements)
6549         return ExprError(Diag(TheCall->getBeginLoc(),
6550                               diag::err_vec_builtin_incompatible_vector)
6551                          << TheCall->getDirectCallee()
6552                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
6553                                         TheCall->getArg(1)->getEndLoc()));
6554     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
6555       return ExprError(Diag(TheCall->getBeginLoc(),
6556                             diag::err_vec_builtin_incompatible_vector)
6557                        << TheCall->getDirectCallee()
6558                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6559                                       TheCall->getArg(1)->getEndLoc()));
6560     } else if (numElements != numResElements) {
6561       QualType eltType = LHSType->castAs<VectorType>()->getElementType();
6562       resType = Context.getVectorType(eltType, numResElements,
6563                                       VectorType::GenericVector);
6564     }
6565   }
6566 
6567   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
6568     if (TheCall->getArg(i)->isTypeDependent() ||
6569         TheCall->getArg(i)->isValueDependent())
6570       continue;
6571 
6572     Optional<llvm::APSInt> Result;
6573     if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context)))
6574       return ExprError(Diag(TheCall->getBeginLoc(),
6575                             diag::err_shufflevector_nonconstant_argument)
6576                        << TheCall->getArg(i)->getSourceRange());
6577 
6578     // Allow -1 which will be translated to undef in the IR.
6579     if (Result->isSigned() && Result->isAllOnesValue())
6580       continue;
6581 
6582     if (Result->getActiveBits() > 64 ||
6583         Result->getZExtValue() >= numElements * 2)
6584       return ExprError(Diag(TheCall->getBeginLoc(),
6585                             diag::err_shufflevector_argument_too_large)
6586                        << TheCall->getArg(i)->getSourceRange());
6587   }
6588 
6589   SmallVector<Expr*, 32> exprs;
6590 
6591   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
6592     exprs.push_back(TheCall->getArg(i));
6593     TheCall->setArg(i, nullptr);
6594   }
6595 
6596   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
6597                                          TheCall->getCallee()->getBeginLoc(),
6598                                          TheCall->getRParenLoc());
6599 }
6600 
6601 /// SemaConvertVectorExpr - Handle __builtin_convertvector
6602 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
6603                                        SourceLocation BuiltinLoc,
6604                                        SourceLocation RParenLoc) {
6605   ExprValueKind VK = VK_PRValue;
6606   ExprObjectKind OK = OK_Ordinary;
6607   QualType DstTy = TInfo->getType();
6608   QualType SrcTy = E->getType();
6609 
6610   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
6611     return ExprError(Diag(BuiltinLoc,
6612                           diag::err_convertvector_non_vector)
6613                      << E->getSourceRange());
6614   if (!DstTy->isVectorType() && !DstTy->isDependentType())
6615     return ExprError(Diag(BuiltinLoc,
6616                           diag::err_convertvector_non_vector_type));
6617 
6618   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
6619     unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
6620     unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
6621     if (SrcElts != DstElts)
6622       return ExprError(Diag(BuiltinLoc,
6623                             diag::err_convertvector_incompatible_vector)
6624                        << E->getSourceRange());
6625   }
6626 
6627   return new (Context)
6628       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
6629 }
6630 
6631 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
6632 // This is declared to take (const void*, ...) and can take two
6633 // optional constant int args.
6634 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
6635   unsigned NumArgs = TheCall->getNumArgs();
6636 
6637   if (NumArgs > 3)
6638     return Diag(TheCall->getEndLoc(),
6639                 diag::err_typecheck_call_too_many_args_at_most)
6640            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6641 
6642   // Argument 0 is checked for us and the remaining arguments must be
6643   // constant integers.
6644   for (unsigned i = 1; i != NumArgs; ++i)
6645     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
6646       return true;
6647 
6648   return false;
6649 }
6650 
6651 /// SemaBuiltinArithmeticFence - Handle __arithmetic_fence.
6652 bool Sema::SemaBuiltinArithmeticFence(CallExpr *TheCall) {
6653   if (!Context.getTargetInfo().checkArithmeticFenceSupported())
6654     return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
6655            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6656   if (checkArgCount(*this, TheCall, 1))
6657     return true;
6658   Expr *Arg = TheCall->getArg(0);
6659   if (Arg->isInstantiationDependent())
6660     return false;
6661 
6662   QualType ArgTy = Arg->getType();
6663   if (!ArgTy->hasFloatingRepresentation())
6664     return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector)
6665            << ArgTy;
6666   if (Arg->isLValue()) {
6667     ExprResult FirstArg = DefaultLvalueConversion(Arg);
6668     TheCall->setArg(0, FirstArg.get());
6669   }
6670   TheCall->setType(TheCall->getArg(0)->getType());
6671   return false;
6672 }
6673 
6674 /// SemaBuiltinAssume - Handle __assume (MS Extension).
6675 // __assume does not evaluate its arguments, and should warn if its argument
6676 // has side effects.
6677 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
6678   Expr *Arg = TheCall->getArg(0);
6679   if (Arg->isInstantiationDependent()) return false;
6680 
6681   if (Arg->HasSideEffects(Context))
6682     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
6683         << Arg->getSourceRange()
6684         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
6685 
6686   return false;
6687 }
6688 
6689 /// Handle __builtin_alloca_with_align. This is declared
6690 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
6691 /// than 8.
6692 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
6693   // The alignment must be a constant integer.
6694   Expr *Arg = TheCall->getArg(1);
6695 
6696   // We can't check the value of a dependent argument.
6697   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6698     if (const auto *UE =
6699             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
6700       if (UE->getKind() == UETT_AlignOf ||
6701           UE->getKind() == UETT_PreferredAlignOf)
6702         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
6703             << Arg->getSourceRange();
6704 
6705     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
6706 
6707     if (!Result.isPowerOf2())
6708       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6709              << Arg->getSourceRange();
6710 
6711     if (Result < Context.getCharWidth())
6712       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
6713              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6714 
6715     if (Result > std::numeric_limits<int32_t>::max())
6716       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
6717              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6718   }
6719 
6720   return false;
6721 }
6722 
6723 /// Handle __builtin_assume_aligned. This is declared
6724 /// as (const void*, size_t, ...) and can take one optional constant int arg.
6725 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
6726   unsigned NumArgs = TheCall->getNumArgs();
6727 
6728   if (NumArgs > 3)
6729     return Diag(TheCall->getEndLoc(),
6730                 diag::err_typecheck_call_too_many_args_at_most)
6731            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6732 
6733   // The alignment must be a constant integer.
6734   Expr *Arg = TheCall->getArg(1);
6735 
6736   // We can't check the value of a dependent argument.
6737   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6738     llvm::APSInt Result;
6739     if (SemaBuiltinConstantArg(TheCall, 1, Result))
6740       return true;
6741 
6742     if (!Result.isPowerOf2())
6743       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6744              << Arg->getSourceRange();
6745 
6746     if (Result > Sema::MaximumAlignment)
6747       Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
6748           << Arg->getSourceRange() << Sema::MaximumAlignment;
6749   }
6750 
6751   if (NumArgs > 2) {
6752     ExprResult Arg(TheCall->getArg(2));
6753     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6754       Context.getSizeType(), false);
6755     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6756     if (Arg.isInvalid()) return true;
6757     TheCall->setArg(2, Arg.get());
6758   }
6759 
6760   return false;
6761 }
6762 
6763 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
6764   unsigned BuiltinID =
6765       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
6766   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6767 
6768   unsigned NumArgs = TheCall->getNumArgs();
6769   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6770   if (NumArgs < NumRequiredArgs) {
6771     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
6772            << 0 /* function call */ << NumRequiredArgs << NumArgs
6773            << TheCall->getSourceRange();
6774   }
6775   if (NumArgs >= NumRequiredArgs + 0x100) {
6776     return Diag(TheCall->getEndLoc(),
6777                 diag::err_typecheck_call_too_many_args_at_most)
6778            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6779            << TheCall->getSourceRange();
6780   }
6781   unsigned i = 0;
6782 
6783   // For formatting call, check buffer arg.
6784   if (!IsSizeCall) {
6785     ExprResult Arg(TheCall->getArg(i));
6786     InitializedEntity Entity = InitializedEntity::InitializeParameter(
6787         Context, Context.VoidPtrTy, false);
6788     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6789     if (Arg.isInvalid())
6790       return true;
6791     TheCall->setArg(i, Arg.get());
6792     i++;
6793   }
6794 
6795   // Check string literal arg.
6796   unsigned FormatIdx = i;
6797   {
6798     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
6799     if (Arg.isInvalid())
6800       return true;
6801     TheCall->setArg(i, Arg.get());
6802     i++;
6803   }
6804 
6805   // Make sure variadic args are scalar.
6806   unsigned FirstDataArg = i;
6807   while (i < NumArgs) {
6808     ExprResult Arg = DefaultVariadicArgumentPromotion(
6809         TheCall->getArg(i), VariadicFunction, nullptr);
6810     if (Arg.isInvalid())
6811       return true;
6812     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
6813     if (ArgSize.getQuantity() >= 0x100) {
6814       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
6815              << i << (int)ArgSize.getQuantity() << 0xff
6816              << TheCall->getSourceRange();
6817     }
6818     TheCall->setArg(i, Arg.get());
6819     i++;
6820   }
6821 
6822   // Check formatting specifiers. NOTE: We're only doing this for the non-size
6823   // call to avoid duplicate diagnostics.
6824   if (!IsSizeCall) {
6825     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6826     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6827     bool Success = CheckFormatArguments(
6828         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
6829         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
6830         CheckedVarArgs);
6831     if (!Success)
6832       return true;
6833   }
6834 
6835   if (IsSizeCall) {
6836     TheCall->setType(Context.getSizeType());
6837   } else {
6838     TheCall->setType(Context.VoidPtrTy);
6839   }
6840   return false;
6841 }
6842 
6843 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
6844 /// TheCall is a constant expression.
6845 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
6846                                   llvm::APSInt &Result) {
6847   Expr *Arg = TheCall->getArg(ArgNum);
6848   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6849   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6850 
6851   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
6852 
6853   Optional<llvm::APSInt> R;
6854   if (!(R = Arg->getIntegerConstantExpr(Context)))
6855     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6856            << FDecl->getDeclName() << Arg->getSourceRange();
6857   Result = *R;
6858   return false;
6859 }
6860 
6861 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
6862 /// TheCall is a constant expression in the range [Low, High].
6863 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
6864                                        int Low, int High, bool RangeIsError) {
6865   if (isConstantEvaluated())
6866     return false;
6867   llvm::APSInt Result;
6868 
6869   // We can't check the value of a dependent argument.
6870   Expr *Arg = TheCall->getArg(ArgNum);
6871   if (Arg->isTypeDependent() || Arg->isValueDependent())
6872     return false;
6873 
6874   // Check constant-ness first.
6875   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6876     return true;
6877 
6878   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6879     if (RangeIsError)
6880       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
6881              << toString(Result, 10) << Low << High << Arg->getSourceRange();
6882     else
6883       // Defer the warning until we know if the code will be emitted so that
6884       // dead code can ignore this.
6885       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6886                           PDiag(diag::warn_argument_invalid_range)
6887                               << toString(Result, 10) << Low << High
6888                               << Arg->getSourceRange());
6889   }
6890 
6891   return false;
6892 }
6893 
6894 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
6895 /// TheCall is a constant expression is a multiple of Num..
6896 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
6897                                           unsigned Num) {
6898   llvm::APSInt Result;
6899 
6900   // We can't check the value of a dependent argument.
6901   Expr *Arg = TheCall->getArg(ArgNum);
6902   if (Arg->isTypeDependent() || Arg->isValueDependent())
6903     return false;
6904 
6905   // Check constant-ness first.
6906   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6907     return true;
6908 
6909   if (Result.getSExtValue() % Num != 0)
6910     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6911            << Num << Arg->getSourceRange();
6912 
6913   return false;
6914 }
6915 
6916 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
6917 /// constant expression representing a power of 2.
6918 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
6919   llvm::APSInt Result;
6920 
6921   // We can't check the value of a dependent argument.
6922   Expr *Arg = TheCall->getArg(ArgNum);
6923   if (Arg->isTypeDependent() || Arg->isValueDependent())
6924     return false;
6925 
6926   // Check constant-ness first.
6927   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6928     return true;
6929 
6930   // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
6931   // and only if x is a power of 2.
6932   if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
6933     return false;
6934 
6935   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
6936          << Arg->getSourceRange();
6937 }
6938 
6939 static bool IsShiftedByte(llvm::APSInt Value) {
6940   if (Value.isNegative())
6941     return false;
6942 
6943   // Check if it's a shifted byte, by shifting it down
6944   while (true) {
6945     // If the value fits in the bottom byte, the check passes.
6946     if (Value < 0x100)
6947       return true;
6948 
6949     // Otherwise, if the value has _any_ bits in the bottom byte, the check
6950     // fails.
6951     if ((Value & 0xFF) != 0)
6952       return false;
6953 
6954     // If the bottom 8 bits are all 0, but something above that is nonzero,
6955     // then shifting the value right by 8 bits won't affect whether it's a
6956     // shifted byte or not. So do that, and go round again.
6957     Value >>= 8;
6958   }
6959 }
6960 
6961 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
6962 /// a constant expression representing an arbitrary byte value shifted left by
6963 /// a multiple of 8 bits.
6964 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
6965                                              unsigned ArgBits) {
6966   llvm::APSInt Result;
6967 
6968   // We can't check the value of a dependent argument.
6969   Expr *Arg = TheCall->getArg(ArgNum);
6970   if (Arg->isTypeDependent() || Arg->isValueDependent())
6971     return false;
6972 
6973   // Check constant-ness first.
6974   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6975     return true;
6976 
6977   // Truncate to the given size.
6978   Result = Result.getLoBits(ArgBits);
6979   Result.setIsUnsigned(true);
6980 
6981   if (IsShiftedByte(Result))
6982     return false;
6983 
6984   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
6985          << Arg->getSourceRange();
6986 }
6987 
6988 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
6989 /// TheCall is a constant expression representing either a shifted byte value,
6990 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
6991 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
6992 /// Arm MVE intrinsics.
6993 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
6994                                                    int ArgNum,
6995                                                    unsigned ArgBits) {
6996   llvm::APSInt Result;
6997 
6998   // We can't check the value of a dependent argument.
6999   Expr *Arg = TheCall->getArg(ArgNum);
7000   if (Arg->isTypeDependent() || Arg->isValueDependent())
7001     return false;
7002 
7003   // Check constant-ness first.
7004   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7005     return true;
7006 
7007   // Truncate to the given size.
7008   Result = Result.getLoBits(ArgBits);
7009   Result.setIsUnsigned(true);
7010 
7011   // Check to see if it's in either of the required forms.
7012   if (IsShiftedByte(Result) ||
7013       (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
7014     return false;
7015 
7016   return Diag(TheCall->getBeginLoc(),
7017               diag::err_argument_not_shifted_byte_or_xxff)
7018          << Arg->getSourceRange();
7019 }
7020 
7021 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
7022 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
7023   if (BuiltinID == AArch64::BI__builtin_arm_irg) {
7024     if (checkArgCount(*this, TheCall, 2))
7025       return true;
7026     Expr *Arg0 = TheCall->getArg(0);
7027     Expr *Arg1 = TheCall->getArg(1);
7028 
7029     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7030     if (FirstArg.isInvalid())
7031       return true;
7032     QualType FirstArgType = FirstArg.get()->getType();
7033     if (!FirstArgType->isAnyPointerType())
7034       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7035                << "first" << FirstArgType << Arg0->getSourceRange();
7036     TheCall->setArg(0, FirstArg.get());
7037 
7038     ExprResult SecArg = DefaultLvalueConversion(Arg1);
7039     if (SecArg.isInvalid())
7040       return true;
7041     QualType SecArgType = SecArg.get()->getType();
7042     if (!SecArgType->isIntegerType())
7043       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
7044                << "second" << SecArgType << Arg1->getSourceRange();
7045 
7046     // Derive the return type from the pointer argument.
7047     TheCall->setType(FirstArgType);
7048     return false;
7049   }
7050 
7051   if (BuiltinID == AArch64::BI__builtin_arm_addg) {
7052     if (checkArgCount(*this, TheCall, 2))
7053       return true;
7054 
7055     Expr *Arg0 = TheCall->getArg(0);
7056     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7057     if (FirstArg.isInvalid())
7058       return true;
7059     QualType FirstArgType = FirstArg.get()->getType();
7060     if (!FirstArgType->isAnyPointerType())
7061       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7062                << "first" << FirstArgType << Arg0->getSourceRange();
7063     TheCall->setArg(0, FirstArg.get());
7064 
7065     // Derive the return type from the pointer argument.
7066     TheCall->setType(FirstArgType);
7067 
7068     // Second arg must be an constant in range [0,15]
7069     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
7070   }
7071 
7072   if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
7073     if (checkArgCount(*this, TheCall, 2))
7074       return true;
7075     Expr *Arg0 = TheCall->getArg(0);
7076     Expr *Arg1 = TheCall->getArg(1);
7077 
7078     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7079     if (FirstArg.isInvalid())
7080       return true;
7081     QualType FirstArgType = FirstArg.get()->getType();
7082     if (!FirstArgType->isAnyPointerType())
7083       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7084                << "first" << FirstArgType << Arg0->getSourceRange();
7085 
7086     QualType SecArgType = Arg1->getType();
7087     if (!SecArgType->isIntegerType())
7088       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
7089                << "second" << SecArgType << Arg1->getSourceRange();
7090     TheCall->setType(Context.IntTy);
7091     return false;
7092   }
7093 
7094   if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
7095       BuiltinID == AArch64::BI__builtin_arm_stg) {
7096     if (checkArgCount(*this, TheCall, 1))
7097       return true;
7098     Expr *Arg0 = TheCall->getArg(0);
7099     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7100     if (FirstArg.isInvalid())
7101       return true;
7102 
7103     QualType FirstArgType = FirstArg.get()->getType();
7104     if (!FirstArgType->isAnyPointerType())
7105       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7106                << "first" << FirstArgType << Arg0->getSourceRange();
7107     TheCall->setArg(0, FirstArg.get());
7108 
7109     // Derive the return type from the pointer argument.
7110     if (BuiltinID == AArch64::BI__builtin_arm_ldg)
7111       TheCall->setType(FirstArgType);
7112     return false;
7113   }
7114 
7115   if (BuiltinID == AArch64::BI__builtin_arm_subp) {
7116     Expr *ArgA = TheCall->getArg(0);
7117     Expr *ArgB = TheCall->getArg(1);
7118 
7119     ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
7120     ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
7121 
7122     if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
7123       return true;
7124 
7125     QualType ArgTypeA = ArgExprA.get()->getType();
7126     QualType ArgTypeB = ArgExprB.get()->getType();
7127 
7128     auto isNull = [&] (Expr *E) -> bool {
7129       return E->isNullPointerConstant(
7130                         Context, Expr::NPC_ValueDependentIsNotNull); };
7131 
7132     // argument should be either a pointer or null
7133     if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
7134       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
7135         << "first" << ArgTypeA << ArgA->getSourceRange();
7136 
7137     if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
7138       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
7139         << "second" << ArgTypeB << ArgB->getSourceRange();
7140 
7141     // Ensure Pointee types are compatible
7142     if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
7143         ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
7144       QualType pointeeA = ArgTypeA->getPointeeType();
7145       QualType pointeeB = ArgTypeB->getPointeeType();
7146       if (!Context.typesAreCompatible(
7147              Context.getCanonicalType(pointeeA).getUnqualifiedType(),
7148              Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
7149         return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
7150           << ArgTypeA <<  ArgTypeB << ArgA->getSourceRange()
7151           << ArgB->getSourceRange();
7152       }
7153     }
7154 
7155     // at least one argument should be pointer type
7156     if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
7157       return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
7158         <<  ArgTypeA << ArgTypeB << ArgA->getSourceRange();
7159 
7160     if (isNull(ArgA)) // adopt type of the other pointer
7161       ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
7162 
7163     if (isNull(ArgB))
7164       ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
7165 
7166     TheCall->setArg(0, ArgExprA.get());
7167     TheCall->setArg(1, ArgExprB.get());
7168     TheCall->setType(Context.LongLongTy);
7169     return false;
7170   }
7171   assert(false && "Unhandled ARM MTE intrinsic");
7172   return true;
7173 }
7174 
7175 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
7176 /// TheCall is an ARM/AArch64 special register string literal.
7177 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
7178                                     int ArgNum, unsigned ExpectedFieldNum,
7179                                     bool AllowName) {
7180   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
7181                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
7182                       BuiltinID == ARM::BI__builtin_arm_rsr ||
7183                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
7184                       BuiltinID == ARM::BI__builtin_arm_wsr ||
7185                       BuiltinID == ARM::BI__builtin_arm_wsrp;
7186   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
7187                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
7188                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
7189                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
7190                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
7191                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
7192   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
7193 
7194   // We can't check the value of a dependent argument.
7195   Expr *Arg = TheCall->getArg(ArgNum);
7196   if (Arg->isTypeDependent() || Arg->isValueDependent())
7197     return false;
7198 
7199   // Check if the argument is a string literal.
7200   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
7201     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
7202            << Arg->getSourceRange();
7203 
7204   // Check the type of special register given.
7205   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
7206   SmallVector<StringRef, 6> Fields;
7207   Reg.split(Fields, ":");
7208 
7209   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
7210     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
7211            << Arg->getSourceRange();
7212 
7213   // If the string is the name of a register then we cannot check that it is
7214   // valid here but if the string is of one the forms described in ACLE then we
7215   // can check that the supplied fields are integers and within the valid
7216   // ranges.
7217   if (Fields.size() > 1) {
7218     bool FiveFields = Fields.size() == 5;
7219 
7220     bool ValidString = true;
7221     if (IsARMBuiltin) {
7222       ValidString &= Fields[0].startswith_insensitive("cp") ||
7223                      Fields[0].startswith_insensitive("p");
7224       if (ValidString)
7225         Fields[0] = Fields[0].drop_front(
7226             Fields[0].startswith_insensitive("cp") ? 2 : 1);
7227 
7228       ValidString &= Fields[2].startswith_insensitive("c");
7229       if (ValidString)
7230         Fields[2] = Fields[2].drop_front(1);
7231 
7232       if (FiveFields) {
7233         ValidString &= Fields[3].startswith_insensitive("c");
7234         if (ValidString)
7235           Fields[3] = Fields[3].drop_front(1);
7236       }
7237     }
7238 
7239     SmallVector<int, 5> Ranges;
7240     if (FiveFields)
7241       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
7242     else
7243       Ranges.append({15, 7, 15});
7244 
7245     for (unsigned i=0; i<Fields.size(); ++i) {
7246       int IntField;
7247       ValidString &= !Fields[i].getAsInteger(10, IntField);
7248       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
7249     }
7250 
7251     if (!ValidString)
7252       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
7253              << Arg->getSourceRange();
7254   } else if (IsAArch64Builtin && Fields.size() == 1) {
7255     // If the register name is one of those that appear in the condition below
7256     // and the special register builtin being used is one of the write builtins,
7257     // then we require that the argument provided for writing to the register
7258     // is an integer constant expression. This is because it will be lowered to
7259     // an MSR (immediate) instruction, so we need to know the immediate at
7260     // compile time.
7261     if (TheCall->getNumArgs() != 2)
7262       return false;
7263 
7264     std::string RegLower = Reg.lower();
7265     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
7266         RegLower != "pan" && RegLower != "uao")
7267       return false;
7268 
7269     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
7270   }
7271 
7272   return false;
7273 }
7274 
7275 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity.
7276 /// Emit an error and return true on failure; return false on success.
7277 /// TypeStr is a string containing the type descriptor of the value returned by
7278 /// the builtin and the descriptors of the expected type of the arguments.
7279 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, const char *TypeStr) {
7280 
7281   assert((TypeStr[0] != '\0') &&
7282          "Invalid types in PPC MMA builtin declaration");
7283 
7284   unsigned Mask = 0;
7285   unsigned ArgNum = 0;
7286 
7287   // The first type in TypeStr is the type of the value returned by the
7288   // builtin. So we first read that type and change the type of TheCall.
7289   QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7290   TheCall->setType(type);
7291 
7292   while (*TypeStr != '\0') {
7293     Mask = 0;
7294     QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7295     if (ArgNum >= TheCall->getNumArgs()) {
7296       ArgNum++;
7297       break;
7298     }
7299 
7300     Expr *Arg = TheCall->getArg(ArgNum);
7301     QualType ArgType = Arg->getType();
7302 
7303     if ((ExpectedType->isVoidPointerType() && !ArgType->isPointerType()) ||
7304         (!ExpectedType->isVoidPointerType() &&
7305            ArgType.getCanonicalType() != ExpectedType))
7306       return Diag(Arg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
7307              << ArgType << ExpectedType << 1 << 0 << 0;
7308 
7309     // If the value of the Mask is not 0, we have a constraint in the size of
7310     // the integer argument so here we ensure the argument is a constant that
7311     // is in the valid range.
7312     if (Mask != 0 &&
7313         SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true))
7314       return true;
7315 
7316     ArgNum++;
7317   }
7318 
7319   // In case we exited early from the previous loop, there are other types to
7320   // read from TypeStr. So we need to read them all to ensure we have the right
7321   // number of arguments in TheCall and if it is not the case, to display a
7322   // better error message.
7323   while (*TypeStr != '\0') {
7324     (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7325     ArgNum++;
7326   }
7327   if (checkArgCount(*this, TheCall, ArgNum))
7328     return true;
7329 
7330   return false;
7331 }
7332 
7333 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
7334 /// This checks that the target supports __builtin_longjmp and
7335 /// that val is a constant 1.
7336 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
7337   if (!Context.getTargetInfo().hasSjLjLowering())
7338     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
7339            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7340 
7341   Expr *Arg = TheCall->getArg(1);
7342   llvm::APSInt Result;
7343 
7344   // TODO: This is less than ideal. Overload this to take a value.
7345   if (SemaBuiltinConstantArg(TheCall, 1, Result))
7346     return true;
7347 
7348   if (Result != 1)
7349     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
7350            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
7351 
7352   return false;
7353 }
7354 
7355 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
7356 /// This checks that the target supports __builtin_setjmp.
7357 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
7358   if (!Context.getTargetInfo().hasSjLjLowering())
7359     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
7360            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7361   return false;
7362 }
7363 
7364 namespace {
7365 
7366 class UncoveredArgHandler {
7367   enum { Unknown = -1, AllCovered = -2 };
7368 
7369   signed FirstUncoveredArg = Unknown;
7370   SmallVector<const Expr *, 4> DiagnosticExprs;
7371 
7372 public:
7373   UncoveredArgHandler() = default;
7374 
7375   bool hasUncoveredArg() const {
7376     return (FirstUncoveredArg >= 0);
7377   }
7378 
7379   unsigned getUncoveredArg() const {
7380     assert(hasUncoveredArg() && "no uncovered argument");
7381     return FirstUncoveredArg;
7382   }
7383 
7384   void setAllCovered() {
7385     // A string has been found with all arguments covered, so clear out
7386     // the diagnostics.
7387     DiagnosticExprs.clear();
7388     FirstUncoveredArg = AllCovered;
7389   }
7390 
7391   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
7392     assert(NewFirstUncoveredArg >= 0 && "Outside range");
7393 
7394     // Don't update if a previous string covers all arguments.
7395     if (FirstUncoveredArg == AllCovered)
7396       return;
7397 
7398     // UncoveredArgHandler tracks the highest uncovered argument index
7399     // and with it all the strings that match this index.
7400     if (NewFirstUncoveredArg == FirstUncoveredArg)
7401       DiagnosticExprs.push_back(StrExpr);
7402     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
7403       DiagnosticExprs.clear();
7404       DiagnosticExprs.push_back(StrExpr);
7405       FirstUncoveredArg = NewFirstUncoveredArg;
7406     }
7407   }
7408 
7409   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
7410 };
7411 
7412 enum StringLiteralCheckType {
7413   SLCT_NotALiteral,
7414   SLCT_UncheckedLiteral,
7415   SLCT_CheckedLiteral
7416 };
7417 
7418 } // namespace
7419 
7420 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
7421                                      BinaryOperatorKind BinOpKind,
7422                                      bool AddendIsRight) {
7423   unsigned BitWidth = Offset.getBitWidth();
7424   unsigned AddendBitWidth = Addend.getBitWidth();
7425   // There might be negative interim results.
7426   if (Addend.isUnsigned()) {
7427     Addend = Addend.zext(++AddendBitWidth);
7428     Addend.setIsSigned(true);
7429   }
7430   // Adjust the bit width of the APSInts.
7431   if (AddendBitWidth > BitWidth) {
7432     Offset = Offset.sext(AddendBitWidth);
7433     BitWidth = AddendBitWidth;
7434   } else if (BitWidth > AddendBitWidth) {
7435     Addend = Addend.sext(BitWidth);
7436   }
7437 
7438   bool Ov = false;
7439   llvm::APSInt ResOffset = Offset;
7440   if (BinOpKind == BO_Add)
7441     ResOffset = Offset.sadd_ov(Addend, Ov);
7442   else {
7443     assert(AddendIsRight && BinOpKind == BO_Sub &&
7444            "operator must be add or sub with addend on the right");
7445     ResOffset = Offset.ssub_ov(Addend, Ov);
7446   }
7447 
7448   // We add an offset to a pointer here so we should support an offset as big as
7449   // possible.
7450   if (Ov) {
7451     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
7452            "index (intermediate) result too big");
7453     Offset = Offset.sext(2 * BitWidth);
7454     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
7455     return;
7456   }
7457 
7458   Offset = ResOffset;
7459 }
7460 
7461 namespace {
7462 
7463 // This is a wrapper class around StringLiteral to support offsetted string
7464 // literals as format strings. It takes the offset into account when returning
7465 // the string and its length or the source locations to display notes correctly.
7466 class FormatStringLiteral {
7467   const StringLiteral *FExpr;
7468   int64_t Offset;
7469 
7470  public:
7471   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
7472       : FExpr(fexpr), Offset(Offset) {}
7473 
7474   StringRef getString() const {
7475     return FExpr->getString().drop_front(Offset);
7476   }
7477 
7478   unsigned getByteLength() const {
7479     return FExpr->getByteLength() - getCharByteWidth() * Offset;
7480   }
7481 
7482   unsigned getLength() const { return FExpr->getLength() - Offset; }
7483   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
7484 
7485   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
7486 
7487   QualType getType() const { return FExpr->getType(); }
7488 
7489   bool isAscii() const { return FExpr->isAscii(); }
7490   bool isWide() const { return FExpr->isWide(); }
7491   bool isUTF8() const { return FExpr->isUTF8(); }
7492   bool isUTF16() const { return FExpr->isUTF16(); }
7493   bool isUTF32() const { return FExpr->isUTF32(); }
7494   bool isPascal() const { return FExpr->isPascal(); }
7495 
7496   SourceLocation getLocationOfByte(
7497       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
7498       const TargetInfo &Target, unsigned *StartToken = nullptr,
7499       unsigned *StartTokenByteOffset = nullptr) const {
7500     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
7501                                     StartToken, StartTokenByteOffset);
7502   }
7503 
7504   SourceLocation getBeginLoc() const LLVM_READONLY {
7505     return FExpr->getBeginLoc().getLocWithOffset(Offset);
7506   }
7507 
7508   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
7509 };
7510 
7511 }  // namespace
7512 
7513 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
7514                               const Expr *OrigFormatExpr,
7515                               ArrayRef<const Expr *> Args,
7516                               bool HasVAListArg, unsigned format_idx,
7517                               unsigned firstDataArg,
7518                               Sema::FormatStringType Type,
7519                               bool inFunctionCall,
7520                               Sema::VariadicCallType CallType,
7521                               llvm::SmallBitVector &CheckedVarArgs,
7522                               UncoveredArgHandler &UncoveredArg,
7523                               bool IgnoreStringsWithoutSpecifiers);
7524 
7525 // Determine if an expression is a string literal or constant string.
7526 // If this function returns false on the arguments to a function expecting a
7527 // format string, we will usually need to emit a warning.
7528 // True string literals are then checked by CheckFormatString.
7529 static StringLiteralCheckType
7530 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
7531                       bool HasVAListArg, unsigned format_idx,
7532                       unsigned firstDataArg, Sema::FormatStringType Type,
7533                       Sema::VariadicCallType CallType, bool InFunctionCall,
7534                       llvm::SmallBitVector &CheckedVarArgs,
7535                       UncoveredArgHandler &UncoveredArg,
7536                       llvm::APSInt Offset,
7537                       bool IgnoreStringsWithoutSpecifiers = false) {
7538   if (S.isConstantEvaluated())
7539     return SLCT_NotALiteral;
7540  tryAgain:
7541   assert(Offset.isSigned() && "invalid offset");
7542 
7543   if (E->isTypeDependent() || E->isValueDependent())
7544     return SLCT_NotALiteral;
7545 
7546   E = E->IgnoreParenCasts();
7547 
7548   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
7549     // Technically -Wformat-nonliteral does not warn about this case.
7550     // The behavior of printf and friends in this case is implementation
7551     // dependent.  Ideally if the format string cannot be null then
7552     // it should have a 'nonnull' attribute in the function prototype.
7553     return SLCT_UncheckedLiteral;
7554 
7555   switch (E->getStmtClass()) {
7556   case Stmt::BinaryConditionalOperatorClass:
7557   case Stmt::ConditionalOperatorClass: {
7558     // The expression is a literal if both sub-expressions were, and it was
7559     // completely checked only if both sub-expressions were checked.
7560     const AbstractConditionalOperator *C =
7561         cast<AbstractConditionalOperator>(E);
7562 
7563     // Determine whether it is necessary to check both sub-expressions, for
7564     // example, because the condition expression is a constant that can be
7565     // evaluated at compile time.
7566     bool CheckLeft = true, CheckRight = true;
7567 
7568     bool Cond;
7569     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
7570                                                  S.isConstantEvaluated())) {
7571       if (Cond)
7572         CheckRight = false;
7573       else
7574         CheckLeft = false;
7575     }
7576 
7577     // We need to maintain the offsets for the right and the left hand side
7578     // separately to check if every possible indexed expression is a valid
7579     // string literal. They might have different offsets for different string
7580     // literals in the end.
7581     StringLiteralCheckType Left;
7582     if (!CheckLeft)
7583       Left = SLCT_UncheckedLiteral;
7584     else {
7585       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
7586                                    HasVAListArg, format_idx, firstDataArg,
7587                                    Type, CallType, InFunctionCall,
7588                                    CheckedVarArgs, UncoveredArg, Offset,
7589                                    IgnoreStringsWithoutSpecifiers);
7590       if (Left == SLCT_NotALiteral || !CheckRight) {
7591         return Left;
7592       }
7593     }
7594 
7595     StringLiteralCheckType Right = checkFormatStringExpr(
7596         S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
7597         Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7598         IgnoreStringsWithoutSpecifiers);
7599 
7600     return (CheckLeft && Left < Right) ? Left : Right;
7601   }
7602 
7603   case Stmt::ImplicitCastExprClass:
7604     E = cast<ImplicitCastExpr>(E)->getSubExpr();
7605     goto tryAgain;
7606 
7607   case Stmt::OpaqueValueExprClass:
7608     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
7609       E = src;
7610       goto tryAgain;
7611     }
7612     return SLCT_NotALiteral;
7613 
7614   case Stmt::PredefinedExprClass:
7615     // While __func__, etc., are technically not string literals, they
7616     // cannot contain format specifiers and thus are not a security
7617     // liability.
7618     return SLCT_UncheckedLiteral;
7619 
7620   case Stmt::DeclRefExprClass: {
7621     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7622 
7623     // As an exception, do not flag errors for variables binding to
7624     // const string literals.
7625     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
7626       bool isConstant = false;
7627       QualType T = DR->getType();
7628 
7629       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
7630         isConstant = AT->getElementType().isConstant(S.Context);
7631       } else if (const PointerType *PT = T->getAs<PointerType>()) {
7632         isConstant = T.isConstant(S.Context) &&
7633                      PT->getPointeeType().isConstant(S.Context);
7634       } else if (T->isObjCObjectPointerType()) {
7635         // In ObjC, there is usually no "const ObjectPointer" type,
7636         // so don't check if the pointee type is constant.
7637         isConstant = T.isConstant(S.Context);
7638       }
7639 
7640       if (isConstant) {
7641         if (const Expr *Init = VD->getAnyInitializer()) {
7642           // Look through initializers like const char c[] = { "foo" }
7643           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
7644             if (InitList->isStringLiteralInit())
7645               Init = InitList->getInit(0)->IgnoreParenImpCasts();
7646           }
7647           return checkFormatStringExpr(S, Init, Args,
7648                                        HasVAListArg, format_idx,
7649                                        firstDataArg, Type, CallType,
7650                                        /*InFunctionCall*/ false, CheckedVarArgs,
7651                                        UncoveredArg, Offset);
7652         }
7653       }
7654 
7655       // For vprintf* functions (i.e., HasVAListArg==true), we add a
7656       // special check to see if the format string is a function parameter
7657       // of the function calling the printf function.  If the function
7658       // has an attribute indicating it is a printf-like function, then we
7659       // should suppress warnings concerning non-literals being used in a call
7660       // to a vprintf function.  For example:
7661       //
7662       // void
7663       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
7664       //      va_list ap;
7665       //      va_start(ap, fmt);
7666       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
7667       //      ...
7668       // }
7669       if (HasVAListArg) {
7670         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
7671           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
7672             int PVIndex = PV->getFunctionScopeIndex() + 1;
7673             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
7674               // adjust for implicit parameter
7675               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
7676                 if (MD->isInstance())
7677                   ++PVIndex;
7678               // We also check if the formats are compatible.
7679               // We can't pass a 'scanf' string to a 'printf' function.
7680               if (PVIndex == PVFormat->getFormatIdx() &&
7681                   Type == S.GetFormatStringType(PVFormat))
7682                 return SLCT_UncheckedLiteral;
7683             }
7684           }
7685         }
7686       }
7687     }
7688 
7689     return SLCT_NotALiteral;
7690   }
7691 
7692   case Stmt::CallExprClass:
7693   case Stmt::CXXMemberCallExprClass: {
7694     const CallExpr *CE = cast<CallExpr>(E);
7695     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
7696       bool IsFirst = true;
7697       StringLiteralCheckType CommonResult;
7698       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
7699         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
7700         StringLiteralCheckType Result = checkFormatStringExpr(
7701             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7702             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7703             IgnoreStringsWithoutSpecifiers);
7704         if (IsFirst) {
7705           CommonResult = Result;
7706           IsFirst = false;
7707         }
7708       }
7709       if (!IsFirst)
7710         return CommonResult;
7711 
7712       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
7713         unsigned BuiltinID = FD->getBuiltinID();
7714         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
7715             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
7716           const Expr *Arg = CE->getArg(0);
7717           return checkFormatStringExpr(S, Arg, Args,
7718                                        HasVAListArg, format_idx,
7719                                        firstDataArg, Type, CallType,
7720                                        InFunctionCall, CheckedVarArgs,
7721                                        UncoveredArg, Offset,
7722                                        IgnoreStringsWithoutSpecifiers);
7723         }
7724       }
7725     }
7726 
7727     return SLCT_NotALiteral;
7728   }
7729   case Stmt::ObjCMessageExprClass: {
7730     const auto *ME = cast<ObjCMessageExpr>(E);
7731     if (const auto *MD = ME->getMethodDecl()) {
7732       if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
7733         // As a special case heuristic, if we're using the method -[NSBundle
7734         // localizedStringForKey:value:table:], ignore any key strings that lack
7735         // format specifiers. The idea is that if the key doesn't have any
7736         // format specifiers then its probably just a key to map to the
7737         // localized strings. If it does have format specifiers though, then its
7738         // likely that the text of the key is the format string in the
7739         // programmer's language, and should be checked.
7740         const ObjCInterfaceDecl *IFace;
7741         if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
7742             IFace->getIdentifier()->isStr("NSBundle") &&
7743             MD->getSelector().isKeywordSelector(
7744                 {"localizedStringForKey", "value", "table"})) {
7745           IgnoreStringsWithoutSpecifiers = true;
7746         }
7747 
7748         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
7749         return checkFormatStringExpr(
7750             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7751             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7752             IgnoreStringsWithoutSpecifiers);
7753       }
7754     }
7755 
7756     return SLCT_NotALiteral;
7757   }
7758   case Stmt::ObjCStringLiteralClass:
7759   case Stmt::StringLiteralClass: {
7760     const StringLiteral *StrE = nullptr;
7761 
7762     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
7763       StrE = ObjCFExpr->getString();
7764     else
7765       StrE = cast<StringLiteral>(E);
7766 
7767     if (StrE) {
7768       if (Offset.isNegative() || Offset > StrE->getLength()) {
7769         // TODO: It would be better to have an explicit warning for out of
7770         // bounds literals.
7771         return SLCT_NotALiteral;
7772       }
7773       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
7774       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
7775                         firstDataArg, Type, InFunctionCall, CallType,
7776                         CheckedVarArgs, UncoveredArg,
7777                         IgnoreStringsWithoutSpecifiers);
7778       return SLCT_CheckedLiteral;
7779     }
7780 
7781     return SLCT_NotALiteral;
7782   }
7783   case Stmt::BinaryOperatorClass: {
7784     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
7785 
7786     // A string literal + an int offset is still a string literal.
7787     if (BinOp->isAdditiveOp()) {
7788       Expr::EvalResult LResult, RResult;
7789 
7790       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
7791           LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7792       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
7793           RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7794 
7795       if (LIsInt != RIsInt) {
7796         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
7797 
7798         if (LIsInt) {
7799           if (BinOpKind == BO_Add) {
7800             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
7801             E = BinOp->getRHS();
7802             goto tryAgain;
7803           }
7804         } else {
7805           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
7806           E = BinOp->getLHS();
7807           goto tryAgain;
7808         }
7809       }
7810     }
7811 
7812     return SLCT_NotALiteral;
7813   }
7814   case Stmt::UnaryOperatorClass: {
7815     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
7816     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
7817     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
7818       Expr::EvalResult IndexResult;
7819       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
7820                                        Expr::SE_NoSideEffects,
7821                                        S.isConstantEvaluated())) {
7822         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
7823                    /*RHS is int*/ true);
7824         E = ASE->getBase();
7825         goto tryAgain;
7826       }
7827     }
7828 
7829     return SLCT_NotALiteral;
7830   }
7831 
7832   default:
7833     return SLCT_NotALiteral;
7834   }
7835 }
7836 
7837 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
7838   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
7839       .Case("scanf", FST_Scanf)
7840       .Cases("printf", "printf0", FST_Printf)
7841       .Cases("NSString", "CFString", FST_NSString)
7842       .Case("strftime", FST_Strftime)
7843       .Case("strfmon", FST_Strfmon)
7844       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
7845       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
7846       .Case("os_trace", FST_OSLog)
7847       .Case("os_log", FST_OSLog)
7848       .Default(FST_Unknown);
7849 }
7850 
7851 /// CheckFormatArguments - Check calls to printf and scanf (and similar
7852 /// functions) for correct use of format strings.
7853 /// Returns true if a format string has been fully checked.
7854 bool Sema::CheckFormatArguments(const FormatAttr *Format,
7855                                 ArrayRef<const Expr *> Args,
7856                                 bool IsCXXMember,
7857                                 VariadicCallType CallType,
7858                                 SourceLocation Loc, SourceRange Range,
7859                                 llvm::SmallBitVector &CheckedVarArgs) {
7860   FormatStringInfo FSI;
7861   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
7862     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
7863                                 FSI.FirstDataArg, GetFormatStringType(Format),
7864                                 CallType, Loc, Range, CheckedVarArgs);
7865   return false;
7866 }
7867 
7868 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
7869                                 bool HasVAListArg, unsigned format_idx,
7870                                 unsigned firstDataArg, FormatStringType Type,
7871                                 VariadicCallType CallType,
7872                                 SourceLocation Loc, SourceRange Range,
7873                                 llvm::SmallBitVector &CheckedVarArgs) {
7874   // CHECK: printf/scanf-like function is called with no format string.
7875   if (format_idx >= Args.size()) {
7876     Diag(Loc, diag::warn_missing_format_string) << Range;
7877     return false;
7878   }
7879 
7880   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
7881 
7882   // CHECK: format string is not a string literal.
7883   //
7884   // Dynamically generated format strings are difficult to
7885   // automatically vet at compile time.  Requiring that format strings
7886   // are string literals: (1) permits the checking of format strings by
7887   // the compiler and thereby (2) can practically remove the source of
7888   // many format string exploits.
7889 
7890   // Format string can be either ObjC string (e.g. @"%d") or
7891   // C string (e.g. "%d")
7892   // ObjC string uses the same format specifiers as C string, so we can use
7893   // the same format string checking logic for both ObjC and C strings.
7894   UncoveredArgHandler UncoveredArg;
7895   StringLiteralCheckType CT =
7896       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
7897                             format_idx, firstDataArg, Type, CallType,
7898                             /*IsFunctionCall*/ true, CheckedVarArgs,
7899                             UncoveredArg,
7900                             /*no string offset*/ llvm::APSInt(64, false) = 0);
7901 
7902   // Generate a diagnostic where an uncovered argument is detected.
7903   if (UncoveredArg.hasUncoveredArg()) {
7904     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
7905     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
7906     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
7907   }
7908 
7909   if (CT != SLCT_NotALiteral)
7910     // Literal format string found, check done!
7911     return CT == SLCT_CheckedLiteral;
7912 
7913   // Strftime is particular as it always uses a single 'time' argument,
7914   // so it is safe to pass a non-literal string.
7915   if (Type == FST_Strftime)
7916     return false;
7917 
7918   // Do not emit diag when the string param is a macro expansion and the
7919   // format is either NSString or CFString. This is a hack to prevent
7920   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
7921   // which are usually used in place of NS and CF string literals.
7922   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
7923   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
7924     return false;
7925 
7926   // If there are no arguments specified, warn with -Wformat-security, otherwise
7927   // warn only with -Wformat-nonliteral.
7928   if (Args.size() == firstDataArg) {
7929     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
7930       << OrigFormatExpr->getSourceRange();
7931     switch (Type) {
7932     default:
7933       break;
7934     case FST_Kprintf:
7935     case FST_FreeBSDKPrintf:
7936     case FST_Printf:
7937       Diag(FormatLoc, diag::note_format_security_fixit)
7938         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
7939       break;
7940     case FST_NSString:
7941       Diag(FormatLoc, diag::note_format_security_fixit)
7942         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
7943       break;
7944     }
7945   } else {
7946     Diag(FormatLoc, diag::warn_format_nonliteral)
7947       << OrigFormatExpr->getSourceRange();
7948   }
7949   return false;
7950 }
7951 
7952 namespace {
7953 
7954 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
7955 protected:
7956   Sema &S;
7957   const FormatStringLiteral *FExpr;
7958   const Expr *OrigFormatExpr;
7959   const Sema::FormatStringType FSType;
7960   const unsigned FirstDataArg;
7961   const unsigned NumDataArgs;
7962   const char *Beg; // Start of format string.
7963   const bool HasVAListArg;
7964   ArrayRef<const Expr *> Args;
7965   unsigned FormatIdx;
7966   llvm::SmallBitVector CoveredArgs;
7967   bool usesPositionalArgs = false;
7968   bool atFirstArg = true;
7969   bool inFunctionCall;
7970   Sema::VariadicCallType CallType;
7971   llvm::SmallBitVector &CheckedVarArgs;
7972   UncoveredArgHandler &UncoveredArg;
7973 
7974 public:
7975   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
7976                      const Expr *origFormatExpr,
7977                      const Sema::FormatStringType type, unsigned firstDataArg,
7978                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
7979                      ArrayRef<const Expr *> Args, unsigned formatIdx,
7980                      bool inFunctionCall, Sema::VariadicCallType callType,
7981                      llvm::SmallBitVector &CheckedVarArgs,
7982                      UncoveredArgHandler &UncoveredArg)
7983       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
7984         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
7985         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
7986         inFunctionCall(inFunctionCall), CallType(callType),
7987         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
7988     CoveredArgs.resize(numDataArgs);
7989     CoveredArgs.reset();
7990   }
7991 
7992   void DoneProcessing();
7993 
7994   void HandleIncompleteSpecifier(const char *startSpecifier,
7995                                  unsigned specifierLen) override;
7996 
7997   void HandleInvalidLengthModifier(
7998                            const analyze_format_string::FormatSpecifier &FS,
7999                            const analyze_format_string::ConversionSpecifier &CS,
8000                            const char *startSpecifier, unsigned specifierLen,
8001                            unsigned DiagID);
8002 
8003   void HandleNonStandardLengthModifier(
8004                     const analyze_format_string::FormatSpecifier &FS,
8005                     const char *startSpecifier, unsigned specifierLen);
8006 
8007   void HandleNonStandardConversionSpecifier(
8008                     const analyze_format_string::ConversionSpecifier &CS,
8009                     const char *startSpecifier, unsigned specifierLen);
8010 
8011   void HandlePosition(const char *startPos, unsigned posLen) override;
8012 
8013   void HandleInvalidPosition(const char *startSpecifier,
8014                              unsigned specifierLen,
8015                              analyze_format_string::PositionContext p) override;
8016 
8017   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
8018 
8019   void HandleNullChar(const char *nullCharacter) override;
8020 
8021   template <typename Range>
8022   static void
8023   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
8024                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
8025                        bool IsStringLocation, Range StringRange,
8026                        ArrayRef<FixItHint> Fixit = None);
8027 
8028 protected:
8029   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
8030                                         const char *startSpec,
8031                                         unsigned specifierLen,
8032                                         const char *csStart, unsigned csLen);
8033 
8034   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
8035                                          const char *startSpec,
8036                                          unsigned specifierLen);
8037 
8038   SourceRange getFormatStringRange();
8039   CharSourceRange getSpecifierRange(const char *startSpecifier,
8040                                     unsigned specifierLen);
8041   SourceLocation getLocationOfByte(const char *x);
8042 
8043   const Expr *getDataArg(unsigned i) const;
8044 
8045   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
8046                     const analyze_format_string::ConversionSpecifier &CS,
8047                     const char *startSpecifier, unsigned specifierLen,
8048                     unsigned argIndex);
8049 
8050   template <typename Range>
8051   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
8052                             bool IsStringLocation, Range StringRange,
8053                             ArrayRef<FixItHint> Fixit = None);
8054 };
8055 
8056 } // namespace
8057 
8058 SourceRange CheckFormatHandler::getFormatStringRange() {
8059   return OrigFormatExpr->getSourceRange();
8060 }
8061 
8062 CharSourceRange CheckFormatHandler::
8063 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
8064   SourceLocation Start = getLocationOfByte(startSpecifier);
8065   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
8066 
8067   // Advance the end SourceLocation by one due to half-open ranges.
8068   End = End.getLocWithOffset(1);
8069 
8070   return CharSourceRange::getCharRange(Start, End);
8071 }
8072 
8073 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
8074   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
8075                                   S.getLangOpts(), S.Context.getTargetInfo());
8076 }
8077 
8078 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
8079                                                    unsigned specifierLen){
8080   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
8081                        getLocationOfByte(startSpecifier),
8082                        /*IsStringLocation*/true,
8083                        getSpecifierRange(startSpecifier, specifierLen));
8084 }
8085 
8086 void CheckFormatHandler::HandleInvalidLengthModifier(
8087     const analyze_format_string::FormatSpecifier &FS,
8088     const analyze_format_string::ConversionSpecifier &CS,
8089     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
8090   using namespace analyze_format_string;
8091 
8092   const LengthModifier &LM = FS.getLengthModifier();
8093   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8094 
8095   // See if we know how to fix this length modifier.
8096   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8097   if (FixedLM) {
8098     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8099                          getLocationOfByte(LM.getStart()),
8100                          /*IsStringLocation*/true,
8101                          getSpecifierRange(startSpecifier, specifierLen));
8102 
8103     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8104       << FixedLM->toString()
8105       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8106 
8107   } else {
8108     FixItHint Hint;
8109     if (DiagID == diag::warn_format_nonsensical_length)
8110       Hint = FixItHint::CreateRemoval(LMRange);
8111 
8112     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8113                          getLocationOfByte(LM.getStart()),
8114                          /*IsStringLocation*/true,
8115                          getSpecifierRange(startSpecifier, specifierLen),
8116                          Hint);
8117   }
8118 }
8119 
8120 void CheckFormatHandler::HandleNonStandardLengthModifier(
8121     const analyze_format_string::FormatSpecifier &FS,
8122     const char *startSpecifier, unsigned specifierLen) {
8123   using namespace analyze_format_string;
8124 
8125   const LengthModifier &LM = FS.getLengthModifier();
8126   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8127 
8128   // See if we know how to fix this length modifier.
8129   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8130   if (FixedLM) {
8131     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8132                            << LM.toString() << 0,
8133                          getLocationOfByte(LM.getStart()),
8134                          /*IsStringLocation*/true,
8135                          getSpecifierRange(startSpecifier, specifierLen));
8136 
8137     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8138       << FixedLM->toString()
8139       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8140 
8141   } else {
8142     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8143                            << LM.toString() << 0,
8144                          getLocationOfByte(LM.getStart()),
8145                          /*IsStringLocation*/true,
8146                          getSpecifierRange(startSpecifier, specifierLen));
8147   }
8148 }
8149 
8150 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
8151     const analyze_format_string::ConversionSpecifier &CS,
8152     const char *startSpecifier, unsigned specifierLen) {
8153   using namespace analyze_format_string;
8154 
8155   // See if we know how to fix this conversion specifier.
8156   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
8157   if (FixedCS) {
8158     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8159                           << CS.toString() << /*conversion specifier*/1,
8160                          getLocationOfByte(CS.getStart()),
8161                          /*IsStringLocation*/true,
8162                          getSpecifierRange(startSpecifier, specifierLen));
8163 
8164     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
8165     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
8166       << FixedCS->toString()
8167       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
8168   } else {
8169     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8170                           << CS.toString() << /*conversion specifier*/1,
8171                          getLocationOfByte(CS.getStart()),
8172                          /*IsStringLocation*/true,
8173                          getSpecifierRange(startSpecifier, specifierLen));
8174   }
8175 }
8176 
8177 void CheckFormatHandler::HandlePosition(const char *startPos,
8178                                         unsigned posLen) {
8179   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
8180                                getLocationOfByte(startPos),
8181                                /*IsStringLocation*/true,
8182                                getSpecifierRange(startPos, posLen));
8183 }
8184 
8185 void
8186 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
8187                                      analyze_format_string::PositionContext p) {
8188   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
8189                          << (unsigned) p,
8190                        getLocationOfByte(startPos), /*IsStringLocation*/true,
8191                        getSpecifierRange(startPos, posLen));
8192 }
8193 
8194 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
8195                                             unsigned posLen) {
8196   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
8197                                getLocationOfByte(startPos),
8198                                /*IsStringLocation*/true,
8199                                getSpecifierRange(startPos, posLen));
8200 }
8201 
8202 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
8203   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
8204     // The presence of a null character is likely an error.
8205     EmitFormatDiagnostic(
8206       S.PDiag(diag::warn_printf_format_string_contains_null_char),
8207       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
8208       getFormatStringRange());
8209   }
8210 }
8211 
8212 // Note that this may return NULL if there was an error parsing or building
8213 // one of the argument expressions.
8214 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
8215   return Args[FirstDataArg + i];
8216 }
8217 
8218 void CheckFormatHandler::DoneProcessing() {
8219   // Does the number of data arguments exceed the number of
8220   // format conversions in the format string?
8221   if (!HasVAListArg) {
8222       // Find any arguments that weren't covered.
8223     CoveredArgs.flip();
8224     signed notCoveredArg = CoveredArgs.find_first();
8225     if (notCoveredArg >= 0) {
8226       assert((unsigned)notCoveredArg < NumDataArgs);
8227       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
8228     } else {
8229       UncoveredArg.setAllCovered();
8230     }
8231   }
8232 }
8233 
8234 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
8235                                    const Expr *ArgExpr) {
8236   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
8237          "Invalid state");
8238 
8239   if (!ArgExpr)
8240     return;
8241 
8242   SourceLocation Loc = ArgExpr->getBeginLoc();
8243 
8244   if (S.getSourceManager().isInSystemMacro(Loc))
8245     return;
8246 
8247   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
8248   for (auto E : DiagnosticExprs)
8249     PDiag << E->getSourceRange();
8250 
8251   CheckFormatHandler::EmitFormatDiagnostic(
8252                                   S, IsFunctionCall, DiagnosticExprs[0],
8253                                   PDiag, Loc, /*IsStringLocation*/false,
8254                                   DiagnosticExprs[0]->getSourceRange());
8255 }
8256 
8257 bool
8258 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
8259                                                      SourceLocation Loc,
8260                                                      const char *startSpec,
8261                                                      unsigned specifierLen,
8262                                                      const char *csStart,
8263                                                      unsigned csLen) {
8264   bool keepGoing = true;
8265   if (argIndex < NumDataArgs) {
8266     // Consider the argument coverered, even though the specifier doesn't
8267     // make sense.
8268     CoveredArgs.set(argIndex);
8269   }
8270   else {
8271     // If argIndex exceeds the number of data arguments we
8272     // don't issue a warning because that is just a cascade of warnings (and
8273     // they may have intended '%%' anyway). We don't want to continue processing
8274     // the format string after this point, however, as we will like just get
8275     // gibberish when trying to match arguments.
8276     keepGoing = false;
8277   }
8278 
8279   StringRef Specifier(csStart, csLen);
8280 
8281   // If the specifier in non-printable, it could be the first byte of a UTF-8
8282   // sequence. In that case, print the UTF-8 code point. If not, print the byte
8283   // hex value.
8284   std::string CodePointStr;
8285   if (!llvm::sys::locale::isPrint(*csStart)) {
8286     llvm::UTF32 CodePoint;
8287     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
8288     const llvm::UTF8 *E =
8289         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
8290     llvm::ConversionResult Result =
8291         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
8292 
8293     if (Result != llvm::conversionOK) {
8294       unsigned char FirstChar = *csStart;
8295       CodePoint = (llvm::UTF32)FirstChar;
8296     }
8297 
8298     llvm::raw_string_ostream OS(CodePointStr);
8299     if (CodePoint < 256)
8300       OS << "\\x" << llvm::format("%02x", CodePoint);
8301     else if (CodePoint <= 0xFFFF)
8302       OS << "\\u" << llvm::format("%04x", CodePoint);
8303     else
8304       OS << "\\U" << llvm::format("%08x", CodePoint);
8305     OS.flush();
8306     Specifier = CodePointStr;
8307   }
8308 
8309   EmitFormatDiagnostic(
8310       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
8311       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
8312 
8313   return keepGoing;
8314 }
8315 
8316 void
8317 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
8318                                                       const char *startSpec,
8319                                                       unsigned specifierLen) {
8320   EmitFormatDiagnostic(
8321     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
8322     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
8323 }
8324 
8325 bool
8326 CheckFormatHandler::CheckNumArgs(
8327   const analyze_format_string::FormatSpecifier &FS,
8328   const analyze_format_string::ConversionSpecifier &CS,
8329   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
8330 
8331   if (argIndex >= NumDataArgs) {
8332     PartialDiagnostic PDiag = FS.usesPositionalArg()
8333       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
8334            << (argIndex+1) << NumDataArgs)
8335       : S.PDiag(diag::warn_printf_insufficient_data_args);
8336     EmitFormatDiagnostic(
8337       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
8338       getSpecifierRange(startSpecifier, specifierLen));
8339 
8340     // Since more arguments than conversion tokens are given, by extension
8341     // all arguments are covered, so mark this as so.
8342     UncoveredArg.setAllCovered();
8343     return false;
8344   }
8345   return true;
8346 }
8347 
8348 template<typename Range>
8349 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
8350                                               SourceLocation Loc,
8351                                               bool IsStringLocation,
8352                                               Range StringRange,
8353                                               ArrayRef<FixItHint> FixIt) {
8354   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
8355                        Loc, IsStringLocation, StringRange, FixIt);
8356 }
8357 
8358 /// If the format string is not within the function call, emit a note
8359 /// so that the function call and string are in diagnostic messages.
8360 ///
8361 /// \param InFunctionCall if true, the format string is within the function
8362 /// call and only one diagnostic message will be produced.  Otherwise, an
8363 /// extra note will be emitted pointing to location of the format string.
8364 ///
8365 /// \param ArgumentExpr the expression that is passed as the format string
8366 /// argument in the function call.  Used for getting locations when two
8367 /// diagnostics are emitted.
8368 ///
8369 /// \param PDiag the callee should already have provided any strings for the
8370 /// diagnostic message.  This function only adds locations and fixits
8371 /// to diagnostics.
8372 ///
8373 /// \param Loc primary location for diagnostic.  If two diagnostics are
8374 /// required, one will be at Loc and a new SourceLocation will be created for
8375 /// the other one.
8376 ///
8377 /// \param IsStringLocation if true, Loc points to the format string should be
8378 /// used for the note.  Otherwise, Loc points to the argument list and will
8379 /// be used with PDiag.
8380 ///
8381 /// \param StringRange some or all of the string to highlight.  This is
8382 /// templated so it can accept either a CharSourceRange or a SourceRange.
8383 ///
8384 /// \param FixIt optional fix it hint for the format string.
8385 template <typename Range>
8386 void CheckFormatHandler::EmitFormatDiagnostic(
8387     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
8388     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
8389     Range StringRange, ArrayRef<FixItHint> FixIt) {
8390   if (InFunctionCall) {
8391     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
8392     D << StringRange;
8393     D << FixIt;
8394   } else {
8395     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
8396       << ArgumentExpr->getSourceRange();
8397 
8398     const Sema::SemaDiagnosticBuilder &Note =
8399       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
8400              diag::note_format_string_defined);
8401 
8402     Note << StringRange;
8403     Note << FixIt;
8404   }
8405 }
8406 
8407 //===--- CHECK: Printf format string checking ------------------------------===//
8408 
8409 namespace {
8410 
8411 class CheckPrintfHandler : public CheckFormatHandler {
8412 public:
8413   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8414                      const Expr *origFormatExpr,
8415                      const Sema::FormatStringType type, unsigned firstDataArg,
8416                      unsigned numDataArgs, bool isObjC, const char *beg,
8417                      bool hasVAListArg, ArrayRef<const Expr *> Args,
8418                      unsigned formatIdx, bool inFunctionCall,
8419                      Sema::VariadicCallType CallType,
8420                      llvm::SmallBitVector &CheckedVarArgs,
8421                      UncoveredArgHandler &UncoveredArg)
8422       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8423                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
8424                            inFunctionCall, CallType, CheckedVarArgs,
8425                            UncoveredArg) {}
8426 
8427   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
8428 
8429   /// Returns true if '%@' specifiers are allowed in the format string.
8430   bool allowsObjCArg() const {
8431     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
8432            FSType == Sema::FST_OSTrace;
8433   }
8434 
8435   bool HandleInvalidPrintfConversionSpecifier(
8436                                       const analyze_printf::PrintfSpecifier &FS,
8437                                       const char *startSpecifier,
8438                                       unsigned specifierLen) override;
8439 
8440   void handleInvalidMaskType(StringRef MaskType) override;
8441 
8442   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8443                              const char *startSpecifier,
8444                              unsigned specifierLen) override;
8445   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8446                        const char *StartSpecifier,
8447                        unsigned SpecifierLen,
8448                        const Expr *E);
8449 
8450   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
8451                     const char *startSpecifier, unsigned specifierLen);
8452   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
8453                            const analyze_printf::OptionalAmount &Amt,
8454                            unsigned type,
8455                            const char *startSpecifier, unsigned specifierLen);
8456   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8457                   const analyze_printf::OptionalFlag &flag,
8458                   const char *startSpecifier, unsigned specifierLen);
8459   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
8460                          const analyze_printf::OptionalFlag &ignoredFlag,
8461                          const analyze_printf::OptionalFlag &flag,
8462                          const char *startSpecifier, unsigned specifierLen);
8463   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
8464                            const Expr *E);
8465 
8466   void HandleEmptyObjCModifierFlag(const char *startFlag,
8467                                    unsigned flagLen) override;
8468 
8469   void HandleInvalidObjCModifierFlag(const char *startFlag,
8470                                             unsigned flagLen) override;
8471 
8472   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
8473                                            const char *flagsEnd,
8474                                            const char *conversionPosition)
8475                                              override;
8476 };
8477 
8478 } // namespace
8479 
8480 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
8481                                       const analyze_printf::PrintfSpecifier &FS,
8482                                       const char *startSpecifier,
8483                                       unsigned specifierLen) {
8484   const analyze_printf::PrintfConversionSpecifier &CS =
8485     FS.getConversionSpecifier();
8486 
8487   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8488                                           getLocationOfByte(CS.getStart()),
8489                                           startSpecifier, specifierLen,
8490                                           CS.getStart(), CS.getLength());
8491 }
8492 
8493 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
8494   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
8495 }
8496 
8497 bool CheckPrintfHandler::HandleAmount(
8498                                const analyze_format_string::OptionalAmount &Amt,
8499                                unsigned k, const char *startSpecifier,
8500                                unsigned specifierLen) {
8501   if (Amt.hasDataArgument()) {
8502     if (!HasVAListArg) {
8503       unsigned argIndex = Amt.getArgIndex();
8504       if (argIndex >= NumDataArgs) {
8505         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
8506                                << k,
8507                              getLocationOfByte(Amt.getStart()),
8508                              /*IsStringLocation*/true,
8509                              getSpecifierRange(startSpecifier, specifierLen));
8510         // Don't do any more checking.  We will just emit
8511         // spurious errors.
8512         return false;
8513       }
8514 
8515       // Type check the data argument.  It should be an 'int'.
8516       // Although not in conformance with C99, we also allow the argument to be
8517       // an 'unsigned int' as that is a reasonably safe case.  GCC also
8518       // doesn't emit a warning for that case.
8519       CoveredArgs.set(argIndex);
8520       const Expr *Arg = getDataArg(argIndex);
8521       if (!Arg)
8522         return false;
8523 
8524       QualType T = Arg->getType();
8525 
8526       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
8527       assert(AT.isValid());
8528 
8529       if (!AT.matchesType(S.Context, T)) {
8530         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
8531                                << k << AT.getRepresentativeTypeName(S.Context)
8532                                << T << Arg->getSourceRange(),
8533                              getLocationOfByte(Amt.getStart()),
8534                              /*IsStringLocation*/true,
8535                              getSpecifierRange(startSpecifier, specifierLen));
8536         // Don't do any more checking.  We will just emit
8537         // spurious errors.
8538         return false;
8539       }
8540     }
8541   }
8542   return true;
8543 }
8544 
8545 void CheckPrintfHandler::HandleInvalidAmount(
8546                                       const analyze_printf::PrintfSpecifier &FS,
8547                                       const analyze_printf::OptionalAmount &Amt,
8548                                       unsigned type,
8549                                       const char *startSpecifier,
8550                                       unsigned specifierLen) {
8551   const analyze_printf::PrintfConversionSpecifier &CS =
8552     FS.getConversionSpecifier();
8553 
8554   FixItHint fixit =
8555     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
8556       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
8557                                  Amt.getConstantLength()))
8558       : FixItHint();
8559 
8560   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
8561                          << type << CS.toString(),
8562                        getLocationOfByte(Amt.getStart()),
8563                        /*IsStringLocation*/true,
8564                        getSpecifierRange(startSpecifier, specifierLen),
8565                        fixit);
8566 }
8567 
8568 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8569                                     const analyze_printf::OptionalFlag &flag,
8570                                     const char *startSpecifier,
8571                                     unsigned specifierLen) {
8572   // Warn about pointless flag with a fixit removal.
8573   const analyze_printf::PrintfConversionSpecifier &CS =
8574     FS.getConversionSpecifier();
8575   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
8576                          << flag.toString() << CS.toString(),
8577                        getLocationOfByte(flag.getPosition()),
8578                        /*IsStringLocation*/true,
8579                        getSpecifierRange(startSpecifier, specifierLen),
8580                        FixItHint::CreateRemoval(
8581                          getSpecifierRange(flag.getPosition(), 1)));
8582 }
8583 
8584 void CheckPrintfHandler::HandleIgnoredFlag(
8585                                 const analyze_printf::PrintfSpecifier &FS,
8586                                 const analyze_printf::OptionalFlag &ignoredFlag,
8587                                 const analyze_printf::OptionalFlag &flag,
8588                                 const char *startSpecifier,
8589                                 unsigned specifierLen) {
8590   // Warn about ignored flag with a fixit removal.
8591   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
8592                          << ignoredFlag.toString() << flag.toString(),
8593                        getLocationOfByte(ignoredFlag.getPosition()),
8594                        /*IsStringLocation*/true,
8595                        getSpecifierRange(startSpecifier, specifierLen),
8596                        FixItHint::CreateRemoval(
8597                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
8598 }
8599 
8600 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
8601                                                      unsigned flagLen) {
8602   // Warn about an empty flag.
8603   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
8604                        getLocationOfByte(startFlag),
8605                        /*IsStringLocation*/true,
8606                        getSpecifierRange(startFlag, flagLen));
8607 }
8608 
8609 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
8610                                                        unsigned flagLen) {
8611   // Warn about an invalid flag.
8612   auto Range = getSpecifierRange(startFlag, flagLen);
8613   StringRef flag(startFlag, flagLen);
8614   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
8615                       getLocationOfByte(startFlag),
8616                       /*IsStringLocation*/true,
8617                       Range, FixItHint::CreateRemoval(Range));
8618 }
8619 
8620 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
8621     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
8622     // Warn about using '[...]' without a '@' conversion.
8623     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
8624     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
8625     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
8626                          getLocationOfByte(conversionPosition),
8627                          /*IsStringLocation*/true,
8628                          Range, FixItHint::CreateRemoval(Range));
8629 }
8630 
8631 // Determines if the specified is a C++ class or struct containing
8632 // a member with the specified name and kind (e.g. a CXXMethodDecl named
8633 // "c_str()").
8634 template<typename MemberKind>
8635 static llvm::SmallPtrSet<MemberKind*, 1>
8636 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
8637   const RecordType *RT = Ty->getAs<RecordType>();
8638   llvm::SmallPtrSet<MemberKind*, 1> Results;
8639 
8640   if (!RT)
8641     return Results;
8642   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
8643   if (!RD || !RD->getDefinition())
8644     return Results;
8645 
8646   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
8647                  Sema::LookupMemberName);
8648   R.suppressDiagnostics();
8649 
8650   // We just need to include all members of the right kind turned up by the
8651   // filter, at this point.
8652   if (S.LookupQualifiedName(R, RT->getDecl()))
8653     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8654       NamedDecl *decl = (*I)->getUnderlyingDecl();
8655       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
8656         Results.insert(FK);
8657     }
8658   return Results;
8659 }
8660 
8661 /// Check if we could call '.c_str()' on an object.
8662 ///
8663 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
8664 /// allow the call, or if it would be ambiguous).
8665 bool Sema::hasCStrMethod(const Expr *E) {
8666   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8667 
8668   MethodSet Results =
8669       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
8670   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8671        MI != ME; ++MI)
8672     if ((*MI)->getMinRequiredArguments() == 0)
8673       return true;
8674   return false;
8675 }
8676 
8677 // Check if a (w)string was passed when a (w)char* was needed, and offer a
8678 // better diagnostic if so. AT is assumed to be valid.
8679 // Returns true when a c_str() conversion method is found.
8680 bool CheckPrintfHandler::checkForCStrMembers(
8681     const analyze_printf::ArgType &AT, const Expr *E) {
8682   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8683 
8684   MethodSet Results =
8685       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
8686 
8687   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8688        MI != ME; ++MI) {
8689     const CXXMethodDecl *Method = *MI;
8690     if (Method->getMinRequiredArguments() == 0 &&
8691         AT.matchesType(S.Context, Method->getReturnType())) {
8692       // FIXME: Suggest parens if the expression needs them.
8693       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
8694       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
8695           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
8696       return true;
8697     }
8698   }
8699 
8700   return false;
8701 }
8702 
8703 bool
8704 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
8705                                             &FS,
8706                                           const char *startSpecifier,
8707                                           unsigned specifierLen) {
8708   using namespace analyze_format_string;
8709   using namespace analyze_printf;
8710 
8711   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
8712 
8713   if (FS.consumesDataArgument()) {
8714     if (atFirstArg) {
8715         atFirstArg = false;
8716         usesPositionalArgs = FS.usesPositionalArg();
8717     }
8718     else if (usesPositionalArgs != FS.usesPositionalArg()) {
8719       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8720                                         startSpecifier, specifierLen);
8721       return false;
8722     }
8723   }
8724 
8725   // First check if the field width, precision, and conversion specifier
8726   // have matching data arguments.
8727   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
8728                     startSpecifier, specifierLen)) {
8729     return false;
8730   }
8731 
8732   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
8733                     startSpecifier, specifierLen)) {
8734     return false;
8735   }
8736 
8737   if (!CS.consumesDataArgument()) {
8738     // FIXME: Technically specifying a precision or field width here
8739     // makes no sense.  Worth issuing a warning at some point.
8740     return true;
8741   }
8742 
8743   // Consume the argument.
8744   unsigned argIndex = FS.getArgIndex();
8745   if (argIndex < NumDataArgs) {
8746     // The check to see if the argIndex is valid will come later.
8747     // We set the bit here because we may exit early from this
8748     // function if we encounter some other error.
8749     CoveredArgs.set(argIndex);
8750   }
8751 
8752   // FreeBSD kernel extensions.
8753   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
8754       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
8755     // We need at least two arguments.
8756     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
8757       return false;
8758 
8759     // Claim the second argument.
8760     CoveredArgs.set(argIndex + 1);
8761 
8762     // Type check the first argument (int for %b, pointer for %D)
8763     const Expr *Ex = getDataArg(argIndex);
8764     const analyze_printf::ArgType &AT =
8765       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
8766         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
8767     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
8768       EmitFormatDiagnostic(
8769           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8770               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
8771               << false << Ex->getSourceRange(),
8772           Ex->getBeginLoc(), /*IsStringLocation*/ false,
8773           getSpecifierRange(startSpecifier, specifierLen));
8774 
8775     // Type check the second argument (char * for both %b and %D)
8776     Ex = getDataArg(argIndex + 1);
8777     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
8778     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
8779       EmitFormatDiagnostic(
8780           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8781               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
8782               << false << Ex->getSourceRange(),
8783           Ex->getBeginLoc(), /*IsStringLocation*/ false,
8784           getSpecifierRange(startSpecifier, specifierLen));
8785 
8786      return true;
8787   }
8788 
8789   // Check for using an Objective-C specific conversion specifier
8790   // in a non-ObjC literal.
8791   if (!allowsObjCArg() && CS.isObjCArg()) {
8792     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8793                                                   specifierLen);
8794   }
8795 
8796   // %P can only be used with os_log.
8797   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
8798     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8799                                                   specifierLen);
8800   }
8801 
8802   // %n is not allowed with os_log.
8803   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
8804     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
8805                          getLocationOfByte(CS.getStart()),
8806                          /*IsStringLocation*/ false,
8807                          getSpecifierRange(startSpecifier, specifierLen));
8808 
8809     return true;
8810   }
8811 
8812   // Only scalars are allowed for os_trace.
8813   if (FSType == Sema::FST_OSTrace &&
8814       (CS.getKind() == ConversionSpecifier::PArg ||
8815        CS.getKind() == ConversionSpecifier::sArg ||
8816        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
8817     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8818                                                   specifierLen);
8819   }
8820 
8821   // Check for use of public/private annotation outside of os_log().
8822   if (FSType != Sema::FST_OSLog) {
8823     if (FS.isPublic().isSet()) {
8824       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8825                                << "public",
8826                            getLocationOfByte(FS.isPublic().getPosition()),
8827                            /*IsStringLocation*/ false,
8828                            getSpecifierRange(startSpecifier, specifierLen));
8829     }
8830     if (FS.isPrivate().isSet()) {
8831       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8832                                << "private",
8833                            getLocationOfByte(FS.isPrivate().getPosition()),
8834                            /*IsStringLocation*/ false,
8835                            getSpecifierRange(startSpecifier, specifierLen));
8836     }
8837   }
8838 
8839   // Check for invalid use of field width
8840   if (!FS.hasValidFieldWidth()) {
8841     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
8842         startSpecifier, specifierLen);
8843   }
8844 
8845   // Check for invalid use of precision
8846   if (!FS.hasValidPrecision()) {
8847     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
8848         startSpecifier, specifierLen);
8849   }
8850 
8851   // Precision is mandatory for %P specifier.
8852   if (CS.getKind() == ConversionSpecifier::PArg &&
8853       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
8854     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
8855                          getLocationOfByte(startSpecifier),
8856                          /*IsStringLocation*/ false,
8857                          getSpecifierRange(startSpecifier, specifierLen));
8858   }
8859 
8860   // Check each flag does not conflict with any other component.
8861   if (!FS.hasValidThousandsGroupingPrefix())
8862     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
8863   if (!FS.hasValidLeadingZeros())
8864     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
8865   if (!FS.hasValidPlusPrefix())
8866     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
8867   if (!FS.hasValidSpacePrefix())
8868     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
8869   if (!FS.hasValidAlternativeForm())
8870     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
8871   if (!FS.hasValidLeftJustified())
8872     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
8873 
8874   // Check that flags are not ignored by another flag
8875   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
8876     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
8877         startSpecifier, specifierLen);
8878   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
8879     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
8880             startSpecifier, specifierLen);
8881 
8882   // Check the length modifier is valid with the given conversion specifier.
8883   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8884                                  S.getLangOpts()))
8885     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8886                                 diag::warn_format_nonsensical_length);
8887   else if (!FS.hasStandardLengthModifier())
8888     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8889   else if (!FS.hasStandardLengthConversionCombination())
8890     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8891                                 diag::warn_format_non_standard_conversion_spec);
8892 
8893   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8894     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8895 
8896   // The remaining checks depend on the data arguments.
8897   if (HasVAListArg)
8898     return true;
8899 
8900   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8901     return false;
8902 
8903   const Expr *Arg = getDataArg(argIndex);
8904   if (!Arg)
8905     return true;
8906 
8907   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
8908 }
8909 
8910 static bool requiresParensToAddCast(const Expr *E) {
8911   // FIXME: We should have a general way to reason about operator
8912   // precedence and whether parens are actually needed here.
8913   // Take care of a few common cases where they aren't.
8914   const Expr *Inside = E->IgnoreImpCasts();
8915   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
8916     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
8917 
8918   switch (Inside->getStmtClass()) {
8919   case Stmt::ArraySubscriptExprClass:
8920   case Stmt::CallExprClass:
8921   case Stmt::CharacterLiteralClass:
8922   case Stmt::CXXBoolLiteralExprClass:
8923   case Stmt::DeclRefExprClass:
8924   case Stmt::FloatingLiteralClass:
8925   case Stmt::IntegerLiteralClass:
8926   case Stmt::MemberExprClass:
8927   case Stmt::ObjCArrayLiteralClass:
8928   case Stmt::ObjCBoolLiteralExprClass:
8929   case Stmt::ObjCBoxedExprClass:
8930   case Stmt::ObjCDictionaryLiteralClass:
8931   case Stmt::ObjCEncodeExprClass:
8932   case Stmt::ObjCIvarRefExprClass:
8933   case Stmt::ObjCMessageExprClass:
8934   case Stmt::ObjCPropertyRefExprClass:
8935   case Stmt::ObjCStringLiteralClass:
8936   case Stmt::ObjCSubscriptRefExprClass:
8937   case Stmt::ParenExprClass:
8938   case Stmt::StringLiteralClass:
8939   case Stmt::UnaryOperatorClass:
8940     return false;
8941   default:
8942     return true;
8943   }
8944 }
8945 
8946 static std::pair<QualType, StringRef>
8947 shouldNotPrintDirectly(const ASTContext &Context,
8948                        QualType IntendedTy,
8949                        const Expr *E) {
8950   // Use a 'while' to peel off layers of typedefs.
8951   QualType TyTy = IntendedTy;
8952   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
8953     StringRef Name = UserTy->getDecl()->getName();
8954     QualType CastTy = llvm::StringSwitch<QualType>(Name)
8955       .Case("CFIndex", Context.getNSIntegerType())
8956       .Case("NSInteger", Context.getNSIntegerType())
8957       .Case("NSUInteger", Context.getNSUIntegerType())
8958       .Case("SInt32", Context.IntTy)
8959       .Case("UInt32", Context.UnsignedIntTy)
8960       .Default(QualType());
8961 
8962     if (!CastTy.isNull())
8963       return std::make_pair(CastTy, Name);
8964 
8965     TyTy = UserTy->desugar();
8966   }
8967 
8968   // Strip parens if necessary.
8969   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
8970     return shouldNotPrintDirectly(Context,
8971                                   PE->getSubExpr()->getType(),
8972                                   PE->getSubExpr());
8973 
8974   // If this is a conditional expression, then its result type is constructed
8975   // via usual arithmetic conversions and thus there might be no necessary
8976   // typedef sugar there.  Recurse to operands to check for NSInteger &
8977   // Co. usage condition.
8978   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8979     QualType TrueTy, FalseTy;
8980     StringRef TrueName, FalseName;
8981 
8982     std::tie(TrueTy, TrueName) =
8983       shouldNotPrintDirectly(Context,
8984                              CO->getTrueExpr()->getType(),
8985                              CO->getTrueExpr());
8986     std::tie(FalseTy, FalseName) =
8987       shouldNotPrintDirectly(Context,
8988                              CO->getFalseExpr()->getType(),
8989                              CO->getFalseExpr());
8990 
8991     if (TrueTy == FalseTy)
8992       return std::make_pair(TrueTy, TrueName);
8993     else if (TrueTy.isNull())
8994       return std::make_pair(FalseTy, FalseName);
8995     else if (FalseTy.isNull())
8996       return std::make_pair(TrueTy, TrueName);
8997   }
8998 
8999   return std::make_pair(QualType(), StringRef());
9000 }
9001 
9002 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
9003 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
9004 /// type do not count.
9005 static bool
9006 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
9007   QualType From = ICE->getSubExpr()->getType();
9008   QualType To = ICE->getType();
9009   // It's an integer promotion if the destination type is the promoted
9010   // source type.
9011   if (ICE->getCastKind() == CK_IntegralCast &&
9012       From->isPromotableIntegerType() &&
9013       S.Context.getPromotedIntegerType(From) == To)
9014     return true;
9015   // Look through vector types, since we do default argument promotion for
9016   // those in OpenCL.
9017   if (const auto *VecTy = From->getAs<ExtVectorType>())
9018     From = VecTy->getElementType();
9019   if (const auto *VecTy = To->getAs<ExtVectorType>())
9020     To = VecTy->getElementType();
9021   // It's a floating promotion if the source type is a lower rank.
9022   return ICE->getCastKind() == CK_FloatingCast &&
9023          S.Context.getFloatingTypeOrder(From, To) < 0;
9024 }
9025 
9026 bool
9027 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
9028                                     const char *StartSpecifier,
9029                                     unsigned SpecifierLen,
9030                                     const Expr *E) {
9031   using namespace analyze_format_string;
9032   using namespace analyze_printf;
9033 
9034   // Now type check the data expression that matches the
9035   // format specifier.
9036   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
9037   if (!AT.isValid())
9038     return true;
9039 
9040   QualType ExprTy = E->getType();
9041   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
9042     ExprTy = TET->getUnderlyingExpr()->getType();
9043   }
9044 
9045   // Diagnose attempts to print a boolean value as a character. Unlike other
9046   // -Wformat diagnostics, this is fine from a type perspective, but it still
9047   // doesn't make sense.
9048   if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
9049       E->isKnownToHaveBooleanValue()) {
9050     const CharSourceRange &CSR =
9051         getSpecifierRange(StartSpecifier, SpecifierLen);
9052     SmallString<4> FSString;
9053     llvm::raw_svector_ostream os(FSString);
9054     FS.toString(os);
9055     EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
9056                              << FSString,
9057                          E->getExprLoc(), false, CSR);
9058     return true;
9059   }
9060 
9061   analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
9062   if (Match == analyze_printf::ArgType::Match)
9063     return true;
9064 
9065   // Look through argument promotions for our error message's reported type.
9066   // This includes the integral and floating promotions, but excludes array
9067   // and function pointer decay (seeing that an argument intended to be a
9068   // string has type 'char [6]' is probably more confusing than 'char *') and
9069   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
9070   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
9071     if (isArithmeticArgumentPromotion(S, ICE)) {
9072       E = ICE->getSubExpr();
9073       ExprTy = E->getType();
9074 
9075       // Check if we didn't match because of an implicit cast from a 'char'
9076       // or 'short' to an 'int'.  This is done because printf is a varargs
9077       // function.
9078       if (ICE->getType() == S.Context.IntTy ||
9079           ICE->getType() == S.Context.UnsignedIntTy) {
9080         // All further checking is done on the subexpression
9081         const analyze_printf::ArgType::MatchKind ImplicitMatch =
9082             AT.matchesType(S.Context, ExprTy);
9083         if (ImplicitMatch == analyze_printf::ArgType::Match)
9084           return true;
9085         if (ImplicitMatch == ArgType::NoMatchPedantic ||
9086             ImplicitMatch == ArgType::NoMatchTypeConfusion)
9087           Match = ImplicitMatch;
9088       }
9089     }
9090   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
9091     // Special case for 'a', which has type 'int' in C.
9092     // Note, however, that we do /not/ want to treat multibyte constants like
9093     // 'MooV' as characters! This form is deprecated but still exists. In
9094     // addition, don't treat expressions as of type 'char' if one byte length
9095     // modifier is provided.
9096     if (ExprTy == S.Context.IntTy &&
9097         FS.getLengthModifier().getKind() != LengthModifier::AsChar)
9098       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
9099         ExprTy = S.Context.CharTy;
9100   }
9101 
9102   // Look through enums to their underlying type.
9103   bool IsEnum = false;
9104   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
9105     ExprTy = EnumTy->getDecl()->getIntegerType();
9106     IsEnum = true;
9107   }
9108 
9109   // %C in an Objective-C context prints a unichar, not a wchar_t.
9110   // If the argument is an integer of some kind, believe the %C and suggest
9111   // a cast instead of changing the conversion specifier.
9112   QualType IntendedTy = ExprTy;
9113   if (isObjCContext() &&
9114       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
9115     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
9116         !ExprTy->isCharType()) {
9117       // 'unichar' is defined as a typedef of unsigned short, but we should
9118       // prefer using the typedef if it is visible.
9119       IntendedTy = S.Context.UnsignedShortTy;
9120 
9121       // While we are here, check if the value is an IntegerLiteral that happens
9122       // to be within the valid range.
9123       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
9124         const llvm::APInt &V = IL->getValue();
9125         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
9126           return true;
9127       }
9128 
9129       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
9130                           Sema::LookupOrdinaryName);
9131       if (S.LookupName(Result, S.getCurScope())) {
9132         NamedDecl *ND = Result.getFoundDecl();
9133         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
9134           if (TD->getUnderlyingType() == IntendedTy)
9135             IntendedTy = S.Context.getTypedefType(TD);
9136       }
9137     }
9138   }
9139 
9140   // Special-case some of Darwin's platform-independence types by suggesting
9141   // casts to primitive types that are known to be large enough.
9142   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
9143   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
9144     QualType CastTy;
9145     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
9146     if (!CastTy.isNull()) {
9147       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
9148       // (long in ASTContext). Only complain to pedants.
9149       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
9150           (AT.isSizeT() || AT.isPtrdiffT()) &&
9151           AT.matchesType(S.Context, CastTy))
9152         Match = ArgType::NoMatchPedantic;
9153       IntendedTy = CastTy;
9154       ShouldNotPrintDirectly = true;
9155     }
9156   }
9157 
9158   // We may be able to offer a FixItHint if it is a supported type.
9159   PrintfSpecifier fixedFS = FS;
9160   bool Success =
9161       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
9162 
9163   if (Success) {
9164     // Get the fix string from the fixed format specifier
9165     SmallString<16> buf;
9166     llvm::raw_svector_ostream os(buf);
9167     fixedFS.toString(os);
9168 
9169     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
9170 
9171     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
9172       unsigned Diag;
9173       switch (Match) {
9174       case ArgType::Match: llvm_unreachable("expected non-matching");
9175       case ArgType::NoMatchPedantic:
9176         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9177         break;
9178       case ArgType::NoMatchTypeConfusion:
9179         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9180         break;
9181       case ArgType::NoMatch:
9182         Diag = diag::warn_format_conversion_argument_type_mismatch;
9183         break;
9184       }
9185 
9186       // In this case, the specifier is wrong and should be changed to match
9187       // the argument.
9188       EmitFormatDiagnostic(S.PDiag(Diag)
9189                                << AT.getRepresentativeTypeName(S.Context)
9190                                << IntendedTy << IsEnum << E->getSourceRange(),
9191                            E->getBeginLoc(),
9192                            /*IsStringLocation*/ false, SpecRange,
9193                            FixItHint::CreateReplacement(SpecRange, os.str()));
9194     } else {
9195       // The canonical type for formatting this value is different from the
9196       // actual type of the expression. (This occurs, for example, with Darwin's
9197       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
9198       // should be printed as 'long' for 64-bit compatibility.)
9199       // Rather than emitting a normal format/argument mismatch, we want to
9200       // add a cast to the recommended type (and correct the format string
9201       // if necessary).
9202       SmallString<16> CastBuf;
9203       llvm::raw_svector_ostream CastFix(CastBuf);
9204       CastFix << "(";
9205       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
9206       CastFix << ")";
9207 
9208       SmallVector<FixItHint,4> Hints;
9209       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
9210         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
9211 
9212       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
9213         // If there's already a cast present, just replace it.
9214         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
9215         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
9216 
9217       } else if (!requiresParensToAddCast(E)) {
9218         // If the expression has high enough precedence,
9219         // just write the C-style cast.
9220         Hints.push_back(
9221             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9222       } else {
9223         // Otherwise, add parens around the expression as well as the cast.
9224         CastFix << "(";
9225         Hints.push_back(
9226             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9227 
9228         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
9229         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
9230       }
9231 
9232       if (ShouldNotPrintDirectly) {
9233         // The expression has a type that should not be printed directly.
9234         // We extract the name from the typedef because we don't want to show
9235         // the underlying type in the diagnostic.
9236         StringRef Name;
9237         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
9238           Name = TypedefTy->getDecl()->getName();
9239         else
9240           Name = CastTyName;
9241         unsigned Diag = Match == ArgType::NoMatchPedantic
9242                             ? diag::warn_format_argument_needs_cast_pedantic
9243                             : diag::warn_format_argument_needs_cast;
9244         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
9245                                            << E->getSourceRange(),
9246                              E->getBeginLoc(), /*IsStringLocation=*/false,
9247                              SpecRange, Hints);
9248       } else {
9249         // In this case, the expression could be printed using a different
9250         // specifier, but we've decided that the specifier is probably correct
9251         // and we should cast instead. Just use the normal warning message.
9252         EmitFormatDiagnostic(
9253             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9254                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
9255                 << E->getSourceRange(),
9256             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
9257       }
9258     }
9259   } else {
9260     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
9261                                                    SpecifierLen);
9262     // Since the warning for passing non-POD types to variadic functions
9263     // was deferred until now, we emit a warning for non-POD
9264     // arguments here.
9265     switch (S.isValidVarArgType(ExprTy)) {
9266     case Sema::VAK_Valid:
9267     case Sema::VAK_ValidInCXX11: {
9268       unsigned Diag;
9269       switch (Match) {
9270       case ArgType::Match: llvm_unreachable("expected non-matching");
9271       case ArgType::NoMatchPedantic:
9272         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9273         break;
9274       case ArgType::NoMatchTypeConfusion:
9275         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9276         break;
9277       case ArgType::NoMatch:
9278         Diag = diag::warn_format_conversion_argument_type_mismatch;
9279         break;
9280       }
9281 
9282       EmitFormatDiagnostic(
9283           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
9284                         << IsEnum << CSR << E->getSourceRange(),
9285           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9286       break;
9287     }
9288     case Sema::VAK_Undefined:
9289     case Sema::VAK_MSVCUndefined:
9290       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
9291                                << S.getLangOpts().CPlusPlus11 << ExprTy
9292                                << CallType
9293                                << AT.getRepresentativeTypeName(S.Context) << CSR
9294                                << E->getSourceRange(),
9295                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9296       checkForCStrMembers(AT, E);
9297       break;
9298 
9299     case Sema::VAK_Invalid:
9300       if (ExprTy->isObjCObjectType())
9301         EmitFormatDiagnostic(
9302             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
9303                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9304                 << AT.getRepresentativeTypeName(S.Context) << CSR
9305                 << E->getSourceRange(),
9306             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9307       else
9308         // FIXME: If this is an initializer list, suggest removing the braces
9309         // or inserting a cast to the target type.
9310         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
9311             << isa<InitListExpr>(E) << ExprTy << CallType
9312             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
9313       break;
9314     }
9315 
9316     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
9317            "format string specifier index out of range");
9318     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
9319   }
9320 
9321   return true;
9322 }
9323 
9324 //===--- CHECK: Scanf format string checking ------------------------------===//
9325 
9326 namespace {
9327 
9328 class CheckScanfHandler : public CheckFormatHandler {
9329 public:
9330   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
9331                     const Expr *origFormatExpr, Sema::FormatStringType type,
9332                     unsigned firstDataArg, unsigned numDataArgs,
9333                     const char *beg, bool hasVAListArg,
9334                     ArrayRef<const Expr *> Args, unsigned formatIdx,
9335                     bool inFunctionCall, Sema::VariadicCallType CallType,
9336                     llvm::SmallBitVector &CheckedVarArgs,
9337                     UncoveredArgHandler &UncoveredArg)
9338       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
9339                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
9340                            inFunctionCall, CallType, CheckedVarArgs,
9341                            UncoveredArg) {}
9342 
9343   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
9344                             const char *startSpecifier,
9345                             unsigned specifierLen) override;
9346 
9347   bool HandleInvalidScanfConversionSpecifier(
9348           const analyze_scanf::ScanfSpecifier &FS,
9349           const char *startSpecifier,
9350           unsigned specifierLen) override;
9351 
9352   void HandleIncompleteScanList(const char *start, const char *end) override;
9353 };
9354 
9355 } // namespace
9356 
9357 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
9358                                                  const char *end) {
9359   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
9360                        getLocationOfByte(end), /*IsStringLocation*/true,
9361                        getSpecifierRange(start, end - start));
9362 }
9363 
9364 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
9365                                         const analyze_scanf::ScanfSpecifier &FS,
9366                                         const char *startSpecifier,
9367                                         unsigned specifierLen) {
9368   const analyze_scanf::ScanfConversionSpecifier &CS =
9369     FS.getConversionSpecifier();
9370 
9371   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
9372                                           getLocationOfByte(CS.getStart()),
9373                                           startSpecifier, specifierLen,
9374                                           CS.getStart(), CS.getLength());
9375 }
9376 
9377 bool CheckScanfHandler::HandleScanfSpecifier(
9378                                        const analyze_scanf::ScanfSpecifier &FS,
9379                                        const char *startSpecifier,
9380                                        unsigned specifierLen) {
9381   using namespace analyze_scanf;
9382   using namespace analyze_format_string;
9383 
9384   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
9385 
9386   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
9387   // be used to decide if we are using positional arguments consistently.
9388   if (FS.consumesDataArgument()) {
9389     if (atFirstArg) {
9390       atFirstArg = false;
9391       usesPositionalArgs = FS.usesPositionalArg();
9392     }
9393     else if (usesPositionalArgs != FS.usesPositionalArg()) {
9394       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9395                                         startSpecifier, specifierLen);
9396       return false;
9397     }
9398   }
9399 
9400   // Check if the field with is non-zero.
9401   const OptionalAmount &Amt = FS.getFieldWidth();
9402   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
9403     if (Amt.getConstantAmount() == 0) {
9404       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
9405                                                    Amt.getConstantLength());
9406       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
9407                            getLocationOfByte(Amt.getStart()),
9408                            /*IsStringLocation*/true, R,
9409                            FixItHint::CreateRemoval(R));
9410     }
9411   }
9412 
9413   if (!FS.consumesDataArgument()) {
9414     // FIXME: Technically specifying a precision or field width here
9415     // makes no sense.  Worth issuing a warning at some point.
9416     return true;
9417   }
9418 
9419   // Consume the argument.
9420   unsigned argIndex = FS.getArgIndex();
9421   if (argIndex < NumDataArgs) {
9422       // The check to see if the argIndex is valid will come later.
9423       // We set the bit here because we may exit early from this
9424       // function if we encounter some other error.
9425     CoveredArgs.set(argIndex);
9426   }
9427 
9428   // Check the length modifier is valid with the given conversion specifier.
9429   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
9430                                  S.getLangOpts()))
9431     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9432                                 diag::warn_format_nonsensical_length);
9433   else if (!FS.hasStandardLengthModifier())
9434     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9435   else if (!FS.hasStandardLengthConversionCombination())
9436     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9437                                 diag::warn_format_non_standard_conversion_spec);
9438 
9439   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
9440     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9441 
9442   // The remaining checks depend on the data arguments.
9443   if (HasVAListArg)
9444     return true;
9445 
9446   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9447     return false;
9448 
9449   // Check that the argument type matches the format specifier.
9450   const Expr *Ex = getDataArg(argIndex);
9451   if (!Ex)
9452     return true;
9453 
9454   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
9455 
9456   if (!AT.isValid()) {
9457     return true;
9458   }
9459 
9460   analyze_format_string::ArgType::MatchKind Match =
9461       AT.matchesType(S.Context, Ex->getType());
9462   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
9463   if (Match == analyze_format_string::ArgType::Match)
9464     return true;
9465 
9466   ScanfSpecifier fixedFS = FS;
9467   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
9468                                  S.getLangOpts(), S.Context);
9469 
9470   unsigned Diag =
9471       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9472                : diag::warn_format_conversion_argument_type_mismatch;
9473 
9474   if (Success) {
9475     // Get the fix string from the fixed format specifier.
9476     SmallString<128> buf;
9477     llvm::raw_svector_ostream os(buf);
9478     fixedFS.toString(os);
9479 
9480     EmitFormatDiagnostic(
9481         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
9482                       << Ex->getType() << false << Ex->getSourceRange(),
9483         Ex->getBeginLoc(),
9484         /*IsStringLocation*/ false,
9485         getSpecifierRange(startSpecifier, specifierLen),
9486         FixItHint::CreateReplacement(
9487             getSpecifierRange(startSpecifier, specifierLen), os.str()));
9488   } else {
9489     EmitFormatDiagnostic(S.PDiag(Diag)
9490                              << AT.getRepresentativeTypeName(S.Context)
9491                              << Ex->getType() << false << Ex->getSourceRange(),
9492                          Ex->getBeginLoc(),
9493                          /*IsStringLocation*/ false,
9494                          getSpecifierRange(startSpecifier, specifierLen));
9495   }
9496 
9497   return true;
9498 }
9499 
9500 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
9501                               const Expr *OrigFormatExpr,
9502                               ArrayRef<const Expr *> Args,
9503                               bool HasVAListArg, unsigned format_idx,
9504                               unsigned firstDataArg,
9505                               Sema::FormatStringType Type,
9506                               bool inFunctionCall,
9507                               Sema::VariadicCallType CallType,
9508                               llvm::SmallBitVector &CheckedVarArgs,
9509                               UncoveredArgHandler &UncoveredArg,
9510                               bool IgnoreStringsWithoutSpecifiers) {
9511   // CHECK: is the format string a wide literal?
9512   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
9513     CheckFormatHandler::EmitFormatDiagnostic(
9514         S, inFunctionCall, Args[format_idx],
9515         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
9516         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9517     return;
9518   }
9519 
9520   // Str - The format string.  NOTE: this is NOT null-terminated!
9521   StringRef StrRef = FExpr->getString();
9522   const char *Str = StrRef.data();
9523   // Account for cases where the string literal is truncated in a declaration.
9524   const ConstantArrayType *T =
9525     S.Context.getAsConstantArrayType(FExpr->getType());
9526   assert(T && "String literal not of constant array type!");
9527   size_t TypeSize = T->getSize().getZExtValue();
9528   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9529   const unsigned numDataArgs = Args.size() - firstDataArg;
9530 
9531   if (IgnoreStringsWithoutSpecifiers &&
9532       !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
9533           Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
9534     return;
9535 
9536   // Emit a warning if the string literal is truncated and does not contain an
9537   // embedded null character.
9538   if (TypeSize <= StrRef.size() &&
9539       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
9540     CheckFormatHandler::EmitFormatDiagnostic(
9541         S, inFunctionCall, Args[format_idx],
9542         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
9543         FExpr->getBeginLoc(),
9544         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
9545     return;
9546   }
9547 
9548   // CHECK: empty format string?
9549   if (StrLen == 0 && numDataArgs > 0) {
9550     CheckFormatHandler::EmitFormatDiagnostic(
9551         S, inFunctionCall, Args[format_idx],
9552         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
9553         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9554     return;
9555   }
9556 
9557   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
9558       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
9559       Type == Sema::FST_OSTrace) {
9560     CheckPrintfHandler H(
9561         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
9562         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
9563         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
9564         CheckedVarArgs, UncoveredArg);
9565 
9566     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
9567                                                   S.getLangOpts(),
9568                                                   S.Context.getTargetInfo(),
9569                                             Type == Sema::FST_FreeBSDKPrintf))
9570       H.DoneProcessing();
9571   } else if (Type == Sema::FST_Scanf) {
9572     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9573                         numDataArgs, Str, HasVAListArg, Args, format_idx,
9574                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
9575 
9576     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
9577                                                  S.getLangOpts(),
9578                                                  S.Context.getTargetInfo()))
9579       H.DoneProcessing();
9580   } // TODO: handle other formats
9581 }
9582 
9583 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
9584   // Str - The format string.  NOTE: this is NOT null-terminated!
9585   StringRef StrRef = FExpr->getString();
9586   const char *Str = StrRef.data();
9587   // Account for cases where the string literal is truncated in a declaration.
9588   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
9589   assert(T && "String literal not of constant array type!");
9590   size_t TypeSize = T->getSize().getZExtValue();
9591   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9592   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
9593                                                          getLangOpts(),
9594                                                          Context.getTargetInfo());
9595 }
9596 
9597 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
9598 
9599 // Returns the related absolute value function that is larger, of 0 if one
9600 // does not exist.
9601 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
9602   switch (AbsFunction) {
9603   default:
9604     return 0;
9605 
9606   case Builtin::BI__builtin_abs:
9607     return Builtin::BI__builtin_labs;
9608   case Builtin::BI__builtin_labs:
9609     return Builtin::BI__builtin_llabs;
9610   case Builtin::BI__builtin_llabs:
9611     return 0;
9612 
9613   case Builtin::BI__builtin_fabsf:
9614     return Builtin::BI__builtin_fabs;
9615   case Builtin::BI__builtin_fabs:
9616     return Builtin::BI__builtin_fabsl;
9617   case Builtin::BI__builtin_fabsl:
9618     return 0;
9619 
9620   case Builtin::BI__builtin_cabsf:
9621     return Builtin::BI__builtin_cabs;
9622   case Builtin::BI__builtin_cabs:
9623     return Builtin::BI__builtin_cabsl;
9624   case Builtin::BI__builtin_cabsl:
9625     return 0;
9626 
9627   case Builtin::BIabs:
9628     return Builtin::BIlabs;
9629   case Builtin::BIlabs:
9630     return Builtin::BIllabs;
9631   case Builtin::BIllabs:
9632     return 0;
9633 
9634   case Builtin::BIfabsf:
9635     return Builtin::BIfabs;
9636   case Builtin::BIfabs:
9637     return Builtin::BIfabsl;
9638   case Builtin::BIfabsl:
9639     return 0;
9640 
9641   case Builtin::BIcabsf:
9642    return Builtin::BIcabs;
9643   case Builtin::BIcabs:
9644     return Builtin::BIcabsl;
9645   case Builtin::BIcabsl:
9646     return 0;
9647   }
9648 }
9649 
9650 // Returns the argument type of the absolute value function.
9651 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
9652                                              unsigned AbsType) {
9653   if (AbsType == 0)
9654     return QualType();
9655 
9656   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
9657   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
9658   if (Error != ASTContext::GE_None)
9659     return QualType();
9660 
9661   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
9662   if (!FT)
9663     return QualType();
9664 
9665   if (FT->getNumParams() != 1)
9666     return QualType();
9667 
9668   return FT->getParamType(0);
9669 }
9670 
9671 // Returns the best absolute value function, or zero, based on type and
9672 // current absolute value function.
9673 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
9674                                    unsigned AbsFunctionKind) {
9675   unsigned BestKind = 0;
9676   uint64_t ArgSize = Context.getTypeSize(ArgType);
9677   for (unsigned Kind = AbsFunctionKind; Kind != 0;
9678        Kind = getLargerAbsoluteValueFunction(Kind)) {
9679     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
9680     if (Context.getTypeSize(ParamType) >= ArgSize) {
9681       if (BestKind == 0)
9682         BestKind = Kind;
9683       else if (Context.hasSameType(ParamType, ArgType)) {
9684         BestKind = Kind;
9685         break;
9686       }
9687     }
9688   }
9689   return BestKind;
9690 }
9691 
9692 enum AbsoluteValueKind {
9693   AVK_Integer,
9694   AVK_Floating,
9695   AVK_Complex
9696 };
9697 
9698 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
9699   if (T->isIntegralOrEnumerationType())
9700     return AVK_Integer;
9701   if (T->isRealFloatingType())
9702     return AVK_Floating;
9703   if (T->isAnyComplexType())
9704     return AVK_Complex;
9705 
9706   llvm_unreachable("Type not integer, floating, or complex");
9707 }
9708 
9709 // Changes the absolute value function to a different type.  Preserves whether
9710 // the function is a builtin.
9711 static unsigned changeAbsFunction(unsigned AbsKind,
9712                                   AbsoluteValueKind ValueKind) {
9713   switch (ValueKind) {
9714   case AVK_Integer:
9715     switch (AbsKind) {
9716     default:
9717       return 0;
9718     case Builtin::BI__builtin_fabsf:
9719     case Builtin::BI__builtin_fabs:
9720     case Builtin::BI__builtin_fabsl:
9721     case Builtin::BI__builtin_cabsf:
9722     case Builtin::BI__builtin_cabs:
9723     case Builtin::BI__builtin_cabsl:
9724       return Builtin::BI__builtin_abs;
9725     case Builtin::BIfabsf:
9726     case Builtin::BIfabs:
9727     case Builtin::BIfabsl:
9728     case Builtin::BIcabsf:
9729     case Builtin::BIcabs:
9730     case Builtin::BIcabsl:
9731       return Builtin::BIabs;
9732     }
9733   case AVK_Floating:
9734     switch (AbsKind) {
9735     default:
9736       return 0;
9737     case Builtin::BI__builtin_abs:
9738     case Builtin::BI__builtin_labs:
9739     case Builtin::BI__builtin_llabs:
9740     case Builtin::BI__builtin_cabsf:
9741     case Builtin::BI__builtin_cabs:
9742     case Builtin::BI__builtin_cabsl:
9743       return Builtin::BI__builtin_fabsf;
9744     case Builtin::BIabs:
9745     case Builtin::BIlabs:
9746     case Builtin::BIllabs:
9747     case Builtin::BIcabsf:
9748     case Builtin::BIcabs:
9749     case Builtin::BIcabsl:
9750       return Builtin::BIfabsf;
9751     }
9752   case AVK_Complex:
9753     switch (AbsKind) {
9754     default:
9755       return 0;
9756     case Builtin::BI__builtin_abs:
9757     case Builtin::BI__builtin_labs:
9758     case Builtin::BI__builtin_llabs:
9759     case Builtin::BI__builtin_fabsf:
9760     case Builtin::BI__builtin_fabs:
9761     case Builtin::BI__builtin_fabsl:
9762       return Builtin::BI__builtin_cabsf;
9763     case Builtin::BIabs:
9764     case Builtin::BIlabs:
9765     case Builtin::BIllabs:
9766     case Builtin::BIfabsf:
9767     case Builtin::BIfabs:
9768     case Builtin::BIfabsl:
9769       return Builtin::BIcabsf;
9770     }
9771   }
9772   llvm_unreachable("Unable to convert function");
9773 }
9774 
9775 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
9776   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
9777   if (!FnInfo)
9778     return 0;
9779 
9780   switch (FDecl->getBuiltinID()) {
9781   default:
9782     return 0;
9783   case Builtin::BI__builtin_abs:
9784   case Builtin::BI__builtin_fabs:
9785   case Builtin::BI__builtin_fabsf:
9786   case Builtin::BI__builtin_fabsl:
9787   case Builtin::BI__builtin_labs:
9788   case Builtin::BI__builtin_llabs:
9789   case Builtin::BI__builtin_cabs:
9790   case Builtin::BI__builtin_cabsf:
9791   case Builtin::BI__builtin_cabsl:
9792   case Builtin::BIabs:
9793   case Builtin::BIlabs:
9794   case Builtin::BIllabs:
9795   case Builtin::BIfabs:
9796   case Builtin::BIfabsf:
9797   case Builtin::BIfabsl:
9798   case Builtin::BIcabs:
9799   case Builtin::BIcabsf:
9800   case Builtin::BIcabsl:
9801     return FDecl->getBuiltinID();
9802   }
9803   llvm_unreachable("Unknown Builtin type");
9804 }
9805 
9806 // If the replacement is valid, emit a note with replacement function.
9807 // Additionally, suggest including the proper header if not already included.
9808 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
9809                             unsigned AbsKind, QualType ArgType) {
9810   bool EmitHeaderHint = true;
9811   const char *HeaderName = nullptr;
9812   const char *FunctionName = nullptr;
9813   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
9814     FunctionName = "std::abs";
9815     if (ArgType->isIntegralOrEnumerationType()) {
9816       HeaderName = "cstdlib";
9817     } else if (ArgType->isRealFloatingType()) {
9818       HeaderName = "cmath";
9819     } else {
9820       llvm_unreachable("Invalid Type");
9821     }
9822 
9823     // Lookup all std::abs
9824     if (NamespaceDecl *Std = S.getStdNamespace()) {
9825       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
9826       R.suppressDiagnostics();
9827       S.LookupQualifiedName(R, Std);
9828 
9829       for (const auto *I : R) {
9830         const FunctionDecl *FDecl = nullptr;
9831         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
9832           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
9833         } else {
9834           FDecl = dyn_cast<FunctionDecl>(I);
9835         }
9836         if (!FDecl)
9837           continue;
9838 
9839         // Found std::abs(), check that they are the right ones.
9840         if (FDecl->getNumParams() != 1)
9841           continue;
9842 
9843         // Check that the parameter type can handle the argument.
9844         QualType ParamType = FDecl->getParamDecl(0)->getType();
9845         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
9846             S.Context.getTypeSize(ArgType) <=
9847                 S.Context.getTypeSize(ParamType)) {
9848           // Found a function, don't need the header hint.
9849           EmitHeaderHint = false;
9850           break;
9851         }
9852       }
9853     }
9854   } else {
9855     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
9856     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
9857 
9858     if (HeaderName) {
9859       DeclarationName DN(&S.Context.Idents.get(FunctionName));
9860       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
9861       R.suppressDiagnostics();
9862       S.LookupName(R, S.getCurScope());
9863 
9864       if (R.isSingleResult()) {
9865         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
9866         if (FD && FD->getBuiltinID() == AbsKind) {
9867           EmitHeaderHint = false;
9868         } else {
9869           return;
9870         }
9871       } else if (!R.empty()) {
9872         return;
9873       }
9874     }
9875   }
9876 
9877   S.Diag(Loc, diag::note_replace_abs_function)
9878       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
9879 
9880   if (!HeaderName)
9881     return;
9882 
9883   if (!EmitHeaderHint)
9884     return;
9885 
9886   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
9887                                                     << FunctionName;
9888 }
9889 
9890 template <std::size_t StrLen>
9891 static bool IsStdFunction(const FunctionDecl *FDecl,
9892                           const char (&Str)[StrLen]) {
9893   if (!FDecl)
9894     return false;
9895   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
9896     return false;
9897   if (!FDecl->isInStdNamespace())
9898     return false;
9899 
9900   return true;
9901 }
9902 
9903 // Warn when using the wrong abs() function.
9904 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
9905                                       const FunctionDecl *FDecl) {
9906   if (Call->getNumArgs() != 1)
9907     return;
9908 
9909   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
9910   bool IsStdAbs = IsStdFunction(FDecl, "abs");
9911   if (AbsKind == 0 && !IsStdAbs)
9912     return;
9913 
9914   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9915   QualType ParamType = Call->getArg(0)->getType();
9916 
9917   // Unsigned types cannot be negative.  Suggest removing the absolute value
9918   // function call.
9919   if (ArgType->isUnsignedIntegerType()) {
9920     const char *FunctionName =
9921         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
9922     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
9923     Diag(Call->getExprLoc(), diag::note_remove_abs)
9924         << FunctionName
9925         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
9926     return;
9927   }
9928 
9929   // Taking the absolute value of a pointer is very suspicious, they probably
9930   // wanted to index into an array, dereference a pointer, call a function, etc.
9931   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
9932     unsigned DiagType = 0;
9933     if (ArgType->isFunctionType())
9934       DiagType = 1;
9935     else if (ArgType->isArrayType())
9936       DiagType = 2;
9937 
9938     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
9939     return;
9940   }
9941 
9942   // std::abs has overloads which prevent most of the absolute value problems
9943   // from occurring.
9944   if (IsStdAbs)
9945     return;
9946 
9947   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
9948   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
9949 
9950   // The argument and parameter are the same kind.  Check if they are the right
9951   // size.
9952   if (ArgValueKind == ParamValueKind) {
9953     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
9954       return;
9955 
9956     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
9957     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
9958         << FDecl << ArgType << ParamType;
9959 
9960     if (NewAbsKind == 0)
9961       return;
9962 
9963     emitReplacement(*this, Call->getExprLoc(),
9964                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9965     return;
9966   }
9967 
9968   // ArgValueKind != ParamValueKind
9969   // The wrong type of absolute value function was used.  Attempt to find the
9970   // proper one.
9971   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
9972   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
9973   if (NewAbsKind == 0)
9974     return;
9975 
9976   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
9977       << FDecl << ParamValueKind << ArgValueKind;
9978 
9979   emitReplacement(*this, Call->getExprLoc(),
9980                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9981 }
9982 
9983 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
9984 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
9985                                 const FunctionDecl *FDecl) {
9986   if (!Call || !FDecl) return;
9987 
9988   // Ignore template specializations and macros.
9989   if (inTemplateInstantiation()) return;
9990   if (Call->getExprLoc().isMacroID()) return;
9991 
9992   // Only care about the one template argument, two function parameter std::max
9993   if (Call->getNumArgs() != 2) return;
9994   if (!IsStdFunction(FDecl, "max")) return;
9995   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
9996   if (!ArgList) return;
9997   if (ArgList->size() != 1) return;
9998 
9999   // Check that template type argument is unsigned integer.
10000   const auto& TA = ArgList->get(0);
10001   if (TA.getKind() != TemplateArgument::Type) return;
10002   QualType ArgType = TA.getAsType();
10003   if (!ArgType->isUnsignedIntegerType()) return;
10004 
10005   // See if either argument is a literal zero.
10006   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
10007     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
10008     if (!MTE) return false;
10009     const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
10010     if (!Num) return false;
10011     if (Num->getValue() != 0) return false;
10012     return true;
10013   };
10014 
10015   const Expr *FirstArg = Call->getArg(0);
10016   const Expr *SecondArg = Call->getArg(1);
10017   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
10018   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
10019 
10020   // Only warn when exactly one argument is zero.
10021   if (IsFirstArgZero == IsSecondArgZero) return;
10022 
10023   SourceRange FirstRange = FirstArg->getSourceRange();
10024   SourceRange SecondRange = SecondArg->getSourceRange();
10025 
10026   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
10027 
10028   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
10029       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
10030 
10031   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
10032   SourceRange RemovalRange;
10033   if (IsFirstArgZero) {
10034     RemovalRange = SourceRange(FirstRange.getBegin(),
10035                                SecondRange.getBegin().getLocWithOffset(-1));
10036   } else {
10037     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
10038                                SecondRange.getEnd());
10039   }
10040 
10041   Diag(Call->getExprLoc(), diag::note_remove_max_call)
10042         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
10043         << FixItHint::CreateRemoval(RemovalRange);
10044 }
10045 
10046 //===--- CHECK: Standard memory functions ---------------------------------===//
10047 
10048 /// Takes the expression passed to the size_t parameter of functions
10049 /// such as memcmp, strncat, etc and warns if it's a comparison.
10050 ///
10051 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
10052 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
10053                                            IdentifierInfo *FnName,
10054                                            SourceLocation FnLoc,
10055                                            SourceLocation RParenLoc) {
10056   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
10057   if (!Size)
10058     return false;
10059 
10060   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
10061   if (!Size->isComparisonOp() && !Size->isLogicalOp())
10062     return false;
10063 
10064   SourceRange SizeRange = Size->getSourceRange();
10065   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
10066       << SizeRange << FnName;
10067   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
10068       << FnName
10069       << FixItHint::CreateInsertion(
10070              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
10071       << FixItHint::CreateRemoval(RParenLoc);
10072   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
10073       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
10074       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
10075                                     ")");
10076 
10077   return true;
10078 }
10079 
10080 /// Determine whether the given type is or contains a dynamic class type
10081 /// (e.g., whether it has a vtable).
10082 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
10083                                                      bool &IsContained) {
10084   // Look through array types while ignoring qualifiers.
10085   const Type *Ty = T->getBaseElementTypeUnsafe();
10086   IsContained = false;
10087 
10088   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
10089   RD = RD ? RD->getDefinition() : nullptr;
10090   if (!RD || RD->isInvalidDecl())
10091     return nullptr;
10092 
10093   if (RD->isDynamicClass())
10094     return RD;
10095 
10096   // Check all the fields.  If any bases were dynamic, the class is dynamic.
10097   // It's impossible for a class to transitively contain itself by value, so
10098   // infinite recursion is impossible.
10099   for (auto *FD : RD->fields()) {
10100     bool SubContained;
10101     if (const CXXRecordDecl *ContainedRD =
10102             getContainedDynamicClass(FD->getType(), SubContained)) {
10103       IsContained = true;
10104       return ContainedRD;
10105     }
10106   }
10107 
10108   return nullptr;
10109 }
10110 
10111 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
10112   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
10113     if (Unary->getKind() == UETT_SizeOf)
10114       return Unary;
10115   return nullptr;
10116 }
10117 
10118 /// If E is a sizeof expression, returns its argument expression,
10119 /// otherwise returns NULL.
10120 static const Expr *getSizeOfExprArg(const Expr *E) {
10121   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10122     if (!SizeOf->isArgumentType())
10123       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
10124   return nullptr;
10125 }
10126 
10127 /// If E is a sizeof expression, returns its argument type.
10128 static QualType getSizeOfArgType(const Expr *E) {
10129   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10130     return SizeOf->getTypeOfArgument();
10131   return QualType();
10132 }
10133 
10134 namespace {
10135 
10136 struct SearchNonTrivialToInitializeField
10137     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
10138   using Super =
10139       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
10140 
10141   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
10142 
10143   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
10144                      SourceLocation SL) {
10145     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10146       asDerived().visitArray(PDIK, AT, SL);
10147       return;
10148     }
10149 
10150     Super::visitWithKind(PDIK, FT, SL);
10151   }
10152 
10153   void visitARCStrong(QualType FT, SourceLocation SL) {
10154     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10155   }
10156   void visitARCWeak(QualType FT, SourceLocation SL) {
10157     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10158   }
10159   void visitStruct(QualType FT, SourceLocation SL) {
10160     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
10161       visit(FD->getType(), FD->getLocation());
10162   }
10163   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
10164                   const ArrayType *AT, SourceLocation SL) {
10165     visit(getContext().getBaseElementType(AT), SL);
10166   }
10167   void visitTrivial(QualType FT, SourceLocation SL) {}
10168 
10169   static void diag(QualType RT, const Expr *E, Sema &S) {
10170     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
10171   }
10172 
10173   ASTContext &getContext() { return S.getASTContext(); }
10174 
10175   const Expr *E;
10176   Sema &S;
10177 };
10178 
10179 struct SearchNonTrivialToCopyField
10180     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
10181   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
10182 
10183   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
10184 
10185   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
10186                      SourceLocation SL) {
10187     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10188       asDerived().visitArray(PCK, AT, SL);
10189       return;
10190     }
10191 
10192     Super::visitWithKind(PCK, FT, SL);
10193   }
10194 
10195   void visitARCStrong(QualType FT, SourceLocation SL) {
10196     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10197   }
10198   void visitARCWeak(QualType FT, SourceLocation SL) {
10199     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10200   }
10201   void visitStruct(QualType FT, SourceLocation SL) {
10202     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
10203       visit(FD->getType(), FD->getLocation());
10204   }
10205   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
10206                   SourceLocation SL) {
10207     visit(getContext().getBaseElementType(AT), SL);
10208   }
10209   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
10210                 SourceLocation SL) {}
10211   void visitTrivial(QualType FT, SourceLocation SL) {}
10212   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
10213 
10214   static void diag(QualType RT, const Expr *E, Sema &S) {
10215     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
10216   }
10217 
10218   ASTContext &getContext() { return S.getASTContext(); }
10219 
10220   const Expr *E;
10221   Sema &S;
10222 };
10223 
10224 }
10225 
10226 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
10227 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
10228   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
10229 
10230   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
10231     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
10232       return false;
10233 
10234     return doesExprLikelyComputeSize(BO->getLHS()) ||
10235            doesExprLikelyComputeSize(BO->getRHS());
10236   }
10237 
10238   return getAsSizeOfExpr(SizeofExpr) != nullptr;
10239 }
10240 
10241 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
10242 ///
10243 /// \code
10244 ///   #define MACRO 0
10245 ///   foo(MACRO);
10246 ///   foo(0);
10247 /// \endcode
10248 ///
10249 /// This should return true for the first call to foo, but not for the second
10250 /// (regardless of whether foo is a macro or function).
10251 static bool isArgumentExpandedFromMacro(SourceManager &SM,
10252                                         SourceLocation CallLoc,
10253                                         SourceLocation ArgLoc) {
10254   if (!CallLoc.isMacroID())
10255     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
10256 
10257   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
10258          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
10259 }
10260 
10261 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
10262 /// last two arguments transposed.
10263 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
10264   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
10265     return;
10266 
10267   const Expr *SizeArg =
10268     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
10269 
10270   auto isLiteralZero = [](const Expr *E) {
10271     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
10272   };
10273 
10274   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
10275   SourceLocation CallLoc = Call->getRParenLoc();
10276   SourceManager &SM = S.getSourceManager();
10277   if (isLiteralZero(SizeArg) &&
10278       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
10279 
10280     SourceLocation DiagLoc = SizeArg->getExprLoc();
10281 
10282     // Some platforms #define bzero to __builtin_memset. See if this is the
10283     // case, and if so, emit a better diagnostic.
10284     if (BId == Builtin::BIbzero ||
10285         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
10286                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
10287       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
10288       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
10289     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
10290       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
10291       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
10292     }
10293     return;
10294   }
10295 
10296   // If the second argument to a memset is a sizeof expression and the third
10297   // isn't, this is also likely an error. This should catch
10298   // 'memset(buf, sizeof(buf), 0xff)'.
10299   if (BId == Builtin::BImemset &&
10300       doesExprLikelyComputeSize(Call->getArg(1)) &&
10301       !doesExprLikelyComputeSize(Call->getArg(2))) {
10302     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
10303     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
10304     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
10305     return;
10306   }
10307 }
10308 
10309 /// Check for dangerous or invalid arguments to memset().
10310 ///
10311 /// This issues warnings on known problematic, dangerous or unspecified
10312 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
10313 /// function calls.
10314 ///
10315 /// \param Call The call expression to diagnose.
10316 void Sema::CheckMemaccessArguments(const CallExpr *Call,
10317                                    unsigned BId,
10318                                    IdentifierInfo *FnName) {
10319   assert(BId != 0);
10320 
10321   // It is possible to have a non-standard definition of memset.  Validate
10322   // we have enough arguments, and if not, abort further checking.
10323   unsigned ExpectedNumArgs =
10324       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
10325   if (Call->getNumArgs() < ExpectedNumArgs)
10326     return;
10327 
10328   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
10329                       BId == Builtin::BIstrndup ? 1 : 2);
10330   unsigned LenArg =
10331       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
10332   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
10333 
10334   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
10335                                      Call->getBeginLoc(), Call->getRParenLoc()))
10336     return;
10337 
10338   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
10339   CheckMemaccessSize(*this, BId, Call);
10340 
10341   // We have special checking when the length is a sizeof expression.
10342   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
10343   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
10344   llvm::FoldingSetNodeID SizeOfArgID;
10345 
10346   // Although widely used, 'bzero' is not a standard function. Be more strict
10347   // with the argument types before allowing diagnostics and only allow the
10348   // form bzero(ptr, sizeof(...)).
10349   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10350   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
10351     return;
10352 
10353   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
10354     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
10355     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
10356 
10357     QualType DestTy = Dest->getType();
10358     QualType PointeeTy;
10359     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
10360       PointeeTy = DestPtrTy->getPointeeType();
10361 
10362       // Never warn about void type pointers. This can be used to suppress
10363       // false positives.
10364       if (PointeeTy->isVoidType())
10365         continue;
10366 
10367       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
10368       // actually comparing the expressions for equality. Because computing the
10369       // expression IDs can be expensive, we only do this if the diagnostic is
10370       // enabled.
10371       if (SizeOfArg &&
10372           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
10373                            SizeOfArg->getExprLoc())) {
10374         // We only compute IDs for expressions if the warning is enabled, and
10375         // cache the sizeof arg's ID.
10376         if (SizeOfArgID == llvm::FoldingSetNodeID())
10377           SizeOfArg->Profile(SizeOfArgID, Context, true);
10378         llvm::FoldingSetNodeID DestID;
10379         Dest->Profile(DestID, Context, true);
10380         if (DestID == SizeOfArgID) {
10381           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
10382           //       over sizeof(src) as well.
10383           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
10384           StringRef ReadableName = FnName->getName();
10385 
10386           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
10387             if (UnaryOp->getOpcode() == UO_AddrOf)
10388               ActionIdx = 1; // If its an address-of operator, just remove it.
10389           if (!PointeeTy->isIncompleteType() &&
10390               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
10391             ActionIdx = 2; // If the pointee's size is sizeof(char),
10392                            // suggest an explicit length.
10393 
10394           // If the function is defined as a builtin macro, do not show macro
10395           // expansion.
10396           SourceLocation SL = SizeOfArg->getExprLoc();
10397           SourceRange DSR = Dest->getSourceRange();
10398           SourceRange SSR = SizeOfArg->getSourceRange();
10399           SourceManager &SM = getSourceManager();
10400 
10401           if (SM.isMacroArgExpansion(SL)) {
10402             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
10403             SL = SM.getSpellingLoc(SL);
10404             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
10405                              SM.getSpellingLoc(DSR.getEnd()));
10406             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
10407                              SM.getSpellingLoc(SSR.getEnd()));
10408           }
10409 
10410           DiagRuntimeBehavior(SL, SizeOfArg,
10411                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
10412                                 << ReadableName
10413                                 << PointeeTy
10414                                 << DestTy
10415                                 << DSR
10416                                 << SSR);
10417           DiagRuntimeBehavior(SL, SizeOfArg,
10418                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
10419                                 << ActionIdx
10420                                 << SSR);
10421 
10422           break;
10423         }
10424       }
10425 
10426       // Also check for cases where the sizeof argument is the exact same
10427       // type as the memory argument, and where it points to a user-defined
10428       // record type.
10429       if (SizeOfArgTy != QualType()) {
10430         if (PointeeTy->isRecordType() &&
10431             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
10432           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
10433                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
10434                                 << FnName << SizeOfArgTy << ArgIdx
10435                                 << PointeeTy << Dest->getSourceRange()
10436                                 << LenExpr->getSourceRange());
10437           break;
10438         }
10439       }
10440     } else if (DestTy->isArrayType()) {
10441       PointeeTy = DestTy;
10442     }
10443 
10444     if (PointeeTy == QualType())
10445       continue;
10446 
10447     // Always complain about dynamic classes.
10448     bool IsContained;
10449     if (const CXXRecordDecl *ContainedRD =
10450             getContainedDynamicClass(PointeeTy, IsContained)) {
10451 
10452       unsigned OperationType = 0;
10453       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
10454       // "overwritten" if we're warning about the destination for any call
10455       // but memcmp; otherwise a verb appropriate to the call.
10456       if (ArgIdx != 0 || IsCmp) {
10457         if (BId == Builtin::BImemcpy)
10458           OperationType = 1;
10459         else if(BId == Builtin::BImemmove)
10460           OperationType = 2;
10461         else if (IsCmp)
10462           OperationType = 3;
10463       }
10464 
10465       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10466                           PDiag(diag::warn_dyn_class_memaccess)
10467                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
10468                               << IsContained << ContainedRD << OperationType
10469                               << Call->getCallee()->getSourceRange());
10470     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
10471              BId != Builtin::BImemset)
10472       DiagRuntimeBehavior(
10473         Dest->getExprLoc(), Dest,
10474         PDiag(diag::warn_arc_object_memaccess)
10475           << ArgIdx << FnName << PointeeTy
10476           << Call->getCallee()->getSourceRange());
10477     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
10478       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10479           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
10480         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10481                             PDiag(diag::warn_cstruct_memaccess)
10482                                 << ArgIdx << FnName << PointeeTy << 0);
10483         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
10484       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10485                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
10486         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10487                             PDiag(diag::warn_cstruct_memaccess)
10488                                 << ArgIdx << FnName << PointeeTy << 1);
10489         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
10490       } else {
10491         continue;
10492       }
10493     } else
10494       continue;
10495 
10496     DiagRuntimeBehavior(
10497       Dest->getExprLoc(), Dest,
10498       PDiag(diag::note_bad_memaccess_silence)
10499         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
10500     break;
10501   }
10502 }
10503 
10504 // A little helper routine: ignore addition and subtraction of integer literals.
10505 // This intentionally does not ignore all integer constant expressions because
10506 // we don't want to remove sizeof().
10507 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
10508   Ex = Ex->IgnoreParenCasts();
10509 
10510   while (true) {
10511     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
10512     if (!BO || !BO->isAdditiveOp())
10513       break;
10514 
10515     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
10516     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
10517 
10518     if (isa<IntegerLiteral>(RHS))
10519       Ex = LHS;
10520     else if (isa<IntegerLiteral>(LHS))
10521       Ex = RHS;
10522     else
10523       break;
10524   }
10525 
10526   return Ex;
10527 }
10528 
10529 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
10530                                                       ASTContext &Context) {
10531   // Only handle constant-sized or VLAs, but not flexible members.
10532   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
10533     // Only issue the FIXIT for arrays of size > 1.
10534     if (CAT->getSize().getSExtValue() <= 1)
10535       return false;
10536   } else if (!Ty->isVariableArrayType()) {
10537     return false;
10538   }
10539   return true;
10540 }
10541 
10542 // Warn if the user has made the 'size' argument to strlcpy or strlcat
10543 // be the size of the source, instead of the destination.
10544 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
10545                                     IdentifierInfo *FnName) {
10546 
10547   // Don't crash if the user has the wrong number of arguments
10548   unsigned NumArgs = Call->getNumArgs();
10549   if ((NumArgs != 3) && (NumArgs != 4))
10550     return;
10551 
10552   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
10553   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
10554   const Expr *CompareWithSrc = nullptr;
10555 
10556   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
10557                                      Call->getBeginLoc(), Call->getRParenLoc()))
10558     return;
10559 
10560   // Look for 'strlcpy(dst, x, sizeof(x))'
10561   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
10562     CompareWithSrc = Ex;
10563   else {
10564     // Look for 'strlcpy(dst, x, strlen(x))'
10565     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
10566       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
10567           SizeCall->getNumArgs() == 1)
10568         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
10569     }
10570   }
10571 
10572   if (!CompareWithSrc)
10573     return;
10574 
10575   // Determine if the argument to sizeof/strlen is equal to the source
10576   // argument.  In principle there's all kinds of things you could do
10577   // here, for instance creating an == expression and evaluating it with
10578   // EvaluateAsBooleanCondition, but this uses a more direct technique:
10579   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
10580   if (!SrcArgDRE)
10581     return;
10582 
10583   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
10584   if (!CompareWithSrcDRE ||
10585       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
10586     return;
10587 
10588   const Expr *OriginalSizeArg = Call->getArg(2);
10589   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
10590       << OriginalSizeArg->getSourceRange() << FnName;
10591 
10592   // Output a FIXIT hint if the destination is an array (rather than a
10593   // pointer to an array).  This could be enhanced to handle some
10594   // pointers if we know the actual size, like if DstArg is 'array+2'
10595   // we could say 'sizeof(array)-2'.
10596   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
10597   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
10598     return;
10599 
10600   SmallString<128> sizeString;
10601   llvm::raw_svector_ostream OS(sizeString);
10602   OS << "sizeof(";
10603   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10604   OS << ")";
10605 
10606   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
10607       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
10608                                       OS.str());
10609 }
10610 
10611 /// Check if two expressions refer to the same declaration.
10612 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
10613   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
10614     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
10615       return D1->getDecl() == D2->getDecl();
10616   return false;
10617 }
10618 
10619 static const Expr *getStrlenExprArg(const Expr *E) {
10620   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10621     const FunctionDecl *FD = CE->getDirectCallee();
10622     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
10623       return nullptr;
10624     return CE->getArg(0)->IgnoreParenCasts();
10625   }
10626   return nullptr;
10627 }
10628 
10629 // Warn on anti-patterns as the 'size' argument to strncat.
10630 // The correct size argument should look like following:
10631 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
10632 void Sema::CheckStrncatArguments(const CallExpr *CE,
10633                                  IdentifierInfo *FnName) {
10634   // Don't crash if the user has the wrong number of arguments.
10635   if (CE->getNumArgs() < 3)
10636     return;
10637   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
10638   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
10639   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
10640 
10641   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
10642                                      CE->getRParenLoc()))
10643     return;
10644 
10645   // Identify common expressions, which are wrongly used as the size argument
10646   // to strncat and may lead to buffer overflows.
10647   unsigned PatternType = 0;
10648   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
10649     // - sizeof(dst)
10650     if (referToTheSameDecl(SizeOfArg, DstArg))
10651       PatternType = 1;
10652     // - sizeof(src)
10653     else if (referToTheSameDecl(SizeOfArg, SrcArg))
10654       PatternType = 2;
10655   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
10656     if (BE->getOpcode() == BO_Sub) {
10657       const Expr *L = BE->getLHS()->IgnoreParenCasts();
10658       const Expr *R = BE->getRHS()->IgnoreParenCasts();
10659       // - sizeof(dst) - strlen(dst)
10660       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
10661           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
10662         PatternType = 1;
10663       // - sizeof(src) - (anything)
10664       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
10665         PatternType = 2;
10666     }
10667   }
10668 
10669   if (PatternType == 0)
10670     return;
10671 
10672   // Generate the diagnostic.
10673   SourceLocation SL = LenArg->getBeginLoc();
10674   SourceRange SR = LenArg->getSourceRange();
10675   SourceManager &SM = getSourceManager();
10676 
10677   // If the function is defined as a builtin macro, do not show macro expansion.
10678   if (SM.isMacroArgExpansion(SL)) {
10679     SL = SM.getSpellingLoc(SL);
10680     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
10681                      SM.getSpellingLoc(SR.getEnd()));
10682   }
10683 
10684   // Check if the destination is an array (rather than a pointer to an array).
10685   QualType DstTy = DstArg->getType();
10686   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
10687                                                                     Context);
10688   if (!isKnownSizeArray) {
10689     if (PatternType == 1)
10690       Diag(SL, diag::warn_strncat_wrong_size) << SR;
10691     else
10692       Diag(SL, diag::warn_strncat_src_size) << SR;
10693     return;
10694   }
10695 
10696   if (PatternType == 1)
10697     Diag(SL, diag::warn_strncat_large_size) << SR;
10698   else
10699     Diag(SL, diag::warn_strncat_src_size) << SR;
10700 
10701   SmallString<128> sizeString;
10702   llvm::raw_svector_ostream OS(sizeString);
10703   OS << "sizeof(";
10704   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10705   OS << ") - ";
10706   OS << "strlen(";
10707   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10708   OS << ") - 1";
10709 
10710   Diag(SL, diag::note_strncat_wrong_size)
10711     << FixItHint::CreateReplacement(SR, OS.str());
10712 }
10713 
10714 namespace {
10715 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
10716                                 const UnaryOperator *UnaryExpr, const Decl *D) {
10717   if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) {
10718     S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
10719         << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
10720     return;
10721   }
10722 }
10723 
10724 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
10725                                  const UnaryOperator *UnaryExpr) {
10726   if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
10727     const Decl *D = Lvalue->getDecl();
10728     if (isa<DeclaratorDecl>(D))
10729       if (!dyn_cast<DeclaratorDecl>(D)->getType()->isReferenceType())
10730         return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
10731   }
10732 
10733   if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
10734     return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
10735                                       Lvalue->getMemberDecl());
10736 }
10737 
10738 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
10739                             const UnaryOperator *UnaryExpr) {
10740   const auto *Lambda = dyn_cast<LambdaExpr>(
10741       UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens());
10742   if (!Lambda)
10743     return;
10744 
10745   S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
10746       << CalleeName << 2 /*object: lambda expression*/;
10747 }
10748 
10749 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
10750                                   const DeclRefExpr *Lvalue) {
10751   const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
10752   if (Var == nullptr)
10753     return;
10754 
10755   S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
10756       << CalleeName << 0 /*object: */ << Var;
10757 }
10758 
10759 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
10760                             const CastExpr *Cast) {
10761   SmallString<128> SizeString;
10762   llvm::raw_svector_ostream OS(SizeString);
10763 
10764   clang::CastKind Kind = Cast->getCastKind();
10765   if (Kind == clang::CK_BitCast &&
10766       !Cast->getSubExpr()->getType()->isFunctionPointerType())
10767     return;
10768   if (Kind == clang::CK_IntegralToPointer &&
10769       !isa<IntegerLiteral>(
10770           Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
10771     return;
10772 
10773   switch (Cast->getCastKind()) {
10774   case clang::CK_BitCast:
10775   case clang::CK_IntegralToPointer:
10776   case clang::CK_FunctionToPointerDecay:
10777     OS << '\'';
10778     Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
10779     OS << '\'';
10780     break;
10781   default:
10782     return;
10783   }
10784 
10785   S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
10786       << CalleeName << 0 /*object: */ << OS.str();
10787 }
10788 } // namespace
10789 
10790 /// Alerts the user that they are attempting to free a non-malloc'd object.
10791 void Sema::CheckFreeArguments(const CallExpr *E) {
10792   const std::string CalleeName =
10793       dyn_cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
10794 
10795   { // Prefer something that doesn't involve a cast to make things simpler.
10796     const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
10797     if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
10798       switch (UnaryExpr->getOpcode()) {
10799       case UnaryOperator::Opcode::UO_AddrOf:
10800         return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
10801       case UnaryOperator::Opcode::UO_Plus:
10802         return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
10803       default:
10804         break;
10805       }
10806 
10807     if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
10808       if (Lvalue->getType()->isArrayType())
10809         return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
10810 
10811     if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
10812       Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
10813           << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
10814       return;
10815     }
10816 
10817     if (isa<BlockExpr>(Arg)) {
10818       Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
10819           << CalleeName << 1 /*object: block*/;
10820       return;
10821     }
10822   }
10823   // Maybe the cast was important, check after the other cases.
10824   if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
10825     return CheckFreeArgumentsCast(*this, CalleeName, Cast);
10826 }
10827 
10828 void
10829 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
10830                          SourceLocation ReturnLoc,
10831                          bool isObjCMethod,
10832                          const AttrVec *Attrs,
10833                          const FunctionDecl *FD) {
10834   // Check if the return value is null but should not be.
10835   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
10836        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
10837       CheckNonNullExpr(*this, RetValExp))
10838     Diag(ReturnLoc, diag::warn_null_ret)
10839       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
10840 
10841   // C++11 [basic.stc.dynamic.allocation]p4:
10842   //   If an allocation function declared with a non-throwing
10843   //   exception-specification fails to allocate storage, it shall return
10844   //   a null pointer. Any other allocation function that fails to allocate
10845   //   storage shall indicate failure only by throwing an exception [...]
10846   if (FD) {
10847     OverloadedOperatorKind Op = FD->getOverloadedOperator();
10848     if (Op == OO_New || Op == OO_Array_New) {
10849       const FunctionProtoType *Proto
10850         = FD->getType()->castAs<FunctionProtoType>();
10851       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
10852           CheckNonNullExpr(*this, RetValExp))
10853         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
10854           << FD << getLangOpts().CPlusPlus11;
10855     }
10856   }
10857 
10858   // PPC MMA non-pointer types are not allowed as return type. Checking the type
10859   // here prevent the user from using a PPC MMA type as trailing return type.
10860   if (Context.getTargetInfo().getTriple().isPPC64())
10861     CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
10862 }
10863 
10864 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
10865 
10866 /// Check for comparisons of floating point operands using != and ==.
10867 /// Issue a warning if these are no self-comparisons, as they are not likely
10868 /// to do what the programmer intended.
10869 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
10870   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
10871   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
10872 
10873   // Special case: check for x == x (which is OK).
10874   // Do not emit warnings for such cases.
10875   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
10876     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
10877       if (DRL->getDecl() == DRR->getDecl())
10878         return;
10879 
10880   // Special case: check for comparisons against literals that can be exactly
10881   //  represented by APFloat.  In such cases, do not emit a warning.  This
10882   //  is a heuristic: often comparison against such literals are used to
10883   //  detect if a value in a variable has not changed.  This clearly can
10884   //  lead to false negatives.
10885   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
10886     if (FLL->isExact())
10887       return;
10888   } else
10889     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
10890       if (FLR->isExact())
10891         return;
10892 
10893   // Check for comparisons with builtin types.
10894   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
10895     if (CL->getBuiltinCallee())
10896       return;
10897 
10898   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
10899     if (CR->getBuiltinCallee())
10900       return;
10901 
10902   // Emit the diagnostic.
10903   Diag(Loc, diag::warn_floatingpoint_eq)
10904     << LHS->getSourceRange() << RHS->getSourceRange();
10905 }
10906 
10907 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
10908 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
10909 
10910 namespace {
10911 
10912 /// Structure recording the 'active' range of an integer-valued
10913 /// expression.
10914 struct IntRange {
10915   /// The number of bits active in the int. Note that this includes exactly one
10916   /// sign bit if !NonNegative.
10917   unsigned Width;
10918 
10919   /// True if the int is known not to have negative values. If so, all leading
10920   /// bits before Width are known zero, otherwise they are known to be the
10921   /// same as the MSB within Width.
10922   bool NonNegative;
10923 
10924   IntRange(unsigned Width, bool NonNegative)
10925       : Width(Width), NonNegative(NonNegative) {}
10926 
10927   /// Number of bits excluding the sign bit.
10928   unsigned valueBits() const {
10929     return NonNegative ? Width : Width - 1;
10930   }
10931 
10932   /// Returns the range of the bool type.
10933   static IntRange forBoolType() {
10934     return IntRange(1, true);
10935   }
10936 
10937   /// Returns the range of an opaque value of the given integral type.
10938   static IntRange forValueOfType(ASTContext &C, QualType T) {
10939     return forValueOfCanonicalType(C,
10940                           T->getCanonicalTypeInternal().getTypePtr());
10941   }
10942 
10943   /// Returns the range of an opaque value of a canonical integral type.
10944   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
10945     assert(T->isCanonicalUnqualified());
10946 
10947     if (const VectorType *VT = dyn_cast<VectorType>(T))
10948       T = VT->getElementType().getTypePtr();
10949     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
10950       T = CT->getElementType().getTypePtr();
10951     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
10952       T = AT->getValueType().getTypePtr();
10953 
10954     if (!C.getLangOpts().CPlusPlus) {
10955       // For enum types in C code, use the underlying datatype.
10956       if (const EnumType *ET = dyn_cast<EnumType>(T))
10957         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
10958     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
10959       // For enum types in C++, use the known bit width of the enumerators.
10960       EnumDecl *Enum = ET->getDecl();
10961       // In C++11, enums can have a fixed underlying type. Use this type to
10962       // compute the range.
10963       if (Enum->isFixed()) {
10964         return IntRange(C.getIntWidth(QualType(T, 0)),
10965                         !ET->isSignedIntegerOrEnumerationType());
10966       }
10967 
10968       unsigned NumPositive = Enum->getNumPositiveBits();
10969       unsigned NumNegative = Enum->getNumNegativeBits();
10970 
10971       if (NumNegative == 0)
10972         return IntRange(NumPositive, true/*NonNegative*/);
10973       else
10974         return IntRange(std::max(NumPositive + 1, NumNegative),
10975                         false/*NonNegative*/);
10976     }
10977 
10978     if (const auto *EIT = dyn_cast<ExtIntType>(T))
10979       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
10980 
10981     const BuiltinType *BT = cast<BuiltinType>(T);
10982     assert(BT->isInteger());
10983 
10984     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10985   }
10986 
10987   /// Returns the "target" range of a canonical integral type, i.e.
10988   /// the range of values expressible in the type.
10989   ///
10990   /// This matches forValueOfCanonicalType except that enums have the
10991   /// full range of their type, not the range of their enumerators.
10992   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
10993     assert(T->isCanonicalUnqualified());
10994 
10995     if (const VectorType *VT = dyn_cast<VectorType>(T))
10996       T = VT->getElementType().getTypePtr();
10997     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
10998       T = CT->getElementType().getTypePtr();
10999     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11000       T = AT->getValueType().getTypePtr();
11001     if (const EnumType *ET = dyn_cast<EnumType>(T))
11002       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
11003 
11004     if (const auto *EIT = dyn_cast<ExtIntType>(T))
11005       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11006 
11007     const BuiltinType *BT = cast<BuiltinType>(T);
11008     assert(BT->isInteger());
11009 
11010     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11011   }
11012 
11013   /// Returns the supremum of two ranges: i.e. their conservative merge.
11014   static IntRange join(IntRange L, IntRange R) {
11015     bool Unsigned = L.NonNegative && R.NonNegative;
11016     return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
11017                     L.NonNegative && R.NonNegative);
11018   }
11019 
11020   /// Return the range of a bitwise-AND of the two ranges.
11021   static IntRange bit_and(IntRange L, IntRange R) {
11022     unsigned Bits = std::max(L.Width, R.Width);
11023     bool NonNegative = false;
11024     if (L.NonNegative) {
11025       Bits = std::min(Bits, L.Width);
11026       NonNegative = true;
11027     }
11028     if (R.NonNegative) {
11029       Bits = std::min(Bits, R.Width);
11030       NonNegative = true;
11031     }
11032     return IntRange(Bits, NonNegative);
11033   }
11034 
11035   /// Return the range of a sum of the two ranges.
11036   static IntRange sum(IntRange L, IntRange R) {
11037     bool Unsigned = L.NonNegative && R.NonNegative;
11038     return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
11039                     Unsigned);
11040   }
11041 
11042   /// Return the range of a difference of the two ranges.
11043   static IntRange difference(IntRange L, IntRange R) {
11044     // We need a 1-bit-wider range if:
11045     //   1) LHS can be negative: least value can be reduced.
11046     //   2) RHS can be negative: greatest value can be increased.
11047     bool CanWiden = !L.NonNegative || !R.NonNegative;
11048     bool Unsigned = L.NonNegative && R.Width == 0;
11049     return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
11050                         !Unsigned,
11051                     Unsigned);
11052   }
11053 
11054   /// Return the range of a product of the two ranges.
11055   static IntRange product(IntRange L, IntRange R) {
11056     // If both LHS and RHS can be negative, we can form
11057     //   -2^L * -2^R = 2^(L + R)
11058     // which requires L + R + 1 value bits to represent.
11059     bool CanWiden = !L.NonNegative && !R.NonNegative;
11060     bool Unsigned = L.NonNegative && R.NonNegative;
11061     return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
11062                     Unsigned);
11063   }
11064 
11065   /// Return the range of a remainder operation between the two ranges.
11066   static IntRange rem(IntRange L, IntRange R) {
11067     // The result of a remainder can't be larger than the result of
11068     // either side. The sign of the result is the sign of the LHS.
11069     bool Unsigned = L.NonNegative;
11070     return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
11071                     Unsigned);
11072   }
11073 };
11074 
11075 } // namespace
11076 
11077 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
11078                               unsigned MaxWidth) {
11079   if (value.isSigned() && value.isNegative())
11080     return IntRange(value.getMinSignedBits(), false);
11081 
11082   if (value.getBitWidth() > MaxWidth)
11083     value = value.trunc(MaxWidth);
11084 
11085   // isNonNegative() just checks the sign bit without considering
11086   // signedness.
11087   return IntRange(value.getActiveBits(), true);
11088 }
11089 
11090 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
11091                               unsigned MaxWidth) {
11092   if (result.isInt())
11093     return GetValueRange(C, result.getInt(), MaxWidth);
11094 
11095   if (result.isVector()) {
11096     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
11097     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
11098       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
11099       R = IntRange::join(R, El);
11100     }
11101     return R;
11102   }
11103 
11104   if (result.isComplexInt()) {
11105     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
11106     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
11107     return IntRange::join(R, I);
11108   }
11109 
11110   // This can happen with lossless casts to intptr_t of "based" lvalues.
11111   // Assume it might use arbitrary bits.
11112   // FIXME: The only reason we need to pass the type in here is to get
11113   // the sign right on this one case.  It would be nice if APValue
11114   // preserved this.
11115   assert(result.isLValue() || result.isAddrLabelDiff());
11116   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
11117 }
11118 
11119 static QualType GetExprType(const Expr *E) {
11120   QualType Ty = E->getType();
11121   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
11122     Ty = AtomicRHS->getValueType();
11123   return Ty;
11124 }
11125 
11126 /// Pseudo-evaluate the given integer expression, estimating the
11127 /// range of values it might take.
11128 ///
11129 /// \param MaxWidth The width to which the value will be truncated.
11130 /// \param Approximate If \c true, return a likely range for the result: in
11131 ///        particular, assume that aritmetic on narrower types doesn't leave
11132 ///        those types. If \c false, return a range including all possible
11133 ///        result values.
11134 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
11135                              bool InConstantContext, bool Approximate) {
11136   E = E->IgnoreParens();
11137 
11138   // Try a full evaluation first.
11139   Expr::EvalResult result;
11140   if (E->EvaluateAsRValue(result, C, InConstantContext))
11141     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
11142 
11143   // I think we only want to look through implicit casts here; if the
11144   // user has an explicit widening cast, we should treat the value as
11145   // being of the new, wider type.
11146   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
11147     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
11148       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
11149                           Approximate);
11150 
11151     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
11152 
11153     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
11154                          CE->getCastKind() == CK_BooleanToSignedIntegral;
11155 
11156     // Assume that non-integer casts can span the full range of the type.
11157     if (!isIntegerCast)
11158       return OutputTypeRange;
11159 
11160     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
11161                                      std::min(MaxWidth, OutputTypeRange.Width),
11162                                      InConstantContext, Approximate);
11163 
11164     // Bail out if the subexpr's range is as wide as the cast type.
11165     if (SubRange.Width >= OutputTypeRange.Width)
11166       return OutputTypeRange;
11167 
11168     // Otherwise, we take the smaller width, and we're non-negative if
11169     // either the output type or the subexpr is.
11170     return IntRange(SubRange.Width,
11171                     SubRange.NonNegative || OutputTypeRange.NonNegative);
11172   }
11173 
11174   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11175     // If we can fold the condition, just take that operand.
11176     bool CondResult;
11177     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
11178       return GetExprRange(C,
11179                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
11180                           MaxWidth, InConstantContext, Approximate);
11181 
11182     // Otherwise, conservatively merge.
11183     // GetExprRange requires an integer expression, but a throw expression
11184     // results in a void type.
11185     Expr *E = CO->getTrueExpr();
11186     IntRange L = E->getType()->isVoidType()
11187                      ? IntRange{0, true}
11188                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
11189     E = CO->getFalseExpr();
11190     IntRange R = E->getType()->isVoidType()
11191                      ? IntRange{0, true}
11192                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
11193     return IntRange::join(L, R);
11194   }
11195 
11196   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11197     IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
11198 
11199     switch (BO->getOpcode()) {
11200     case BO_Cmp:
11201       llvm_unreachable("builtin <=> should have class type");
11202 
11203     // Boolean-valued operations are single-bit and positive.
11204     case BO_LAnd:
11205     case BO_LOr:
11206     case BO_LT:
11207     case BO_GT:
11208     case BO_LE:
11209     case BO_GE:
11210     case BO_EQ:
11211     case BO_NE:
11212       return IntRange::forBoolType();
11213 
11214     // The type of the assignments is the type of the LHS, so the RHS
11215     // is not necessarily the same type.
11216     case BO_MulAssign:
11217     case BO_DivAssign:
11218     case BO_RemAssign:
11219     case BO_AddAssign:
11220     case BO_SubAssign:
11221     case BO_XorAssign:
11222     case BO_OrAssign:
11223       // TODO: bitfields?
11224       return IntRange::forValueOfType(C, GetExprType(E));
11225 
11226     // Simple assignments just pass through the RHS, which will have
11227     // been coerced to the LHS type.
11228     case BO_Assign:
11229       // TODO: bitfields?
11230       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11231                           Approximate);
11232 
11233     // Operations with opaque sources are black-listed.
11234     case BO_PtrMemD:
11235     case BO_PtrMemI:
11236       return IntRange::forValueOfType(C, GetExprType(E));
11237 
11238     // Bitwise-and uses the *infinum* of the two source ranges.
11239     case BO_And:
11240     case BO_AndAssign:
11241       Combine = IntRange::bit_and;
11242       break;
11243 
11244     // Left shift gets black-listed based on a judgement call.
11245     case BO_Shl:
11246       // ...except that we want to treat '1 << (blah)' as logically
11247       // positive.  It's an important idiom.
11248       if (IntegerLiteral *I
11249             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
11250         if (I->getValue() == 1) {
11251           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
11252           return IntRange(R.Width, /*NonNegative*/ true);
11253         }
11254       }
11255       LLVM_FALLTHROUGH;
11256 
11257     case BO_ShlAssign:
11258       return IntRange::forValueOfType(C, GetExprType(E));
11259 
11260     // Right shift by a constant can narrow its left argument.
11261     case BO_Shr:
11262     case BO_ShrAssign: {
11263       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext,
11264                                 Approximate);
11265 
11266       // If the shift amount is a positive constant, drop the width by
11267       // that much.
11268       if (Optional<llvm::APSInt> shift =
11269               BO->getRHS()->getIntegerConstantExpr(C)) {
11270         if (shift->isNonNegative()) {
11271           unsigned zext = shift->getZExtValue();
11272           if (zext >= L.Width)
11273             L.Width = (L.NonNegative ? 0 : 1);
11274           else
11275             L.Width -= zext;
11276         }
11277       }
11278 
11279       return L;
11280     }
11281 
11282     // Comma acts as its right operand.
11283     case BO_Comma:
11284       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11285                           Approximate);
11286 
11287     case BO_Add:
11288       if (!Approximate)
11289         Combine = IntRange::sum;
11290       break;
11291 
11292     case BO_Sub:
11293       if (BO->getLHS()->getType()->isPointerType())
11294         return IntRange::forValueOfType(C, GetExprType(E));
11295       if (!Approximate)
11296         Combine = IntRange::difference;
11297       break;
11298 
11299     case BO_Mul:
11300       if (!Approximate)
11301         Combine = IntRange::product;
11302       break;
11303 
11304     // The width of a division result is mostly determined by the size
11305     // of the LHS.
11306     case BO_Div: {
11307       // Don't 'pre-truncate' the operands.
11308       unsigned opWidth = C.getIntWidth(GetExprType(E));
11309       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext,
11310                                 Approximate);
11311 
11312       // If the divisor is constant, use that.
11313       if (Optional<llvm::APSInt> divisor =
11314               BO->getRHS()->getIntegerConstantExpr(C)) {
11315         unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
11316         if (log2 >= L.Width)
11317           L.Width = (L.NonNegative ? 0 : 1);
11318         else
11319           L.Width = std::min(L.Width - log2, MaxWidth);
11320         return L;
11321       }
11322 
11323       // Otherwise, just use the LHS's width.
11324       // FIXME: This is wrong if the LHS could be its minimal value and the RHS
11325       // could be -1.
11326       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext,
11327                                 Approximate);
11328       return IntRange(L.Width, L.NonNegative && R.NonNegative);
11329     }
11330 
11331     case BO_Rem:
11332       Combine = IntRange::rem;
11333       break;
11334 
11335     // The default behavior is okay for these.
11336     case BO_Xor:
11337     case BO_Or:
11338       break;
11339     }
11340 
11341     // Combine the two ranges, but limit the result to the type in which we
11342     // performed the computation.
11343     QualType T = GetExprType(E);
11344     unsigned opWidth = C.getIntWidth(T);
11345     IntRange L =
11346         GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate);
11347     IntRange R =
11348         GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate);
11349     IntRange C = Combine(L, R);
11350     C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
11351     C.Width = std::min(C.Width, MaxWidth);
11352     return C;
11353   }
11354 
11355   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
11356     switch (UO->getOpcode()) {
11357     // Boolean-valued operations are white-listed.
11358     case UO_LNot:
11359       return IntRange::forBoolType();
11360 
11361     // Operations with opaque sources are black-listed.
11362     case UO_Deref:
11363     case UO_AddrOf: // should be impossible
11364       return IntRange::forValueOfType(C, GetExprType(E));
11365 
11366     default:
11367       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11368                           Approximate);
11369     }
11370   }
11371 
11372   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
11373     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
11374                         Approximate);
11375 
11376   if (const auto *BitField = E->getSourceBitField())
11377     return IntRange(BitField->getBitWidthValue(C),
11378                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
11379 
11380   return IntRange::forValueOfType(C, GetExprType(E));
11381 }
11382 
11383 static IntRange GetExprRange(ASTContext &C, const Expr *E,
11384                              bool InConstantContext, bool Approximate) {
11385   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
11386                       Approximate);
11387 }
11388 
11389 /// Checks whether the given value, which currently has the given
11390 /// source semantics, has the same value when coerced through the
11391 /// target semantics.
11392 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
11393                                  const llvm::fltSemantics &Src,
11394                                  const llvm::fltSemantics &Tgt) {
11395   llvm::APFloat truncated = value;
11396 
11397   bool ignored;
11398   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
11399   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
11400 
11401   return truncated.bitwiseIsEqual(value);
11402 }
11403 
11404 /// Checks whether the given value, which currently has the given
11405 /// source semantics, has the same value when coerced through the
11406 /// target semantics.
11407 ///
11408 /// The value might be a vector of floats (or a complex number).
11409 static bool IsSameFloatAfterCast(const APValue &value,
11410                                  const llvm::fltSemantics &Src,
11411                                  const llvm::fltSemantics &Tgt) {
11412   if (value.isFloat())
11413     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
11414 
11415   if (value.isVector()) {
11416     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
11417       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
11418         return false;
11419     return true;
11420   }
11421 
11422   assert(value.isComplexFloat());
11423   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
11424           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
11425 }
11426 
11427 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
11428                                        bool IsListInit = false);
11429 
11430 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
11431   // Suppress cases where we are comparing against an enum constant.
11432   if (const DeclRefExpr *DR =
11433       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
11434     if (isa<EnumConstantDecl>(DR->getDecl()))
11435       return true;
11436 
11437   // Suppress cases where the value is expanded from a macro, unless that macro
11438   // is how a language represents a boolean literal. This is the case in both C
11439   // and Objective-C.
11440   SourceLocation BeginLoc = E->getBeginLoc();
11441   if (BeginLoc.isMacroID()) {
11442     StringRef MacroName = Lexer::getImmediateMacroName(
11443         BeginLoc, S.getSourceManager(), S.getLangOpts());
11444     return MacroName != "YES" && MacroName != "NO" &&
11445            MacroName != "true" && MacroName != "false";
11446   }
11447 
11448   return false;
11449 }
11450 
11451 static bool isKnownToHaveUnsignedValue(Expr *E) {
11452   return E->getType()->isIntegerType() &&
11453          (!E->getType()->isSignedIntegerType() ||
11454           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
11455 }
11456 
11457 namespace {
11458 /// The promoted range of values of a type. In general this has the
11459 /// following structure:
11460 ///
11461 ///     |-----------| . . . |-----------|
11462 ///     ^           ^       ^           ^
11463 ///    Min       HoleMin  HoleMax      Max
11464 ///
11465 /// ... where there is only a hole if a signed type is promoted to unsigned
11466 /// (in which case Min and Max are the smallest and largest representable
11467 /// values).
11468 struct PromotedRange {
11469   // Min, or HoleMax if there is a hole.
11470   llvm::APSInt PromotedMin;
11471   // Max, or HoleMin if there is a hole.
11472   llvm::APSInt PromotedMax;
11473 
11474   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
11475     if (R.Width == 0)
11476       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
11477     else if (R.Width >= BitWidth && !Unsigned) {
11478       // Promotion made the type *narrower*. This happens when promoting
11479       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
11480       // Treat all values of 'signed int' as being in range for now.
11481       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
11482       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
11483     } else {
11484       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
11485                         .extOrTrunc(BitWidth);
11486       PromotedMin.setIsUnsigned(Unsigned);
11487 
11488       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
11489                         .extOrTrunc(BitWidth);
11490       PromotedMax.setIsUnsigned(Unsigned);
11491     }
11492   }
11493 
11494   // Determine whether this range is contiguous (has no hole).
11495   bool isContiguous() const { return PromotedMin <= PromotedMax; }
11496 
11497   // Where a constant value is within the range.
11498   enum ComparisonResult {
11499     LT = 0x1,
11500     LE = 0x2,
11501     GT = 0x4,
11502     GE = 0x8,
11503     EQ = 0x10,
11504     NE = 0x20,
11505     InRangeFlag = 0x40,
11506 
11507     Less = LE | LT | NE,
11508     Min = LE | InRangeFlag,
11509     InRange = InRangeFlag,
11510     Max = GE | InRangeFlag,
11511     Greater = GE | GT | NE,
11512 
11513     OnlyValue = LE | GE | EQ | InRangeFlag,
11514     InHole = NE
11515   };
11516 
11517   ComparisonResult compare(const llvm::APSInt &Value) const {
11518     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
11519            Value.isUnsigned() == PromotedMin.isUnsigned());
11520     if (!isContiguous()) {
11521       assert(Value.isUnsigned() && "discontiguous range for signed compare");
11522       if (Value.isMinValue()) return Min;
11523       if (Value.isMaxValue()) return Max;
11524       if (Value >= PromotedMin) return InRange;
11525       if (Value <= PromotedMax) return InRange;
11526       return InHole;
11527     }
11528 
11529     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
11530     case -1: return Less;
11531     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
11532     case 1:
11533       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
11534       case -1: return InRange;
11535       case 0: return Max;
11536       case 1: return Greater;
11537       }
11538     }
11539 
11540     llvm_unreachable("impossible compare result");
11541   }
11542 
11543   static llvm::Optional<StringRef>
11544   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
11545     if (Op == BO_Cmp) {
11546       ComparisonResult LTFlag = LT, GTFlag = GT;
11547       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
11548 
11549       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
11550       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
11551       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
11552       return llvm::None;
11553     }
11554 
11555     ComparisonResult TrueFlag, FalseFlag;
11556     if (Op == BO_EQ) {
11557       TrueFlag = EQ;
11558       FalseFlag = NE;
11559     } else if (Op == BO_NE) {
11560       TrueFlag = NE;
11561       FalseFlag = EQ;
11562     } else {
11563       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
11564         TrueFlag = LT;
11565         FalseFlag = GE;
11566       } else {
11567         TrueFlag = GT;
11568         FalseFlag = LE;
11569       }
11570       if (Op == BO_GE || Op == BO_LE)
11571         std::swap(TrueFlag, FalseFlag);
11572     }
11573     if (R & TrueFlag)
11574       return StringRef("true");
11575     if (R & FalseFlag)
11576       return StringRef("false");
11577     return llvm::None;
11578   }
11579 };
11580 }
11581 
11582 static bool HasEnumType(Expr *E) {
11583   // Strip off implicit integral promotions.
11584   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
11585     if (ICE->getCastKind() != CK_IntegralCast &&
11586         ICE->getCastKind() != CK_NoOp)
11587       break;
11588     E = ICE->getSubExpr();
11589   }
11590 
11591   return E->getType()->isEnumeralType();
11592 }
11593 
11594 static int classifyConstantValue(Expr *Constant) {
11595   // The values of this enumeration are used in the diagnostics
11596   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
11597   enum ConstantValueKind {
11598     Miscellaneous = 0,
11599     LiteralTrue,
11600     LiteralFalse
11601   };
11602   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
11603     return BL->getValue() ? ConstantValueKind::LiteralTrue
11604                           : ConstantValueKind::LiteralFalse;
11605   return ConstantValueKind::Miscellaneous;
11606 }
11607 
11608 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
11609                                         Expr *Constant, Expr *Other,
11610                                         const llvm::APSInt &Value,
11611                                         bool RhsConstant) {
11612   if (S.inTemplateInstantiation())
11613     return false;
11614 
11615   Expr *OriginalOther = Other;
11616 
11617   Constant = Constant->IgnoreParenImpCasts();
11618   Other = Other->IgnoreParenImpCasts();
11619 
11620   // Suppress warnings on tautological comparisons between values of the same
11621   // enumeration type. There are only two ways we could warn on this:
11622   //  - If the constant is outside the range of representable values of
11623   //    the enumeration. In such a case, we should warn about the cast
11624   //    to enumeration type, not about the comparison.
11625   //  - If the constant is the maximum / minimum in-range value. For an
11626   //    enumeratin type, such comparisons can be meaningful and useful.
11627   if (Constant->getType()->isEnumeralType() &&
11628       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
11629     return false;
11630 
11631   IntRange OtherValueRange = GetExprRange(
11632       S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false);
11633 
11634   QualType OtherT = Other->getType();
11635   if (const auto *AT = OtherT->getAs<AtomicType>())
11636     OtherT = AT->getValueType();
11637   IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
11638 
11639   // Special case for ObjC BOOL on targets where its a typedef for a signed char
11640   // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
11641   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
11642                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
11643                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
11644 
11645   // Whether we're treating Other as being a bool because of the form of
11646   // expression despite it having another type (typically 'int' in C).
11647   bool OtherIsBooleanDespiteType =
11648       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
11649   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
11650     OtherTypeRange = OtherValueRange = IntRange::forBoolType();
11651 
11652   // Check if all values in the range of possible values of this expression
11653   // lead to the same comparison outcome.
11654   PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(),
11655                                         Value.isUnsigned());
11656   auto Cmp = OtherPromotedValueRange.compare(Value);
11657   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
11658   if (!Result)
11659     return false;
11660 
11661   // Also consider the range determined by the type alone. This allows us to
11662   // classify the warning under the proper diagnostic group.
11663   bool TautologicalTypeCompare = false;
11664   {
11665     PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
11666                                          Value.isUnsigned());
11667     auto TypeCmp = OtherPromotedTypeRange.compare(Value);
11668     if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
11669                                                        RhsConstant)) {
11670       TautologicalTypeCompare = true;
11671       Cmp = TypeCmp;
11672       Result = TypeResult;
11673     }
11674   }
11675 
11676   // Don't warn if the non-constant operand actually always evaluates to the
11677   // same value.
11678   if (!TautologicalTypeCompare && OtherValueRange.Width == 0)
11679     return false;
11680 
11681   // Suppress the diagnostic for an in-range comparison if the constant comes
11682   // from a macro or enumerator. We don't want to diagnose
11683   //
11684   //   some_long_value <= INT_MAX
11685   //
11686   // when sizeof(int) == sizeof(long).
11687   bool InRange = Cmp & PromotedRange::InRangeFlag;
11688   if (InRange && IsEnumConstOrFromMacro(S, Constant))
11689     return false;
11690 
11691   // A comparison of an unsigned bit-field against 0 is really a type problem,
11692   // even though at the type level the bit-field might promote to 'signed int'.
11693   if (Other->refersToBitField() && InRange && Value == 0 &&
11694       Other->getType()->isUnsignedIntegerOrEnumerationType())
11695     TautologicalTypeCompare = true;
11696 
11697   // If this is a comparison to an enum constant, include that
11698   // constant in the diagnostic.
11699   const EnumConstantDecl *ED = nullptr;
11700   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
11701     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
11702 
11703   // Should be enough for uint128 (39 decimal digits)
11704   SmallString<64> PrettySourceValue;
11705   llvm::raw_svector_ostream OS(PrettySourceValue);
11706   if (ED) {
11707     OS << '\'' << *ED << "' (" << Value << ")";
11708   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
11709                Constant->IgnoreParenImpCasts())) {
11710     OS << (BL->getValue() ? "YES" : "NO");
11711   } else {
11712     OS << Value;
11713   }
11714 
11715   if (!TautologicalTypeCompare) {
11716     S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
11717         << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative
11718         << E->getOpcodeStr() << OS.str() << *Result
11719         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11720     return true;
11721   }
11722 
11723   if (IsObjCSignedCharBool) {
11724     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
11725                           S.PDiag(diag::warn_tautological_compare_objc_bool)
11726                               << OS.str() << *Result);
11727     return true;
11728   }
11729 
11730   // FIXME: We use a somewhat different formatting for the in-range cases and
11731   // cases involving boolean values for historical reasons. We should pick a
11732   // consistent way of presenting these diagnostics.
11733   if (!InRange || Other->isKnownToHaveBooleanValue()) {
11734 
11735     S.DiagRuntimeBehavior(
11736         E->getOperatorLoc(), E,
11737         S.PDiag(!InRange ? diag::warn_out_of_range_compare
11738                          : diag::warn_tautological_bool_compare)
11739             << OS.str() << classifyConstantValue(Constant) << OtherT
11740             << OtherIsBooleanDespiteType << *Result
11741             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
11742   } else {
11743     bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
11744     unsigned Diag =
11745         (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
11746             ? (HasEnumType(OriginalOther)
11747                    ? diag::warn_unsigned_enum_always_true_comparison
11748                    : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
11749                               : diag::warn_unsigned_always_true_comparison)
11750             : diag::warn_tautological_constant_compare;
11751 
11752     S.Diag(E->getOperatorLoc(), Diag)
11753         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
11754         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11755   }
11756 
11757   return true;
11758 }
11759 
11760 /// Analyze the operands of the given comparison.  Implements the
11761 /// fallback case from AnalyzeComparison.
11762 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
11763   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11764   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11765 }
11766 
11767 /// Implements -Wsign-compare.
11768 ///
11769 /// \param E the binary operator to check for warnings
11770 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
11771   // The type the comparison is being performed in.
11772   QualType T = E->getLHS()->getType();
11773 
11774   // Only analyze comparison operators where both sides have been converted to
11775   // the same type.
11776   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
11777     return AnalyzeImpConvsInComparison(S, E);
11778 
11779   // Don't analyze value-dependent comparisons directly.
11780   if (E->isValueDependent())
11781     return AnalyzeImpConvsInComparison(S, E);
11782 
11783   Expr *LHS = E->getLHS();
11784   Expr *RHS = E->getRHS();
11785 
11786   if (T->isIntegralType(S.Context)) {
11787     Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context);
11788     Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context);
11789 
11790     // We don't care about expressions whose result is a constant.
11791     if (RHSValue && LHSValue)
11792       return AnalyzeImpConvsInComparison(S, E);
11793 
11794     // We only care about expressions where just one side is literal
11795     if ((bool)RHSValue ^ (bool)LHSValue) {
11796       // Is the constant on the RHS or LHS?
11797       const bool RhsConstant = (bool)RHSValue;
11798       Expr *Const = RhsConstant ? RHS : LHS;
11799       Expr *Other = RhsConstant ? LHS : RHS;
11800       const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
11801 
11802       // Check whether an integer constant comparison results in a value
11803       // of 'true' or 'false'.
11804       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
11805         return AnalyzeImpConvsInComparison(S, E);
11806     }
11807   }
11808 
11809   if (!T->hasUnsignedIntegerRepresentation()) {
11810     // We don't do anything special if this isn't an unsigned integral
11811     // comparison:  we're only interested in integral comparisons, and
11812     // signed comparisons only happen in cases we don't care to warn about.
11813     return AnalyzeImpConvsInComparison(S, E);
11814   }
11815 
11816   LHS = LHS->IgnoreParenImpCasts();
11817   RHS = RHS->IgnoreParenImpCasts();
11818 
11819   if (!S.getLangOpts().CPlusPlus) {
11820     // Avoid warning about comparison of integers with different signs when
11821     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
11822     // the type of `E`.
11823     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
11824       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11825     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
11826       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11827   }
11828 
11829   // Check to see if one of the (unmodified) operands is of different
11830   // signedness.
11831   Expr *signedOperand, *unsignedOperand;
11832   if (LHS->getType()->hasSignedIntegerRepresentation()) {
11833     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
11834            "unsigned comparison between two signed integer expressions?");
11835     signedOperand = LHS;
11836     unsignedOperand = RHS;
11837   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
11838     signedOperand = RHS;
11839     unsignedOperand = LHS;
11840   } else {
11841     return AnalyzeImpConvsInComparison(S, E);
11842   }
11843 
11844   // Otherwise, calculate the effective range of the signed operand.
11845   IntRange signedRange = GetExprRange(
11846       S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true);
11847 
11848   // Go ahead and analyze implicit conversions in the operands.  Note
11849   // that we skip the implicit conversions on both sides.
11850   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
11851   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
11852 
11853   // If the signed range is non-negative, -Wsign-compare won't fire.
11854   if (signedRange.NonNegative)
11855     return;
11856 
11857   // For (in)equality comparisons, if the unsigned operand is a
11858   // constant which cannot collide with a overflowed signed operand,
11859   // then reinterpreting the signed operand as unsigned will not
11860   // change the result of the comparison.
11861   if (E->isEqualityOp()) {
11862     unsigned comparisonWidth = S.Context.getIntWidth(T);
11863     IntRange unsignedRange =
11864         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(),
11865                      /*Approximate*/ true);
11866 
11867     // We should never be unable to prove that the unsigned operand is
11868     // non-negative.
11869     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
11870 
11871     if (unsignedRange.Width < comparisonWidth)
11872       return;
11873   }
11874 
11875   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
11876                         S.PDiag(diag::warn_mixed_sign_comparison)
11877                             << LHS->getType() << RHS->getType()
11878                             << LHS->getSourceRange() << RHS->getSourceRange());
11879 }
11880 
11881 /// Analyzes an attempt to assign the given value to a bitfield.
11882 ///
11883 /// Returns true if there was something fishy about the attempt.
11884 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
11885                                       SourceLocation InitLoc) {
11886   assert(Bitfield->isBitField());
11887   if (Bitfield->isInvalidDecl())
11888     return false;
11889 
11890   // White-list bool bitfields.
11891   QualType BitfieldType = Bitfield->getType();
11892   if (BitfieldType->isBooleanType())
11893      return false;
11894 
11895   if (BitfieldType->isEnumeralType()) {
11896     EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
11897     // If the underlying enum type was not explicitly specified as an unsigned
11898     // type and the enum contain only positive values, MSVC++ will cause an
11899     // inconsistency by storing this as a signed type.
11900     if (S.getLangOpts().CPlusPlus11 &&
11901         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
11902         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
11903         BitfieldEnumDecl->getNumNegativeBits() == 0) {
11904       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
11905           << BitfieldEnumDecl;
11906     }
11907   }
11908 
11909   if (Bitfield->getType()->isBooleanType())
11910     return false;
11911 
11912   // Ignore value- or type-dependent expressions.
11913   if (Bitfield->getBitWidth()->isValueDependent() ||
11914       Bitfield->getBitWidth()->isTypeDependent() ||
11915       Init->isValueDependent() ||
11916       Init->isTypeDependent())
11917     return false;
11918 
11919   Expr *OriginalInit = Init->IgnoreParenImpCasts();
11920   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
11921 
11922   Expr::EvalResult Result;
11923   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
11924                                    Expr::SE_AllowSideEffects)) {
11925     // The RHS is not constant.  If the RHS has an enum type, make sure the
11926     // bitfield is wide enough to hold all the values of the enum without
11927     // truncation.
11928     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
11929       EnumDecl *ED = EnumTy->getDecl();
11930       bool SignedBitfield = BitfieldType->isSignedIntegerType();
11931 
11932       // Enum types are implicitly signed on Windows, so check if there are any
11933       // negative enumerators to see if the enum was intended to be signed or
11934       // not.
11935       bool SignedEnum = ED->getNumNegativeBits() > 0;
11936 
11937       // Check for surprising sign changes when assigning enum values to a
11938       // bitfield of different signedness.  If the bitfield is signed and we
11939       // have exactly the right number of bits to store this unsigned enum,
11940       // suggest changing the enum to an unsigned type. This typically happens
11941       // on Windows where unfixed enums always use an underlying type of 'int'.
11942       unsigned DiagID = 0;
11943       if (SignedEnum && !SignedBitfield) {
11944         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
11945       } else if (SignedBitfield && !SignedEnum &&
11946                  ED->getNumPositiveBits() == FieldWidth) {
11947         DiagID = diag::warn_signed_bitfield_enum_conversion;
11948       }
11949 
11950       if (DiagID) {
11951         S.Diag(InitLoc, DiagID) << Bitfield << ED;
11952         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
11953         SourceRange TypeRange =
11954             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
11955         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
11956             << SignedEnum << TypeRange;
11957       }
11958 
11959       // Compute the required bitwidth. If the enum has negative values, we need
11960       // one more bit than the normal number of positive bits to represent the
11961       // sign bit.
11962       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
11963                                                   ED->getNumNegativeBits())
11964                                        : ED->getNumPositiveBits();
11965 
11966       // Check the bitwidth.
11967       if (BitsNeeded > FieldWidth) {
11968         Expr *WidthExpr = Bitfield->getBitWidth();
11969         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
11970             << Bitfield << ED;
11971         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
11972             << BitsNeeded << ED << WidthExpr->getSourceRange();
11973       }
11974     }
11975 
11976     return false;
11977   }
11978 
11979   llvm::APSInt Value = Result.Val.getInt();
11980 
11981   unsigned OriginalWidth = Value.getBitWidth();
11982 
11983   if (!Value.isSigned() || Value.isNegative())
11984     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
11985       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
11986         OriginalWidth = Value.getMinSignedBits();
11987 
11988   if (OriginalWidth <= FieldWidth)
11989     return false;
11990 
11991   // Compute the value which the bitfield will contain.
11992   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
11993   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
11994 
11995   // Check whether the stored value is equal to the original value.
11996   TruncatedValue = TruncatedValue.extend(OriginalWidth);
11997   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
11998     return false;
11999 
12000   // Special-case bitfields of width 1: booleans are naturally 0/1, and
12001   // therefore don't strictly fit into a signed bitfield of width 1.
12002   if (FieldWidth == 1 && Value == 1)
12003     return false;
12004 
12005   std::string PrettyValue = toString(Value, 10);
12006   std::string PrettyTrunc = toString(TruncatedValue, 10);
12007 
12008   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
12009     << PrettyValue << PrettyTrunc << OriginalInit->getType()
12010     << Init->getSourceRange();
12011 
12012   return true;
12013 }
12014 
12015 /// Analyze the given simple or compound assignment for warning-worthy
12016 /// operations.
12017 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
12018   // Just recurse on the LHS.
12019   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12020 
12021   // We want to recurse on the RHS as normal unless we're assigning to
12022   // a bitfield.
12023   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
12024     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
12025                                   E->getOperatorLoc())) {
12026       // Recurse, ignoring any implicit conversions on the RHS.
12027       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
12028                                         E->getOperatorLoc());
12029     }
12030   }
12031 
12032   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12033 
12034   // Diagnose implicitly sequentially-consistent atomic assignment.
12035   if (E->getLHS()->getType()->isAtomicType())
12036     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12037 }
12038 
12039 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
12040 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
12041                             SourceLocation CContext, unsigned diag,
12042                             bool pruneControlFlow = false) {
12043   if (pruneControlFlow) {
12044     S.DiagRuntimeBehavior(E->getExprLoc(), E,
12045                           S.PDiag(diag)
12046                               << SourceType << T << E->getSourceRange()
12047                               << SourceRange(CContext));
12048     return;
12049   }
12050   S.Diag(E->getExprLoc(), diag)
12051     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
12052 }
12053 
12054 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
12055 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
12056                             SourceLocation CContext,
12057                             unsigned diag, bool pruneControlFlow = false) {
12058   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
12059 }
12060 
12061 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
12062   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
12063       S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
12064 }
12065 
12066 static void adornObjCBoolConversionDiagWithTernaryFixit(
12067     Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
12068   Expr *Ignored = SourceExpr->IgnoreImplicit();
12069   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
12070     Ignored = OVE->getSourceExpr();
12071   bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
12072                      isa<BinaryOperator>(Ignored) ||
12073                      isa<CXXOperatorCallExpr>(Ignored);
12074   SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
12075   if (NeedsParens)
12076     Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
12077             << FixItHint::CreateInsertion(EndLoc, ")");
12078   Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
12079 }
12080 
12081 /// Diagnose an implicit cast from a floating point value to an integer value.
12082 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
12083                                     SourceLocation CContext) {
12084   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
12085   const bool PruneWarnings = S.inTemplateInstantiation();
12086 
12087   Expr *InnerE = E->IgnoreParenImpCasts();
12088   // We also want to warn on, e.g., "int i = -1.234"
12089   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
12090     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
12091       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
12092 
12093   const bool IsLiteral =
12094       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
12095 
12096   llvm::APFloat Value(0.0);
12097   bool IsConstant =
12098     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
12099   if (!IsConstant) {
12100     if (isObjCSignedCharBool(S, T)) {
12101       return adornObjCBoolConversionDiagWithTernaryFixit(
12102           S, E,
12103           S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
12104               << E->getType());
12105     }
12106 
12107     return DiagnoseImpCast(S, E, T, CContext,
12108                            diag::warn_impcast_float_integer, PruneWarnings);
12109   }
12110 
12111   bool isExact = false;
12112 
12113   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
12114                             T->hasUnsignedIntegerRepresentation());
12115   llvm::APFloat::opStatus Result = Value.convertToInteger(
12116       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
12117 
12118   // FIXME: Force the precision of the source value down so we don't print
12119   // digits which are usually useless (we don't really care here if we
12120   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
12121   // would automatically print the shortest representation, but it's a bit
12122   // tricky to implement.
12123   SmallString<16> PrettySourceValue;
12124   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
12125   precision = (precision * 59 + 195) / 196;
12126   Value.toString(PrettySourceValue, precision);
12127 
12128   if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
12129     return adornObjCBoolConversionDiagWithTernaryFixit(
12130         S, E,
12131         S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
12132             << PrettySourceValue);
12133   }
12134 
12135   if (Result == llvm::APFloat::opOK && isExact) {
12136     if (IsLiteral) return;
12137     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
12138                            PruneWarnings);
12139   }
12140 
12141   // Conversion of a floating-point value to a non-bool integer where the
12142   // integral part cannot be represented by the integer type is undefined.
12143   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
12144     return DiagnoseImpCast(
12145         S, E, T, CContext,
12146         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
12147                   : diag::warn_impcast_float_to_integer_out_of_range,
12148         PruneWarnings);
12149 
12150   unsigned DiagID = 0;
12151   if (IsLiteral) {
12152     // Warn on floating point literal to integer.
12153     DiagID = diag::warn_impcast_literal_float_to_integer;
12154   } else if (IntegerValue == 0) {
12155     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
12156       return DiagnoseImpCast(S, E, T, CContext,
12157                              diag::warn_impcast_float_integer, PruneWarnings);
12158     }
12159     // Warn on non-zero to zero conversion.
12160     DiagID = diag::warn_impcast_float_to_integer_zero;
12161   } else {
12162     if (IntegerValue.isUnsigned()) {
12163       if (!IntegerValue.isMaxValue()) {
12164         return DiagnoseImpCast(S, E, T, CContext,
12165                                diag::warn_impcast_float_integer, PruneWarnings);
12166       }
12167     } else {  // IntegerValue.isSigned()
12168       if (!IntegerValue.isMaxSignedValue() &&
12169           !IntegerValue.isMinSignedValue()) {
12170         return DiagnoseImpCast(S, E, T, CContext,
12171                                diag::warn_impcast_float_integer, PruneWarnings);
12172       }
12173     }
12174     // Warn on evaluatable floating point expression to integer conversion.
12175     DiagID = diag::warn_impcast_float_to_integer;
12176   }
12177 
12178   SmallString<16> PrettyTargetValue;
12179   if (IsBool)
12180     PrettyTargetValue = Value.isZero() ? "false" : "true";
12181   else
12182     IntegerValue.toString(PrettyTargetValue);
12183 
12184   if (PruneWarnings) {
12185     S.DiagRuntimeBehavior(E->getExprLoc(), E,
12186                           S.PDiag(DiagID)
12187                               << E->getType() << T.getUnqualifiedType()
12188                               << PrettySourceValue << PrettyTargetValue
12189                               << E->getSourceRange() << SourceRange(CContext));
12190   } else {
12191     S.Diag(E->getExprLoc(), DiagID)
12192         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
12193         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
12194   }
12195 }
12196 
12197 /// Analyze the given compound assignment for the possible losing of
12198 /// floating-point precision.
12199 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
12200   assert(isa<CompoundAssignOperator>(E) &&
12201          "Must be compound assignment operation");
12202   // Recurse on the LHS and RHS in here
12203   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12204   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12205 
12206   if (E->getLHS()->getType()->isAtomicType())
12207     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
12208 
12209   // Now check the outermost expression
12210   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
12211   const auto *RBT = cast<CompoundAssignOperator>(E)
12212                         ->getComputationResultType()
12213                         ->getAs<BuiltinType>();
12214 
12215   // The below checks assume source is floating point.
12216   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
12217 
12218   // If source is floating point but target is an integer.
12219   if (ResultBT->isInteger())
12220     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
12221                            E->getExprLoc(), diag::warn_impcast_float_integer);
12222 
12223   if (!ResultBT->isFloatingPoint())
12224     return;
12225 
12226   // If both source and target are floating points, warn about losing precision.
12227   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12228       QualType(ResultBT, 0), QualType(RBT, 0));
12229   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
12230     // warn about dropping FP rank.
12231     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
12232                     diag::warn_impcast_float_result_precision);
12233 }
12234 
12235 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
12236                                       IntRange Range) {
12237   if (!Range.Width) return "0";
12238 
12239   llvm::APSInt ValueInRange = Value;
12240   ValueInRange.setIsSigned(!Range.NonNegative);
12241   ValueInRange = ValueInRange.trunc(Range.Width);
12242   return toString(ValueInRange, 10);
12243 }
12244 
12245 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
12246   if (!isa<ImplicitCastExpr>(Ex))
12247     return false;
12248 
12249   Expr *InnerE = Ex->IgnoreParenImpCasts();
12250   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
12251   const Type *Source =
12252     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
12253   if (Target->isDependentType())
12254     return false;
12255 
12256   const BuiltinType *FloatCandidateBT =
12257     dyn_cast<BuiltinType>(ToBool ? Source : Target);
12258   const Type *BoolCandidateType = ToBool ? Target : Source;
12259 
12260   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
12261           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
12262 }
12263 
12264 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
12265                                              SourceLocation CC) {
12266   unsigned NumArgs = TheCall->getNumArgs();
12267   for (unsigned i = 0; i < NumArgs; ++i) {
12268     Expr *CurrA = TheCall->getArg(i);
12269     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
12270       continue;
12271 
12272     bool IsSwapped = ((i > 0) &&
12273         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
12274     IsSwapped |= ((i < (NumArgs - 1)) &&
12275         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
12276     if (IsSwapped) {
12277       // Warn on this floating-point to bool conversion.
12278       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
12279                       CurrA->getType(), CC,
12280                       diag::warn_impcast_floating_point_to_bool);
12281     }
12282   }
12283 }
12284 
12285 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
12286                                    SourceLocation CC) {
12287   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
12288                         E->getExprLoc()))
12289     return;
12290 
12291   // Don't warn on functions which have return type nullptr_t.
12292   if (isa<CallExpr>(E))
12293     return;
12294 
12295   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
12296   const Expr::NullPointerConstantKind NullKind =
12297       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
12298   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
12299     return;
12300 
12301   // Return if target type is a safe conversion.
12302   if (T->isAnyPointerType() || T->isBlockPointerType() ||
12303       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
12304     return;
12305 
12306   SourceLocation Loc = E->getSourceRange().getBegin();
12307 
12308   // Venture through the macro stacks to get to the source of macro arguments.
12309   // The new location is a better location than the complete location that was
12310   // passed in.
12311   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
12312   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
12313 
12314   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
12315   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
12316     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
12317         Loc, S.SourceMgr, S.getLangOpts());
12318     if (MacroName == "NULL")
12319       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
12320   }
12321 
12322   // Only warn if the null and context location are in the same macro expansion.
12323   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
12324     return;
12325 
12326   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
12327       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
12328       << FixItHint::CreateReplacement(Loc,
12329                                       S.getFixItZeroLiteralForType(T, Loc));
12330 }
12331 
12332 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12333                                   ObjCArrayLiteral *ArrayLiteral);
12334 
12335 static void
12336 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12337                            ObjCDictionaryLiteral *DictionaryLiteral);
12338 
12339 /// Check a single element within a collection literal against the
12340 /// target element type.
12341 static void checkObjCCollectionLiteralElement(Sema &S,
12342                                               QualType TargetElementType,
12343                                               Expr *Element,
12344                                               unsigned ElementKind) {
12345   // Skip a bitcast to 'id' or qualified 'id'.
12346   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
12347     if (ICE->getCastKind() == CK_BitCast &&
12348         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
12349       Element = ICE->getSubExpr();
12350   }
12351 
12352   QualType ElementType = Element->getType();
12353   ExprResult ElementResult(Element);
12354   if (ElementType->getAs<ObjCObjectPointerType>() &&
12355       S.CheckSingleAssignmentConstraints(TargetElementType,
12356                                          ElementResult,
12357                                          false, false)
12358         != Sema::Compatible) {
12359     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
12360         << ElementType << ElementKind << TargetElementType
12361         << Element->getSourceRange();
12362   }
12363 
12364   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
12365     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
12366   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
12367     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
12368 }
12369 
12370 /// Check an Objective-C array literal being converted to the given
12371 /// target type.
12372 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12373                                   ObjCArrayLiteral *ArrayLiteral) {
12374   if (!S.NSArrayDecl)
12375     return;
12376 
12377   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12378   if (!TargetObjCPtr)
12379     return;
12380 
12381   if (TargetObjCPtr->isUnspecialized() ||
12382       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12383         != S.NSArrayDecl->getCanonicalDecl())
12384     return;
12385 
12386   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12387   if (TypeArgs.size() != 1)
12388     return;
12389 
12390   QualType TargetElementType = TypeArgs[0];
12391   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
12392     checkObjCCollectionLiteralElement(S, TargetElementType,
12393                                       ArrayLiteral->getElement(I),
12394                                       0);
12395   }
12396 }
12397 
12398 /// Check an Objective-C dictionary literal being converted to the given
12399 /// target type.
12400 static void
12401 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12402                            ObjCDictionaryLiteral *DictionaryLiteral) {
12403   if (!S.NSDictionaryDecl)
12404     return;
12405 
12406   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12407   if (!TargetObjCPtr)
12408     return;
12409 
12410   if (TargetObjCPtr->isUnspecialized() ||
12411       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12412         != S.NSDictionaryDecl->getCanonicalDecl())
12413     return;
12414 
12415   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12416   if (TypeArgs.size() != 2)
12417     return;
12418 
12419   QualType TargetKeyType = TypeArgs[0];
12420   QualType TargetObjectType = TypeArgs[1];
12421   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
12422     auto Element = DictionaryLiteral->getKeyValueElement(I);
12423     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
12424     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
12425   }
12426 }
12427 
12428 // Helper function to filter out cases for constant width constant conversion.
12429 // Don't warn on char array initialization or for non-decimal values.
12430 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
12431                                           SourceLocation CC) {
12432   // If initializing from a constant, and the constant starts with '0',
12433   // then it is a binary, octal, or hexadecimal.  Allow these constants
12434   // to fill all the bits, even if there is a sign change.
12435   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
12436     const char FirstLiteralCharacter =
12437         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
12438     if (FirstLiteralCharacter == '0')
12439       return false;
12440   }
12441 
12442   // If the CC location points to a '{', and the type is char, then assume
12443   // assume it is an array initialization.
12444   if (CC.isValid() && T->isCharType()) {
12445     const char FirstContextCharacter =
12446         S.getSourceManager().getCharacterData(CC)[0];
12447     if (FirstContextCharacter == '{')
12448       return false;
12449   }
12450 
12451   return true;
12452 }
12453 
12454 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
12455   const auto *IL = dyn_cast<IntegerLiteral>(E);
12456   if (!IL) {
12457     if (auto *UO = dyn_cast<UnaryOperator>(E)) {
12458       if (UO->getOpcode() == UO_Minus)
12459         return dyn_cast<IntegerLiteral>(UO->getSubExpr());
12460     }
12461   }
12462 
12463   return IL;
12464 }
12465 
12466 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
12467   E = E->IgnoreParenImpCasts();
12468   SourceLocation ExprLoc = E->getExprLoc();
12469 
12470   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
12471     BinaryOperator::Opcode Opc = BO->getOpcode();
12472     Expr::EvalResult Result;
12473     // Do not diagnose unsigned shifts.
12474     if (Opc == BO_Shl) {
12475       const auto *LHS = getIntegerLiteral(BO->getLHS());
12476       const auto *RHS = getIntegerLiteral(BO->getRHS());
12477       if (LHS && LHS->getValue() == 0)
12478         S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
12479       else if (!E->isValueDependent() && LHS && RHS &&
12480                RHS->getValue().isNonNegative() &&
12481                E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
12482         S.Diag(ExprLoc, diag::warn_left_shift_always)
12483             << (Result.Val.getInt() != 0);
12484       else if (E->getType()->isSignedIntegerType())
12485         S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
12486     }
12487   }
12488 
12489   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
12490     const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
12491     const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
12492     if (!LHS || !RHS)
12493       return;
12494     if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
12495         (RHS->getValue() == 0 || RHS->getValue() == 1))
12496       // Do not diagnose common idioms.
12497       return;
12498     if (LHS->getValue() != 0 && RHS->getValue() != 0)
12499       S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
12500   }
12501 }
12502 
12503 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
12504                                     SourceLocation CC,
12505                                     bool *ICContext = nullptr,
12506                                     bool IsListInit = false) {
12507   if (E->isTypeDependent() || E->isValueDependent()) return;
12508 
12509   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
12510   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
12511   if (Source == Target) return;
12512   if (Target->isDependentType()) return;
12513 
12514   // If the conversion context location is invalid don't complain. We also
12515   // don't want to emit a warning if the issue occurs from the expansion of
12516   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
12517   // delay this check as long as possible. Once we detect we are in that
12518   // scenario, we just return.
12519   if (CC.isInvalid())
12520     return;
12521 
12522   if (Source->isAtomicType())
12523     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
12524 
12525   // Diagnose implicit casts to bool.
12526   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
12527     if (isa<StringLiteral>(E))
12528       // Warn on string literal to bool.  Checks for string literals in logical
12529       // and expressions, for instance, assert(0 && "error here"), are
12530       // prevented by a check in AnalyzeImplicitConversions().
12531       return DiagnoseImpCast(S, E, T, CC,
12532                              diag::warn_impcast_string_literal_to_bool);
12533     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
12534         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
12535       // This covers the literal expressions that evaluate to Objective-C
12536       // objects.
12537       return DiagnoseImpCast(S, E, T, CC,
12538                              diag::warn_impcast_objective_c_literal_to_bool);
12539     }
12540     if (Source->isPointerType() || Source->canDecayToPointerType()) {
12541       // Warn on pointer to bool conversion that is always true.
12542       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
12543                                      SourceRange(CC));
12544     }
12545   }
12546 
12547   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
12548   // is a typedef for signed char (macOS), then that constant value has to be 1
12549   // or 0.
12550   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
12551     Expr::EvalResult Result;
12552     if (E->EvaluateAsInt(Result, S.getASTContext(),
12553                          Expr::SE_AllowSideEffects)) {
12554       if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
12555         adornObjCBoolConversionDiagWithTernaryFixit(
12556             S, E,
12557             S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
12558                 << toString(Result.Val.getInt(), 10));
12559       }
12560       return;
12561     }
12562   }
12563 
12564   // Check implicit casts from Objective-C collection literals to specialized
12565   // collection types, e.g., NSArray<NSString *> *.
12566   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
12567     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
12568   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
12569     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
12570 
12571   // Strip vector types.
12572   if (isa<VectorType>(Source)) {
12573     if (Target->isVLSTBuiltinType() &&
12574         (S.Context.areCompatibleSveTypes(QualType(Target, 0),
12575                                          QualType(Source, 0)) ||
12576          S.Context.areLaxCompatibleSveTypes(QualType(Target, 0),
12577                                             QualType(Source, 0))))
12578       return;
12579 
12580     if (!isa<VectorType>(Target)) {
12581       if (S.SourceMgr.isInSystemMacro(CC))
12582         return;
12583       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
12584     }
12585 
12586     // If the vector cast is cast between two vectors of the same size, it is
12587     // a bitcast, not a conversion.
12588     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
12589       return;
12590 
12591     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
12592     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
12593   }
12594   if (auto VecTy = dyn_cast<VectorType>(Target))
12595     Target = VecTy->getElementType().getTypePtr();
12596 
12597   // Strip complex types.
12598   if (isa<ComplexType>(Source)) {
12599     if (!isa<ComplexType>(Target)) {
12600       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
12601         return;
12602 
12603       return DiagnoseImpCast(S, E, T, CC,
12604                              S.getLangOpts().CPlusPlus
12605                                  ? diag::err_impcast_complex_scalar
12606                                  : diag::warn_impcast_complex_scalar);
12607     }
12608 
12609     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
12610     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
12611   }
12612 
12613   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
12614   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
12615 
12616   // If the source is floating point...
12617   if (SourceBT && SourceBT->isFloatingPoint()) {
12618     // ...and the target is floating point...
12619     if (TargetBT && TargetBT->isFloatingPoint()) {
12620       // ...then warn if we're dropping FP rank.
12621 
12622       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12623           QualType(SourceBT, 0), QualType(TargetBT, 0));
12624       if (Order > 0) {
12625         // Don't warn about float constants that are precisely
12626         // representable in the target type.
12627         Expr::EvalResult result;
12628         if (E->EvaluateAsRValue(result, S.Context)) {
12629           // Value might be a float, a float vector, or a float complex.
12630           if (IsSameFloatAfterCast(result.Val,
12631                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
12632                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
12633             return;
12634         }
12635 
12636         if (S.SourceMgr.isInSystemMacro(CC))
12637           return;
12638 
12639         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
12640       }
12641       // ... or possibly if we're increasing rank, too
12642       else if (Order < 0) {
12643         if (S.SourceMgr.isInSystemMacro(CC))
12644           return;
12645 
12646         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
12647       }
12648       return;
12649     }
12650 
12651     // If the target is integral, always warn.
12652     if (TargetBT && TargetBT->isInteger()) {
12653       if (S.SourceMgr.isInSystemMacro(CC))
12654         return;
12655 
12656       DiagnoseFloatingImpCast(S, E, T, CC);
12657     }
12658 
12659     // Detect the case where a call result is converted from floating-point to
12660     // to bool, and the final argument to the call is converted from bool, to
12661     // discover this typo:
12662     //
12663     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
12664     //
12665     // FIXME: This is an incredibly special case; is there some more general
12666     // way to detect this class of misplaced-parentheses bug?
12667     if (Target->isBooleanType() && isa<CallExpr>(E)) {
12668       // Check last argument of function call to see if it is an
12669       // implicit cast from a type matching the type the result
12670       // is being cast to.
12671       CallExpr *CEx = cast<CallExpr>(E);
12672       if (unsigned NumArgs = CEx->getNumArgs()) {
12673         Expr *LastA = CEx->getArg(NumArgs - 1);
12674         Expr *InnerE = LastA->IgnoreParenImpCasts();
12675         if (isa<ImplicitCastExpr>(LastA) &&
12676             InnerE->getType()->isBooleanType()) {
12677           // Warn on this floating-point to bool conversion
12678           DiagnoseImpCast(S, E, T, CC,
12679                           diag::warn_impcast_floating_point_to_bool);
12680         }
12681       }
12682     }
12683     return;
12684   }
12685 
12686   // Valid casts involving fixed point types should be accounted for here.
12687   if (Source->isFixedPointType()) {
12688     if (Target->isUnsaturatedFixedPointType()) {
12689       Expr::EvalResult Result;
12690       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
12691                                   S.isConstantEvaluated())) {
12692         llvm::APFixedPoint Value = Result.Val.getFixedPoint();
12693         llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
12694         llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T);
12695         if (Value > MaxVal || Value < MinVal) {
12696           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12697                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12698                                     << Value.toString() << T
12699                                     << E->getSourceRange()
12700                                     << clang::SourceRange(CC));
12701           return;
12702         }
12703       }
12704     } else if (Target->isIntegerType()) {
12705       Expr::EvalResult Result;
12706       if (!S.isConstantEvaluated() &&
12707           E->EvaluateAsFixedPoint(Result, S.Context,
12708                                   Expr::SE_AllowSideEffects)) {
12709         llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
12710 
12711         bool Overflowed;
12712         llvm::APSInt IntResult = FXResult.convertToInt(
12713             S.Context.getIntWidth(T),
12714             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
12715 
12716         if (Overflowed) {
12717           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12718                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12719                                     << FXResult.toString() << T
12720                                     << E->getSourceRange()
12721                                     << clang::SourceRange(CC));
12722           return;
12723         }
12724       }
12725     }
12726   } else if (Target->isUnsaturatedFixedPointType()) {
12727     if (Source->isIntegerType()) {
12728       Expr::EvalResult Result;
12729       if (!S.isConstantEvaluated() &&
12730           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
12731         llvm::APSInt Value = Result.Val.getInt();
12732 
12733         bool Overflowed;
12734         llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
12735             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
12736 
12737         if (Overflowed) {
12738           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12739                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12740                                     << toString(Value, /*Radix=*/10) << T
12741                                     << E->getSourceRange()
12742                                     << clang::SourceRange(CC));
12743           return;
12744         }
12745       }
12746     }
12747   }
12748 
12749   // If we are casting an integer type to a floating point type without
12750   // initialization-list syntax, we might lose accuracy if the floating
12751   // point type has a narrower significand than the integer type.
12752   if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
12753       TargetBT->isFloatingType() && !IsListInit) {
12754     // Determine the number of precision bits in the source integer type.
12755     IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(),
12756                                         /*Approximate*/ true);
12757     unsigned int SourcePrecision = SourceRange.Width;
12758 
12759     // Determine the number of precision bits in the
12760     // target floating point type.
12761     unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
12762         S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12763 
12764     if (SourcePrecision > 0 && TargetPrecision > 0 &&
12765         SourcePrecision > TargetPrecision) {
12766 
12767       if (Optional<llvm::APSInt> SourceInt =
12768               E->getIntegerConstantExpr(S.Context)) {
12769         // If the source integer is a constant, convert it to the target
12770         // floating point type. Issue a warning if the value changes
12771         // during the whole conversion.
12772         llvm::APFloat TargetFloatValue(
12773             S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12774         llvm::APFloat::opStatus ConversionStatus =
12775             TargetFloatValue.convertFromAPInt(
12776                 *SourceInt, SourceBT->isSignedInteger(),
12777                 llvm::APFloat::rmNearestTiesToEven);
12778 
12779         if (ConversionStatus != llvm::APFloat::opOK) {
12780           SmallString<32> PrettySourceValue;
12781           SourceInt->toString(PrettySourceValue, 10);
12782           SmallString<32> PrettyTargetValue;
12783           TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
12784 
12785           S.DiagRuntimeBehavior(
12786               E->getExprLoc(), E,
12787               S.PDiag(diag::warn_impcast_integer_float_precision_constant)
12788                   << PrettySourceValue << PrettyTargetValue << E->getType() << T
12789                   << E->getSourceRange() << clang::SourceRange(CC));
12790         }
12791       } else {
12792         // Otherwise, the implicit conversion may lose precision.
12793         DiagnoseImpCast(S, E, T, CC,
12794                         diag::warn_impcast_integer_float_precision);
12795       }
12796     }
12797   }
12798 
12799   DiagnoseNullConversion(S, E, T, CC);
12800 
12801   S.DiscardMisalignedMemberAddress(Target, E);
12802 
12803   if (Target->isBooleanType())
12804     DiagnoseIntInBoolContext(S, E);
12805 
12806   if (!Source->isIntegerType() || !Target->isIntegerType())
12807     return;
12808 
12809   // TODO: remove this early return once the false positives for constant->bool
12810   // in templates, macros, etc, are reduced or removed.
12811   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
12812     return;
12813 
12814   if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
12815       !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
12816     return adornObjCBoolConversionDiagWithTernaryFixit(
12817         S, E,
12818         S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
12819             << E->getType());
12820   }
12821 
12822   IntRange SourceTypeRange =
12823       IntRange::forTargetOfCanonicalType(S.Context, Source);
12824   IntRange LikelySourceRange =
12825       GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true);
12826   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
12827 
12828   if (LikelySourceRange.Width > TargetRange.Width) {
12829     // If the source is a constant, use a default-on diagnostic.
12830     // TODO: this should happen for bitfield stores, too.
12831     Expr::EvalResult Result;
12832     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
12833                          S.isConstantEvaluated())) {
12834       llvm::APSInt Value(32);
12835       Value = Result.Val.getInt();
12836 
12837       if (S.SourceMgr.isInSystemMacro(CC))
12838         return;
12839 
12840       std::string PrettySourceValue = toString(Value, 10);
12841       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
12842 
12843       S.DiagRuntimeBehavior(
12844           E->getExprLoc(), E,
12845           S.PDiag(diag::warn_impcast_integer_precision_constant)
12846               << PrettySourceValue << PrettyTargetValue << E->getType() << T
12847               << E->getSourceRange() << SourceRange(CC));
12848       return;
12849     }
12850 
12851     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
12852     if (S.SourceMgr.isInSystemMacro(CC))
12853       return;
12854 
12855     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
12856       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
12857                              /* pruneControlFlow */ true);
12858     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
12859   }
12860 
12861   if (TargetRange.Width > SourceTypeRange.Width) {
12862     if (auto *UO = dyn_cast<UnaryOperator>(E))
12863       if (UO->getOpcode() == UO_Minus)
12864         if (Source->isUnsignedIntegerType()) {
12865           if (Target->isUnsignedIntegerType())
12866             return DiagnoseImpCast(S, E, T, CC,
12867                                    diag::warn_impcast_high_order_zero_bits);
12868           if (Target->isSignedIntegerType())
12869             return DiagnoseImpCast(S, E, T, CC,
12870                                    diag::warn_impcast_nonnegative_result);
12871         }
12872   }
12873 
12874   if (TargetRange.Width == LikelySourceRange.Width &&
12875       !TargetRange.NonNegative && LikelySourceRange.NonNegative &&
12876       Source->isSignedIntegerType()) {
12877     // Warn when doing a signed to signed conversion, warn if the positive
12878     // source value is exactly the width of the target type, which will
12879     // cause a negative value to be stored.
12880 
12881     Expr::EvalResult Result;
12882     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
12883         !S.SourceMgr.isInSystemMacro(CC)) {
12884       llvm::APSInt Value = Result.Val.getInt();
12885       if (isSameWidthConstantConversion(S, E, T, CC)) {
12886         std::string PrettySourceValue = toString(Value, 10);
12887         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
12888 
12889         S.DiagRuntimeBehavior(
12890             E->getExprLoc(), E,
12891             S.PDiag(diag::warn_impcast_integer_precision_constant)
12892                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
12893                 << E->getSourceRange() << SourceRange(CC));
12894         return;
12895       }
12896     }
12897 
12898     // Fall through for non-constants to give a sign conversion warning.
12899   }
12900 
12901   if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) ||
12902       (!TargetRange.NonNegative && LikelySourceRange.NonNegative &&
12903        LikelySourceRange.Width == TargetRange.Width)) {
12904     if (S.SourceMgr.isInSystemMacro(CC))
12905       return;
12906 
12907     unsigned DiagID = diag::warn_impcast_integer_sign;
12908 
12909     // Traditionally, gcc has warned about this under -Wsign-compare.
12910     // We also want to warn about it in -Wconversion.
12911     // So if -Wconversion is off, use a completely identical diagnostic
12912     // in the sign-compare group.
12913     // The conditional-checking code will
12914     if (ICContext) {
12915       DiagID = diag::warn_impcast_integer_sign_conditional;
12916       *ICContext = true;
12917     }
12918 
12919     return DiagnoseImpCast(S, E, T, CC, DiagID);
12920   }
12921 
12922   // Diagnose conversions between different enumeration types.
12923   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
12924   // type, to give us better diagnostics.
12925   QualType SourceType = E->getType();
12926   if (!S.getLangOpts().CPlusPlus) {
12927     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12928       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
12929         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
12930         SourceType = S.Context.getTypeDeclType(Enum);
12931         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
12932       }
12933   }
12934 
12935   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
12936     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
12937       if (SourceEnum->getDecl()->hasNameForLinkage() &&
12938           TargetEnum->getDecl()->hasNameForLinkage() &&
12939           SourceEnum != TargetEnum) {
12940         if (S.SourceMgr.isInSystemMacro(CC))
12941           return;
12942 
12943         return DiagnoseImpCast(S, E, SourceType, T, CC,
12944                                diag::warn_impcast_different_enum_types);
12945       }
12946 }
12947 
12948 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
12949                                      SourceLocation CC, QualType T);
12950 
12951 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
12952                                     SourceLocation CC, bool &ICContext) {
12953   E = E->IgnoreParenImpCasts();
12954 
12955   if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
12956     return CheckConditionalOperator(S, CO, CC, T);
12957 
12958   AnalyzeImplicitConversions(S, E, CC);
12959   if (E->getType() != T)
12960     return CheckImplicitConversion(S, E, T, CC, &ICContext);
12961 }
12962 
12963 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
12964                                      SourceLocation CC, QualType T) {
12965   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
12966 
12967   Expr *TrueExpr = E->getTrueExpr();
12968   if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
12969     TrueExpr = BCO->getCommon();
12970 
12971   bool Suspicious = false;
12972   CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
12973   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
12974 
12975   if (T->isBooleanType())
12976     DiagnoseIntInBoolContext(S, E);
12977 
12978   // If -Wconversion would have warned about either of the candidates
12979   // for a signedness conversion to the context type...
12980   if (!Suspicious) return;
12981 
12982   // ...but it's currently ignored...
12983   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
12984     return;
12985 
12986   // ...then check whether it would have warned about either of the
12987   // candidates for a signedness conversion to the condition type.
12988   if (E->getType() == T) return;
12989 
12990   Suspicious = false;
12991   CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(),
12992                           E->getType(), CC, &Suspicious);
12993   if (!Suspicious)
12994     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
12995                             E->getType(), CC, &Suspicious);
12996 }
12997 
12998 /// Check conversion of given expression to boolean.
12999 /// Input argument E is a logical expression.
13000 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
13001   if (S.getLangOpts().Bool)
13002     return;
13003   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
13004     return;
13005   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
13006 }
13007 
13008 namespace {
13009 struct AnalyzeImplicitConversionsWorkItem {
13010   Expr *E;
13011   SourceLocation CC;
13012   bool IsListInit;
13013 };
13014 }
13015 
13016 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
13017 /// that should be visited are added to WorkList.
13018 static void AnalyzeImplicitConversions(
13019     Sema &S, AnalyzeImplicitConversionsWorkItem Item,
13020     llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
13021   Expr *OrigE = Item.E;
13022   SourceLocation CC = Item.CC;
13023 
13024   QualType T = OrigE->getType();
13025   Expr *E = OrigE->IgnoreParenImpCasts();
13026 
13027   // Propagate whether we are in a C++ list initialization expression.
13028   // If so, we do not issue warnings for implicit int-float conversion
13029   // precision loss, because C++11 narrowing already handles it.
13030   bool IsListInit = Item.IsListInit ||
13031                     (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
13032 
13033   if (E->isTypeDependent() || E->isValueDependent())
13034     return;
13035 
13036   Expr *SourceExpr = E;
13037   // Examine, but don't traverse into the source expression of an
13038   // OpaqueValueExpr, since it may have multiple parents and we don't want to
13039   // emit duplicate diagnostics. Its fine to examine the form or attempt to
13040   // evaluate it in the context of checking the specific conversion to T though.
13041   if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
13042     if (auto *Src = OVE->getSourceExpr())
13043       SourceExpr = Src;
13044 
13045   if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
13046     if (UO->getOpcode() == UO_Not &&
13047         UO->getSubExpr()->isKnownToHaveBooleanValue())
13048       S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
13049           << OrigE->getSourceRange() << T->isBooleanType()
13050           << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
13051 
13052   // For conditional operators, we analyze the arguments as if they
13053   // were being fed directly into the output.
13054   if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
13055     CheckConditionalOperator(S, CO, CC, T);
13056     return;
13057   }
13058 
13059   // Check implicit argument conversions for function calls.
13060   if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
13061     CheckImplicitArgumentConversions(S, Call, CC);
13062 
13063   // Go ahead and check any implicit conversions we might have skipped.
13064   // The non-canonical typecheck is just an optimization;
13065   // CheckImplicitConversion will filter out dead implicit conversions.
13066   if (SourceExpr->getType() != T)
13067     CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit);
13068 
13069   // Now continue drilling into this expression.
13070 
13071   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
13072     // The bound subexpressions in a PseudoObjectExpr are not reachable
13073     // as transitive children.
13074     // FIXME: Use a more uniform representation for this.
13075     for (auto *SE : POE->semantics())
13076       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
13077         WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
13078   }
13079 
13080   // Skip past explicit casts.
13081   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
13082     E = CE->getSubExpr()->IgnoreParenImpCasts();
13083     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
13084       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
13085     WorkList.push_back({E, CC, IsListInit});
13086     return;
13087   }
13088 
13089   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13090     // Do a somewhat different check with comparison operators.
13091     if (BO->isComparisonOp())
13092       return AnalyzeComparison(S, BO);
13093 
13094     // And with simple assignments.
13095     if (BO->getOpcode() == BO_Assign)
13096       return AnalyzeAssignment(S, BO);
13097     // And with compound assignments.
13098     if (BO->isAssignmentOp())
13099       return AnalyzeCompoundAssignment(S, BO);
13100   }
13101 
13102   // These break the otherwise-useful invariant below.  Fortunately,
13103   // we don't really need to recurse into them, because any internal
13104   // expressions should have been analyzed already when they were
13105   // built into statements.
13106   if (isa<StmtExpr>(E)) return;
13107 
13108   // Don't descend into unevaluated contexts.
13109   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
13110 
13111   // Now just recurse over the expression's children.
13112   CC = E->getExprLoc();
13113   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
13114   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
13115   for (Stmt *SubStmt : E->children()) {
13116     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
13117     if (!ChildExpr)
13118       continue;
13119 
13120     if (IsLogicalAndOperator &&
13121         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
13122       // Ignore checking string literals that are in logical and operators.
13123       // This is a common pattern for asserts.
13124       continue;
13125     WorkList.push_back({ChildExpr, CC, IsListInit});
13126   }
13127 
13128   if (BO && BO->isLogicalOp()) {
13129     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
13130     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13131       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13132 
13133     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
13134     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13135       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13136   }
13137 
13138   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
13139     if (U->getOpcode() == UO_LNot) {
13140       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
13141     } else if (U->getOpcode() != UO_AddrOf) {
13142       if (U->getSubExpr()->getType()->isAtomicType())
13143         S.Diag(U->getSubExpr()->getBeginLoc(),
13144                diag::warn_atomic_implicit_seq_cst);
13145     }
13146   }
13147 }
13148 
13149 /// AnalyzeImplicitConversions - Find and report any interesting
13150 /// implicit conversions in the given expression.  There are a couple
13151 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
13152 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
13153                                        bool IsListInit/*= false*/) {
13154   llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
13155   WorkList.push_back({OrigE, CC, IsListInit});
13156   while (!WorkList.empty())
13157     AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
13158 }
13159 
13160 /// Diagnose integer type and any valid implicit conversion to it.
13161 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
13162   // Taking into account implicit conversions,
13163   // allow any integer.
13164   if (!E->getType()->isIntegerType()) {
13165     S.Diag(E->getBeginLoc(),
13166            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
13167     return true;
13168   }
13169   // Potentially emit standard warnings for implicit conversions if enabled
13170   // using -Wconversion.
13171   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
13172   return false;
13173 }
13174 
13175 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
13176 // Returns true when emitting a warning about taking the address of a reference.
13177 static bool CheckForReference(Sema &SemaRef, const Expr *E,
13178                               const PartialDiagnostic &PD) {
13179   E = E->IgnoreParenImpCasts();
13180 
13181   const FunctionDecl *FD = nullptr;
13182 
13183   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13184     if (!DRE->getDecl()->getType()->isReferenceType())
13185       return false;
13186   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13187     if (!M->getMemberDecl()->getType()->isReferenceType())
13188       return false;
13189   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
13190     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
13191       return false;
13192     FD = Call->getDirectCallee();
13193   } else {
13194     return false;
13195   }
13196 
13197   SemaRef.Diag(E->getExprLoc(), PD);
13198 
13199   // If possible, point to location of function.
13200   if (FD) {
13201     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
13202   }
13203 
13204   return true;
13205 }
13206 
13207 // Returns true if the SourceLocation is expanded from any macro body.
13208 // Returns false if the SourceLocation is invalid, is from not in a macro
13209 // expansion, or is from expanded from a top-level macro argument.
13210 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
13211   if (Loc.isInvalid())
13212     return false;
13213 
13214   while (Loc.isMacroID()) {
13215     if (SM.isMacroBodyExpansion(Loc))
13216       return true;
13217     Loc = SM.getImmediateMacroCallerLoc(Loc);
13218   }
13219 
13220   return false;
13221 }
13222 
13223 /// Diagnose pointers that are always non-null.
13224 /// \param E the expression containing the pointer
13225 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
13226 /// compared to a null pointer
13227 /// \param IsEqual True when the comparison is equal to a null pointer
13228 /// \param Range Extra SourceRange to highlight in the diagnostic
13229 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
13230                                         Expr::NullPointerConstantKind NullKind,
13231                                         bool IsEqual, SourceRange Range) {
13232   if (!E)
13233     return;
13234 
13235   // Don't warn inside macros.
13236   if (E->getExprLoc().isMacroID()) {
13237     const SourceManager &SM = getSourceManager();
13238     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
13239         IsInAnyMacroBody(SM, Range.getBegin()))
13240       return;
13241   }
13242   E = E->IgnoreImpCasts();
13243 
13244   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
13245 
13246   if (isa<CXXThisExpr>(E)) {
13247     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
13248                                 : diag::warn_this_bool_conversion;
13249     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
13250     return;
13251   }
13252 
13253   bool IsAddressOf = false;
13254 
13255   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13256     if (UO->getOpcode() != UO_AddrOf)
13257       return;
13258     IsAddressOf = true;
13259     E = UO->getSubExpr();
13260   }
13261 
13262   if (IsAddressOf) {
13263     unsigned DiagID = IsCompare
13264                           ? diag::warn_address_of_reference_null_compare
13265                           : diag::warn_address_of_reference_bool_conversion;
13266     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
13267                                          << IsEqual;
13268     if (CheckForReference(*this, E, PD)) {
13269       return;
13270     }
13271   }
13272 
13273   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
13274     bool IsParam = isa<NonNullAttr>(NonnullAttr);
13275     std::string Str;
13276     llvm::raw_string_ostream S(Str);
13277     E->printPretty(S, nullptr, getPrintingPolicy());
13278     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
13279                                 : diag::warn_cast_nonnull_to_bool;
13280     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
13281       << E->getSourceRange() << Range << IsEqual;
13282     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
13283   };
13284 
13285   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
13286   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
13287     if (auto *Callee = Call->getDirectCallee()) {
13288       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
13289         ComplainAboutNonnullParamOrCall(A);
13290         return;
13291       }
13292     }
13293   }
13294 
13295   // Expect to find a single Decl.  Skip anything more complicated.
13296   ValueDecl *D = nullptr;
13297   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
13298     D = R->getDecl();
13299   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13300     D = M->getMemberDecl();
13301   }
13302 
13303   // Weak Decls can be null.
13304   if (!D || D->isWeak())
13305     return;
13306 
13307   // Check for parameter decl with nonnull attribute
13308   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
13309     if (getCurFunction() &&
13310         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
13311       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
13312         ComplainAboutNonnullParamOrCall(A);
13313         return;
13314       }
13315 
13316       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
13317         // Skip function template not specialized yet.
13318         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
13319           return;
13320         auto ParamIter = llvm::find(FD->parameters(), PV);
13321         assert(ParamIter != FD->param_end());
13322         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
13323 
13324         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
13325           if (!NonNull->args_size()) {
13326               ComplainAboutNonnullParamOrCall(NonNull);
13327               return;
13328           }
13329 
13330           for (const ParamIdx &ArgNo : NonNull->args()) {
13331             if (ArgNo.getASTIndex() == ParamNo) {
13332               ComplainAboutNonnullParamOrCall(NonNull);
13333               return;
13334             }
13335           }
13336         }
13337       }
13338     }
13339   }
13340 
13341   QualType T = D->getType();
13342   const bool IsArray = T->isArrayType();
13343   const bool IsFunction = T->isFunctionType();
13344 
13345   // Address of function is used to silence the function warning.
13346   if (IsAddressOf && IsFunction) {
13347     return;
13348   }
13349 
13350   // Found nothing.
13351   if (!IsAddressOf && !IsFunction && !IsArray)
13352     return;
13353 
13354   // Pretty print the expression for the diagnostic.
13355   std::string Str;
13356   llvm::raw_string_ostream S(Str);
13357   E->printPretty(S, nullptr, getPrintingPolicy());
13358 
13359   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
13360                               : diag::warn_impcast_pointer_to_bool;
13361   enum {
13362     AddressOf,
13363     FunctionPointer,
13364     ArrayPointer
13365   } DiagType;
13366   if (IsAddressOf)
13367     DiagType = AddressOf;
13368   else if (IsFunction)
13369     DiagType = FunctionPointer;
13370   else if (IsArray)
13371     DiagType = ArrayPointer;
13372   else
13373     llvm_unreachable("Could not determine diagnostic.");
13374   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
13375                                 << Range << IsEqual;
13376 
13377   if (!IsFunction)
13378     return;
13379 
13380   // Suggest '&' to silence the function warning.
13381   Diag(E->getExprLoc(), diag::note_function_warning_silence)
13382       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
13383 
13384   // Check to see if '()' fixit should be emitted.
13385   QualType ReturnType;
13386   UnresolvedSet<4> NonTemplateOverloads;
13387   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
13388   if (ReturnType.isNull())
13389     return;
13390 
13391   if (IsCompare) {
13392     // There are two cases here.  If there is null constant, the only suggest
13393     // for a pointer return type.  If the null is 0, then suggest if the return
13394     // type is a pointer or an integer type.
13395     if (!ReturnType->isPointerType()) {
13396       if (NullKind == Expr::NPCK_ZeroExpression ||
13397           NullKind == Expr::NPCK_ZeroLiteral) {
13398         if (!ReturnType->isIntegerType())
13399           return;
13400       } else {
13401         return;
13402       }
13403     }
13404   } else { // !IsCompare
13405     // For function to bool, only suggest if the function pointer has bool
13406     // return type.
13407     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
13408       return;
13409   }
13410   Diag(E->getExprLoc(), diag::note_function_to_function_call)
13411       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
13412 }
13413 
13414 /// Diagnoses "dangerous" implicit conversions within the given
13415 /// expression (which is a full expression).  Implements -Wconversion
13416 /// and -Wsign-compare.
13417 ///
13418 /// \param CC the "context" location of the implicit conversion, i.e.
13419 ///   the most location of the syntactic entity requiring the implicit
13420 ///   conversion
13421 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
13422   // Don't diagnose in unevaluated contexts.
13423   if (isUnevaluatedContext())
13424     return;
13425 
13426   // Don't diagnose for value- or type-dependent expressions.
13427   if (E->isTypeDependent() || E->isValueDependent())
13428     return;
13429 
13430   // Check for array bounds violations in cases where the check isn't triggered
13431   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
13432   // ArraySubscriptExpr is on the RHS of a variable initialization.
13433   CheckArrayAccess(E);
13434 
13435   // This is not the right CC for (e.g.) a variable initialization.
13436   AnalyzeImplicitConversions(*this, E, CC);
13437 }
13438 
13439 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
13440 /// Input argument E is a logical expression.
13441 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
13442   ::CheckBoolLikeConversion(*this, E, CC);
13443 }
13444 
13445 /// Diagnose when expression is an integer constant expression and its evaluation
13446 /// results in integer overflow
13447 void Sema::CheckForIntOverflow (Expr *E) {
13448   // Use a work list to deal with nested struct initializers.
13449   SmallVector<Expr *, 2> Exprs(1, E);
13450 
13451   do {
13452     Expr *OriginalE = Exprs.pop_back_val();
13453     Expr *E = OriginalE->IgnoreParenCasts();
13454 
13455     if (isa<BinaryOperator>(E)) {
13456       E->EvaluateForOverflow(Context);
13457       continue;
13458     }
13459 
13460     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
13461       Exprs.append(InitList->inits().begin(), InitList->inits().end());
13462     else if (isa<ObjCBoxedExpr>(OriginalE))
13463       E->EvaluateForOverflow(Context);
13464     else if (auto Call = dyn_cast<CallExpr>(E))
13465       Exprs.append(Call->arg_begin(), Call->arg_end());
13466     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
13467       Exprs.append(Message->arg_begin(), Message->arg_end());
13468   } while (!Exprs.empty());
13469 }
13470 
13471 namespace {
13472 
13473 /// Visitor for expressions which looks for unsequenced operations on the
13474 /// same object.
13475 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
13476   using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
13477 
13478   /// A tree of sequenced regions within an expression. Two regions are
13479   /// unsequenced if one is an ancestor or a descendent of the other. When we
13480   /// finish processing an expression with sequencing, such as a comma
13481   /// expression, we fold its tree nodes into its parent, since they are
13482   /// unsequenced with respect to nodes we will visit later.
13483   class SequenceTree {
13484     struct Value {
13485       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
13486       unsigned Parent : 31;
13487       unsigned Merged : 1;
13488     };
13489     SmallVector<Value, 8> Values;
13490 
13491   public:
13492     /// A region within an expression which may be sequenced with respect
13493     /// to some other region.
13494     class Seq {
13495       friend class SequenceTree;
13496 
13497       unsigned Index;
13498 
13499       explicit Seq(unsigned N) : Index(N) {}
13500 
13501     public:
13502       Seq() : Index(0) {}
13503     };
13504 
13505     SequenceTree() { Values.push_back(Value(0)); }
13506     Seq root() const { return Seq(0); }
13507 
13508     /// Create a new sequence of operations, which is an unsequenced
13509     /// subset of \p Parent. This sequence of operations is sequenced with
13510     /// respect to other children of \p Parent.
13511     Seq allocate(Seq Parent) {
13512       Values.push_back(Value(Parent.Index));
13513       return Seq(Values.size() - 1);
13514     }
13515 
13516     /// Merge a sequence of operations into its parent.
13517     void merge(Seq S) {
13518       Values[S.Index].Merged = true;
13519     }
13520 
13521     /// Determine whether two operations are unsequenced. This operation
13522     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
13523     /// should have been merged into its parent as appropriate.
13524     bool isUnsequenced(Seq Cur, Seq Old) {
13525       unsigned C = representative(Cur.Index);
13526       unsigned Target = representative(Old.Index);
13527       while (C >= Target) {
13528         if (C == Target)
13529           return true;
13530         C = Values[C].Parent;
13531       }
13532       return false;
13533     }
13534 
13535   private:
13536     /// Pick a representative for a sequence.
13537     unsigned representative(unsigned K) {
13538       if (Values[K].Merged)
13539         // Perform path compression as we go.
13540         return Values[K].Parent = representative(Values[K].Parent);
13541       return K;
13542     }
13543   };
13544 
13545   /// An object for which we can track unsequenced uses.
13546   using Object = const NamedDecl *;
13547 
13548   /// Different flavors of object usage which we track. We only track the
13549   /// least-sequenced usage of each kind.
13550   enum UsageKind {
13551     /// A read of an object. Multiple unsequenced reads are OK.
13552     UK_Use,
13553 
13554     /// A modification of an object which is sequenced before the value
13555     /// computation of the expression, such as ++n in C++.
13556     UK_ModAsValue,
13557 
13558     /// A modification of an object which is not sequenced before the value
13559     /// computation of the expression, such as n++.
13560     UK_ModAsSideEffect,
13561 
13562     UK_Count = UK_ModAsSideEffect + 1
13563   };
13564 
13565   /// Bundle together a sequencing region and the expression corresponding
13566   /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
13567   struct Usage {
13568     const Expr *UsageExpr;
13569     SequenceTree::Seq Seq;
13570 
13571     Usage() : UsageExpr(nullptr), Seq() {}
13572   };
13573 
13574   struct UsageInfo {
13575     Usage Uses[UK_Count];
13576 
13577     /// Have we issued a diagnostic for this object already?
13578     bool Diagnosed;
13579 
13580     UsageInfo() : Uses(), Diagnosed(false) {}
13581   };
13582   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
13583 
13584   Sema &SemaRef;
13585 
13586   /// Sequenced regions within the expression.
13587   SequenceTree Tree;
13588 
13589   /// Declaration modifications and references which we have seen.
13590   UsageInfoMap UsageMap;
13591 
13592   /// The region we are currently within.
13593   SequenceTree::Seq Region;
13594 
13595   /// Filled in with declarations which were modified as a side-effect
13596   /// (that is, post-increment operations).
13597   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
13598 
13599   /// Expressions to check later. We defer checking these to reduce
13600   /// stack usage.
13601   SmallVectorImpl<const Expr *> &WorkList;
13602 
13603   /// RAII object wrapping the visitation of a sequenced subexpression of an
13604   /// expression. At the end of this process, the side-effects of the evaluation
13605   /// become sequenced with respect to the value computation of the result, so
13606   /// we downgrade any UK_ModAsSideEffect within the evaluation to
13607   /// UK_ModAsValue.
13608   struct SequencedSubexpression {
13609     SequencedSubexpression(SequenceChecker &Self)
13610       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
13611       Self.ModAsSideEffect = &ModAsSideEffect;
13612     }
13613 
13614     ~SequencedSubexpression() {
13615       for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
13616         // Add a new usage with usage kind UK_ModAsValue, and then restore
13617         // the previous usage with UK_ModAsSideEffect (thus clearing it if
13618         // the previous one was empty).
13619         UsageInfo &UI = Self.UsageMap[M.first];
13620         auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
13621         Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
13622         SideEffectUsage = M.second;
13623       }
13624       Self.ModAsSideEffect = OldModAsSideEffect;
13625     }
13626 
13627     SequenceChecker &Self;
13628     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
13629     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
13630   };
13631 
13632   /// RAII object wrapping the visitation of a subexpression which we might
13633   /// choose to evaluate as a constant. If any subexpression is evaluated and
13634   /// found to be non-constant, this allows us to suppress the evaluation of
13635   /// the outer expression.
13636   class EvaluationTracker {
13637   public:
13638     EvaluationTracker(SequenceChecker &Self)
13639         : Self(Self), Prev(Self.EvalTracker) {
13640       Self.EvalTracker = this;
13641     }
13642 
13643     ~EvaluationTracker() {
13644       Self.EvalTracker = Prev;
13645       if (Prev)
13646         Prev->EvalOK &= EvalOK;
13647     }
13648 
13649     bool evaluate(const Expr *E, bool &Result) {
13650       if (!EvalOK || E->isValueDependent())
13651         return false;
13652       EvalOK = E->EvaluateAsBooleanCondition(
13653           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
13654       return EvalOK;
13655     }
13656 
13657   private:
13658     SequenceChecker &Self;
13659     EvaluationTracker *Prev;
13660     bool EvalOK = true;
13661   } *EvalTracker = nullptr;
13662 
13663   /// Find the object which is produced by the specified expression,
13664   /// if any.
13665   Object getObject(const Expr *E, bool Mod) const {
13666     E = E->IgnoreParenCasts();
13667     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13668       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
13669         return getObject(UO->getSubExpr(), Mod);
13670     } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13671       if (BO->getOpcode() == BO_Comma)
13672         return getObject(BO->getRHS(), Mod);
13673       if (Mod && BO->isAssignmentOp())
13674         return getObject(BO->getLHS(), Mod);
13675     } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13676       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
13677       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
13678         return ME->getMemberDecl();
13679     } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13680       // FIXME: If this is a reference, map through to its value.
13681       return DRE->getDecl();
13682     return nullptr;
13683   }
13684 
13685   /// Note that an object \p O was modified or used by an expression
13686   /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
13687   /// the object \p O as obtained via the \p UsageMap.
13688   void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
13689     // Get the old usage for the given object and usage kind.
13690     Usage &U = UI.Uses[UK];
13691     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
13692       // If we have a modification as side effect and are in a sequenced
13693       // subexpression, save the old Usage so that we can restore it later
13694       // in SequencedSubexpression::~SequencedSubexpression.
13695       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
13696         ModAsSideEffect->push_back(std::make_pair(O, U));
13697       // Then record the new usage with the current sequencing region.
13698       U.UsageExpr = UsageExpr;
13699       U.Seq = Region;
13700     }
13701   }
13702 
13703   /// Check whether a modification or use of an object \p O in an expression
13704   /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
13705   /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
13706   /// \p IsModMod is true when we are checking for a mod-mod unsequenced
13707   /// usage and false we are checking for a mod-use unsequenced usage.
13708   void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
13709                   UsageKind OtherKind, bool IsModMod) {
13710     if (UI.Diagnosed)
13711       return;
13712 
13713     const Usage &U = UI.Uses[OtherKind];
13714     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
13715       return;
13716 
13717     const Expr *Mod = U.UsageExpr;
13718     const Expr *ModOrUse = UsageExpr;
13719     if (OtherKind == UK_Use)
13720       std::swap(Mod, ModOrUse);
13721 
13722     SemaRef.DiagRuntimeBehavior(
13723         Mod->getExprLoc(), {Mod, ModOrUse},
13724         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
13725                                : diag::warn_unsequenced_mod_use)
13726             << O << SourceRange(ModOrUse->getExprLoc()));
13727     UI.Diagnosed = true;
13728   }
13729 
13730   // A note on note{Pre, Post}{Use, Mod}:
13731   //
13732   // (It helps to follow the algorithm with an expression such as
13733   //  "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
13734   //  operations before C++17 and both are well-defined in C++17).
13735   //
13736   // When visiting a node which uses/modify an object we first call notePreUse
13737   // or notePreMod before visiting its sub-expression(s). At this point the
13738   // children of the current node have not yet been visited and so the eventual
13739   // uses/modifications resulting from the children of the current node have not
13740   // been recorded yet.
13741   //
13742   // We then visit the children of the current node. After that notePostUse or
13743   // notePostMod is called. These will 1) detect an unsequenced modification
13744   // as side effect (as in "k++ + k") and 2) add a new usage with the
13745   // appropriate usage kind.
13746   //
13747   // We also have to be careful that some operation sequences modification as
13748   // side effect as well (for example: || or ,). To account for this we wrap
13749   // the visitation of such a sub-expression (for example: the LHS of || or ,)
13750   // with SequencedSubexpression. SequencedSubexpression is an RAII object
13751   // which record usages which are modifications as side effect, and then
13752   // downgrade them (or more accurately restore the previous usage which was a
13753   // modification as side effect) when exiting the scope of the sequenced
13754   // subexpression.
13755 
13756   void notePreUse(Object O, const Expr *UseExpr) {
13757     UsageInfo &UI = UsageMap[O];
13758     // Uses conflict with other modifications.
13759     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
13760   }
13761 
13762   void notePostUse(Object O, const Expr *UseExpr) {
13763     UsageInfo &UI = UsageMap[O];
13764     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
13765                /*IsModMod=*/false);
13766     addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
13767   }
13768 
13769   void notePreMod(Object O, const Expr *ModExpr) {
13770     UsageInfo &UI = UsageMap[O];
13771     // Modifications conflict with other modifications and with uses.
13772     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
13773     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
13774   }
13775 
13776   void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
13777     UsageInfo &UI = UsageMap[O];
13778     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
13779                /*IsModMod=*/true);
13780     addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
13781   }
13782 
13783 public:
13784   SequenceChecker(Sema &S, const Expr *E,
13785                   SmallVectorImpl<const Expr *> &WorkList)
13786       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
13787     Visit(E);
13788     // Silence a -Wunused-private-field since WorkList is now unused.
13789     // TODO: Evaluate if it can be used, and if not remove it.
13790     (void)this->WorkList;
13791   }
13792 
13793   void VisitStmt(const Stmt *S) {
13794     // Skip all statements which aren't expressions for now.
13795   }
13796 
13797   void VisitExpr(const Expr *E) {
13798     // By default, just recurse to evaluated subexpressions.
13799     Base::VisitStmt(E);
13800   }
13801 
13802   void VisitCastExpr(const CastExpr *E) {
13803     Object O = Object();
13804     if (E->getCastKind() == CK_LValueToRValue)
13805       O = getObject(E->getSubExpr(), false);
13806 
13807     if (O)
13808       notePreUse(O, E);
13809     VisitExpr(E);
13810     if (O)
13811       notePostUse(O, E);
13812   }
13813 
13814   void VisitSequencedExpressions(const Expr *SequencedBefore,
13815                                  const Expr *SequencedAfter) {
13816     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
13817     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
13818     SequenceTree::Seq OldRegion = Region;
13819 
13820     {
13821       SequencedSubexpression SeqBefore(*this);
13822       Region = BeforeRegion;
13823       Visit(SequencedBefore);
13824     }
13825 
13826     Region = AfterRegion;
13827     Visit(SequencedAfter);
13828 
13829     Region = OldRegion;
13830 
13831     Tree.merge(BeforeRegion);
13832     Tree.merge(AfterRegion);
13833   }
13834 
13835   void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
13836     // C++17 [expr.sub]p1:
13837     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
13838     //   expression E1 is sequenced before the expression E2.
13839     if (SemaRef.getLangOpts().CPlusPlus17)
13840       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
13841     else {
13842       Visit(ASE->getLHS());
13843       Visit(ASE->getRHS());
13844     }
13845   }
13846 
13847   void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
13848   void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
13849   void VisitBinPtrMem(const BinaryOperator *BO) {
13850     // C++17 [expr.mptr.oper]p4:
13851     //  Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
13852     //  the expression E1 is sequenced before the expression E2.
13853     if (SemaRef.getLangOpts().CPlusPlus17)
13854       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13855     else {
13856       Visit(BO->getLHS());
13857       Visit(BO->getRHS());
13858     }
13859   }
13860 
13861   void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
13862   void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
13863   void VisitBinShlShr(const BinaryOperator *BO) {
13864     // C++17 [expr.shift]p4:
13865     //  The expression E1 is sequenced before the expression E2.
13866     if (SemaRef.getLangOpts().CPlusPlus17)
13867       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13868     else {
13869       Visit(BO->getLHS());
13870       Visit(BO->getRHS());
13871     }
13872   }
13873 
13874   void VisitBinComma(const BinaryOperator *BO) {
13875     // C++11 [expr.comma]p1:
13876     //   Every value computation and side effect associated with the left
13877     //   expression is sequenced before every value computation and side
13878     //   effect associated with the right expression.
13879     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13880   }
13881 
13882   void VisitBinAssign(const BinaryOperator *BO) {
13883     SequenceTree::Seq RHSRegion;
13884     SequenceTree::Seq LHSRegion;
13885     if (SemaRef.getLangOpts().CPlusPlus17) {
13886       RHSRegion = Tree.allocate(Region);
13887       LHSRegion = Tree.allocate(Region);
13888     } else {
13889       RHSRegion = Region;
13890       LHSRegion = Region;
13891     }
13892     SequenceTree::Seq OldRegion = Region;
13893 
13894     // C++11 [expr.ass]p1:
13895     //  [...] the assignment is sequenced after the value computation
13896     //  of the right and left operands, [...]
13897     //
13898     // so check it before inspecting the operands and update the
13899     // map afterwards.
13900     Object O = getObject(BO->getLHS(), /*Mod=*/true);
13901     if (O)
13902       notePreMod(O, BO);
13903 
13904     if (SemaRef.getLangOpts().CPlusPlus17) {
13905       // C++17 [expr.ass]p1:
13906       //  [...] The right operand is sequenced before the left operand. [...]
13907       {
13908         SequencedSubexpression SeqBefore(*this);
13909         Region = RHSRegion;
13910         Visit(BO->getRHS());
13911       }
13912 
13913       Region = LHSRegion;
13914       Visit(BO->getLHS());
13915 
13916       if (O && isa<CompoundAssignOperator>(BO))
13917         notePostUse(O, BO);
13918 
13919     } else {
13920       // C++11 does not specify any sequencing between the LHS and RHS.
13921       Region = LHSRegion;
13922       Visit(BO->getLHS());
13923 
13924       if (O && isa<CompoundAssignOperator>(BO))
13925         notePostUse(O, BO);
13926 
13927       Region = RHSRegion;
13928       Visit(BO->getRHS());
13929     }
13930 
13931     // C++11 [expr.ass]p1:
13932     //  the assignment is sequenced [...] before the value computation of the
13933     //  assignment expression.
13934     // C11 6.5.16/3 has no such rule.
13935     Region = OldRegion;
13936     if (O)
13937       notePostMod(O, BO,
13938                   SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
13939                                                   : UK_ModAsSideEffect);
13940     if (SemaRef.getLangOpts().CPlusPlus17) {
13941       Tree.merge(RHSRegion);
13942       Tree.merge(LHSRegion);
13943     }
13944   }
13945 
13946   void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
13947     VisitBinAssign(CAO);
13948   }
13949 
13950   void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
13951   void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
13952   void VisitUnaryPreIncDec(const UnaryOperator *UO) {
13953     Object O = getObject(UO->getSubExpr(), true);
13954     if (!O)
13955       return VisitExpr(UO);
13956 
13957     notePreMod(O, UO);
13958     Visit(UO->getSubExpr());
13959     // C++11 [expr.pre.incr]p1:
13960     //   the expression ++x is equivalent to x+=1
13961     notePostMod(O, UO,
13962                 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
13963                                                 : UK_ModAsSideEffect);
13964   }
13965 
13966   void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
13967   void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
13968   void VisitUnaryPostIncDec(const UnaryOperator *UO) {
13969     Object O = getObject(UO->getSubExpr(), true);
13970     if (!O)
13971       return VisitExpr(UO);
13972 
13973     notePreMod(O, UO);
13974     Visit(UO->getSubExpr());
13975     notePostMod(O, UO, UK_ModAsSideEffect);
13976   }
13977 
13978   void VisitBinLOr(const BinaryOperator *BO) {
13979     // C++11 [expr.log.or]p2:
13980     //  If the second expression is evaluated, every value computation and
13981     //  side effect associated with the first expression is sequenced before
13982     //  every value computation and side effect associated with the
13983     //  second expression.
13984     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
13985     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
13986     SequenceTree::Seq OldRegion = Region;
13987 
13988     EvaluationTracker Eval(*this);
13989     {
13990       SequencedSubexpression Sequenced(*this);
13991       Region = LHSRegion;
13992       Visit(BO->getLHS());
13993     }
13994 
13995     // C++11 [expr.log.or]p1:
13996     //  [...] the second operand is not evaluated if the first operand
13997     //  evaluates to true.
13998     bool EvalResult = false;
13999     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14000     bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
14001     if (ShouldVisitRHS) {
14002       Region = RHSRegion;
14003       Visit(BO->getRHS());
14004     }
14005 
14006     Region = OldRegion;
14007     Tree.merge(LHSRegion);
14008     Tree.merge(RHSRegion);
14009   }
14010 
14011   void VisitBinLAnd(const BinaryOperator *BO) {
14012     // C++11 [expr.log.and]p2:
14013     //  If the second expression is evaluated, every value computation and
14014     //  side effect associated with the first expression is sequenced before
14015     //  every value computation and side effect associated with the
14016     //  second expression.
14017     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14018     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14019     SequenceTree::Seq OldRegion = Region;
14020 
14021     EvaluationTracker Eval(*this);
14022     {
14023       SequencedSubexpression Sequenced(*this);
14024       Region = LHSRegion;
14025       Visit(BO->getLHS());
14026     }
14027 
14028     // C++11 [expr.log.and]p1:
14029     //  [...] the second operand is not evaluated if the first operand is false.
14030     bool EvalResult = false;
14031     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14032     bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
14033     if (ShouldVisitRHS) {
14034       Region = RHSRegion;
14035       Visit(BO->getRHS());
14036     }
14037 
14038     Region = OldRegion;
14039     Tree.merge(LHSRegion);
14040     Tree.merge(RHSRegion);
14041   }
14042 
14043   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
14044     // C++11 [expr.cond]p1:
14045     //  [...] Every value computation and side effect associated with the first
14046     //  expression is sequenced before every value computation and side effect
14047     //  associated with the second or third expression.
14048     SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
14049 
14050     // No sequencing is specified between the true and false expression.
14051     // However since exactly one of both is going to be evaluated we can
14052     // consider them to be sequenced. This is needed to avoid warning on
14053     // something like "x ? y+= 1 : y += 2;" in the case where we will visit
14054     // both the true and false expressions because we can't evaluate x.
14055     // This will still allow us to detect an expression like (pre C++17)
14056     // "(x ? y += 1 : y += 2) = y".
14057     //
14058     // We don't wrap the visitation of the true and false expression with
14059     // SequencedSubexpression because we don't want to downgrade modifications
14060     // as side effect in the true and false expressions after the visition
14061     // is done. (for example in the expression "(x ? y++ : y++) + y" we should
14062     // not warn between the two "y++", but we should warn between the "y++"
14063     // and the "y".
14064     SequenceTree::Seq TrueRegion = Tree.allocate(Region);
14065     SequenceTree::Seq FalseRegion = Tree.allocate(Region);
14066     SequenceTree::Seq OldRegion = Region;
14067 
14068     EvaluationTracker Eval(*this);
14069     {
14070       SequencedSubexpression Sequenced(*this);
14071       Region = ConditionRegion;
14072       Visit(CO->getCond());
14073     }
14074 
14075     // C++11 [expr.cond]p1:
14076     // [...] The first expression is contextually converted to bool (Clause 4).
14077     // It is evaluated and if it is true, the result of the conditional
14078     // expression is the value of the second expression, otherwise that of the
14079     // third expression. Only one of the second and third expressions is
14080     // evaluated. [...]
14081     bool EvalResult = false;
14082     bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
14083     bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
14084     bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
14085     if (ShouldVisitTrueExpr) {
14086       Region = TrueRegion;
14087       Visit(CO->getTrueExpr());
14088     }
14089     if (ShouldVisitFalseExpr) {
14090       Region = FalseRegion;
14091       Visit(CO->getFalseExpr());
14092     }
14093 
14094     Region = OldRegion;
14095     Tree.merge(ConditionRegion);
14096     Tree.merge(TrueRegion);
14097     Tree.merge(FalseRegion);
14098   }
14099 
14100   void VisitCallExpr(const CallExpr *CE) {
14101     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
14102 
14103     if (CE->isUnevaluatedBuiltinCall(Context))
14104       return;
14105 
14106     // C++11 [intro.execution]p15:
14107     //   When calling a function [...], every value computation and side effect
14108     //   associated with any argument expression, or with the postfix expression
14109     //   designating the called function, is sequenced before execution of every
14110     //   expression or statement in the body of the function [and thus before
14111     //   the value computation of its result].
14112     SequencedSubexpression Sequenced(*this);
14113     SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
14114       // C++17 [expr.call]p5
14115       //   The postfix-expression is sequenced before each expression in the
14116       //   expression-list and any default argument. [...]
14117       SequenceTree::Seq CalleeRegion;
14118       SequenceTree::Seq OtherRegion;
14119       if (SemaRef.getLangOpts().CPlusPlus17) {
14120         CalleeRegion = Tree.allocate(Region);
14121         OtherRegion = Tree.allocate(Region);
14122       } else {
14123         CalleeRegion = Region;
14124         OtherRegion = Region;
14125       }
14126       SequenceTree::Seq OldRegion = Region;
14127 
14128       // Visit the callee expression first.
14129       Region = CalleeRegion;
14130       if (SemaRef.getLangOpts().CPlusPlus17) {
14131         SequencedSubexpression Sequenced(*this);
14132         Visit(CE->getCallee());
14133       } else {
14134         Visit(CE->getCallee());
14135       }
14136 
14137       // Then visit the argument expressions.
14138       Region = OtherRegion;
14139       for (const Expr *Argument : CE->arguments())
14140         Visit(Argument);
14141 
14142       Region = OldRegion;
14143       if (SemaRef.getLangOpts().CPlusPlus17) {
14144         Tree.merge(CalleeRegion);
14145         Tree.merge(OtherRegion);
14146       }
14147     });
14148   }
14149 
14150   void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
14151     // C++17 [over.match.oper]p2:
14152     //   [...] the operator notation is first transformed to the equivalent
14153     //   function-call notation as summarized in Table 12 (where @ denotes one
14154     //   of the operators covered in the specified subclause). However, the
14155     //   operands are sequenced in the order prescribed for the built-in
14156     //   operator (Clause 8).
14157     //
14158     // From the above only overloaded binary operators and overloaded call
14159     // operators have sequencing rules in C++17 that we need to handle
14160     // separately.
14161     if (!SemaRef.getLangOpts().CPlusPlus17 ||
14162         (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
14163       return VisitCallExpr(CXXOCE);
14164 
14165     enum {
14166       NoSequencing,
14167       LHSBeforeRHS,
14168       RHSBeforeLHS,
14169       LHSBeforeRest
14170     } SequencingKind;
14171     switch (CXXOCE->getOperator()) {
14172     case OO_Equal:
14173     case OO_PlusEqual:
14174     case OO_MinusEqual:
14175     case OO_StarEqual:
14176     case OO_SlashEqual:
14177     case OO_PercentEqual:
14178     case OO_CaretEqual:
14179     case OO_AmpEqual:
14180     case OO_PipeEqual:
14181     case OO_LessLessEqual:
14182     case OO_GreaterGreaterEqual:
14183       SequencingKind = RHSBeforeLHS;
14184       break;
14185 
14186     case OO_LessLess:
14187     case OO_GreaterGreater:
14188     case OO_AmpAmp:
14189     case OO_PipePipe:
14190     case OO_Comma:
14191     case OO_ArrowStar:
14192     case OO_Subscript:
14193       SequencingKind = LHSBeforeRHS;
14194       break;
14195 
14196     case OO_Call:
14197       SequencingKind = LHSBeforeRest;
14198       break;
14199 
14200     default:
14201       SequencingKind = NoSequencing;
14202       break;
14203     }
14204 
14205     if (SequencingKind == NoSequencing)
14206       return VisitCallExpr(CXXOCE);
14207 
14208     // This is a call, so all subexpressions are sequenced before the result.
14209     SequencedSubexpression Sequenced(*this);
14210 
14211     SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
14212       assert(SemaRef.getLangOpts().CPlusPlus17 &&
14213              "Should only get there with C++17 and above!");
14214       assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
14215              "Should only get there with an overloaded binary operator"
14216              " or an overloaded call operator!");
14217 
14218       if (SequencingKind == LHSBeforeRest) {
14219         assert(CXXOCE->getOperator() == OO_Call &&
14220                "We should only have an overloaded call operator here!");
14221 
14222         // This is very similar to VisitCallExpr, except that we only have the
14223         // C++17 case. The postfix-expression is the first argument of the
14224         // CXXOperatorCallExpr. The expressions in the expression-list, if any,
14225         // are in the following arguments.
14226         //
14227         // Note that we intentionally do not visit the callee expression since
14228         // it is just a decayed reference to a function.
14229         SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
14230         SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
14231         SequenceTree::Seq OldRegion = Region;
14232 
14233         assert(CXXOCE->getNumArgs() >= 1 &&
14234                "An overloaded call operator must have at least one argument"
14235                " for the postfix-expression!");
14236         const Expr *PostfixExpr = CXXOCE->getArgs()[0];
14237         llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
14238                                           CXXOCE->getNumArgs() - 1);
14239 
14240         // Visit the postfix-expression first.
14241         {
14242           Region = PostfixExprRegion;
14243           SequencedSubexpression Sequenced(*this);
14244           Visit(PostfixExpr);
14245         }
14246 
14247         // Then visit the argument expressions.
14248         Region = ArgsRegion;
14249         for (const Expr *Arg : Args)
14250           Visit(Arg);
14251 
14252         Region = OldRegion;
14253         Tree.merge(PostfixExprRegion);
14254         Tree.merge(ArgsRegion);
14255       } else {
14256         assert(CXXOCE->getNumArgs() == 2 &&
14257                "Should only have two arguments here!");
14258         assert((SequencingKind == LHSBeforeRHS ||
14259                 SequencingKind == RHSBeforeLHS) &&
14260                "Unexpected sequencing kind!");
14261 
14262         // We do not visit the callee expression since it is just a decayed
14263         // reference to a function.
14264         const Expr *E1 = CXXOCE->getArg(0);
14265         const Expr *E2 = CXXOCE->getArg(1);
14266         if (SequencingKind == RHSBeforeLHS)
14267           std::swap(E1, E2);
14268 
14269         return VisitSequencedExpressions(E1, E2);
14270       }
14271     });
14272   }
14273 
14274   void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
14275     // This is a call, so all subexpressions are sequenced before the result.
14276     SequencedSubexpression Sequenced(*this);
14277 
14278     if (!CCE->isListInitialization())
14279       return VisitExpr(CCE);
14280 
14281     // In C++11, list initializations are sequenced.
14282     SmallVector<SequenceTree::Seq, 32> Elts;
14283     SequenceTree::Seq Parent = Region;
14284     for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
14285                                               E = CCE->arg_end();
14286          I != E; ++I) {
14287       Region = Tree.allocate(Parent);
14288       Elts.push_back(Region);
14289       Visit(*I);
14290     }
14291 
14292     // Forget that the initializers are sequenced.
14293     Region = Parent;
14294     for (unsigned I = 0; I < Elts.size(); ++I)
14295       Tree.merge(Elts[I]);
14296   }
14297 
14298   void VisitInitListExpr(const InitListExpr *ILE) {
14299     if (!SemaRef.getLangOpts().CPlusPlus11)
14300       return VisitExpr(ILE);
14301 
14302     // In C++11, list initializations are sequenced.
14303     SmallVector<SequenceTree::Seq, 32> Elts;
14304     SequenceTree::Seq Parent = Region;
14305     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
14306       const Expr *E = ILE->getInit(I);
14307       if (!E)
14308         continue;
14309       Region = Tree.allocate(Parent);
14310       Elts.push_back(Region);
14311       Visit(E);
14312     }
14313 
14314     // Forget that the initializers are sequenced.
14315     Region = Parent;
14316     for (unsigned I = 0; I < Elts.size(); ++I)
14317       Tree.merge(Elts[I]);
14318   }
14319 };
14320 
14321 } // namespace
14322 
14323 void Sema::CheckUnsequencedOperations(const Expr *E) {
14324   SmallVector<const Expr *, 8> WorkList;
14325   WorkList.push_back(E);
14326   while (!WorkList.empty()) {
14327     const Expr *Item = WorkList.pop_back_val();
14328     SequenceChecker(*this, Item, WorkList);
14329   }
14330 }
14331 
14332 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
14333                               bool IsConstexpr) {
14334   llvm::SaveAndRestore<bool> ConstantContext(
14335       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
14336   CheckImplicitConversions(E, CheckLoc);
14337   if (!E->isInstantiationDependent())
14338     CheckUnsequencedOperations(E);
14339   if (!IsConstexpr && !E->isValueDependent())
14340     CheckForIntOverflow(E);
14341   DiagnoseMisalignedMembers();
14342 }
14343 
14344 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
14345                                        FieldDecl *BitField,
14346                                        Expr *Init) {
14347   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
14348 }
14349 
14350 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
14351                                          SourceLocation Loc) {
14352   if (!PType->isVariablyModifiedType())
14353     return;
14354   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
14355     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
14356     return;
14357   }
14358   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
14359     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
14360     return;
14361   }
14362   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
14363     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
14364     return;
14365   }
14366 
14367   const ArrayType *AT = S.Context.getAsArrayType(PType);
14368   if (!AT)
14369     return;
14370 
14371   if (AT->getSizeModifier() != ArrayType::Star) {
14372     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
14373     return;
14374   }
14375 
14376   S.Diag(Loc, diag::err_array_star_in_function_definition);
14377 }
14378 
14379 /// CheckParmsForFunctionDef - Check that the parameters of the given
14380 /// function are appropriate for the definition of a function. This
14381 /// takes care of any checks that cannot be performed on the
14382 /// declaration itself, e.g., that the types of each of the function
14383 /// parameters are complete.
14384 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
14385                                     bool CheckParameterNames) {
14386   bool HasInvalidParm = false;
14387   for (ParmVarDecl *Param : Parameters) {
14388     // C99 6.7.5.3p4: the parameters in a parameter type list in a
14389     // function declarator that is part of a function definition of
14390     // that function shall not have incomplete type.
14391     //
14392     // This is also C++ [dcl.fct]p6.
14393     if (!Param->isInvalidDecl() &&
14394         RequireCompleteType(Param->getLocation(), Param->getType(),
14395                             diag::err_typecheck_decl_incomplete_type)) {
14396       Param->setInvalidDecl();
14397       HasInvalidParm = true;
14398     }
14399 
14400     // C99 6.9.1p5: If the declarator includes a parameter type list, the
14401     // declaration of each parameter shall include an identifier.
14402     if (CheckParameterNames && Param->getIdentifier() == nullptr &&
14403         !Param->isImplicit() && !getLangOpts().CPlusPlus) {
14404       // Diagnose this as an extension in C17 and earlier.
14405       if (!getLangOpts().C2x)
14406         Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
14407     }
14408 
14409     // C99 6.7.5.3p12:
14410     //   If the function declarator is not part of a definition of that
14411     //   function, parameters may have incomplete type and may use the [*]
14412     //   notation in their sequences of declarator specifiers to specify
14413     //   variable length array types.
14414     QualType PType = Param->getOriginalType();
14415     // FIXME: This diagnostic should point the '[*]' if source-location
14416     // information is added for it.
14417     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
14418 
14419     // If the parameter is a c++ class type and it has to be destructed in the
14420     // callee function, declare the destructor so that it can be called by the
14421     // callee function. Do not perform any direct access check on the dtor here.
14422     if (!Param->isInvalidDecl()) {
14423       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
14424         if (!ClassDecl->isInvalidDecl() &&
14425             !ClassDecl->hasIrrelevantDestructor() &&
14426             !ClassDecl->isDependentContext() &&
14427             ClassDecl->isParamDestroyedInCallee()) {
14428           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
14429           MarkFunctionReferenced(Param->getLocation(), Destructor);
14430           DiagnoseUseOfDecl(Destructor, Param->getLocation());
14431         }
14432       }
14433     }
14434 
14435     // Parameters with the pass_object_size attribute only need to be marked
14436     // constant at function definitions. Because we lack information about
14437     // whether we're on a declaration or definition when we're instantiating the
14438     // attribute, we need to check for constness here.
14439     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
14440       if (!Param->getType().isConstQualified())
14441         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
14442             << Attr->getSpelling() << 1;
14443 
14444     // Check for parameter names shadowing fields from the class.
14445     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
14446       // The owning context for the parameter should be the function, but we
14447       // want to see if this function's declaration context is a record.
14448       DeclContext *DC = Param->getDeclContext();
14449       if (DC && DC->isFunctionOrMethod()) {
14450         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
14451           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
14452                                      RD, /*DeclIsField*/ false);
14453       }
14454     }
14455   }
14456 
14457   return HasInvalidParm;
14458 }
14459 
14460 Optional<std::pair<CharUnits, CharUnits>>
14461 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx);
14462 
14463 /// Compute the alignment and offset of the base class object given the
14464 /// derived-to-base cast expression and the alignment and offset of the derived
14465 /// class object.
14466 static std::pair<CharUnits, CharUnits>
14467 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
14468                                    CharUnits BaseAlignment, CharUnits Offset,
14469                                    ASTContext &Ctx) {
14470   for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
14471        ++PathI) {
14472     const CXXBaseSpecifier *Base = *PathI;
14473     const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
14474     if (Base->isVirtual()) {
14475       // The complete object may have a lower alignment than the non-virtual
14476       // alignment of the base, in which case the base may be misaligned. Choose
14477       // the smaller of the non-virtual alignment and BaseAlignment, which is a
14478       // conservative lower bound of the complete object alignment.
14479       CharUnits NonVirtualAlignment =
14480           Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment();
14481       BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
14482       Offset = CharUnits::Zero();
14483     } else {
14484       const ASTRecordLayout &RL =
14485           Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
14486       Offset += RL.getBaseClassOffset(BaseDecl);
14487     }
14488     DerivedType = Base->getType();
14489   }
14490 
14491   return std::make_pair(BaseAlignment, Offset);
14492 }
14493 
14494 /// Compute the alignment and offset of a binary additive operator.
14495 static Optional<std::pair<CharUnits, CharUnits>>
14496 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
14497                                      bool IsSub, ASTContext &Ctx) {
14498   QualType PointeeType = PtrE->getType()->getPointeeType();
14499 
14500   if (!PointeeType->isConstantSizeType())
14501     return llvm::None;
14502 
14503   auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
14504 
14505   if (!P)
14506     return llvm::None;
14507 
14508   CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
14509   if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
14510     CharUnits Offset = EltSize * IdxRes->getExtValue();
14511     if (IsSub)
14512       Offset = -Offset;
14513     return std::make_pair(P->first, P->second + Offset);
14514   }
14515 
14516   // If the integer expression isn't a constant expression, compute the lower
14517   // bound of the alignment using the alignment and offset of the pointer
14518   // expression and the element size.
14519   return std::make_pair(
14520       P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
14521       CharUnits::Zero());
14522 }
14523 
14524 /// This helper function takes an lvalue expression and returns the alignment of
14525 /// a VarDecl and a constant offset from the VarDecl.
14526 Optional<std::pair<CharUnits, CharUnits>>
14527 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) {
14528   E = E->IgnoreParens();
14529   switch (E->getStmtClass()) {
14530   default:
14531     break;
14532   case Stmt::CStyleCastExprClass:
14533   case Stmt::CXXStaticCastExprClass:
14534   case Stmt::ImplicitCastExprClass: {
14535     auto *CE = cast<CastExpr>(E);
14536     const Expr *From = CE->getSubExpr();
14537     switch (CE->getCastKind()) {
14538     default:
14539       break;
14540     case CK_NoOp:
14541       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14542     case CK_UncheckedDerivedToBase:
14543     case CK_DerivedToBase: {
14544       auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14545       if (!P)
14546         break;
14547       return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
14548                                                 P->second, Ctx);
14549     }
14550     }
14551     break;
14552   }
14553   case Stmt::ArraySubscriptExprClass: {
14554     auto *ASE = cast<ArraySubscriptExpr>(E);
14555     return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(),
14556                                                 false, Ctx);
14557   }
14558   case Stmt::DeclRefExprClass: {
14559     if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
14560       // FIXME: If VD is captured by copy or is an escaping __block variable,
14561       // use the alignment of VD's type.
14562       if (!VD->getType()->isReferenceType())
14563         return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
14564       if (VD->hasInit())
14565         return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
14566     }
14567     break;
14568   }
14569   case Stmt::MemberExprClass: {
14570     auto *ME = cast<MemberExpr>(E);
14571     auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
14572     if (!FD || FD->getType()->isReferenceType() ||
14573         FD->getParent()->isInvalidDecl())
14574       break;
14575     Optional<std::pair<CharUnits, CharUnits>> P;
14576     if (ME->isArrow())
14577       P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
14578     else
14579       P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
14580     if (!P)
14581       break;
14582     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
14583     uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
14584     return std::make_pair(P->first,
14585                           P->second + CharUnits::fromQuantity(Offset));
14586   }
14587   case Stmt::UnaryOperatorClass: {
14588     auto *UO = cast<UnaryOperator>(E);
14589     switch (UO->getOpcode()) {
14590     default:
14591       break;
14592     case UO_Deref:
14593       return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx);
14594     }
14595     break;
14596   }
14597   case Stmt::BinaryOperatorClass: {
14598     auto *BO = cast<BinaryOperator>(E);
14599     auto Opcode = BO->getOpcode();
14600     switch (Opcode) {
14601     default:
14602       break;
14603     case BO_Comma:
14604       return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx);
14605     }
14606     break;
14607   }
14608   }
14609   return llvm::None;
14610 }
14611 
14612 /// This helper function takes a pointer expression and returns the alignment of
14613 /// a VarDecl and a constant offset from the VarDecl.
14614 Optional<std::pair<CharUnits, CharUnits>>
14615 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) {
14616   E = E->IgnoreParens();
14617   switch (E->getStmtClass()) {
14618   default:
14619     break;
14620   case Stmt::CStyleCastExprClass:
14621   case Stmt::CXXStaticCastExprClass:
14622   case Stmt::ImplicitCastExprClass: {
14623     auto *CE = cast<CastExpr>(E);
14624     const Expr *From = CE->getSubExpr();
14625     switch (CE->getCastKind()) {
14626     default:
14627       break;
14628     case CK_NoOp:
14629       return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14630     case CK_ArrayToPointerDecay:
14631       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14632     case CK_UncheckedDerivedToBase:
14633     case CK_DerivedToBase: {
14634       auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14635       if (!P)
14636         break;
14637       return getDerivedToBaseAlignmentAndOffset(
14638           CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
14639     }
14640     }
14641     break;
14642   }
14643   case Stmt::CXXThisExprClass: {
14644     auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
14645     CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment();
14646     return std::make_pair(Alignment, CharUnits::Zero());
14647   }
14648   case Stmt::UnaryOperatorClass: {
14649     auto *UO = cast<UnaryOperator>(E);
14650     if (UO->getOpcode() == UO_AddrOf)
14651       return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx);
14652     break;
14653   }
14654   case Stmt::BinaryOperatorClass: {
14655     auto *BO = cast<BinaryOperator>(E);
14656     auto Opcode = BO->getOpcode();
14657     switch (Opcode) {
14658     default:
14659       break;
14660     case BO_Add:
14661     case BO_Sub: {
14662       const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
14663       if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
14664         std::swap(LHS, RHS);
14665       return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
14666                                                   Ctx);
14667     }
14668     case BO_Comma:
14669       return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
14670     }
14671     break;
14672   }
14673   }
14674   return llvm::None;
14675 }
14676 
14677 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
14678   // See if we can compute the alignment of a VarDecl and an offset from it.
14679   Optional<std::pair<CharUnits, CharUnits>> P =
14680       getBaseAlignmentAndOffsetFromPtr(E, S.Context);
14681 
14682   if (P)
14683     return P->first.alignmentAtOffset(P->second);
14684 
14685   // If that failed, return the type's alignment.
14686   return S.Context.getTypeAlignInChars(E->getType()->getPointeeType());
14687 }
14688 
14689 /// CheckCastAlign - Implements -Wcast-align, which warns when a
14690 /// pointer cast increases the alignment requirements.
14691 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
14692   // This is actually a lot of work to potentially be doing on every
14693   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
14694   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
14695     return;
14696 
14697   // Ignore dependent types.
14698   if (T->isDependentType() || Op->getType()->isDependentType())
14699     return;
14700 
14701   // Require that the destination be a pointer type.
14702   const PointerType *DestPtr = T->getAs<PointerType>();
14703   if (!DestPtr) return;
14704 
14705   // If the destination has alignment 1, we're done.
14706   QualType DestPointee = DestPtr->getPointeeType();
14707   if (DestPointee->isIncompleteType()) return;
14708   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
14709   if (DestAlign.isOne()) return;
14710 
14711   // Require that the source be a pointer type.
14712   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
14713   if (!SrcPtr) return;
14714   QualType SrcPointee = SrcPtr->getPointeeType();
14715 
14716   // Explicitly allow casts from cv void*.  We already implicitly
14717   // allowed casts to cv void*, since they have alignment 1.
14718   // Also allow casts involving incomplete types, which implicitly
14719   // includes 'void'.
14720   if (SrcPointee->isIncompleteType()) return;
14721 
14722   CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
14723 
14724   if (SrcAlign >= DestAlign) return;
14725 
14726   Diag(TRange.getBegin(), diag::warn_cast_align)
14727     << Op->getType() << T
14728     << static_cast<unsigned>(SrcAlign.getQuantity())
14729     << static_cast<unsigned>(DestAlign.getQuantity())
14730     << TRange << Op->getSourceRange();
14731 }
14732 
14733 /// Check whether this array fits the idiom of a size-one tail padded
14734 /// array member of a struct.
14735 ///
14736 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
14737 /// commonly used to emulate flexible arrays in C89 code.
14738 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
14739                                     const NamedDecl *ND) {
14740   if (Size != 1 || !ND) return false;
14741 
14742   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
14743   if (!FD) return false;
14744 
14745   // Don't consider sizes resulting from macro expansions or template argument
14746   // substitution to form C89 tail-padded arrays.
14747 
14748   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
14749   while (TInfo) {
14750     TypeLoc TL = TInfo->getTypeLoc();
14751     // Look through typedefs.
14752     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
14753       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
14754       TInfo = TDL->getTypeSourceInfo();
14755       continue;
14756     }
14757     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
14758       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
14759       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
14760         return false;
14761     }
14762     break;
14763   }
14764 
14765   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
14766   if (!RD) return false;
14767   if (RD->isUnion()) return false;
14768   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
14769     if (!CRD->isStandardLayout()) return false;
14770   }
14771 
14772   // See if this is the last field decl in the record.
14773   const Decl *D = FD;
14774   while ((D = D->getNextDeclInContext()))
14775     if (isa<FieldDecl>(D))
14776       return false;
14777   return true;
14778 }
14779 
14780 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
14781                             const ArraySubscriptExpr *ASE,
14782                             bool AllowOnePastEnd, bool IndexNegated) {
14783   // Already diagnosed by the constant evaluator.
14784   if (isConstantEvaluated())
14785     return;
14786 
14787   IndexExpr = IndexExpr->IgnoreParenImpCasts();
14788   if (IndexExpr->isValueDependent())
14789     return;
14790 
14791   const Type *EffectiveType =
14792       BaseExpr->getType()->getPointeeOrArrayElementType();
14793   BaseExpr = BaseExpr->IgnoreParenCasts();
14794   const ConstantArrayType *ArrayTy =
14795       Context.getAsConstantArrayType(BaseExpr->getType());
14796 
14797   const Type *BaseType =
14798       ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
14799   bool IsUnboundedArray = (BaseType == nullptr);
14800   if (EffectiveType->isDependentType() ||
14801       (!IsUnboundedArray && BaseType->isDependentType()))
14802     return;
14803 
14804   Expr::EvalResult Result;
14805   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
14806     return;
14807 
14808   llvm::APSInt index = Result.Val.getInt();
14809   if (IndexNegated) {
14810     index.setIsUnsigned(false);
14811     index = -index;
14812   }
14813 
14814   const NamedDecl *ND = nullptr;
14815   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14816     ND = DRE->getDecl();
14817   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
14818     ND = ME->getMemberDecl();
14819 
14820   if (IsUnboundedArray) {
14821     if (index.isUnsigned() || !index.isNegative()) {
14822       const auto &ASTC = getASTContext();
14823       unsigned AddrBits =
14824           ASTC.getTargetInfo().getPointerWidth(ASTC.getTargetAddressSpace(
14825               EffectiveType->getCanonicalTypeInternal()));
14826       if (index.getBitWidth() < AddrBits)
14827         index = index.zext(AddrBits);
14828       Optional<CharUnits> ElemCharUnits =
14829           ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
14830       // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
14831       // pointer) bounds-checking isn't meaningful.
14832       if (!ElemCharUnits)
14833         return;
14834       llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
14835       // If index has more active bits than address space, we already know
14836       // we have a bounds violation to warn about.  Otherwise, compute
14837       // address of (index + 1)th element, and warn about bounds violation
14838       // only if that address exceeds address space.
14839       if (index.getActiveBits() <= AddrBits) {
14840         bool Overflow;
14841         llvm::APInt Product(index);
14842         Product += 1;
14843         Product = Product.umul_ov(ElemBytes, Overflow);
14844         if (!Overflow && Product.getActiveBits() <= AddrBits)
14845           return;
14846       }
14847 
14848       // Need to compute max possible elements in address space, since that
14849       // is included in diag message.
14850       llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
14851       MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
14852       MaxElems += 1;
14853       ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
14854       MaxElems = MaxElems.udiv(ElemBytes);
14855 
14856       unsigned DiagID =
14857           ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
14858               : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
14859 
14860       // Diag message shows element size in bits and in "bytes" (platform-
14861       // dependent CharUnits)
14862       DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
14863                           PDiag(DiagID)
14864                               << toString(index, 10, true) << AddrBits
14865                               << (unsigned)ASTC.toBits(*ElemCharUnits)
14866                               << toString(ElemBytes, 10, false)
14867                               << toString(MaxElems, 10, false)
14868                               << (unsigned)MaxElems.getLimitedValue(~0U)
14869                               << IndexExpr->getSourceRange());
14870 
14871       if (!ND) {
14872         // Try harder to find a NamedDecl to point at in the note.
14873         while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
14874           BaseExpr = ASE->getBase()->IgnoreParenCasts();
14875         if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14876           ND = DRE->getDecl();
14877         if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
14878           ND = ME->getMemberDecl();
14879       }
14880 
14881       if (ND)
14882         DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
14883                             PDiag(diag::note_array_declared_here) << ND);
14884     }
14885     return;
14886   }
14887 
14888   if (index.isUnsigned() || !index.isNegative()) {
14889     // It is possible that the type of the base expression after
14890     // IgnoreParenCasts is incomplete, even though the type of the base
14891     // expression before IgnoreParenCasts is complete (see PR39746 for an
14892     // example). In this case we have no information about whether the array
14893     // access exceeds the array bounds. However we can still diagnose an array
14894     // access which precedes the array bounds.
14895     if (BaseType->isIncompleteType())
14896       return;
14897 
14898     llvm::APInt size = ArrayTy->getSize();
14899     if (!size.isStrictlyPositive())
14900       return;
14901 
14902     if (BaseType != EffectiveType) {
14903       // Make sure we're comparing apples to apples when comparing index to size
14904       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
14905       uint64_t array_typesize = Context.getTypeSize(BaseType);
14906       // Handle ptrarith_typesize being zero, such as when casting to void*
14907       if (!ptrarith_typesize) ptrarith_typesize = 1;
14908       if (ptrarith_typesize != array_typesize) {
14909         // There's a cast to a different size type involved
14910         uint64_t ratio = array_typesize / ptrarith_typesize;
14911         // TODO: Be smarter about handling cases where array_typesize is not a
14912         // multiple of ptrarith_typesize
14913         if (ptrarith_typesize * ratio == array_typesize)
14914           size *= llvm::APInt(size.getBitWidth(), ratio);
14915       }
14916     }
14917 
14918     if (size.getBitWidth() > index.getBitWidth())
14919       index = index.zext(size.getBitWidth());
14920     else if (size.getBitWidth() < index.getBitWidth())
14921       size = size.zext(index.getBitWidth());
14922 
14923     // For array subscripting the index must be less than size, but for pointer
14924     // arithmetic also allow the index (offset) to be equal to size since
14925     // computing the next address after the end of the array is legal and
14926     // commonly done e.g. in C++ iterators and range-based for loops.
14927     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
14928       return;
14929 
14930     // Also don't warn for arrays of size 1 which are members of some
14931     // structure. These are often used to approximate flexible arrays in C89
14932     // code.
14933     if (IsTailPaddedMemberArray(*this, size, ND))
14934       return;
14935 
14936     // Suppress the warning if the subscript expression (as identified by the
14937     // ']' location) and the index expression are both from macro expansions
14938     // within a system header.
14939     if (ASE) {
14940       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
14941           ASE->getRBracketLoc());
14942       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
14943         SourceLocation IndexLoc =
14944             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
14945         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
14946           return;
14947       }
14948     }
14949 
14950     unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
14951                           : diag::warn_ptr_arith_exceeds_bounds;
14952 
14953     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
14954                         PDiag(DiagID) << toString(index, 10, true)
14955                                       << toString(size, 10, true)
14956                                       << (unsigned)size.getLimitedValue(~0U)
14957                                       << IndexExpr->getSourceRange());
14958   } else {
14959     unsigned DiagID = diag::warn_array_index_precedes_bounds;
14960     if (!ASE) {
14961       DiagID = diag::warn_ptr_arith_precedes_bounds;
14962       if (index.isNegative()) index = -index;
14963     }
14964 
14965     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
14966                         PDiag(DiagID) << toString(index, 10, true)
14967                                       << IndexExpr->getSourceRange());
14968   }
14969 
14970   if (!ND) {
14971     // Try harder to find a NamedDecl to point at in the note.
14972     while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
14973       BaseExpr = ASE->getBase()->IgnoreParenCasts();
14974     if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14975       ND = DRE->getDecl();
14976     if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
14977       ND = ME->getMemberDecl();
14978   }
14979 
14980   if (ND)
14981     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
14982                         PDiag(diag::note_array_declared_here) << ND);
14983 }
14984 
14985 void Sema::CheckArrayAccess(const Expr *expr) {
14986   int AllowOnePastEnd = 0;
14987   while (expr) {
14988     expr = expr->IgnoreParenImpCasts();
14989     switch (expr->getStmtClass()) {
14990       case Stmt::ArraySubscriptExprClass: {
14991         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
14992         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
14993                          AllowOnePastEnd > 0);
14994         expr = ASE->getBase();
14995         break;
14996       }
14997       case Stmt::MemberExprClass: {
14998         expr = cast<MemberExpr>(expr)->getBase();
14999         break;
15000       }
15001       case Stmt::OMPArraySectionExprClass: {
15002         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
15003         if (ASE->getLowerBound())
15004           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
15005                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
15006         return;
15007       }
15008       case Stmt::UnaryOperatorClass: {
15009         // Only unwrap the * and & unary operators
15010         const UnaryOperator *UO = cast<UnaryOperator>(expr);
15011         expr = UO->getSubExpr();
15012         switch (UO->getOpcode()) {
15013           case UO_AddrOf:
15014             AllowOnePastEnd++;
15015             break;
15016           case UO_Deref:
15017             AllowOnePastEnd--;
15018             break;
15019           default:
15020             return;
15021         }
15022         break;
15023       }
15024       case Stmt::ConditionalOperatorClass: {
15025         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
15026         if (const Expr *lhs = cond->getLHS())
15027           CheckArrayAccess(lhs);
15028         if (const Expr *rhs = cond->getRHS())
15029           CheckArrayAccess(rhs);
15030         return;
15031       }
15032       case Stmt::CXXOperatorCallExprClass: {
15033         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
15034         for (const auto *Arg : OCE->arguments())
15035           CheckArrayAccess(Arg);
15036         return;
15037       }
15038       default:
15039         return;
15040     }
15041   }
15042 }
15043 
15044 //===--- CHECK: Objective-C retain cycles ----------------------------------//
15045 
15046 namespace {
15047 
15048 struct RetainCycleOwner {
15049   VarDecl *Variable = nullptr;
15050   SourceRange Range;
15051   SourceLocation Loc;
15052   bool Indirect = false;
15053 
15054   RetainCycleOwner() = default;
15055 
15056   void setLocsFrom(Expr *e) {
15057     Loc = e->getExprLoc();
15058     Range = e->getSourceRange();
15059   }
15060 };
15061 
15062 } // namespace
15063 
15064 /// Consider whether capturing the given variable can possibly lead to
15065 /// a retain cycle.
15066 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
15067   // In ARC, it's captured strongly iff the variable has __strong
15068   // lifetime.  In MRR, it's captured strongly if the variable is
15069   // __block and has an appropriate type.
15070   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
15071     return false;
15072 
15073   owner.Variable = var;
15074   if (ref)
15075     owner.setLocsFrom(ref);
15076   return true;
15077 }
15078 
15079 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
15080   while (true) {
15081     e = e->IgnoreParens();
15082     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
15083       switch (cast->getCastKind()) {
15084       case CK_BitCast:
15085       case CK_LValueBitCast:
15086       case CK_LValueToRValue:
15087       case CK_ARCReclaimReturnedObject:
15088         e = cast->getSubExpr();
15089         continue;
15090 
15091       default:
15092         return false;
15093       }
15094     }
15095 
15096     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
15097       ObjCIvarDecl *ivar = ref->getDecl();
15098       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
15099         return false;
15100 
15101       // Try to find a retain cycle in the base.
15102       if (!findRetainCycleOwner(S, ref->getBase(), owner))
15103         return false;
15104 
15105       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
15106       owner.Indirect = true;
15107       return true;
15108     }
15109 
15110     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
15111       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
15112       if (!var) return false;
15113       return considerVariable(var, ref, owner);
15114     }
15115 
15116     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
15117       if (member->isArrow()) return false;
15118 
15119       // Don't count this as an indirect ownership.
15120       e = member->getBase();
15121       continue;
15122     }
15123 
15124     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
15125       // Only pay attention to pseudo-objects on property references.
15126       ObjCPropertyRefExpr *pre
15127         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
15128                                               ->IgnoreParens());
15129       if (!pre) return false;
15130       if (pre->isImplicitProperty()) return false;
15131       ObjCPropertyDecl *property = pre->getExplicitProperty();
15132       if (!property->isRetaining() &&
15133           !(property->getPropertyIvarDecl() &&
15134             property->getPropertyIvarDecl()->getType()
15135               .getObjCLifetime() == Qualifiers::OCL_Strong))
15136           return false;
15137 
15138       owner.Indirect = true;
15139       if (pre->isSuperReceiver()) {
15140         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
15141         if (!owner.Variable)
15142           return false;
15143         owner.Loc = pre->getLocation();
15144         owner.Range = pre->getSourceRange();
15145         return true;
15146       }
15147       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
15148                               ->getSourceExpr());
15149       continue;
15150     }
15151 
15152     // Array ivars?
15153 
15154     return false;
15155   }
15156 }
15157 
15158 namespace {
15159 
15160   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
15161     ASTContext &Context;
15162     VarDecl *Variable;
15163     Expr *Capturer = nullptr;
15164     bool VarWillBeReased = false;
15165 
15166     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
15167         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
15168           Context(Context), Variable(variable) {}
15169 
15170     void VisitDeclRefExpr(DeclRefExpr *ref) {
15171       if (ref->getDecl() == Variable && !Capturer)
15172         Capturer = ref;
15173     }
15174 
15175     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
15176       if (Capturer) return;
15177       Visit(ref->getBase());
15178       if (Capturer && ref->isFreeIvar())
15179         Capturer = ref;
15180     }
15181 
15182     void VisitBlockExpr(BlockExpr *block) {
15183       // Look inside nested blocks
15184       if (block->getBlockDecl()->capturesVariable(Variable))
15185         Visit(block->getBlockDecl()->getBody());
15186     }
15187 
15188     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
15189       if (Capturer) return;
15190       if (OVE->getSourceExpr())
15191         Visit(OVE->getSourceExpr());
15192     }
15193 
15194     void VisitBinaryOperator(BinaryOperator *BinOp) {
15195       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
15196         return;
15197       Expr *LHS = BinOp->getLHS();
15198       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
15199         if (DRE->getDecl() != Variable)
15200           return;
15201         if (Expr *RHS = BinOp->getRHS()) {
15202           RHS = RHS->IgnoreParenCasts();
15203           Optional<llvm::APSInt> Value;
15204           VarWillBeReased =
15205               (RHS && (Value = RHS->getIntegerConstantExpr(Context)) &&
15206                *Value == 0);
15207         }
15208       }
15209     }
15210   };
15211 
15212 } // namespace
15213 
15214 /// Check whether the given argument is a block which captures a
15215 /// variable.
15216 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
15217   assert(owner.Variable && owner.Loc.isValid());
15218 
15219   e = e->IgnoreParenCasts();
15220 
15221   // Look through [^{...} copy] and Block_copy(^{...}).
15222   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
15223     Selector Cmd = ME->getSelector();
15224     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
15225       e = ME->getInstanceReceiver();
15226       if (!e)
15227         return nullptr;
15228       e = e->IgnoreParenCasts();
15229     }
15230   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
15231     if (CE->getNumArgs() == 1) {
15232       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
15233       if (Fn) {
15234         const IdentifierInfo *FnI = Fn->getIdentifier();
15235         if (FnI && FnI->isStr("_Block_copy")) {
15236           e = CE->getArg(0)->IgnoreParenCasts();
15237         }
15238       }
15239     }
15240   }
15241 
15242   BlockExpr *block = dyn_cast<BlockExpr>(e);
15243   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
15244     return nullptr;
15245 
15246   FindCaptureVisitor visitor(S.Context, owner.Variable);
15247   visitor.Visit(block->getBlockDecl()->getBody());
15248   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
15249 }
15250 
15251 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
15252                                 RetainCycleOwner &owner) {
15253   assert(capturer);
15254   assert(owner.Variable && owner.Loc.isValid());
15255 
15256   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
15257     << owner.Variable << capturer->getSourceRange();
15258   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
15259     << owner.Indirect << owner.Range;
15260 }
15261 
15262 /// Check for a keyword selector that starts with the word 'add' or
15263 /// 'set'.
15264 static bool isSetterLikeSelector(Selector sel) {
15265   if (sel.isUnarySelector()) return false;
15266 
15267   StringRef str = sel.getNameForSlot(0);
15268   while (!str.empty() && str.front() == '_') str = str.substr(1);
15269   if (str.startswith("set"))
15270     str = str.substr(3);
15271   else if (str.startswith("add")) {
15272     // Specially allow 'addOperationWithBlock:'.
15273     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
15274       return false;
15275     str = str.substr(3);
15276   }
15277   else
15278     return false;
15279 
15280   if (str.empty()) return true;
15281   return !isLowercase(str.front());
15282 }
15283 
15284 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
15285                                                     ObjCMessageExpr *Message) {
15286   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
15287                                                 Message->getReceiverInterface(),
15288                                                 NSAPI::ClassId_NSMutableArray);
15289   if (!IsMutableArray) {
15290     return None;
15291   }
15292 
15293   Selector Sel = Message->getSelector();
15294 
15295   Optional<NSAPI::NSArrayMethodKind> MKOpt =
15296     S.NSAPIObj->getNSArrayMethodKind(Sel);
15297   if (!MKOpt) {
15298     return None;
15299   }
15300 
15301   NSAPI::NSArrayMethodKind MK = *MKOpt;
15302 
15303   switch (MK) {
15304     case NSAPI::NSMutableArr_addObject:
15305     case NSAPI::NSMutableArr_insertObjectAtIndex:
15306     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
15307       return 0;
15308     case NSAPI::NSMutableArr_replaceObjectAtIndex:
15309       return 1;
15310 
15311     default:
15312       return None;
15313   }
15314 
15315   return None;
15316 }
15317 
15318 static
15319 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
15320                                                   ObjCMessageExpr *Message) {
15321   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
15322                                             Message->getReceiverInterface(),
15323                                             NSAPI::ClassId_NSMutableDictionary);
15324   if (!IsMutableDictionary) {
15325     return None;
15326   }
15327 
15328   Selector Sel = Message->getSelector();
15329 
15330   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
15331     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
15332   if (!MKOpt) {
15333     return None;
15334   }
15335 
15336   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
15337 
15338   switch (MK) {
15339     case NSAPI::NSMutableDict_setObjectForKey:
15340     case NSAPI::NSMutableDict_setValueForKey:
15341     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
15342       return 0;
15343 
15344     default:
15345       return None;
15346   }
15347 
15348   return None;
15349 }
15350 
15351 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
15352   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
15353                                                 Message->getReceiverInterface(),
15354                                                 NSAPI::ClassId_NSMutableSet);
15355 
15356   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
15357                                             Message->getReceiverInterface(),
15358                                             NSAPI::ClassId_NSMutableOrderedSet);
15359   if (!IsMutableSet && !IsMutableOrderedSet) {
15360     return None;
15361   }
15362 
15363   Selector Sel = Message->getSelector();
15364 
15365   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
15366   if (!MKOpt) {
15367     return None;
15368   }
15369 
15370   NSAPI::NSSetMethodKind MK = *MKOpt;
15371 
15372   switch (MK) {
15373     case NSAPI::NSMutableSet_addObject:
15374     case NSAPI::NSOrderedSet_setObjectAtIndex:
15375     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
15376     case NSAPI::NSOrderedSet_insertObjectAtIndex:
15377       return 0;
15378     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
15379       return 1;
15380   }
15381 
15382   return None;
15383 }
15384 
15385 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
15386   if (!Message->isInstanceMessage()) {
15387     return;
15388   }
15389 
15390   Optional<int> ArgOpt;
15391 
15392   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
15393       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
15394       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
15395     return;
15396   }
15397 
15398   int ArgIndex = *ArgOpt;
15399 
15400   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
15401   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
15402     Arg = OE->getSourceExpr()->IgnoreImpCasts();
15403   }
15404 
15405   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
15406     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
15407       if (ArgRE->isObjCSelfExpr()) {
15408         Diag(Message->getSourceRange().getBegin(),
15409              diag::warn_objc_circular_container)
15410           << ArgRE->getDecl() << StringRef("'super'");
15411       }
15412     }
15413   } else {
15414     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
15415 
15416     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
15417       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
15418     }
15419 
15420     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
15421       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
15422         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
15423           ValueDecl *Decl = ReceiverRE->getDecl();
15424           Diag(Message->getSourceRange().getBegin(),
15425                diag::warn_objc_circular_container)
15426             << Decl << Decl;
15427           if (!ArgRE->isObjCSelfExpr()) {
15428             Diag(Decl->getLocation(),
15429                  diag::note_objc_circular_container_declared_here)
15430               << Decl;
15431           }
15432         }
15433       }
15434     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
15435       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
15436         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
15437           ObjCIvarDecl *Decl = IvarRE->getDecl();
15438           Diag(Message->getSourceRange().getBegin(),
15439                diag::warn_objc_circular_container)
15440             << Decl << Decl;
15441           Diag(Decl->getLocation(),
15442                diag::note_objc_circular_container_declared_here)
15443             << Decl;
15444         }
15445       }
15446     }
15447   }
15448 }
15449 
15450 /// Check a message send to see if it's likely to cause a retain cycle.
15451 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
15452   // Only check instance methods whose selector looks like a setter.
15453   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
15454     return;
15455 
15456   // Try to find a variable that the receiver is strongly owned by.
15457   RetainCycleOwner owner;
15458   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
15459     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
15460       return;
15461   } else {
15462     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
15463     owner.Variable = getCurMethodDecl()->getSelfDecl();
15464     owner.Loc = msg->getSuperLoc();
15465     owner.Range = msg->getSuperLoc();
15466   }
15467 
15468   // Check whether the receiver is captured by any of the arguments.
15469   const ObjCMethodDecl *MD = msg->getMethodDecl();
15470   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
15471     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
15472       // noescape blocks should not be retained by the method.
15473       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
15474         continue;
15475       return diagnoseRetainCycle(*this, capturer, owner);
15476     }
15477   }
15478 }
15479 
15480 /// Check a property assign to see if it's likely to cause a retain cycle.
15481 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
15482   RetainCycleOwner owner;
15483   if (!findRetainCycleOwner(*this, receiver, owner))
15484     return;
15485 
15486   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
15487     diagnoseRetainCycle(*this, capturer, owner);
15488 }
15489 
15490 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
15491   RetainCycleOwner Owner;
15492   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
15493     return;
15494 
15495   // Because we don't have an expression for the variable, we have to set the
15496   // location explicitly here.
15497   Owner.Loc = Var->getLocation();
15498   Owner.Range = Var->getSourceRange();
15499 
15500   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
15501     diagnoseRetainCycle(*this, Capturer, Owner);
15502 }
15503 
15504 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
15505                                      Expr *RHS, bool isProperty) {
15506   // Check if RHS is an Objective-C object literal, which also can get
15507   // immediately zapped in a weak reference.  Note that we explicitly
15508   // allow ObjCStringLiterals, since those are designed to never really die.
15509   RHS = RHS->IgnoreParenImpCasts();
15510 
15511   // This enum needs to match with the 'select' in
15512   // warn_objc_arc_literal_assign (off-by-1).
15513   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
15514   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
15515     return false;
15516 
15517   S.Diag(Loc, diag::warn_arc_literal_assign)
15518     << (unsigned) Kind
15519     << (isProperty ? 0 : 1)
15520     << RHS->getSourceRange();
15521 
15522   return true;
15523 }
15524 
15525 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
15526                                     Qualifiers::ObjCLifetime LT,
15527                                     Expr *RHS, bool isProperty) {
15528   // Strip off any implicit cast added to get to the one ARC-specific.
15529   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15530     if (cast->getCastKind() == CK_ARCConsumeObject) {
15531       S.Diag(Loc, diag::warn_arc_retained_assign)
15532         << (LT == Qualifiers::OCL_ExplicitNone)
15533         << (isProperty ? 0 : 1)
15534         << RHS->getSourceRange();
15535       return true;
15536     }
15537     RHS = cast->getSubExpr();
15538   }
15539 
15540   if (LT == Qualifiers::OCL_Weak &&
15541       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
15542     return true;
15543 
15544   return false;
15545 }
15546 
15547 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
15548                               QualType LHS, Expr *RHS) {
15549   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
15550 
15551   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
15552     return false;
15553 
15554   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
15555     return true;
15556 
15557   return false;
15558 }
15559 
15560 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
15561                               Expr *LHS, Expr *RHS) {
15562   QualType LHSType;
15563   // PropertyRef on LHS type need be directly obtained from
15564   // its declaration as it has a PseudoType.
15565   ObjCPropertyRefExpr *PRE
15566     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
15567   if (PRE && !PRE->isImplicitProperty()) {
15568     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15569     if (PD)
15570       LHSType = PD->getType();
15571   }
15572 
15573   if (LHSType.isNull())
15574     LHSType = LHS->getType();
15575 
15576   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
15577 
15578   if (LT == Qualifiers::OCL_Weak) {
15579     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
15580       getCurFunction()->markSafeWeakUse(LHS);
15581   }
15582 
15583   if (checkUnsafeAssigns(Loc, LHSType, RHS))
15584     return;
15585 
15586   // FIXME. Check for other life times.
15587   if (LT != Qualifiers::OCL_None)
15588     return;
15589 
15590   if (PRE) {
15591     if (PRE->isImplicitProperty())
15592       return;
15593     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15594     if (!PD)
15595       return;
15596 
15597     unsigned Attributes = PD->getPropertyAttributes();
15598     if (Attributes & ObjCPropertyAttribute::kind_assign) {
15599       // when 'assign' attribute was not explicitly specified
15600       // by user, ignore it and rely on property type itself
15601       // for lifetime info.
15602       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
15603       if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
15604           LHSType->isObjCRetainableType())
15605         return;
15606 
15607       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15608         if (cast->getCastKind() == CK_ARCConsumeObject) {
15609           Diag(Loc, diag::warn_arc_retained_property_assign)
15610           << RHS->getSourceRange();
15611           return;
15612         }
15613         RHS = cast->getSubExpr();
15614       }
15615     } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
15616       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
15617         return;
15618     }
15619   }
15620 }
15621 
15622 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
15623 
15624 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
15625                                         SourceLocation StmtLoc,
15626                                         const NullStmt *Body) {
15627   // Do not warn if the body is a macro that expands to nothing, e.g:
15628   //
15629   // #define CALL(x)
15630   // if (condition)
15631   //   CALL(0);
15632   if (Body->hasLeadingEmptyMacro())
15633     return false;
15634 
15635   // Get line numbers of statement and body.
15636   bool StmtLineInvalid;
15637   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
15638                                                       &StmtLineInvalid);
15639   if (StmtLineInvalid)
15640     return false;
15641 
15642   bool BodyLineInvalid;
15643   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
15644                                                       &BodyLineInvalid);
15645   if (BodyLineInvalid)
15646     return false;
15647 
15648   // Warn if null statement and body are on the same line.
15649   if (StmtLine != BodyLine)
15650     return false;
15651 
15652   return true;
15653 }
15654 
15655 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
15656                                  const Stmt *Body,
15657                                  unsigned DiagID) {
15658   // Since this is a syntactic check, don't emit diagnostic for template
15659   // instantiations, this just adds noise.
15660   if (CurrentInstantiationScope)
15661     return;
15662 
15663   // The body should be a null statement.
15664   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15665   if (!NBody)
15666     return;
15667 
15668   // Do the usual checks.
15669   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15670     return;
15671 
15672   Diag(NBody->getSemiLoc(), DiagID);
15673   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15674 }
15675 
15676 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
15677                                  const Stmt *PossibleBody) {
15678   assert(!CurrentInstantiationScope); // Ensured by caller
15679 
15680   SourceLocation StmtLoc;
15681   const Stmt *Body;
15682   unsigned DiagID;
15683   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
15684     StmtLoc = FS->getRParenLoc();
15685     Body = FS->getBody();
15686     DiagID = diag::warn_empty_for_body;
15687   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
15688     StmtLoc = WS->getCond()->getSourceRange().getEnd();
15689     Body = WS->getBody();
15690     DiagID = diag::warn_empty_while_body;
15691   } else
15692     return; // Neither `for' nor `while'.
15693 
15694   // The body should be a null statement.
15695   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15696   if (!NBody)
15697     return;
15698 
15699   // Skip expensive checks if diagnostic is disabled.
15700   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
15701     return;
15702 
15703   // Do the usual checks.
15704   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15705     return;
15706 
15707   // `for(...);' and `while(...);' are popular idioms, so in order to keep
15708   // noise level low, emit diagnostics only if for/while is followed by a
15709   // CompoundStmt, e.g.:
15710   //    for (int i = 0; i < n; i++);
15711   //    {
15712   //      a(i);
15713   //    }
15714   // or if for/while is followed by a statement with more indentation
15715   // than for/while itself:
15716   //    for (int i = 0; i < n; i++);
15717   //      a(i);
15718   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
15719   if (!ProbableTypo) {
15720     bool BodyColInvalid;
15721     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
15722         PossibleBody->getBeginLoc(), &BodyColInvalid);
15723     if (BodyColInvalid)
15724       return;
15725 
15726     bool StmtColInvalid;
15727     unsigned StmtCol =
15728         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
15729     if (StmtColInvalid)
15730       return;
15731 
15732     if (BodyCol > StmtCol)
15733       ProbableTypo = true;
15734   }
15735 
15736   if (ProbableTypo) {
15737     Diag(NBody->getSemiLoc(), DiagID);
15738     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15739   }
15740 }
15741 
15742 //===--- CHECK: Warn on self move with std::move. -------------------------===//
15743 
15744 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
15745 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
15746                              SourceLocation OpLoc) {
15747   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
15748     return;
15749 
15750   if (inTemplateInstantiation())
15751     return;
15752 
15753   // Strip parens and casts away.
15754   LHSExpr = LHSExpr->IgnoreParenImpCasts();
15755   RHSExpr = RHSExpr->IgnoreParenImpCasts();
15756 
15757   // Check for a call expression
15758   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
15759   if (!CE || CE->getNumArgs() != 1)
15760     return;
15761 
15762   // Check for a call to std::move
15763   if (!CE->isCallToStdMove())
15764     return;
15765 
15766   // Get argument from std::move
15767   RHSExpr = CE->getArg(0);
15768 
15769   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
15770   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
15771 
15772   // Two DeclRefExpr's, check that the decls are the same.
15773   if (LHSDeclRef && RHSDeclRef) {
15774     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15775       return;
15776     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15777         RHSDeclRef->getDecl()->getCanonicalDecl())
15778       return;
15779 
15780     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15781                                         << LHSExpr->getSourceRange()
15782                                         << RHSExpr->getSourceRange();
15783     return;
15784   }
15785 
15786   // Member variables require a different approach to check for self moves.
15787   // MemberExpr's are the same if every nested MemberExpr refers to the same
15788   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
15789   // the base Expr's are CXXThisExpr's.
15790   const Expr *LHSBase = LHSExpr;
15791   const Expr *RHSBase = RHSExpr;
15792   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
15793   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
15794   if (!LHSME || !RHSME)
15795     return;
15796 
15797   while (LHSME && RHSME) {
15798     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
15799         RHSME->getMemberDecl()->getCanonicalDecl())
15800       return;
15801 
15802     LHSBase = LHSME->getBase();
15803     RHSBase = RHSME->getBase();
15804     LHSME = dyn_cast<MemberExpr>(LHSBase);
15805     RHSME = dyn_cast<MemberExpr>(RHSBase);
15806   }
15807 
15808   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
15809   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
15810   if (LHSDeclRef && RHSDeclRef) {
15811     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15812       return;
15813     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15814         RHSDeclRef->getDecl()->getCanonicalDecl())
15815       return;
15816 
15817     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15818                                         << LHSExpr->getSourceRange()
15819                                         << RHSExpr->getSourceRange();
15820     return;
15821   }
15822 
15823   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
15824     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15825                                         << LHSExpr->getSourceRange()
15826                                         << RHSExpr->getSourceRange();
15827 }
15828 
15829 //===--- Layout compatibility ----------------------------------------------//
15830 
15831 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
15832 
15833 /// Check if two enumeration types are layout-compatible.
15834 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
15835   // C++11 [dcl.enum] p8:
15836   // Two enumeration types are layout-compatible if they have the same
15837   // underlying type.
15838   return ED1->isComplete() && ED2->isComplete() &&
15839          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
15840 }
15841 
15842 /// Check if two fields are layout-compatible.
15843 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
15844                                FieldDecl *Field2) {
15845   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
15846     return false;
15847 
15848   if (Field1->isBitField() != Field2->isBitField())
15849     return false;
15850 
15851   if (Field1->isBitField()) {
15852     // Make sure that the bit-fields are the same length.
15853     unsigned Bits1 = Field1->getBitWidthValue(C);
15854     unsigned Bits2 = Field2->getBitWidthValue(C);
15855 
15856     if (Bits1 != Bits2)
15857       return false;
15858   }
15859 
15860   return true;
15861 }
15862 
15863 /// Check if two standard-layout structs are layout-compatible.
15864 /// (C++11 [class.mem] p17)
15865 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
15866                                      RecordDecl *RD2) {
15867   // If both records are C++ classes, check that base classes match.
15868   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
15869     // If one of records is a CXXRecordDecl we are in C++ mode,
15870     // thus the other one is a CXXRecordDecl, too.
15871     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
15872     // Check number of base classes.
15873     if (D1CXX->getNumBases() != D2CXX->getNumBases())
15874       return false;
15875 
15876     // Check the base classes.
15877     for (CXXRecordDecl::base_class_const_iterator
15878                Base1 = D1CXX->bases_begin(),
15879            BaseEnd1 = D1CXX->bases_end(),
15880               Base2 = D2CXX->bases_begin();
15881          Base1 != BaseEnd1;
15882          ++Base1, ++Base2) {
15883       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
15884         return false;
15885     }
15886   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
15887     // If only RD2 is a C++ class, it should have zero base classes.
15888     if (D2CXX->getNumBases() > 0)
15889       return false;
15890   }
15891 
15892   // Check the fields.
15893   RecordDecl::field_iterator Field2 = RD2->field_begin(),
15894                              Field2End = RD2->field_end(),
15895                              Field1 = RD1->field_begin(),
15896                              Field1End = RD1->field_end();
15897   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
15898     if (!isLayoutCompatible(C, *Field1, *Field2))
15899       return false;
15900   }
15901   if (Field1 != Field1End || Field2 != Field2End)
15902     return false;
15903 
15904   return true;
15905 }
15906 
15907 /// Check if two standard-layout unions are layout-compatible.
15908 /// (C++11 [class.mem] p18)
15909 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
15910                                     RecordDecl *RD2) {
15911   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
15912   for (auto *Field2 : RD2->fields())
15913     UnmatchedFields.insert(Field2);
15914 
15915   for (auto *Field1 : RD1->fields()) {
15916     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
15917         I = UnmatchedFields.begin(),
15918         E = UnmatchedFields.end();
15919 
15920     for ( ; I != E; ++I) {
15921       if (isLayoutCompatible(C, Field1, *I)) {
15922         bool Result = UnmatchedFields.erase(*I);
15923         (void) Result;
15924         assert(Result);
15925         break;
15926       }
15927     }
15928     if (I == E)
15929       return false;
15930   }
15931 
15932   return UnmatchedFields.empty();
15933 }
15934 
15935 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
15936                                RecordDecl *RD2) {
15937   if (RD1->isUnion() != RD2->isUnion())
15938     return false;
15939 
15940   if (RD1->isUnion())
15941     return isLayoutCompatibleUnion(C, RD1, RD2);
15942   else
15943     return isLayoutCompatibleStruct(C, RD1, RD2);
15944 }
15945 
15946 /// Check if two types are layout-compatible in C++11 sense.
15947 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
15948   if (T1.isNull() || T2.isNull())
15949     return false;
15950 
15951   // C++11 [basic.types] p11:
15952   // If two types T1 and T2 are the same type, then T1 and T2 are
15953   // layout-compatible types.
15954   if (C.hasSameType(T1, T2))
15955     return true;
15956 
15957   T1 = T1.getCanonicalType().getUnqualifiedType();
15958   T2 = T2.getCanonicalType().getUnqualifiedType();
15959 
15960   const Type::TypeClass TC1 = T1->getTypeClass();
15961   const Type::TypeClass TC2 = T2->getTypeClass();
15962 
15963   if (TC1 != TC2)
15964     return false;
15965 
15966   if (TC1 == Type::Enum) {
15967     return isLayoutCompatible(C,
15968                               cast<EnumType>(T1)->getDecl(),
15969                               cast<EnumType>(T2)->getDecl());
15970   } else if (TC1 == Type::Record) {
15971     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
15972       return false;
15973 
15974     return isLayoutCompatible(C,
15975                               cast<RecordType>(T1)->getDecl(),
15976                               cast<RecordType>(T2)->getDecl());
15977   }
15978 
15979   return false;
15980 }
15981 
15982 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
15983 
15984 /// Given a type tag expression find the type tag itself.
15985 ///
15986 /// \param TypeExpr Type tag expression, as it appears in user's code.
15987 ///
15988 /// \param VD Declaration of an identifier that appears in a type tag.
15989 ///
15990 /// \param MagicValue Type tag magic value.
15991 ///
15992 /// \param isConstantEvaluated wether the evalaution should be performed in
15993 
15994 /// constant context.
15995 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
15996                             const ValueDecl **VD, uint64_t *MagicValue,
15997                             bool isConstantEvaluated) {
15998   while(true) {
15999     if (!TypeExpr)
16000       return false;
16001 
16002     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
16003 
16004     switch (TypeExpr->getStmtClass()) {
16005     case Stmt::UnaryOperatorClass: {
16006       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
16007       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
16008         TypeExpr = UO->getSubExpr();
16009         continue;
16010       }
16011       return false;
16012     }
16013 
16014     case Stmt::DeclRefExprClass: {
16015       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
16016       *VD = DRE->getDecl();
16017       return true;
16018     }
16019 
16020     case Stmt::IntegerLiteralClass: {
16021       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
16022       llvm::APInt MagicValueAPInt = IL->getValue();
16023       if (MagicValueAPInt.getActiveBits() <= 64) {
16024         *MagicValue = MagicValueAPInt.getZExtValue();
16025         return true;
16026       } else
16027         return false;
16028     }
16029 
16030     case Stmt::BinaryConditionalOperatorClass:
16031     case Stmt::ConditionalOperatorClass: {
16032       const AbstractConditionalOperator *ACO =
16033           cast<AbstractConditionalOperator>(TypeExpr);
16034       bool Result;
16035       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
16036                                                      isConstantEvaluated)) {
16037         if (Result)
16038           TypeExpr = ACO->getTrueExpr();
16039         else
16040           TypeExpr = ACO->getFalseExpr();
16041         continue;
16042       }
16043       return false;
16044     }
16045 
16046     case Stmt::BinaryOperatorClass: {
16047       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
16048       if (BO->getOpcode() == BO_Comma) {
16049         TypeExpr = BO->getRHS();
16050         continue;
16051       }
16052       return false;
16053     }
16054 
16055     default:
16056       return false;
16057     }
16058   }
16059 }
16060 
16061 /// Retrieve the C type corresponding to type tag TypeExpr.
16062 ///
16063 /// \param TypeExpr Expression that specifies a type tag.
16064 ///
16065 /// \param MagicValues Registered magic values.
16066 ///
16067 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
16068 ///        kind.
16069 ///
16070 /// \param TypeInfo Information about the corresponding C type.
16071 ///
16072 /// \param isConstantEvaluated wether the evalaution should be performed in
16073 /// constant context.
16074 ///
16075 /// \returns true if the corresponding C type was found.
16076 static bool GetMatchingCType(
16077     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
16078     const ASTContext &Ctx,
16079     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
16080         *MagicValues,
16081     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
16082     bool isConstantEvaluated) {
16083   FoundWrongKind = false;
16084 
16085   // Variable declaration that has type_tag_for_datatype attribute.
16086   const ValueDecl *VD = nullptr;
16087 
16088   uint64_t MagicValue;
16089 
16090   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
16091     return false;
16092 
16093   if (VD) {
16094     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
16095       if (I->getArgumentKind() != ArgumentKind) {
16096         FoundWrongKind = true;
16097         return false;
16098       }
16099       TypeInfo.Type = I->getMatchingCType();
16100       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
16101       TypeInfo.MustBeNull = I->getMustBeNull();
16102       return true;
16103     }
16104     return false;
16105   }
16106 
16107   if (!MagicValues)
16108     return false;
16109 
16110   llvm::DenseMap<Sema::TypeTagMagicValue,
16111                  Sema::TypeTagData>::const_iterator I =
16112       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
16113   if (I == MagicValues->end())
16114     return false;
16115 
16116   TypeInfo = I->second;
16117   return true;
16118 }
16119 
16120 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
16121                                       uint64_t MagicValue, QualType Type,
16122                                       bool LayoutCompatible,
16123                                       bool MustBeNull) {
16124   if (!TypeTagForDatatypeMagicValues)
16125     TypeTagForDatatypeMagicValues.reset(
16126         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
16127 
16128   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
16129   (*TypeTagForDatatypeMagicValues)[Magic] =
16130       TypeTagData(Type, LayoutCompatible, MustBeNull);
16131 }
16132 
16133 static bool IsSameCharType(QualType T1, QualType T2) {
16134   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
16135   if (!BT1)
16136     return false;
16137 
16138   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
16139   if (!BT2)
16140     return false;
16141 
16142   BuiltinType::Kind T1Kind = BT1->getKind();
16143   BuiltinType::Kind T2Kind = BT2->getKind();
16144 
16145   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
16146          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
16147          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
16148          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
16149 }
16150 
16151 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
16152                                     const ArrayRef<const Expr *> ExprArgs,
16153                                     SourceLocation CallSiteLoc) {
16154   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
16155   bool IsPointerAttr = Attr->getIsPointer();
16156 
16157   // Retrieve the argument representing the 'type_tag'.
16158   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
16159   if (TypeTagIdxAST >= ExprArgs.size()) {
16160     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16161         << 0 << Attr->getTypeTagIdx().getSourceIndex();
16162     return;
16163   }
16164   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
16165   bool FoundWrongKind;
16166   TypeTagData TypeInfo;
16167   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
16168                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
16169                         TypeInfo, isConstantEvaluated())) {
16170     if (FoundWrongKind)
16171       Diag(TypeTagExpr->getExprLoc(),
16172            diag::warn_type_tag_for_datatype_wrong_kind)
16173         << TypeTagExpr->getSourceRange();
16174     return;
16175   }
16176 
16177   // Retrieve the argument representing the 'arg_idx'.
16178   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
16179   if (ArgumentIdxAST >= ExprArgs.size()) {
16180     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16181         << 1 << Attr->getArgumentIdx().getSourceIndex();
16182     return;
16183   }
16184   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
16185   if (IsPointerAttr) {
16186     // Skip implicit cast of pointer to `void *' (as a function argument).
16187     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
16188       if (ICE->getType()->isVoidPointerType() &&
16189           ICE->getCastKind() == CK_BitCast)
16190         ArgumentExpr = ICE->getSubExpr();
16191   }
16192   QualType ArgumentType = ArgumentExpr->getType();
16193 
16194   // Passing a `void*' pointer shouldn't trigger a warning.
16195   if (IsPointerAttr && ArgumentType->isVoidPointerType())
16196     return;
16197 
16198   if (TypeInfo.MustBeNull) {
16199     // Type tag with matching void type requires a null pointer.
16200     if (!ArgumentExpr->isNullPointerConstant(Context,
16201                                              Expr::NPC_ValueDependentIsNotNull)) {
16202       Diag(ArgumentExpr->getExprLoc(),
16203            diag::warn_type_safety_null_pointer_required)
16204           << ArgumentKind->getName()
16205           << ArgumentExpr->getSourceRange()
16206           << TypeTagExpr->getSourceRange();
16207     }
16208     return;
16209   }
16210 
16211   QualType RequiredType = TypeInfo.Type;
16212   if (IsPointerAttr)
16213     RequiredType = Context.getPointerType(RequiredType);
16214 
16215   bool mismatch = false;
16216   if (!TypeInfo.LayoutCompatible) {
16217     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
16218 
16219     // C++11 [basic.fundamental] p1:
16220     // Plain char, signed char, and unsigned char are three distinct types.
16221     //
16222     // But we treat plain `char' as equivalent to `signed char' or `unsigned
16223     // char' depending on the current char signedness mode.
16224     if (mismatch)
16225       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
16226                                            RequiredType->getPointeeType())) ||
16227           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
16228         mismatch = false;
16229   } else
16230     if (IsPointerAttr)
16231       mismatch = !isLayoutCompatible(Context,
16232                                      ArgumentType->getPointeeType(),
16233                                      RequiredType->getPointeeType());
16234     else
16235       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
16236 
16237   if (mismatch)
16238     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
16239         << ArgumentType << ArgumentKind
16240         << TypeInfo.LayoutCompatible << RequiredType
16241         << ArgumentExpr->getSourceRange()
16242         << TypeTagExpr->getSourceRange();
16243 }
16244 
16245 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
16246                                          CharUnits Alignment) {
16247   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
16248 }
16249 
16250 void Sema::DiagnoseMisalignedMembers() {
16251   for (MisalignedMember &m : MisalignedMembers) {
16252     const NamedDecl *ND = m.RD;
16253     if (ND->getName().empty()) {
16254       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
16255         ND = TD;
16256     }
16257     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
16258         << m.MD << ND << m.E->getSourceRange();
16259   }
16260   MisalignedMembers.clear();
16261 }
16262 
16263 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
16264   E = E->IgnoreParens();
16265   if (!T->isPointerType() && !T->isIntegerType())
16266     return;
16267   if (isa<UnaryOperator>(E) &&
16268       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
16269     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
16270     if (isa<MemberExpr>(Op)) {
16271       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
16272       if (MA != MisalignedMembers.end() &&
16273           (T->isIntegerType() ||
16274            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
16275                                    Context.getTypeAlignInChars(
16276                                        T->getPointeeType()) <= MA->Alignment))))
16277         MisalignedMembers.erase(MA);
16278     }
16279   }
16280 }
16281 
16282 void Sema::RefersToMemberWithReducedAlignment(
16283     Expr *E,
16284     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
16285         Action) {
16286   const auto *ME = dyn_cast<MemberExpr>(E);
16287   if (!ME)
16288     return;
16289 
16290   // No need to check expressions with an __unaligned-qualified type.
16291   if (E->getType().getQualifiers().hasUnaligned())
16292     return;
16293 
16294   // For a chain of MemberExpr like "a.b.c.d" this list
16295   // will keep FieldDecl's like [d, c, b].
16296   SmallVector<FieldDecl *, 4> ReverseMemberChain;
16297   const MemberExpr *TopME = nullptr;
16298   bool AnyIsPacked = false;
16299   do {
16300     QualType BaseType = ME->getBase()->getType();
16301     if (BaseType->isDependentType())
16302       return;
16303     if (ME->isArrow())
16304       BaseType = BaseType->getPointeeType();
16305     RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
16306     if (RD->isInvalidDecl())
16307       return;
16308 
16309     ValueDecl *MD = ME->getMemberDecl();
16310     auto *FD = dyn_cast<FieldDecl>(MD);
16311     // We do not care about non-data members.
16312     if (!FD || FD->isInvalidDecl())
16313       return;
16314 
16315     AnyIsPacked =
16316         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
16317     ReverseMemberChain.push_back(FD);
16318 
16319     TopME = ME;
16320     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
16321   } while (ME);
16322   assert(TopME && "We did not compute a topmost MemberExpr!");
16323 
16324   // Not the scope of this diagnostic.
16325   if (!AnyIsPacked)
16326     return;
16327 
16328   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
16329   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
16330   // TODO: The innermost base of the member expression may be too complicated.
16331   // For now, just disregard these cases. This is left for future
16332   // improvement.
16333   if (!DRE && !isa<CXXThisExpr>(TopBase))
16334       return;
16335 
16336   // Alignment expected by the whole expression.
16337   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
16338 
16339   // No need to do anything else with this case.
16340   if (ExpectedAlignment.isOne())
16341     return;
16342 
16343   // Synthesize offset of the whole access.
16344   CharUnits Offset;
16345   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
16346        I++) {
16347     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
16348   }
16349 
16350   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
16351   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
16352       ReverseMemberChain.back()->getParent()->getTypeForDecl());
16353 
16354   // The base expression of the innermost MemberExpr may give
16355   // stronger guarantees than the class containing the member.
16356   if (DRE && !TopME->isArrow()) {
16357     const ValueDecl *VD = DRE->getDecl();
16358     if (!VD->getType()->isReferenceType())
16359       CompleteObjectAlignment =
16360           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
16361   }
16362 
16363   // Check if the synthesized offset fulfills the alignment.
16364   if (Offset % ExpectedAlignment != 0 ||
16365       // It may fulfill the offset it but the effective alignment may still be
16366       // lower than the expected expression alignment.
16367       CompleteObjectAlignment < ExpectedAlignment) {
16368     // If this happens, we want to determine a sensible culprit of this.
16369     // Intuitively, watching the chain of member expressions from right to
16370     // left, we start with the required alignment (as required by the field
16371     // type) but some packed attribute in that chain has reduced the alignment.
16372     // It may happen that another packed structure increases it again. But if
16373     // we are here such increase has not been enough. So pointing the first
16374     // FieldDecl that either is packed or else its RecordDecl is,
16375     // seems reasonable.
16376     FieldDecl *FD = nullptr;
16377     CharUnits Alignment;
16378     for (FieldDecl *FDI : ReverseMemberChain) {
16379       if (FDI->hasAttr<PackedAttr>() ||
16380           FDI->getParent()->hasAttr<PackedAttr>()) {
16381         FD = FDI;
16382         Alignment = std::min(
16383             Context.getTypeAlignInChars(FD->getType()),
16384             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
16385         break;
16386       }
16387     }
16388     assert(FD && "We did not find a packed FieldDecl!");
16389     Action(E, FD->getParent(), FD, Alignment);
16390   }
16391 }
16392 
16393 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
16394   using namespace std::placeholders;
16395 
16396   RefersToMemberWithReducedAlignment(
16397       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
16398                      _2, _3, _4));
16399 }
16400 
16401 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall,
16402                                             ExprResult CallResult) {
16403   if (checkArgCount(*this, TheCall, 1))
16404     return ExprError();
16405 
16406   ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
16407   if (MatrixArg.isInvalid())
16408     return MatrixArg;
16409   Expr *Matrix = MatrixArg.get();
16410 
16411   auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
16412   if (!MType) {
16413     Diag(Matrix->getBeginLoc(), diag::err_builtin_matrix_arg);
16414     return ExprError();
16415   }
16416 
16417   // Create returned matrix type by swapping rows and columns of the argument
16418   // matrix type.
16419   QualType ResultType = Context.getConstantMatrixType(
16420       MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
16421 
16422   // Change the return type to the type of the returned matrix.
16423   TheCall->setType(ResultType);
16424 
16425   // Update call argument to use the possibly converted matrix argument.
16426   TheCall->setArg(0, Matrix);
16427   return CallResult;
16428 }
16429 
16430 // Get and verify the matrix dimensions.
16431 static llvm::Optional<unsigned>
16432 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {
16433   SourceLocation ErrorPos;
16434   Optional<llvm::APSInt> Value =
16435       Expr->getIntegerConstantExpr(S.Context, &ErrorPos);
16436   if (!Value) {
16437     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
16438         << Name;
16439     return {};
16440   }
16441   uint64_t Dim = Value->getZExtValue();
16442   if (!ConstantMatrixType::isDimensionValid(Dim)) {
16443     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
16444         << Name << ConstantMatrixType::getMaxElementsPerDimension();
16445     return {};
16446   }
16447   return Dim;
16448 }
16449 
16450 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
16451                                                   ExprResult CallResult) {
16452   if (!getLangOpts().MatrixTypes) {
16453     Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
16454     return ExprError();
16455   }
16456 
16457   if (checkArgCount(*this, TheCall, 4))
16458     return ExprError();
16459 
16460   unsigned PtrArgIdx = 0;
16461   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16462   Expr *RowsExpr = TheCall->getArg(1);
16463   Expr *ColumnsExpr = TheCall->getArg(2);
16464   Expr *StrideExpr = TheCall->getArg(3);
16465 
16466   bool ArgError = false;
16467 
16468   // Check pointer argument.
16469   {
16470     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
16471     if (PtrConv.isInvalid())
16472       return PtrConv;
16473     PtrExpr = PtrConv.get();
16474     TheCall->setArg(0, PtrExpr);
16475     if (PtrExpr->isTypeDependent()) {
16476       TheCall->setType(Context.DependentTy);
16477       return TheCall;
16478     }
16479   }
16480 
16481   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16482   QualType ElementTy;
16483   if (!PtrTy) {
16484     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
16485         << PtrArgIdx + 1;
16486     ArgError = true;
16487   } else {
16488     ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
16489 
16490     if (!ConstantMatrixType::isValidElementType(ElementTy)) {
16491       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
16492           << PtrArgIdx + 1;
16493       ArgError = true;
16494     }
16495   }
16496 
16497   // Apply default Lvalue conversions and convert the expression to size_t.
16498   auto ApplyArgumentConversions = [this](Expr *E) {
16499     ExprResult Conv = DefaultLvalueConversion(E);
16500     if (Conv.isInvalid())
16501       return Conv;
16502 
16503     return tryConvertExprToType(Conv.get(), Context.getSizeType());
16504   };
16505 
16506   // Apply conversion to row and column expressions.
16507   ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
16508   if (!RowsConv.isInvalid()) {
16509     RowsExpr = RowsConv.get();
16510     TheCall->setArg(1, RowsExpr);
16511   } else
16512     RowsExpr = nullptr;
16513 
16514   ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
16515   if (!ColumnsConv.isInvalid()) {
16516     ColumnsExpr = ColumnsConv.get();
16517     TheCall->setArg(2, ColumnsExpr);
16518   } else
16519     ColumnsExpr = nullptr;
16520 
16521   // If any any part of the result matrix type is still pending, just use
16522   // Context.DependentTy, until all parts are resolved.
16523   if ((RowsExpr && RowsExpr->isTypeDependent()) ||
16524       (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
16525     TheCall->setType(Context.DependentTy);
16526     return CallResult;
16527   }
16528 
16529   // Check row and column dimenions.
16530   llvm::Optional<unsigned> MaybeRows;
16531   if (RowsExpr)
16532     MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
16533 
16534   llvm::Optional<unsigned> MaybeColumns;
16535   if (ColumnsExpr)
16536     MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
16537 
16538   // Check stride argument.
16539   ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
16540   if (StrideConv.isInvalid())
16541     return ExprError();
16542   StrideExpr = StrideConv.get();
16543   TheCall->setArg(3, StrideExpr);
16544 
16545   if (MaybeRows) {
16546     if (Optional<llvm::APSInt> Value =
16547             StrideExpr->getIntegerConstantExpr(Context)) {
16548       uint64_t Stride = Value->getZExtValue();
16549       if (Stride < *MaybeRows) {
16550         Diag(StrideExpr->getBeginLoc(),
16551              diag::err_builtin_matrix_stride_too_small);
16552         ArgError = true;
16553       }
16554     }
16555   }
16556 
16557   if (ArgError || !MaybeRows || !MaybeColumns)
16558     return ExprError();
16559 
16560   TheCall->setType(
16561       Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
16562   return CallResult;
16563 }
16564 
16565 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
16566                                                    ExprResult CallResult) {
16567   if (checkArgCount(*this, TheCall, 3))
16568     return ExprError();
16569 
16570   unsigned PtrArgIdx = 1;
16571   Expr *MatrixExpr = TheCall->getArg(0);
16572   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16573   Expr *StrideExpr = TheCall->getArg(2);
16574 
16575   bool ArgError = false;
16576 
16577   {
16578     ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
16579     if (MatrixConv.isInvalid())
16580       return MatrixConv;
16581     MatrixExpr = MatrixConv.get();
16582     TheCall->setArg(0, MatrixExpr);
16583   }
16584   if (MatrixExpr->isTypeDependent()) {
16585     TheCall->setType(Context.DependentTy);
16586     return TheCall;
16587   }
16588 
16589   auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
16590   if (!MatrixTy) {
16591     Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_matrix_arg) << 0;
16592     ArgError = true;
16593   }
16594 
16595   {
16596     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
16597     if (PtrConv.isInvalid())
16598       return PtrConv;
16599     PtrExpr = PtrConv.get();
16600     TheCall->setArg(1, PtrExpr);
16601     if (PtrExpr->isTypeDependent()) {
16602       TheCall->setType(Context.DependentTy);
16603       return TheCall;
16604     }
16605   }
16606 
16607   // Check pointer argument.
16608   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16609   if (!PtrTy) {
16610     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
16611         << PtrArgIdx + 1;
16612     ArgError = true;
16613   } else {
16614     QualType ElementTy = PtrTy->getPointeeType();
16615     if (ElementTy.isConstQualified()) {
16616       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
16617       ArgError = true;
16618     }
16619     ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
16620     if (MatrixTy &&
16621         !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
16622       Diag(PtrExpr->getBeginLoc(),
16623            diag::err_builtin_matrix_pointer_arg_mismatch)
16624           << ElementTy << MatrixTy->getElementType();
16625       ArgError = true;
16626     }
16627   }
16628 
16629   // Apply default Lvalue conversions and convert the stride expression to
16630   // size_t.
16631   {
16632     ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
16633     if (StrideConv.isInvalid())
16634       return StrideConv;
16635 
16636     StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
16637     if (StrideConv.isInvalid())
16638       return StrideConv;
16639     StrideExpr = StrideConv.get();
16640     TheCall->setArg(2, StrideExpr);
16641   }
16642 
16643   // Check stride argument.
16644   if (MatrixTy) {
16645     if (Optional<llvm::APSInt> Value =
16646             StrideExpr->getIntegerConstantExpr(Context)) {
16647       uint64_t Stride = Value->getZExtValue();
16648       if (Stride < MatrixTy->getNumRows()) {
16649         Diag(StrideExpr->getBeginLoc(),
16650              diag::err_builtin_matrix_stride_too_small);
16651         ArgError = true;
16652       }
16653     }
16654   }
16655 
16656   if (ArgError)
16657     return ExprError();
16658 
16659   return CallResult;
16660 }
16661 
16662 /// \brief Enforce the bounds of a TCB
16663 /// CheckTCBEnforcement - Enforces that every function in a named TCB only
16664 /// directly calls other functions in the same TCB as marked by the enforce_tcb
16665 /// and enforce_tcb_leaf attributes.
16666 void Sema::CheckTCBEnforcement(const CallExpr *TheCall,
16667                                const FunctionDecl *Callee) {
16668   const FunctionDecl *Caller = getCurFunctionDecl();
16669 
16670   // Calls to builtins are not enforced.
16671   if (!Caller || !Caller->hasAttr<EnforceTCBAttr>() ||
16672       Callee->getBuiltinID() != 0)
16673     return;
16674 
16675   // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
16676   // all TCBs the callee is a part of.
16677   llvm::StringSet<> CalleeTCBs;
16678   for_each(Callee->specific_attrs<EnforceTCBAttr>(),
16679            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
16680   for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(),
16681            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
16682 
16683   // Go through the TCBs the caller is a part of and emit warnings if Caller
16684   // is in a TCB that the Callee is not.
16685   for_each(
16686       Caller->specific_attrs<EnforceTCBAttr>(),
16687       [&](const auto *A) {
16688         StringRef CallerTCB = A->getTCBName();
16689         if (CalleeTCBs.count(CallerTCB) == 0) {
16690           this->Diag(TheCall->getExprLoc(),
16691                      diag::warn_tcb_enforcement_violation) << Callee
16692                                                            << CallerTCB;
16693         }
16694       });
16695 }
16696