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__assume:
1558   case Builtin::BI__builtin_assume:
1559     if (SemaBuiltinAssume(TheCall))
1560       return ExprError();
1561     break;
1562   case Builtin::BI__builtin_assume_aligned:
1563     if (SemaBuiltinAssumeAligned(TheCall))
1564       return ExprError();
1565     break;
1566   case Builtin::BI__builtin_dynamic_object_size:
1567   case Builtin::BI__builtin_object_size:
1568     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1569       return ExprError();
1570     break;
1571   case Builtin::BI__builtin_longjmp:
1572     if (SemaBuiltinLongjmp(TheCall))
1573       return ExprError();
1574     break;
1575   case Builtin::BI__builtin_setjmp:
1576     if (SemaBuiltinSetjmp(TheCall))
1577       return ExprError();
1578     break;
1579   case Builtin::BI__builtin_classify_type:
1580     if (checkArgCount(*this, TheCall, 1)) return true;
1581     TheCall->setType(Context.IntTy);
1582     break;
1583   case Builtin::BI__builtin_complex:
1584     if (SemaBuiltinComplex(TheCall))
1585       return ExprError();
1586     break;
1587   case Builtin::BI__builtin_constant_p: {
1588     if (checkArgCount(*this, TheCall, 1)) return true;
1589     ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
1590     if (Arg.isInvalid()) return true;
1591     TheCall->setArg(0, Arg.get());
1592     TheCall->setType(Context.IntTy);
1593     break;
1594   }
1595   case Builtin::BI__builtin_launder:
1596     return SemaBuiltinLaunder(*this, TheCall);
1597   case Builtin::BI__sync_fetch_and_add:
1598   case Builtin::BI__sync_fetch_and_add_1:
1599   case Builtin::BI__sync_fetch_and_add_2:
1600   case Builtin::BI__sync_fetch_and_add_4:
1601   case Builtin::BI__sync_fetch_and_add_8:
1602   case Builtin::BI__sync_fetch_and_add_16:
1603   case Builtin::BI__sync_fetch_and_sub:
1604   case Builtin::BI__sync_fetch_and_sub_1:
1605   case Builtin::BI__sync_fetch_and_sub_2:
1606   case Builtin::BI__sync_fetch_and_sub_4:
1607   case Builtin::BI__sync_fetch_and_sub_8:
1608   case Builtin::BI__sync_fetch_and_sub_16:
1609   case Builtin::BI__sync_fetch_and_or:
1610   case Builtin::BI__sync_fetch_and_or_1:
1611   case Builtin::BI__sync_fetch_and_or_2:
1612   case Builtin::BI__sync_fetch_and_or_4:
1613   case Builtin::BI__sync_fetch_and_or_8:
1614   case Builtin::BI__sync_fetch_and_or_16:
1615   case Builtin::BI__sync_fetch_and_and:
1616   case Builtin::BI__sync_fetch_and_and_1:
1617   case Builtin::BI__sync_fetch_and_and_2:
1618   case Builtin::BI__sync_fetch_and_and_4:
1619   case Builtin::BI__sync_fetch_and_and_8:
1620   case Builtin::BI__sync_fetch_and_and_16:
1621   case Builtin::BI__sync_fetch_and_xor:
1622   case Builtin::BI__sync_fetch_and_xor_1:
1623   case Builtin::BI__sync_fetch_and_xor_2:
1624   case Builtin::BI__sync_fetch_and_xor_4:
1625   case Builtin::BI__sync_fetch_and_xor_8:
1626   case Builtin::BI__sync_fetch_and_xor_16:
1627   case Builtin::BI__sync_fetch_and_nand:
1628   case Builtin::BI__sync_fetch_and_nand_1:
1629   case Builtin::BI__sync_fetch_and_nand_2:
1630   case Builtin::BI__sync_fetch_and_nand_4:
1631   case Builtin::BI__sync_fetch_and_nand_8:
1632   case Builtin::BI__sync_fetch_and_nand_16:
1633   case Builtin::BI__sync_add_and_fetch:
1634   case Builtin::BI__sync_add_and_fetch_1:
1635   case Builtin::BI__sync_add_and_fetch_2:
1636   case Builtin::BI__sync_add_and_fetch_4:
1637   case Builtin::BI__sync_add_and_fetch_8:
1638   case Builtin::BI__sync_add_and_fetch_16:
1639   case Builtin::BI__sync_sub_and_fetch:
1640   case Builtin::BI__sync_sub_and_fetch_1:
1641   case Builtin::BI__sync_sub_and_fetch_2:
1642   case Builtin::BI__sync_sub_and_fetch_4:
1643   case Builtin::BI__sync_sub_and_fetch_8:
1644   case Builtin::BI__sync_sub_and_fetch_16:
1645   case Builtin::BI__sync_and_and_fetch:
1646   case Builtin::BI__sync_and_and_fetch_1:
1647   case Builtin::BI__sync_and_and_fetch_2:
1648   case Builtin::BI__sync_and_and_fetch_4:
1649   case Builtin::BI__sync_and_and_fetch_8:
1650   case Builtin::BI__sync_and_and_fetch_16:
1651   case Builtin::BI__sync_or_and_fetch:
1652   case Builtin::BI__sync_or_and_fetch_1:
1653   case Builtin::BI__sync_or_and_fetch_2:
1654   case Builtin::BI__sync_or_and_fetch_4:
1655   case Builtin::BI__sync_or_and_fetch_8:
1656   case Builtin::BI__sync_or_and_fetch_16:
1657   case Builtin::BI__sync_xor_and_fetch:
1658   case Builtin::BI__sync_xor_and_fetch_1:
1659   case Builtin::BI__sync_xor_and_fetch_2:
1660   case Builtin::BI__sync_xor_and_fetch_4:
1661   case Builtin::BI__sync_xor_and_fetch_8:
1662   case Builtin::BI__sync_xor_and_fetch_16:
1663   case Builtin::BI__sync_nand_and_fetch:
1664   case Builtin::BI__sync_nand_and_fetch_1:
1665   case Builtin::BI__sync_nand_and_fetch_2:
1666   case Builtin::BI__sync_nand_and_fetch_4:
1667   case Builtin::BI__sync_nand_and_fetch_8:
1668   case Builtin::BI__sync_nand_and_fetch_16:
1669   case Builtin::BI__sync_val_compare_and_swap:
1670   case Builtin::BI__sync_val_compare_and_swap_1:
1671   case Builtin::BI__sync_val_compare_and_swap_2:
1672   case Builtin::BI__sync_val_compare_and_swap_4:
1673   case Builtin::BI__sync_val_compare_and_swap_8:
1674   case Builtin::BI__sync_val_compare_and_swap_16:
1675   case Builtin::BI__sync_bool_compare_and_swap:
1676   case Builtin::BI__sync_bool_compare_and_swap_1:
1677   case Builtin::BI__sync_bool_compare_and_swap_2:
1678   case Builtin::BI__sync_bool_compare_and_swap_4:
1679   case Builtin::BI__sync_bool_compare_and_swap_8:
1680   case Builtin::BI__sync_bool_compare_and_swap_16:
1681   case Builtin::BI__sync_lock_test_and_set:
1682   case Builtin::BI__sync_lock_test_and_set_1:
1683   case Builtin::BI__sync_lock_test_and_set_2:
1684   case Builtin::BI__sync_lock_test_and_set_4:
1685   case Builtin::BI__sync_lock_test_and_set_8:
1686   case Builtin::BI__sync_lock_test_and_set_16:
1687   case Builtin::BI__sync_lock_release:
1688   case Builtin::BI__sync_lock_release_1:
1689   case Builtin::BI__sync_lock_release_2:
1690   case Builtin::BI__sync_lock_release_4:
1691   case Builtin::BI__sync_lock_release_8:
1692   case Builtin::BI__sync_lock_release_16:
1693   case Builtin::BI__sync_swap:
1694   case Builtin::BI__sync_swap_1:
1695   case Builtin::BI__sync_swap_2:
1696   case Builtin::BI__sync_swap_4:
1697   case Builtin::BI__sync_swap_8:
1698   case Builtin::BI__sync_swap_16:
1699     return SemaBuiltinAtomicOverloaded(TheCallResult);
1700   case Builtin::BI__sync_synchronize:
1701     Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1702         << TheCall->getCallee()->getSourceRange();
1703     break;
1704   case Builtin::BI__builtin_nontemporal_load:
1705   case Builtin::BI__builtin_nontemporal_store:
1706     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1707   case Builtin::BI__builtin_memcpy_inline: {
1708     clang::Expr *SizeOp = TheCall->getArg(2);
1709     // We warn about copying to or from `nullptr` pointers when `size` is
1710     // greater than 0. When `size` is value dependent we cannot evaluate its
1711     // value so we bail out.
1712     if (SizeOp->isValueDependent())
1713       break;
1714     if (!SizeOp->EvaluateKnownConstInt(Context).isNullValue()) {
1715       CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
1716       CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
1717     }
1718     break;
1719   }
1720 #define BUILTIN(ID, TYPE, ATTRS)
1721 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1722   case Builtin::BI##ID: \
1723     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1724 #include "clang/Basic/Builtins.def"
1725   case Builtin::BI__annotation:
1726     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1727       return ExprError();
1728     break;
1729   case Builtin::BI__builtin_annotation:
1730     if (SemaBuiltinAnnotation(*this, TheCall))
1731       return ExprError();
1732     break;
1733   case Builtin::BI__builtin_addressof:
1734     if (SemaBuiltinAddressof(*this, TheCall))
1735       return ExprError();
1736     break;
1737   case Builtin::BI__builtin_is_aligned:
1738   case Builtin::BI__builtin_align_up:
1739   case Builtin::BI__builtin_align_down:
1740     if (SemaBuiltinAlignment(*this, TheCall, BuiltinID))
1741       return ExprError();
1742     break;
1743   case Builtin::BI__builtin_add_overflow:
1744   case Builtin::BI__builtin_sub_overflow:
1745   case Builtin::BI__builtin_mul_overflow:
1746     if (SemaBuiltinOverflow(*this, TheCall, BuiltinID))
1747       return ExprError();
1748     break;
1749   case Builtin::BI__builtin_operator_new:
1750   case Builtin::BI__builtin_operator_delete: {
1751     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1752     ExprResult Res =
1753         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1754     if (Res.isInvalid())
1755       CorrectDelayedTyposInExpr(TheCallResult.get());
1756     return Res;
1757   }
1758   case Builtin::BI__builtin_dump_struct: {
1759     // We first want to ensure we are called with 2 arguments
1760     if (checkArgCount(*this, TheCall, 2))
1761       return ExprError();
1762     // Ensure that the first argument is of type 'struct XX *'
1763     const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1764     const QualType PtrArgType = PtrArg->getType();
1765     if (!PtrArgType->isPointerType() ||
1766         !PtrArgType->getPointeeType()->isRecordType()) {
1767       Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1768           << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1769           << "structure pointer";
1770       return ExprError();
1771     }
1772 
1773     // Ensure that the second argument is of type 'FunctionType'
1774     const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1775     const QualType FnPtrArgType = FnPtrArg->getType();
1776     if (!FnPtrArgType->isPointerType()) {
1777       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1778           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1779           << FnPtrArgType << "'int (*)(const char *, ...)'";
1780       return ExprError();
1781     }
1782 
1783     const auto *FuncType =
1784         FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1785 
1786     if (!FuncType) {
1787       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1788           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1789           << FnPtrArgType << "'int (*)(const char *, ...)'";
1790       return ExprError();
1791     }
1792 
1793     if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1794       if (!FT->getNumParams()) {
1795         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1796             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1797             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1798         return ExprError();
1799       }
1800       QualType PT = FT->getParamType(0);
1801       if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1802           !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1803           !PT->getPointeeType().isConstQualified()) {
1804         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1805             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1806             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1807         return ExprError();
1808       }
1809     }
1810 
1811     TheCall->setType(Context.IntTy);
1812     break;
1813   }
1814   case Builtin::BI__builtin_expect_with_probability: {
1815     // We first want to ensure we are called with 3 arguments
1816     if (checkArgCount(*this, TheCall, 3))
1817       return ExprError();
1818     // then check probability is constant float in range [0.0, 1.0]
1819     const Expr *ProbArg = TheCall->getArg(2);
1820     SmallVector<PartialDiagnosticAt, 8> Notes;
1821     Expr::EvalResult Eval;
1822     Eval.Diag = &Notes;
1823     if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
1824         !Eval.Val.isFloat()) {
1825       Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
1826           << ProbArg->getSourceRange();
1827       for (const PartialDiagnosticAt &PDiag : Notes)
1828         Diag(PDiag.first, PDiag.second);
1829       return ExprError();
1830     }
1831     llvm::APFloat Probability = Eval.Val.getFloat();
1832     bool LoseInfo = false;
1833     Probability.convert(llvm::APFloat::IEEEdouble(),
1834                         llvm::RoundingMode::Dynamic, &LoseInfo);
1835     if (!(Probability >= llvm::APFloat(0.0) &&
1836           Probability <= llvm::APFloat(1.0))) {
1837       Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
1838           << ProbArg->getSourceRange();
1839       return ExprError();
1840     }
1841     break;
1842   }
1843   case Builtin::BI__builtin_preserve_access_index:
1844     if (SemaBuiltinPreserveAI(*this, TheCall))
1845       return ExprError();
1846     break;
1847   case Builtin::BI__builtin_call_with_static_chain:
1848     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1849       return ExprError();
1850     break;
1851   case Builtin::BI__exception_code:
1852   case Builtin::BI_exception_code:
1853     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1854                                  diag::err_seh___except_block))
1855       return ExprError();
1856     break;
1857   case Builtin::BI__exception_info:
1858   case Builtin::BI_exception_info:
1859     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1860                                  diag::err_seh___except_filter))
1861       return ExprError();
1862     break;
1863   case Builtin::BI__GetExceptionInfo:
1864     if (checkArgCount(*this, TheCall, 1))
1865       return ExprError();
1866 
1867     if (CheckCXXThrowOperand(
1868             TheCall->getBeginLoc(),
1869             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1870             TheCall))
1871       return ExprError();
1872 
1873     TheCall->setType(Context.VoidPtrTy);
1874     break;
1875   // OpenCL v2.0, s6.13.16 - Pipe functions
1876   case Builtin::BIread_pipe:
1877   case Builtin::BIwrite_pipe:
1878     // Since those two functions are declared with var args, we need a semantic
1879     // check for the argument.
1880     if (SemaBuiltinRWPipe(*this, TheCall))
1881       return ExprError();
1882     break;
1883   case Builtin::BIreserve_read_pipe:
1884   case Builtin::BIreserve_write_pipe:
1885   case Builtin::BIwork_group_reserve_read_pipe:
1886   case Builtin::BIwork_group_reserve_write_pipe:
1887     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1888       return ExprError();
1889     break;
1890   case Builtin::BIsub_group_reserve_read_pipe:
1891   case Builtin::BIsub_group_reserve_write_pipe:
1892     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1893         SemaBuiltinReserveRWPipe(*this, TheCall))
1894       return ExprError();
1895     break;
1896   case Builtin::BIcommit_read_pipe:
1897   case Builtin::BIcommit_write_pipe:
1898   case Builtin::BIwork_group_commit_read_pipe:
1899   case Builtin::BIwork_group_commit_write_pipe:
1900     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1901       return ExprError();
1902     break;
1903   case Builtin::BIsub_group_commit_read_pipe:
1904   case Builtin::BIsub_group_commit_write_pipe:
1905     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1906         SemaBuiltinCommitRWPipe(*this, TheCall))
1907       return ExprError();
1908     break;
1909   case Builtin::BIget_pipe_num_packets:
1910   case Builtin::BIget_pipe_max_packets:
1911     if (SemaBuiltinPipePackets(*this, TheCall))
1912       return ExprError();
1913     break;
1914   case Builtin::BIto_global:
1915   case Builtin::BIto_local:
1916   case Builtin::BIto_private:
1917     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1918       return ExprError();
1919     break;
1920   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1921   case Builtin::BIenqueue_kernel:
1922     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1923       return ExprError();
1924     break;
1925   case Builtin::BIget_kernel_work_group_size:
1926   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1927     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1928       return ExprError();
1929     break;
1930   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1931   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1932     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1933       return ExprError();
1934     break;
1935   case Builtin::BI__builtin_os_log_format:
1936     Cleanup.setExprNeedsCleanups(true);
1937     LLVM_FALLTHROUGH;
1938   case Builtin::BI__builtin_os_log_format_buffer_size:
1939     if (SemaBuiltinOSLogFormat(TheCall))
1940       return ExprError();
1941     break;
1942   case Builtin::BI__builtin_frame_address:
1943   case Builtin::BI__builtin_return_address: {
1944     if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
1945       return ExprError();
1946 
1947     // -Wframe-address warning if non-zero passed to builtin
1948     // return/frame address.
1949     Expr::EvalResult Result;
1950     if (!TheCall->getArg(0)->isValueDependent() &&
1951         TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
1952         Result.Val.getInt() != 0)
1953       Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
1954           << ((BuiltinID == Builtin::BI__builtin_return_address)
1955                   ? "__builtin_return_address"
1956                   : "__builtin_frame_address")
1957           << TheCall->getSourceRange();
1958     break;
1959   }
1960 
1961   case Builtin::BI__builtin_matrix_transpose:
1962     return SemaBuiltinMatrixTranspose(TheCall, TheCallResult);
1963 
1964   case Builtin::BI__builtin_matrix_column_major_load:
1965     return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
1966 
1967   case Builtin::BI__builtin_matrix_column_major_store:
1968     return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
1969 
1970   case Builtin::BI__builtin_get_device_side_mangled_name: {
1971     auto Check = [](CallExpr *TheCall) {
1972       if (TheCall->getNumArgs() != 1)
1973         return false;
1974       auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());
1975       if (!DRE)
1976         return false;
1977       auto *D = DRE->getDecl();
1978       if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D))
1979         return false;
1980       return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
1981              D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
1982     };
1983     if (!Check(TheCall)) {
1984       Diag(TheCall->getBeginLoc(),
1985            diag::err_hip_invalid_args_builtin_mangled_name);
1986       return ExprError();
1987     }
1988   }
1989   }
1990 
1991   // Since the target specific builtins for each arch overlap, only check those
1992   // of the arch we are compiling for.
1993   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1994     if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
1995       assert(Context.getAuxTargetInfo() &&
1996              "Aux Target Builtin, but not an aux target?");
1997 
1998       if (CheckTSBuiltinFunctionCall(
1999               *Context.getAuxTargetInfo(),
2000               Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
2001         return ExprError();
2002     } else {
2003       if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
2004                                      TheCall))
2005         return ExprError();
2006     }
2007   }
2008 
2009   return TheCallResult;
2010 }
2011 
2012 // Get the valid immediate range for the specified NEON type code.
2013 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
2014   NeonTypeFlags Type(t);
2015   int IsQuad = ForceQuad ? true : Type.isQuad();
2016   switch (Type.getEltType()) {
2017   case NeonTypeFlags::Int8:
2018   case NeonTypeFlags::Poly8:
2019     return shift ? 7 : (8 << IsQuad) - 1;
2020   case NeonTypeFlags::Int16:
2021   case NeonTypeFlags::Poly16:
2022     return shift ? 15 : (4 << IsQuad) - 1;
2023   case NeonTypeFlags::Int32:
2024     return shift ? 31 : (2 << IsQuad) - 1;
2025   case NeonTypeFlags::Int64:
2026   case NeonTypeFlags::Poly64:
2027     return shift ? 63 : (1 << IsQuad) - 1;
2028   case NeonTypeFlags::Poly128:
2029     return shift ? 127 : (1 << IsQuad) - 1;
2030   case NeonTypeFlags::Float16:
2031     assert(!shift && "cannot shift float types!");
2032     return (4 << IsQuad) - 1;
2033   case NeonTypeFlags::Float32:
2034     assert(!shift && "cannot shift float types!");
2035     return (2 << IsQuad) - 1;
2036   case NeonTypeFlags::Float64:
2037     assert(!shift && "cannot shift float types!");
2038     return (1 << IsQuad) - 1;
2039   case NeonTypeFlags::BFloat16:
2040     assert(!shift && "cannot shift float types!");
2041     return (4 << IsQuad) - 1;
2042   }
2043   llvm_unreachable("Invalid NeonTypeFlag!");
2044 }
2045 
2046 /// getNeonEltType - Return the QualType corresponding to the elements of
2047 /// the vector type specified by the NeonTypeFlags.  This is used to check
2048 /// the pointer arguments for Neon load/store intrinsics.
2049 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
2050                                bool IsPolyUnsigned, bool IsInt64Long) {
2051   switch (Flags.getEltType()) {
2052   case NeonTypeFlags::Int8:
2053     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
2054   case NeonTypeFlags::Int16:
2055     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
2056   case NeonTypeFlags::Int32:
2057     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
2058   case NeonTypeFlags::Int64:
2059     if (IsInt64Long)
2060       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
2061     else
2062       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
2063                                 : Context.LongLongTy;
2064   case NeonTypeFlags::Poly8:
2065     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
2066   case NeonTypeFlags::Poly16:
2067     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
2068   case NeonTypeFlags::Poly64:
2069     if (IsInt64Long)
2070       return Context.UnsignedLongTy;
2071     else
2072       return Context.UnsignedLongLongTy;
2073   case NeonTypeFlags::Poly128:
2074     break;
2075   case NeonTypeFlags::Float16:
2076     return Context.HalfTy;
2077   case NeonTypeFlags::Float32:
2078     return Context.FloatTy;
2079   case NeonTypeFlags::Float64:
2080     return Context.DoubleTy;
2081   case NeonTypeFlags::BFloat16:
2082     return Context.BFloat16Ty;
2083   }
2084   llvm_unreachable("Invalid NeonTypeFlag!");
2085 }
2086 
2087 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2088   // Range check SVE intrinsics that take immediate values.
2089   SmallVector<std::tuple<int,int,int>, 3> ImmChecks;
2090 
2091   switch (BuiltinID) {
2092   default:
2093     return false;
2094 #define GET_SVE_IMMEDIATE_CHECK
2095 #include "clang/Basic/arm_sve_sema_rangechecks.inc"
2096 #undef GET_SVE_IMMEDIATE_CHECK
2097   }
2098 
2099   // Perform all the immediate checks for this builtin call.
2100   bool HasError = false;
2101   for (auto &I : ImmChecks) {
2102     int ArgNum, CheckTy, ElementSizeInBits;
2103     std::tie(ArgNum, CheckTy, ElementSizeInBits) = I;
2104 
2105     typedef bool(*OptionSetCheckFnTy)(int64_t Value);
2106 
2107     // Function that checks whether the operand (ArgNum) is an immediate
2108     // that is one of the predefined values.
2109     auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm,
2110                                    int ErrDiag) -> bool {
2111       // We can't check the value of a dependent argument.
2112       Expr *Arg = TheCall->getArg(ArgNum);
2113       if (Arg->isTypeDependent() || Arg->isValueDependent())
2114         return false;
2115 
2116       // Check constant-ness first.
2117       llvm::APSInt Imm;
2118       if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm))
2119         return true;
2120 
2121       if (!CheckImm(Imm.getSExtValue()))
2122         return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange();
2123       return false;
2124     };
2125 
2126     switch ((SVETypeFlags::ImmCheckType)CheckTy) {
2127     case SVETypeFlags::ImmCheck0_31:
2128       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31))
2129         HasError = true;
2130       break;
2131     case SVETypeFlags::ImmCheck0_13:
2132       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13))
2133         HasError = true;
2134       break;
2135     case SVETypeFlags::ImmCheck1_16:
2136       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16))
2137         HasError = true;
2138       break;
2139     case SVETypeFlags::ImmCheck0_7:
2140       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7))
2141         HasError = true;
2142       break;
2143     case SVETypeFlags::ImmCheckExtract:
2144       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2145                                       (2048 / ElementSizeInBits) - 1))
2146         HasError = true;
2147       break;
2148     case SVETypeFlags::ImmCheckShiftRight:
2149       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits))
2150         HasError = true;
2151       break;
2152     case SVETypeFlags::ImmCheckShiftRightNarrow:
2153       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1,
2154                                       ElementSizeInBits / 2))
2155         HasError = true;
2156       break;
2157     case SVETypeFlags::ImmCheckShiftLeft:
2158       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2159                                       ElementSizeInBits - 1))
2160         HasError = true;
2161       break;
2162     case SVETypeFlags::ImmCheckLaneIndex:
2163       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2164                                       (128 / (1 * ElementSizeInBits)) - 1))
2165         HasError = true;
2166       break;
2167     case SVETypeFlags::ImmCheckLaneIndexCompRotate:
2168       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2169                                       (128 / (2 * ElementSizeInBits)) - 1))
2170         HasError = true;
2171       break;
2172     case SVETypeFlags::ImmCheckLaneIndexDot:
2173       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2174                                       (128 / (4 * ElementSizeInBits)) - 1))
2175         HasError = true;
2176       break;
2177     case SVETypeFlags::ImmCheckComplexRot90_270:
2178       if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; },
2179                               diag::err_rotation_argument_to_cadd))
2180         HasError = true;
2181       break;
2182     case SVETypeFlags::ImmCheckComplexRotAll90:
2183       if (CheckImmediateInSet(
2184               [](int64_t V) {
2185                 return V == 0 || V == 90 || V == 180 || V == 270;
2186               },
2187               diag::err_rotation_argument_to_cmla))
2188         HasError = true;
2189       break;
2190     case SVETypeFlags::ImmCheck0_1:
2191       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1))
2192         HasError = true;
2193       break;
2194     case SVETypeFlags::ImmCheck0_2:
2195       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2))
2196         HasError = true;
2197       break;
2198     case SVETypeFlags::ImmCheck0_3:
2199       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3))
2200         HasError = true;
2201       break;
2202     }
2203   }
2204 
2205   return HasError;
2206 }
2207 
2208 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI,
2209                                         unsigned BuiltinID, CallExpr *TheCall) {
2210   llvm::APSInt Result;
2211   uint64_t mask = 0;
2212   unsigned TV = 0;
2213   int PtrArgNum = -1;
2214   bool HasConstPtr = false;
2215   switch (BuiltinID) {
2216 #define GET_NEON_OVERLOAD_CHECK
2217 #include "clang/Basic/arm_neon.inc"
2218 #include "clang/Basic/arm_fp16.inc"
2219 #undef GET_NEON_OVERLOAD_CHECK
2220   }
2221 
2222   // For NEON intrinsics which are overloaded on vector element type, validate
2223   // the immediate which specifies which variant to emit.
2224   unsigned ImmArg = TheCall->getNumArgs()-1;
2225   if (mask) {
2226     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
2227       return true;
2228 
2229     TV = Result.getLimitedValue(64);
2230     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
2231       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
2232              << TheCall->getArg(ImmArg)->getSourceRange();
2233   }
2234 
2235   if (PtrArgNum >= 0) {
2236     // Check that pointer arguments have the specified type.
2237     Expr *Arg = TheCall->getArg(PtrArgNum);
2238     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
2239       Arg = ICE->getSubExpr();
2240     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
2241     QualType RHSTy = RHS.get()->getType();
2242 
2243     llvm::Triple::ArchType Arch = TI.getTriple().getArch();
2244     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
2245                           Arch == llvm::Triple::aarch64_32 ||
2246                           Arch == llvm::Triple::aarch64_be;
2247     bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong;
2248     QualType EltTy =
2249         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
2250     if (HasConstPtr)
2251       EltTy = EltTy.withConst();
2252     QualType LHSTy = Context.getPointerType(EltTy);
2253     AssignConvertType ConvTy;
2254     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
2255     if (RHS.isInvalid())
2256       return true;
2257     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
2258                                  RHS.get(), AA_Assigning))
2259       return true;
2260   }
2261 
2262   // For NEON intrinsics which take an immediate value as part of the
2263   // instruction, range check them here.
2264   unsigned i = 0, l = 0, u = 0;
2265   switch (BuiltinID) {
2266   default:
2267     return false;
2268   #define GET_NEON_IMMEDIATE_CHECK
2269   #include "clang/Basic/arm_neon.inc"
2270   #include "clang/Basic/arm_fp16.inc"
2271   #undef GET_NEON_IMMEDIATE_CHECK
2272   }
2273 
2274   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2275 }
2276 
2277 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2278   switch (BuiltinID) {
2279   default:
2280     return false;
2281   #include "clang/Basic/arm_mve_builtin_sema.inc"
2282   }
2283 }
2284 
2285 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2286                                        CallExpr *TheCall) {
2287   bool Err = false;
2288   switch (BuiltinID) {
2289   default:
2290     return false;
2291 #include "clang/Basic/arm_cde_builtin_sema.inc"
2292   }
2293 
2294   if (Err)
2295     return true;
2296 
2297   return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true);
2298 }
2299 
2300 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI,
2301                                         const Expr *CoprocArg, bool WantCDE) {
2302   if (isConstantEvaluated())
2303     return false;
2304 
2305   // We can't check the value of a dependent argument.
2306   if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent())
2307     return false;
2308 
2309   llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context);
2310   int64_t CoprocNo = CoprocNoAP.getExtValue();
2311   assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative");
2312 
2313   uint32_t CDECoprocMask = TI.getARMCDECoprocMask();
2314   bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo));
2315 
2316   if (IsCDECoproc != WantCDE)
2317     return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc)
2318            << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange();
2319 
2320   return false;
2321 }
2322 
2323 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
2324                                         unsigned MaxWidth) {
2325   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
2326           BuiltinID == ARM::BI__builtin_arm_ldaex ||
2327           BuiltinID == ARM::BI__builtin_arm_strex ||
2328           BuiltinID == ARM::BI__builtin_arm_stlex ||
2329           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2330           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2331           BuiltinID == AArch64::BI__builtin_arm_strex ||
2332           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
2333          "unexpected ARM builtin");
2334   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
2335                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
2336                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2337                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
2338 
2339   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2340 
2341   // Ensure that we have the proper number of arguments.
2342   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
2343     return true;
2344 
2345   // Inspect the pointer argument of the atomic builtin.  This should always be
2346   // a pointer type, whose element is an integral scalar or pointer type.
2347   // Because it is a pointer type, we don't have to worry about any implicit
2348   // casts here.
2349   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
2350   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
2351   if (PointerArgRes.isInvalid())
2352     return true;
2353   PointerArg = PointerArgRes.get();
2354 
2355   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2356   if (!pointerType) {
2357     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
2358         << PointerArg->getType() << PointerArg->getSourceRange();
2359     return true;
2360   }
2361 
2362   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
2363   // task is to insert the appropriate casts into the AST. First work out just
2364   // what the appropriate type is.
2365   QualType ValType = pointerType->getPointeeType();
2366   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
2367   if (IsLdrex)
2368     AddrType.addConst();
2369 
2370   // Issue a warning if the cast is dodgy.
2371   CastKind CastNeeded = CK_NoOp;
2372   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
2373     CastNeeded = CK_BitCast;
2374     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
2375         << PointerArg->getType() << Context.getPointerType(AddrType)
2376         << AA_Passing << PointerArg->getSourceRange();
2377   }
2378 
2379   // Finally, do the cast and replace the argument with the corrected version.
2380   AddrType = Context.getPointerType(AddrType);
2381   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
2382   if (PointerArgRes.isInvalid())
2383     return true;
2384   PointerArg = PointerArgRes.get();
2385 
2386   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
2387 
2388   // In general, we allow ints, floats and pointers to be loaded and stored.
2389   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2390       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
2391     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
2392         << PointerArg->getType() << PointerArg->getSourceRange();
2393     return true;
2394   }
2395 
2396   // But ARM doesn't have instructions to deal with 128-bit versions.
2397   if (Context.getTypeSize(ValType) > MaxWidth) {
2398     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
2399     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
2400         << PointerArg->getType() << PointerArg->getSourceRange();
2401     return true;
2402   }
2403 
2404   switch (ValType.getObjCLifetime()) {
2405   case Qualifiers::OCL_None:
2406   case Qualifiers::OCL_ExplicitNone:
2407     // okay
2408     break;
2409 
2410   case Qualifiers::OCL_Weak:
2411   case Qualifiers::OCL_Strong:
2412   case Qualifiers::OCL_Autoreleasing:
2413     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
2414         << ValType << PointerArg->getSourceRange();
2415     return true;
2416   }
2417 
2418   if (IsLdrex) {
2419     TheCall->setType(ValType);
2420     return false;
2421   }
2422 
2423   // Initialize the argument to be stored.
2424   ExprResult ValArg = TheCall->getArg(0);
2425   InitializedEntity Entity = InitializedEntity::InitializeParameter(
2426       Context, ValType, /*consume*/ false);
2427   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2428   if (ValArg.isInvalid())
2429     return true;
2430   TheCall->setArg(0, ValArg.get());
2431 
2432   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
2433   // but the custom checker bypasses all default analysis.
2434   TheCall->setType(Context.IntTy);
2435   return false;
2436 }
2437 
2438 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2439                                        CallExpr *TheCall) {
2440   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
2441       BuiltinID == ARM::BI__builtin_arm_ldaex ||
2442       BuiltinID == ARM::BI__builtin_arm_strex ||
2443       BuiltinID == ARM::BI__builtin_arm_stlex) {
2444     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
2445   }
2446 
2447   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
2448     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2449       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
2450   }
2451 
2452   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2453       BuiltinID == ARM::BI__builtin_arm_wsr64)
2454     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
2455 
2456   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
2457       BuiltinID == ARM::BI__builtin_arm_rsrp ||
2458       BuiltinID == ARM::BI__builtin_arm_wsr ||
2459       BuiltinID == ARM::BI__builtin_arm_wsrp)
2460     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2461 
2462   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2463     return true;
2464   if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
2465     return true;
2466   if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall))
2467     return true;
2468 
2469   // For intrinsics which take an immediate value as part of the instruction,
2470   // range check them here.
2471   // FIXME: VFP Intrinsics should error if VFP not present.
2472   switch (BuiltinID) {
2473   default: return false;
2474   case ARM::BI__builtin_arm_ssat:
2475     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
2476   case ARM::BI__builtin_arm_usat:
2477     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
2478   case ARM::BI__builtin_arm_ssat16:
2479     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
2480   case ARM::BI__builtin_arm_usat16:
2481     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2482   case ARM::BI__builtin_arm_vcvtr_f:
2483   case ARM::BI__builtin_arm_vcvtr_d:
2484     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
2485   case ARM::BI__builtin_arm_dmb:
2486   case ARM::BI__builtin_arm_dsb:
2487   case ARM::BI__builtin_arm_isb:
2488   case ARM::BI__builtin_arm_dbg:
2489     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
2490   case ARM::BI__builtin_arm_cdp:
2491   case ARM::BI__builtin_arm_cdp2:
2492   case ARM::BI__builtin_arm_mcr:
2493   case ARM::BI__builtin_arm_mcr2:
2494   case ARM::BI__builtin_arm_mrc:
2495   case ARM::BI__builtin_arm_mrc2:
2496   case ARM::BI__builtin_arm_mcrr:
2497   case ARM::BI__builtin_arm_mcrr2:
2498   case ARM::BI__builtin_arm_mrrc:
2499   case ARM::BI__builtin_arm_mrrc2:
2500   case ARM::BI__builtin_arm_ldc:
2501   case ARM::BI__builtin_arm_ldcl:
2502   case ARM::BI__builtin_arm_ldc2:
2503   case ARM::BI__builtin_arm_ldc2l:
2504   case ARM::BI__builtin_arm_stc:
2505   case ARM::BI__builtin_arm_stcl:
2506   case ARM::BI__builtin_arm_stc2:
2507   case ARM::BI__builtin_arm_stc2l:
2508     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) ||
2509            CheckARMCoprocessorImmediate(TI, TheCall->getArg(0),
2510                                         /*WantCDE*/ false);
2511   }
2512 }
2513 
2514 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI,
2515                                            unsigned BuiltinID,
2516                                            CallExpr *TheCall) {
2517   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2518       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2519       BuiltinID == AArch64::BI__builtin_arm_strex ||
2520       BuiltinID == AArch64::BI__builtin_arm_stlex) {
2521     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
2522   }
2523 
2524   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
2525     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2526       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
2527       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
2528       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
2529   }
2530 
2531   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2532       BuiltinID == AArch64::BI__builtin_arm_wsr64)
2533     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2534 
2535   // Memory Tagging Extensions (MTE) Intrinsics
2536   if (BuiltinID == AArch64::BI__builtin_arm_irg ||
2537       BuiltinID == AArch64::BI__builtin_arm_addg ||
2538       BuiltinID == AArch64::BI__builtin_arm_gmi ||
2539       BuiltinID == AArch64::BI__builtin_arm_ldg ||
2540       BuiltinID == AArch64::BI__builtin_arm_stg ||
2541       BuiltinID == AArch64::BI__builtin_arm_subp) {
2542     return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
2543   }
2544 
2545   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
2546       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2547       BuiltinID == AArch64::BI__builtin_arm_wsr ||
2548       BuiltinID == AArch64::BI__builtin_arm_wsrp)
2549     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2550 
2551   // Only check the valid encoding range. Any constant in this range would be
2552   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
2553   // an exception for incorrect registers. This matches MSVC behavior.
2554   if (BuiltinID == AArch64::BI_ReadStatusReg ||
2555       BuiltinID == AArch64::BI_WriteStatusReg)
2556     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
2557 
2558   if (BuiltinID == AArch64::BI__getReg)
2559     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
2560 
2561   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2562     return true;
2563 
2564   if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall))
2565     return true;
2566 
2567   // For intrinsics which take an immediate value as part of the instruction,
2568   // range check them here.
2569   unsigned i = 0, l = 0, u = 0;
2570   switch (BuiltinID) {
2571   default: return false;
2572   case AArch64::BI__builtin_arm_dmb:
2573   case AArch64::BI__builtin_arm_dsb:
2574   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
2575   case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
2576   }
2577 
2578   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2579 }
2580 
2581 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) {
2582   if (Arg->getType()->getAsPlaceholderType())
2583     return false;
2584 
2585   // The first argument needs to be a record field access.
2586   // If it is an array element access, we delay decision
2587   // to BPF backend to check whether the access is a
2588   // field access or not.
2589   return (Arg->IgnoreParens()->getObjectKind() == OK_BitField ||
2590           dyn_cast<MemberExpr>(Arg->IgnoreParens()) ||
2591           dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens()));
2592 }
2593 
2594 static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S,
2595                             QualType VectorTy, QualType EltTy) {
2596   QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType();
2597   if (!Context.hasSameType(VectorEltTy, EltTy)) {
2598     S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types)
2599         << Call->getSourceRange() << VectorEltTy << EltTy;
2600     return false;
2601   }
2602   return true;
2603 }
2604 
2605 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) {
2606   QualType ArgType = Arg->getType();
2607   if (ArgType->getAsPlaceholderType())
2608     return false;
2609 
2610   // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type
2611   // format:
2612   //   1. __builtin_preserve_type_info(*(<type> *)0, flag);
2613   //   2. <type> var;
2614   //      __builtin_preserve_type_info(var, flag);
2615   if (!dyn_cast<DeclRefExpr>(Arg->IgnoreParens()) &&
2616       !dyn_cast<UnaryOperator>(Arg->IgnoreParens()))
2617     return false;
2618 
2619   // Typedef type.
2620   if (ArgType->getAs<TypedefType>())
2621     return true;
2622 
2623   // Record type or Enum type.
2624   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2625   if (const auto *RT = Ty->getAs<RecordType>()) {
2626     if (!RT->getDecl()->getDeclName().isEmpty())
2627       return true;
2628   } else if (const auto *ET = Ty->getAs<EnumType>()) {
2629     if (!ET->getDecl()->getDeclName().isEmpty())
2630       return true;
2631   }
2632 
2633   return false;
2634 }
2635 
2636 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) {
2637   QualType ArgType = Arg->getType();
2638   if (ArgType->getAsPlaceholderType())
2639     return false;
2640 
2641   // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type
2642   // format:
2643   //   __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>,
2644   //                                 flag);
2645   const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens());
2646   if (!UO)
2647     return false;
2648 
2649   const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr());
2650   if (!CE)
2651     return false;
2652   if (CE->getCastKind() != CK_IntegralToPointer &&
2653       CE->getCastKind() != CK_NullToPointer)
2654     return false;
2655 
2656   // The integer must be from an EnumConstantDecl.
2657   const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr());
2658   if (!DR)
2659     return false;
2660 
2661   const EnumConstantDecl *Enumerator =
2662       dyn_cast<EnumConstantDecl>(DR->getDecl());
2663   if (!Enumerator)
2664     return false;
2665 
2666   // The type must be EnumType.
2667   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2668   const auto *ET = Ty->getAs<EnumType>();
2669   if (!ET)
2670     return false;
2671 
2672   // The enum value must be supported.
2673   for (auto *EDI : ET->getDecl()->enumerators()) {
2674     if (EDI == Enumerator)
2675       return true;
2676   }
2677 
2678   return false;
2679 }
2680 
2681 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
2682                                        CallExpr *TheCall) {
2683   assert((BuiltinID == BPF::BI__builtin_preserve_field_info ||
2684           BuiltinID == BPF::BI__builtin_btf_type_id ||
2685           BuiltinID == BPF::BI__builtin_preserve_type_info ||
2686           BuiltinID == BPF::BI__builtin_preserve_enum_value) &&
2687          "unexpected BPF builtin");
2688 
2689   if (checkArgCount(*this, TheCall, 2))
2690     return true;
2691 
2692   // The second argument needs to be a constant int
2693   Expr *Arg = TheCall->getArg(1);
2694   Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context);
2695   diag::kind kind;
2696   if (!Value) {
2697     if (BuiltinID == BPF::BI__builtin_preserve_field_info)
2698       kind = diag::err_preserve_field_info_not_const;
2699     else if (BuiltinID == BPF::BI__builtin_btf_type_id)
2700       kind = diag::err_btf_type_id_not_const;
2701     else if (BuiltinID == BPF::BI__builtin_preserve_type_info)
2702       kind = diag::err_preserve_type_info_not_const;
2703     else
2704       kind = diag::err_preserve_enum_value_not_const;
2705     Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange();
2706     return true;
2707   }
2708 
2709   // The first argument
2710   Arg = TheCall->getArg(0);
2711   bool InvalidArg = false;
2712   bool ReturnUnsignedInt = true;
2713   if (BuiltinID == BPF::BI__builtin_preserve_field_info) {
2714     if (!isValidBPFPreserveFieldInfoArg(Arg)) {
2715       InvalidArg = true;
2716       kind = diag::err_preserve_field_info_not_field;
2717     }
2718   } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) {
2719     if (!isValidBPFPreserveTypeInfoArg(Arg)) {
2720       InvalidArg = true;
2721       kind = diag::err_preserve_type_info_invalid;
2722     }
2723   } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) {
2724     if (!isValidBPFPreserveEnumValueArg(Arg)) {
2725       InvalidArg = true;
2726       kind = diag::err_preserve_enum_value_invalid;
2727     }
2728     ReturnUnsignedInt = false;
2729   } else if (BuiltinID == BPF::BI__builtin_btf_type_id) {
2730     ReturnUnsignedInt = false;
2731   }
2732 
2733   if (InvalidArg) {
2734     Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange();
2735     return true;
2736   }
2737 
2738   if (ReturnUnsignedInt)
2739     TheCall->setType(Context.UnsignedIntTy);
2740   else
2741     TheCall->setType(Context.UnsignedLongTy);
2742   return false;
2743 }
2744 
2745 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2746   struct ArgInfo {
2747     uint8_t OpNum;
2748     bool IsSigned;
2749     uint8_t BitWidth;
2750     uint8_t Align;
2751   };
2752   struct BuiltinInfo {
2753     unsigned BuiltinID;
2754     ArgInfo Infos[2];
2755   };
2756 
2757   static BuiltinInfo Infos[] = {
2758     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
2759     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
2760     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
2761     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  1 }} },
2762     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
2763     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
2764     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
2765     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
2766     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
2767     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
2768     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
2769 
2770     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
2771     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
2772     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
2773     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
2774     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
2775     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
2776     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
2777     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
2778     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
2779     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
2780     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
2781 
2782     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
2783     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
2784     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
2785     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
2786     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
2787     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
2788     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
2789     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
2790     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
2791     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
2792     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
2793     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
2794     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
2795     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
2796     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
2797     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
2798     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
2799     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
2800     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
2801     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
2802     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
2803     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
2804     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
2805     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
2806     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
2807     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
2808     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
2809     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
2810     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
2811     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
2812     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
2813     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
2814     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
2815     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
2816     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
2817     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
2818     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
2819     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
2820     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
2821     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
2822     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
2823     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
2824     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
2825     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
2826     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
2827     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
2828     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
2829     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
2830     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
2831     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
2832     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
2833     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
2834                                                       {{ 1, false, 6,  0 }} },
2835     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
2836     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
2837     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
2838     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
2839     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
2840     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
2841     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
2842                                                       {{ 1, false, 5,  0 }} },
2843     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
2844     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
2845     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
2846     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
2847     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
2848     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
2849                                                        { 2, false, 5,  0 }} },
2850     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
2851                                                        { 2, false, 6,  0 }} },
2852     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
2853                                                        { 3, false, 5,  0 }} },
2854     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
2855                                                        { 3, false, 6,  0 }} },
2856     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
2857     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
2858     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
2859     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
2860     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
2861     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
2862     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
2863     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
2864     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
2865     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
2866     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
2867     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
2868     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
2869     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
2870     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
2871     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
2872                                                       {{ 2, false, 4,  0 },
2873                                                        { 3, false, 5,  0 }} },
2874     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
2875                                                       {{ 2, false, 4,  0 },
2876                                                        { 3, false, 5,  0 }} },
2877     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
2878                                                       {{ 2, false, 4,  0 },
2879                                                        { 3, false, 5,  0 }} },
2880     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
2881                                                       {{ 2, false, 4,  0 },
2882                                                        { 3, false, 5,  0 }} },
2883     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
2884     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
2885     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
2886     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
2887     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
2888     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
2889     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
2890     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
2891     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
2892     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
2893     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
2894                                                        { 2, false, 5,  0 }} },
2895     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
2896                                                        { 2, false, 6,  0 }} },
2897     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
2898     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
2899     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
2900     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
2901     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
2902     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
2903     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
2904     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
2905     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
2906                                                       {{ 1, false, 4,  0 }} },
2907     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
2908     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
2909                                                       {{ 1, false, 4,  0 }} },
2910     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
2911     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
2912     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
2913     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
2914     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
2915     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
2916     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
2917     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
2918     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
2919     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
2920     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
2921     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
2922     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
2923     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
2924     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
2925     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
2926     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
2927     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
2928     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
2929     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
2930                                                       {{ 3, false, 1,  0 }} },
2931     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
2932     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
2933     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
2934     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
2935                                                       {{ 3, false, 1,  0 }} },
2936     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
2937     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
2938     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
2939     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
2940                                                       {{ 3, false, 1,  0 }} },
2941   };
2942 
2943   // Use a dynamically initialized static to sort the table exactly once on
2944   // first run.
2945   static const bool SortOnce =
2946       (llvm::sort(Infos,
2947                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
2948                    return LHS.BuiltinID < RHS.BuiltinID;
2949                  }),
2950        true);
2951   (void)SortOnce;
2952 
2953   const BuiltinInfo *F = llvm::partition_point(
2954       Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
2955   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
2956     return false;
2957 
2958   bool Error = false;
2959 
2960   for (const ArgInfo &A : F->Infos) {
2961     // Ignore empty ArgInfo elements.
2962     if (A.BitWidth == 0)
2963       continue;
2964 
2965     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
2966     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
2967     if (!A.Align) {
2968       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
2969     } else {
2970       unsigned M = 1 << A.Align;
2971       Min *= M;
2972       Max *= M;
2973       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
2974                SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
2975     }
2976   }
2977   return Error;
2978 }
2979 
2980 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
2981                                            CallExpr *TheCall) {
2982   return CheckHexagonBuiltinArgument(BuiltinID, TheCall);
2983 }
2984 
2985 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI,
2986                                         unsigned BuiltinID, CallExpr *TheCall) {
2987   return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) ||
2988          CheckMipsBuiltinArgument(BuiltinID, TheCall);
2989 }
2990 
2991 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
2992                                CallExpr *TheCall) {
2993 
2994   if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
2995       BuiltinID <= Mips::BI__builtin_mips_lwx) {
2996     if (!TI.hasFeature("dsp"))
2997       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
2998   }
2999 
3000   if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
3001       BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
3002     if (!TI.hasFeature("dspr2"))
3003       return Diag(TheCall->getBeginLoc(),
3004                   diag::err_mips_builtin_requires_dspr2);
3005   }
3006 
3007   if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
3008       BuiltinID <= Mips::BI__builtin_msa_xori_b) {
3009     if (!TI.hasFeature("msa"))
3010       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
3011   }
3012 
3013   return false;
3014 }
3015 
3016 // CheckMipsBuiltinArgument - Checks the constant value passed to the
3017 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
3018 // ordering for DSP is unspecified. MSA is ordered by the data format used
3019 // by the underlying instruction i.e., df/m, df/n and then by size.
3020 //
3021 // FIXME: The size tests here should instead be tablegen'd along with the
3022 //        definitions from include/clang/Basic/BuiltinsMips.def.
3023 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
3024 //        be too.
3025 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
3026   unsigned i = 0, l = 0, u = 0, m = 0;
3027   switch (BuiltinID) {
3028   default: return false;
3029   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
3030   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
3031   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
3032   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
3033   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
3034   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
3035   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
3036   // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
3037   // df/m field.
3038   // These intrinsics take an unsigned 3 bit immediate.
3039   case Mips::BI__builtin_msa_bclri_b:
3040   case Mips::BI__builtin_msa_bnegi_b:
3041   case Mips::BI__builtin_msa_bseti_b:
3042   case Mips::BI__builtin_msa_sat_s_b:
3043   case Mips::BI__builtin_msa_sat_u_b:
3044   case Mips::BI__builtin_msa_slli_b:
3045   case Mips::BI__builtin_msa_srai_b:
3046   case Mips::BI__builtin_msa_srari_b:
3047   case Mips::BI__builtin_msa_srli_b:
3048   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
3049   case Mips::BI__builtin_msa_binsli_b:
3050   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
3051   // These intrinsics take an unsigned 4 bit immediate.
3052   case Mips::BI__builtin_msa_bclri_h:
3053   case Mips::BI__builtin_msa_bnegi_h:
3054   case Mips::BI__builtin_msa_bseti_h:
3055   case Mips::BI__builtin_msa_sat_s_h:
3056   case Mips::BI__builtin_msa_sat_u_h:
3057   case Mips::BI__builtin_msa_slli_h:
3058   case Mips::BI__builtin_msa_srai_h:
3059   case Mips::BI__builtin_msa_srari_h:
3060   case Mips::BI__builtin_msa_srli_h:
3061   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
3062   case Mips::BI__builtin_msa_binsli_h:
3063   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
3064   // These intrinsics take an unsigned 5 bit immediate.
3065   // The first block of intrinsics actually have an unsigned 5 bit field,
3066   // not a df/n field.
3067   case Mips::BI__builtin_msa_cfcmsa:
3068   case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
3069   case Mips::BI__builtin_msa_clei_u_b:
3070   case Mips::BI__builtin_msa_clei_u_h:
3071   case Mips::BI__builtin_msa_clei_u_w:
3072   case Mips::BI__builtin_msa_clei_u_d:
3073   case Mips::BI__builtin_msa_clti_u_b:
3074   case Mips::BI__builtin_msa_clti_u_h:
3075   case Mips::BI__builtin_msa_clti_u_w:
3076   case Mips::BI__builtin_msa_clti_u_d:
3077   case Mips::BI__builtin_msa_maxi_u_b:
3078   case Mips::BI__builtin_msa_maxi_u_h:
3079   case Mips::BI__builtin_msa_maxi_u_w:
3080   case Mips::BI__builtin_msa_maxi_u_d:
3081   case Mips::BI__builtin_msa_mini_u_b:
3082   case Mips::BI__builtin_msa_mini_u_h:
3083   case Mips::BI__builtin_msa_mini_u_w:
3084   case Mips::BI__builtin_msa_mini_u_d:
3085   case Mips::BI__builtin_msa_addvi_b:
3086   case Mips::BI__builtin_msa_addvi_h:
3087   case Mips::BI__builtin_msa_addvi_w:
3088   case Mips::BI__builtin_msa_addvi_d:
3089   case Mips::BI__builtin_msa_bclri_w:
3090   case Mips::BI__builtin_msa_bnegi_w:
3091   case Mips::BI__builtin_msa_bseti_w:
3092   case Mips::BI__builtin_msa_sat_s_w:
3093   case Mips::BI__builtin_msa_sat_u_w:
3094   case Mips::BI__builtin_msa_slli_w:
3095   case Mips::BI__builtin_msa_srai_w:
3096   case Mips::BI__builtin_msa_srari_w:
3097   case Mips::BI__builtin_msa_srli_w:
3098   case Mips::BI__builtin_msa_srlri_w:
3099   case Mips::BI__builtin_msa_subvi_b:
3100   case Mips::BI__builtin_msa_subvi_h:
3101   case Mips::BI__builtin_msa_subvi_w:
3102   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
3103   case Mips::BI__builtin_msa_binsli_w:
3104   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
3105   // These intrinsics take an unsigned 6 bit immediate.
3106   case Mips::BI__builtin_msa_bclri_d:
3107   case Mips::BI__builtin_msa_bnegi_d:
3108   case Mips::BI__builtin_msa_bseti_d:
3109   case Mips::BI__builtin_msa_sat_s_d:
3110   case Mips::BI__builtin_msa_sat_u_d:
3111   case Mips::BI__builtin_msa_slli_d:
3112   case Mips::BI__builtin_msa_srai_d:
3113   case Mips::BI__builtin_msa_srari_d:
3114   case Mips::BI__builtin_msa_srli_d:
3115   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
3116   case Mips::BI__builtin_msa_binsli_d:
3117   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
3118   // These intrinsics take a signed 5 bit immediate.
3119   case Mips::BI__builtin_msa_ceqi_b:
3120   case Mips::BI__builtin_msa_ceqi_h:
3121   case Mips::BI__builtin_msa_ceqi_w:
3122   case Mips::BI__builtin_msa_ceqi_d:
3123   case Mips::BI__builtin_msa_clti_s_b:
3124   case Mips::BI__builtin_msa_clti_s_h:
3125   case Mips::BI__builtin_msa_clti_s_w:
3126   case Mips::BI__builtin_msa_clti_s_d:
3127   case Mips::BI__builtin_msa_clei_s_b:
3128   case Mips::BI__builtin_msa_clei_s_h:
3129   case Mips::BI__builtin_msa_clei_s_w:
3130   case Mips::BI__builtin_msa_clei_s_d:
3131   case Mips::BI__builtin_msa_maxi_s_b:
3132   case Mips::BI__builtin_msa_maxi_s_h:
3133   case Mips::BI__builtin_msa_maxi_s_w:
3134   case Mips::BI__builtin_msa_maxi_s_d:
3135   case Mips::BI__builtin_msa_mini_s_b:
3136   case Mips::BI__builtin_msa_mini_s_h:
3137   case Mips::BI__builtin_msa_mini_s_w:
3138   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
3139   // These intrinsics take an unsigned 8 bit immediate.
3140   case Mips::BI__builtin_msa_andi_b:
3141   case Mips::BI__builtin_msa_nori_b:
3142   case Mips::BI__builtin_msa_ori_b:
3143   case Mips::BI__builtin_msa_shf_b:
3144   case Mips::BI__builtin_msa_shf_h:
3145   case Mips::BI__builtin_msa_shf_w:
3146   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
3147   case Mips::BI__builtin_msa_bseli_b:
3148   case Mips::BI__builtin_msa_bmnzi_b:
3149   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
3150   // df/n format
3151   // These intrinsics take an unsigned 4 bit immediate.
3152   case Mips::BI__builtin_msa_copy_s_b:
3153   case Mips::BI__builtin_msa_copy_u_b:
3154   case Mips::BI__builtin_msa_insve_b:
3155   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
3156   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
3157   // These intrinsics take an unsigned 3 bit immediate.
3158   case Mips::BI__builtin_msa_copy_s_h:
3159   case Mips::BI__builtin_msa_copy_u_h:
3160   case Mips::BI__builtin_msa_insve_h:
3161   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
3162   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3163   // These intrinsics take an unsigned 2 bit immediate.
3164   case Mips::BI__builtin_msa_copy_s_w:
3165   case Mips::BI__builtin_msa_copy_u_w:
3166   case Mips::BI__builtin_msa_insve_w:
3167   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
3168   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3169   // These intrinsics take an unsigned 1 bit immediate.
3170   case Mips::BI__builtin_msa_copy_s_d:
3171   case Mips::BI__builtin_msa_copy_u_d:
3172   case Mips::BI__builtin_msa_insve_d:
3173   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
3174   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3175   // Memory offsets and immediate loads.
3176   // These intrinsics take a signed 10 bit immediate.
3177   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
3178   case Mips::BI__builtin_msa_ldi_h:
3179   case Mips::BI__builtin_msa_ldi_w:
3180   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
3181   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3182   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3183   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3184   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3185   case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break;
3186   case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break;
3187   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3188   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3189   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3190   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
3191   case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break;
3192   case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break;
3193   }
3194 
3195   if (!m)
3196     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3197 
3198   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3199          SemaBuiltinConstantArgMultiple(TheCall, i, m);
3200 }
3201 
3202 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str,
3203 /// advancing the pointer over the consumed characters. The decoded type is
3204 /// returned. If the decoded type represents a constant integer with a
3205 /// constraint on its value then Mask is set to that value. The type descriptors
3206 /// used in Str are specific to PPC MMA builtins and are documented in the file
3207 /// defining the PPC builtins.
3208 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str,
3209                                         unsigned &Mask) {
3210   bool RequireICE = false;
3211   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3212   switch (*Str++) {
3213   case 'V':
3214     return Context.getVectorType(Context.UnsignedCharTy, 16,
3215                                  VectorType::VectorKind::AltiVecVector);
3216   case 'i': {
3217     char *End;
3218     unsigned size = strtoul(Str, &End, 10);
3219     assert(End != Str && "Missing constant parameter constraint");
3220     Str = End;
3221     Mask = size;
3222     return Context.IntTy;
3223   }
3224   case 'W': {
3225     char *End;
3226     unsigned size = strtoul(Str, &End, 10);
3227     assert(End != Str && "Missing PowerPC MMA type size");
3228     Str = End;
3229     QualType Type;
3230     switch (size) {
3231   #define PPC_VECTOR_TYPE(typeName, Id, size) \
3232     case size: Type = Context.Id##Ty; break;
3233   #include "clang/Basic/PPCTypes.def"
3234     default: llvm_unreachable("Invalid PowerPC MMA vector type");
3235     }
3236     bool CheckVectorArgs = false;
3237     while (!CheckVectorArgs) {
3238       switch (*Str++) {
3239       case '*':
3240         Type = Context.getPointerType(Type);
3241         break;
3242       case 'C':
3243         Type = Type.withConst();
3244         break;
3245       default:
3246         CheckVectorArgs = true;
3247         --Str;
3248         break;
3249       }
3250     }
3251     return Type;
3252   }
3253   default:
3254     return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true);
3255   }
3256 }
3257 
3258 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3259                                        CallExpr *TheCall) {
3260   unsigned i = 0, l = 0, u = 0;
3261   bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
3262                       BuiltinID == PPC::BI__builtin_divdeu ||
3263                       BuiltinID == PPC::BI__builtin_bpermd;
3264   bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64;
3265   bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
3266                        BuiltinID == PPC::BI__builtin_divweu ||
3267                        BuiltinID == PPC::BI__builtin_divde ||
3268                        BuiltinID == PPC::BI__builtin_divdeu;
3269 
3270   if (Is64BitBltin && !IsTarget64Bit)
3271     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3272            << TheCall->getSourceRange();
3273 
3274   if ((IsBltinExtDiv && !TI.hasFeature("extdiv")) ||
3275       (BuiltinID == PPC::BI__builtin_bpermd && !TI.hasFeature("bpermd")))
3276     return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3277            << TheCall->getSourceRange();
3278 
3279   auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool {
3280     if (!TI.hasFeature("vsx"))
3281       return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3282              << TheCall->getSourceRange();
3283     return false;
3284   };
3285 
3286   switch (BuiltinID) {
3287   default: return false;
3288   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3289   case PPC::BI__builtin_altivec_crypto_vshasigmad:
3290     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3291            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3292   case PPC::BI__builtin_altivec_dss:
3293     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
3294   case PPC::BI__builtin_tbegin:
3295   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
3296   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
3297   case PPC::BI__builtin_tabortwc:
3298   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
3299   case PPC::BI__builtin_tabortwci:
3300   case PPC::BI__builtin_tabortdci:
3301     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3302            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
3303   case PPC::BI__builtin_altivec_dst:
3304   case PPC::BI__builtin_altivec_dstt:
3305   case PPC::BI__builtin_altivec_dstst:
3306   case PPC::BI__builtin_altivec_dststt:
3307     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
3308   case PPC::BI__builtin_vsx_xxpermdi:
3309   case PPC::BI__builtin_vsx_xxsldwi:
3310     return SemaBuiltinVSX(TheCall);
3311   case PPC::BI__builtin_unpack_vector_int128:
3312     return SemaVSXCheck(TheCall) ||
3313            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3314   case PPC::BI__builtin_pack_vector_int128:
3315     return SemaVSXCheck(TheCall);
3316   case PPC::BI__builtin_altivec_vgnb:
3317      return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7);
3318   case PPC::BI__builtin_altivec_vec_replace_elt:
3319   case PPC::BI__builtin_altivec_vec_replace_unaligned: {
3320     QualType VecTy = TheCall->getArg(0)->getType();
3321     QualType EltTy = TheCall->getArg(1)->getType();
3322     unsigned Width = Context.getIntWidth(EltTy);
3323     return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) ||
3324            !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy);
3325   }
3326   case PPC::BI__builtin_vsx_xxeval:
3327      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255);
3328   case PPC::BI__builtin_altivec_vsldbi:
3329      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3330   case PPC::BI__builtin_altivec_vsrdbi:
3331      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3332   case PPC::BI__builtin_vsx_xxpermx:
3333      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7);
3334 #define CUSTOM_BUILTIN(Name, Intr, Types, Acc) \
3335   case PPC::BI__builtin_##Name: \
3336     return SemaBuiltinPPCMMACall(TheCall, Types);
3337 #include "clang/Basic/BuiltinsPPC.def"
3338   }
3339   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3340 }
3341 
3342 // Check if the given type is a non-pointer PPC MMA type. This function is used
3343 // in Sema to prevent invalid uses of restricted PPC MMA types.
3344 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) {
3345   if (Type->isPointerType() || Type->isArrayType())
3346     return false;
3347 
3348   QualType CoreType = Type.getCanonicalType().getUnqualifiedType();
3349 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty
3350   if (false
3351 #include "clang/Basic/PPCTypes.def"
3352      ) {
3353     Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type);
3354     return true;
3355   }
3356   return false;
3357 }
3358 
3359 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID,
3360                                           CallExpr *TheCall) {
3361   // position of memory order and scope arguments in the builtin
3362   unsigned OrderIndex, ScopeIndex;
3363   switch (BuiltinID) {
3364   case AMDGPU::BI__builtin_amdgcn_atomic_inc32:
3365   case AMDGPU::BI__builtin_amdgcn_atomic_inc64:
3366   case AMDGPU::BI__builtin_amdgcn_atomic_dec32:
3367   case AMDGPU::BI__builtin_amdgcn_atomic_dec64:
3368     OrderIndex = 2;
3369     ScopeIndex = 3;
3370     break;
3371   case AMDGPU::BI__builtin_amdgcn_fence:
3372     OrderIndex = 0;
3373     ScopeIndex = 1;
3374     break;
3375   default:
3376     return false;
3377   }
3378 
3379   ExprResult Arg = TheCall->getArg(OrderIndex);
3380   auto ArgExpr = Arg.get();
3381   Expr::EvalResult ArgResult;
3382 
3383   if (!ArgExpr->EvaluateAsInt(ArgResult, Context))
3384     return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int)
3385            << ArgExpr->getType();
3386   auto Ord = ArgResult.Val.getInt().getZExtValue();
3387 
3388   // Check valididty of memory ordering as per C11 / C++11's memody model.
3389   // Only fence needs check. Atomic dec/inc allow all memory orders.
3390   if (!llvm::isValidAtomicOrderingCABI(Ord))
3391     return Diag(ArgExpr->getBeginLoc(),
3392                 diag::warn_atomic_op_has_invalid_memory_order)
3393            << ArgExpr->getSourceRange();
3394   switch (static_cast<llvm::AtomicOrderingCABI>(Ord)) {
3395   case llvm::AtomicOrderingCABI::relaxed:
3396   case llvm::AtomicOrderingCABI::consume:
3397     if (BuiltinID == AMDGPU::BI__builtin_amdgcn_fence)
3398       return Diag(ArgExpr->getBeginLoc(),
3399                   diag::warn_atomic_op_has_invalid_memory_order)
3400              << ArgExpr->getSourceRange();
3401     break;
3402   case llvm::AtomicOrderingCABI::acquire:
3403   case llvm::AtomicOrderingCABI::release:
3404   case llvm::AtomicOrderingCABI::acq_rel:
3405   case llvm::AtomicOrderingCABI::seq_cst:
3406     break;
3407   }
3408 
3409   Arg = TheCall->getArg(ScopeIndex);
3410   ArgExpr = Arg.get();
3411   Expr::EvalResult ArgResult1;
3412   // Check that sync scope is a constant literal
3413   if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context))
3414     return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal)
3415            << ArgExpr->getType();
3416 
3417   return false;
3418 }
3419 
3420 bool Sema::CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum) {
3421   llvm::APSInt Result;
3422 
3423   // We can't check the value of a dependent argument.
3424   Expr *Arg = TheCall->getArg(ArgNum);
3425   if (Arg->isTypeDependent() || Arg->isValueDependent())
3426     return false;
3427 
3428   // Check constant-ness first.
3429   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3430     return true;
3431 
3432   int64_t Val = Result.getSExtValue();
3433   if ((Val >= 0 && Val <= 3) || (Val >= 5 && Val <= 7))
3434     return false;
3435 
3436   return Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_invalid_lmul)
3437          << Arg->getSourceRange();
3438 }
3439 
3440 bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI,
3441                                          unsigned BuiltinID,
3442                                          CallExpr *TheCall) {
3443   // CodeGenFunction can also detect this, but this gives a better error
3444   // message.
3445   bool FeatureMissing = false;
3446   SmallVector<StringRef> ReqFeatures;
3447   StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID);
3448   Features.split(ReqFeatures, ',');
3449 
3450   // Check if each required feature is included
3451   for (StringRef F : ReqFeatures) {
3452     if (TI.hasFeature(F))
3453       continue;
3454 
3455     // If the feature is 64bit, alter the string so it will print better in
3456     // the diagnostic.
3457     if (F == "64bit")
3458       F = "RV64";
3459 
3460     // Convert features like "zbr" and "experimental-zbr" to "Zbr".
3461     F.consume_front("experimental-");
3462     std::string FeatureStr = F.str();
3463     FeatureStr[0] = std::toupper(FeatureStr[0]);
3464 
3465     // Error message
3466     FeatureMissing = true;
3467     Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_requires_extension)
3468         << TheCall->getSourceRange() << StringRef(FeatureStr);
3469   }
3470 
3471   if (FeatureMissing)
3472     return true;
3473 
3474   switch (BuiltinID) {
3475   case RISCV::BI__builtin_rvv_vsetvli:
3476     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3) ||
3477            CheckRISCVLMUL(TheCall, 2);
3478   case RISCV::BI__builtin_rvv_vsetvlimax:
3479     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3) ||
3480            CheckRISCVLMUL(TheCall, 1);
3481   }
3482 
3483   return false;
3484 }
3485 
3486 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3487                                            CallExpr *TheCall) {
3488   if (BuiltinID == SystemZ::BI__builtin_tabort) {
3489     Expr *Arg = TheCall->getArg(0);
3490     if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context))
3491       if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256)
3492         return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
3493                << Arg->getSourceRange();
3494   }
3495 
3496   // For intrinsics which take an immediate value as part of the instruction,
3497   // range check them here.
3498   unsigned i = 0, l = 0, u = 0;
3499   switch (BuiltinID) {
3500   default: return false;
3501   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3502   case SystemZ::BI__builtin_s390_verimb:
3503   case SystemZ::BI__builtin_s390_verimh:
3504   case SystemZ::BI__builtin_s390_verimf:
3505   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
3506   case SystemZ::BI__builtin_s390_vfaeb:
3507   case SystemZ::BI__builtin_s390_vfaeh:
3508   case SystemZ::BI__builtin_s390_vfaef:
3509   case SystemZ::BI__builtin_s390_vfaebs:
3510   case SystemZ::BI__builtin_s390_vfaehs:
3511   case SystemZ::BI__builtin_s390_vfaefs:
3512   case SystemZ::BI__builtin_s390_vfaezb:
3513   case SystemZ::BI__builtin_s390_vfaezh:
3514   case SystemZ::BI__builtin_s390_vfaezf:
3515   case SystemZ::BI__builtin_s390_vfaezbs:
3516   case SystemZ::BI__builtin_s390_vfaezhs:
3517   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
3518   case SystemZ::BI__builtin_s390_vfisb:
3519   case SystemZ::BI__builtin_s390_vfidb:
3520     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3521            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3522   case SystemZ::BI__builtin_s390_vftcisb:
3523   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3524   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3525   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3526   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3527   case SystemZ::BI__builtin_s390_vstrcb:
3528   case SystemZ::BI__builtin_s390_vstrch:
3529   case SystemZ::BI__builtin_s390_vstrcf:
3530   case SystemZ::BI__builtin_s390_vstrczb:
3531   case SystemZ::BI__builtin_s390_vstrczh:
3532   case SystemZ::BI__builtin_s390_vstrczf:
3533   case SystemZ::BI__builtin_s390_vstrcbs:
3534   case SystemZ::BI__builtin_s390_vstrchs:
3535   case SystemZ::BI__builtin_s390_vstrcfs:
3536   case SystemZ::BI__builtin_s390_vstrczbs:
3537   case SystemZ::BI__builtin_s390_vstrczhs:
3538   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
3539   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3540   case SystemZ::BI__builtin_s390_vfminsb:
3541   case SystemZ::BI__builtin_s390_vfmaxsb:
3542   case SystemZ::BI__builtin_s390_vfmindb:
3543   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
3544   case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
3545   case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
3546   }
3547   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3548 }
3549 
3550 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3551 /// This checks that the target supports __builtin_cpu_supports and
3552 /// that the string argument is constant and valid.
3553 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI,
3554                                    CallExpr *TheCall) {
3555   Expr *Arg = TheCall->getArg(0);
3556 
3557   // Check if the argument is a string literal.
3558   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3559     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3560            << Arg->getSourceRange();
3561 
3562   // Check the contents of the string.
3563   StringRef Feature =
3564       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3565   if (!TI.validateCpuSupports(Feature))
3566     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
3567            << Arg->getSourceRange();
3568   return false;
3569 }
3570 
3571 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3572 /// This checks that the target supports __builtin_cpu_is and
3573 /// that the string argument is constant and valid.
3574 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) {
3575   Expr *Arg = TheCall->getArg(0);
3576 
3577   // Check if the argument is a string literal.
3578   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3579     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3580            << Arg->getSourceRange();
3581 
3582   // Check the contents of the string.
3583   StringRef Feature =
3584       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3585   if (!TI.validateCpuIs(Feature))
3586     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
3587            << Arg->getSourceRange();
3588   return false;
3589 }
3590 
3591 // Check if the rounding mode is legal.
3592 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3593   // Indicates if this instruction has rounding control or just SAE.
3594   bool HasRC = false;
3595 
3596   unsigned ArgNum = 0;
3597   switch (BuiltinID) {
3598   default:
3599     return false;
3600   case X86::BI__builtin_ia32_vcvttsd2si32:
3601   case X86::BI__builtin_ia32_vcvttsd2si64:
3602   case X86::BI__builtin_ia32_vcvttsd2usi32:
3603   case X86::BI__builtin_ia32_vcvttsd2usi64:
3604   case X86::BI__builtin_ia32_vcvttss2si32:
3605   case X86::BI__builtin_ia32_vcvttss2si64:
3606   case X86::BI__builtin_ia32_vcvttss2usi32:
3607   case X86::BI__builtin_ia32_vcvttss2usi64:
3608     ArgNum = 1;
3609     break;
3610   case X86::BI__builtin_ia32_maxpd512:
3611   case X86::BI__builtin_ia32_maxps512:
3612   case X86::BI__builtin_ia32_minpd512:
3613   case X86::BI__builtin_ia32_minps512:
3614     ArgNum = 2;
3615     break;
3616   case X86::BI__builtin_ia32_cvtps2pd512_mask:
3617   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
3618   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
3619   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
3620   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
3621   case X86::BI__builtin_ia32_cvttps2dq512_mask:
3622   case X86::BI__builtin_ia32_cvttps2qq512_mask:
3623   case X86::BI__builtin_ia32_cvttps2udq512_mask:
3624   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
3625   case X86::BI__builtin_ia32_exp2pd_mask:
3626   case X86::BI__builtin_ia32_exp2ps_mask:
3627   case X86::BI__builtin_ia32_getexppd512_mask:
3628   case X86::BI__builtin_ia32_getexpps512_mask:
3629   case X86::BI__builtin_ia32_rcp28pd_mask:
3630   case X86::BI__builtin_ia32_rcp28ps_mask:
3631   case X86::BI__builtin_ia32_rsqrt28pd_mask:
3632   case X86::BI__builtin_ia32_rsqrt28ps_mask:
3633   case X86::BI__builtin_ia32_vcomisd:
3634   case X86::BI__builtin_ia32_vcomiss:
3635   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
3636     ArgNum = 3;
3637     break;
3638   case X86::BI__builtin_ia32_cmppd512_mask:
3639   case X86::BI__builtin_ia32_cmpps512_mask:
3640   case X86::BI__builtin_ia32_cmpsd_mask:
3641   case X86::BI__builtin_ia32_cmpss_mask:
3642   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
3643   case X86::BI__builtin_ia32_getexpsd128_round_mask:
3644   case X86::BI__builtin_ia32_getexpss128_round_mask:
3645   case X86::BI__builtin_ia32_getmantpd512_mask:
3646   case X86::BI__builtin_ia32_getmantps512_mask:
3647   case X86::BI__builtin_ia32_maxsd_round_mask:
3648   case X86::BI__builtin_ia32_maxss_round_mask:
3649   case X86::BI__builtin_ia32_minsd_round_mask:
3650   case X86::BI__builtin_ia32_minss_round_mask:
3651   case X86::BI__builtin_ia32_rcp28sd_round_mask:
3652   case X86::BI__builtin_ia32_rcp28ss_round_mask:
3653   case X86::BI__builtin_ia32_reducepd512_mask:
3654   case X86::BI__builtin_ia32_reduceps512_mask:
3655   case X86::BI__builtin_ia32_rndscalepd_mask:
3656   case X86::BI__builtin_ia32_rndscaleps_mask:
3657   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
3658   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
3659     ArgNum = 4;
3660     break;
3661   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3662   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3663   case X86::BI__builtin_ia32_fixupimmps512_mask:
3664   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3665   case X86::BI__builtin_ia32_fixupimmsd_mask:
3666   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3667   case X86::BI__builtin_ia32_fixupimmss_mask:
3668   case X86::BI__builtin_ia32_fixupimmss_maskz:
3669   case X86::BI__builtin_ia32_getmantsd_round_mask:
3670   case X86::BI__builtin_ia32_getmantss_round_mask:
3671   case X86::BI__builtin_ia32_rangepd512_mask:
3672   case X86::BI__builtin_ia32_rangeps512_mask:
3673   case X86::BI__builtin_ia32_rangesd128_round_mask:
3674   case X86::BI__builtin_ia32_rangess128_round_mask:
3675   case X86::BI__builtin_ia32_reducesd_mask:
3676   case X86::BI__builtin_ia32_reducess_mask:
3677   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3678   case X86::BI__builtin_ia32_rndscaless_round_mask:
3679     ArgNum = 5;
3680     break;
3681   case X86::BI__builtin_ia32_vcvtsd2si64:
3682   case X86::BI__builtin_ia32_vcvtsd2si32:
3683   case X86::BI__builtin_ia32_vcvtsd2usi32:
3684   case X86::BI__builtin_ia32_vcvtsd2usi64:
3685   case X86::BI__builtin_ia32_vcvtss2si32:
3686   case X86::BI__builtin_ia32_vcvtss2si64:
3687   case X86::BI__builtin_ia32_vcvtss2usi32:
3688   case X86::BI__builtin_ia32_vcvtss2usi64:
3689   case X86::BI__builtin_ia32_sqrtpd512:
3690   case X86::BI__builtin_ia32_sqrtps512:
3691     ArgNum = 1;
3692     HasRC = true;
3693     break;
3694   case X86::BI__builtin_ia32_addpd512:
3695   case X86::BI__builtin_ia32_addps512:
3696   case X86::BI__builtin_ia32_divpd512:
3697   case X86::BI__builtin_ia32_divps512:
3698   case X86::BI__builtin_ia32_mulpd512:
3699   case X86::BI__builtin_ia32_mulps512:
3700   case X86::BI__builtin_ia32_subpd512:
3701   case X86::BI__builtin_ia32_subps512:
3702   case X86::BI__builtin_ia32_cvtsi2sd64:
3703   case X86::BI__builtin_ia32_cvtsi2ss32:
3704   case X86::BI__builtin_ia32_cvtsi2ss64:
3705   case X86::BI__builtin_ia32_cvtusi2sd64:
3706   case X86::BI__builtin_ia32_cvtusi2ss32:
3707   case X86::BI__builtin_ia32_cvtusi2ss64:
3708     ArgNum = 2;
3709     HasRC = true;
3710     break;
3711   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
3712   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
3713   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
3714   case X86::BI__builtin_ia32_cvtpd2dq512_mask:
3715   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
3716   case X86::BI__builtin_ia32_cvtpd2udq512_mask:
3717   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
3718   case X86::BI__builtin_ia32_cvtps2dq512_mask:
3719   case X86::BI__builtin_ia32_cvtps2qq512_mask:
3720   case X86::BI__builtin_ia32_cvtps2udq512_mask:
3721   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
3722   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
3723   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
3724   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
3725   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
3726     ArgNum = 3;
3727     HasRC = true;
3728     break;
3729   case X86::BI__builtin_ia32_addss_round_mask:
3730   case X86::BI__builtin_ia32_addsd_round_mask:
3731   case X86::BI__builtin_ia32_divss_round_mask:
3732   case X86::BI__builtin_ia32_divsd_round_mask:
3733   case X86::BI__builtin_ia32_mulss_round_mask:
3734   case X86::BI__builtin_ia32_mulsd_round_mask:
3735   case X86::BI__builtin_ia32_subss_round_mask:
3736   case X86::BI__builtin_ia32_subsd_round_mask:
3737   case X86::BI__builtin_ia32_scalefpd512_mask:
3738   case X86::BI__builtin_ia32_scalefps512_mask:
3739   case X86::BI__builtin_ia32_scalefsd_round_mask:
3740   case X86::BI__builtin_ia32_scalefss_round_mask:
3741   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
3742   case X86::BI__builtin_ia32_sqrtsd_round_mask:
3743   case X86::BI__builtin_ia32_sqrtss_round_mask:
3744   case X86::BI__builtin_ia32_vfmaddsd3_mask:
3745   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
3746   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
3747   case X86::BI__builtin_ia32_vfmaddss3_mask:
3748   case X86::BI__builtin_ia32_vfmaddss3_maskz:
3749   case X86::BI__builtin_ia32_vfmaddss3_mask3:
3750   case X86::BI__builtin_ia32_vfmaddpd512_mask:
3751   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
3752   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
3753   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
3754   case X86::BI__builtin_ia32_vfmaddps512_mask:
3755   case X86::BI__builtin_ia32_vfmaddps512_maskz:
3756   case X86::BI__builtin_ia32_vfmaddps512_mask3:
3757   case X86::BI__builtin_ia32_vfmsubps512_mask3:
3758   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
3759   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
3760   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
3761   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
3762   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
3763   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
3764   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
3765   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
3766     ArgNum = 4;
3767     HasRC = true;
3768     break;
3769   }
3770 
3771   llvm::APSInt Result;
3772 
3773   // We can't check the value of a dependent argument.
3774   Expr *Arg = TheCall->getArg(ArgNum);
3775   if (Arg->isTypeDependent() || Arg->isValueDependent())
3776     return false;
3777 
3778   // Check constant-ness first.
3779   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3780     return true;
3781 
3782   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
3783   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
3784   // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
3785   // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
3786   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
3787       Result == 8/*ROUND_NO_EXC*/ ||
3788       (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
3789       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
3790     return false;
3791 
3792   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
3793          << Arg->getSourceRange();
3794 }
3795 
3796 // Check if the gather/scatter scale is legal.
3797 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
3798                                              CallExpr *TheCall) {
3799   unsigned ArgNum = 0;
3800   switch (BuiltinID) {
3801   default:
3802     return false;
3803   case X86::BI__builtin_ia32_gatherpfdpd:
3804   case X86::BI__builtin_ia32_gatherpfdps:
3805   case X86::BI__builtin_ia32_gatherpfqpd:
3806   case X86::BI__builtin_ia32_gatherpfqps:
3807   case X86::BI__builtin_ia32_scatterpfdpd:
3808   case X86::BI__builtin_ia32_scatterpfdps:
3809   case X86::BI__builtin_ia32_scatterpfqpd:
3810   case X86::BI__builtin_ia32_scatterpfqps:
3811     ArgNum = 3;
3812     break;
3813   case X86::BI__builtin_ia32_gatherd_pd:
3814   case X86::BI__builtin_ia32_gatherd_pd256:
3815   case X86::BI__builtin_ia32_gatherq_pd:
3816   case X86::BI__builtin_ia32_gatherq_pd256:
3817   case X86::BI__builtin_ia32_gatherd_ps:
3818   case X86::BI__builtin_ia32_gatherd_ps256:
3819   case X86::BI__builtin_ia32_gatherq_ps:
3820   case X86::BI__builtin_ia32_gatherq_ps256:
3821   case X86::BI__builtin_ia32_gatherd_q:
3822   case X86::BI__builtin_ia32_gatherd_q256:
3823   case X86::BI__builtin_ia32_gatherq_q:
3824   case X86::BI__builtin_ia32_gatherq_q256:
3825   case X86::BI__builtin_ia32_gatherd_d:
3826   case X86::BI__builtin_ia32_gatherd_d256:
3827   case X86::BI__builtin_ia32_gatherq_d:
3828   case X86::BI__builtin_ia32_gatherq_d256:
3829   case X86::BI__builtin_ia32_gather3div2df:
3830   case X86::BI__builtin_ia32_gather3div2di:
3831   case X86::BI__builtin_ia32_gather3div4df:
3832   case X86::BI__builtin_ia32_gather3div4di:
3833   case X86::BI__builtin_ia32_gather3div4sf:
3834   case X86::BI__builtin_ia32_gather3div4si:
3835   case X86::BI__builtin_ia32_gather3div8sf:
3836   case X86::BI__builtin_ia32_gather3div8si:
3837   case X86::BI__builtin_ia32_gather3siv2df:
3838   case X86::BI__builtin_ia32_gather3siv2di:
3839   case X86::BI__builtin_ia32_gather3siv4df:
3840   case X86::BI__builtin_ia32_gather3siv4di:
3841   case X86::BI__builtin_ia32_gather3siv4sf:
3842   case X86::BI__builtin_ia32_gather3siv4si:
3843   case X86::BI__builtin_ia32_gather3siv8sf:
3844   case X86::BI__builtin_ia32_gather3siv8si:
3845   case X86::BI__builtin_ia32_gathersiv8df:
3846   case X86::BI__builtin_ia32_gathersiv16sf:
3847   case X86::BI__builtin_ia32_gatherdiv8df:
3848   case X86::BI__builtin_ia32_gatherdiv16sf:
3849   case X86::BI__builtin_ia32_gathersiv8di:
3850   case X86::BI__builtin_ia32_gathersiv16si:
3851   case X86::BI__builtin_ia32_gatherdiv8di:
3852   case X86::BI__builtin_ia32_gatherdiv16si:
3853   case X86::BI__builtin_ia32_scatterdiv2df:
3854   case X86::BI__builtin_ia32_scatterdiv2di:
3855   case X86::BI__builtin_ia32_scatterdiv4df:
3856   case X86::BI__builtin_ia32_scatterdiv4di:
3857   case X86::BI__builtin_ia32_scatterdiv4sf:
3858   case X86::BI__builtin_ia32_scatterdiv4si:
3859   case X86::BI__builtin_ia32_scatterdiv8sf:
3860   case X86::BI__builtin_ia32_scatterdiv8si:
3861   case X86::BI__builtin_ia32_scattersiv2df:
3862   case X86::BI__builtin_ia32_scattersiv2di:
3863   case X86::BI__builtin_ia32_scattersiv4df:
3864   case X86::BI__builtin_ia32_scattersiv4di:
3865   case X86::BI__builtin_ia32_scattersiv4sf:
3866   case X86::BI__builtin_ia32_scattersiv4si:
3867   case X86::BI__builtin_ia32_scattersiv8sf:
3868   case X86::BI__builtin_ia32_scattersiv8si:
3869   case X86::BI__builtin_ia32_scattersiv8df:
3870   case X86::BI__builtin_ia32_scattersiv16sf:
3871   case X86::BI__builtin_ia32_scatterdiv8df:
3872   case X86::BI__builtin_ia32_scatterdiv16sf:
3873   case X86::BI__builtin_ia32_scattersiv8di:
3874   case X86::BI__builtin_ia32_scattersiv16si:
3875   case X86::BI__builtin_ia32_scatterdiv8di:
3876   case X86::BI__builtin_ia32_scatterdiv16si:
3877     ArgNum = 4;
3878     break;
3879   }
3880 
3881   llvm::APSInt Result;
3882 
3883   // We can't check the value of a dependent argument.
3884   Expr *Arg = TheCall->getArg(ArgNum);
3885   if (Arg->isTypeDependent() || Arg->isValueDependent())
3886     return false;
3887 
3888   // Check constant-ness first.
3889   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3890     return true;
3891 
3892   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
3893     return false;
3894 
3895   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
3896          << Arg->getSourceRange();
3897 }
3898 
3899 enum { TileRegLow = 0, TileRegHigh = 7 };
3900 
3901 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
3902                                              ArrayRef<int> ArgNums) {
3903   for (int ArgNum : ArgNums) {
3904     if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh))
3905       return true;
3906   }
3907   return false;
3908 }
3909 
3910 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall,
3911                                         ArrayRef<int> ArgNums) {
3912   // Because the max number of tile register is TileRegHigh + 1, so here we use
3913   // each bit to represent the usage of them in bitset.
3914   std::bitset<TileRegHigh + 1> ArgValues;
3915   for (int ArgNum : ArgNums) {
3916     Expr *Arg = TheCall->getArg(ArgNum);
3917     if (Arg->isTypeDependent() || Arg->isValueDependent())
3918       continue;
3919 
3920     llvm::APSInt Result;
3921     if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3922       return true;
3923     int ArgExtValue = Result.getExtValue();
3924     assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) &&
3925            "Incorrect tile register num.");
3926     if (ArgValues.test(ArgExtValue))
3927       return Diag(TheCall->getBeginLoc(),
3928                   diag::err_x86_builtin_tile_arg_duplicate)
3929              << TheCall->getArg(ArgNum)->getSourceRange();
3930     ArgValues.set(ArgExtValue);
3931   }
3932   return false;
3933 }
3934 
3935 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
3936                                                 ArrayRef<int> ArgNums) {
3937   return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) ||
3938          CheckX86BuiltinTileDuplicate(TheCall, ArgNums);
3939 }
3940 
3941 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) {
3942   switch (BuiltinID) {
3943   default:
3944     return false;
3945   case X86::BI__builtin_ia32_tileloadd64:
3946   case X86::BI__builtin_ia32_tileloaddt164:
3947   case X86::BI__builtin_ia32_tilestored64:
3948   case X86::BI__builtin_ia32_tilezero:
3949     return CheckX86BuiltinTileArgumentsRange(TheCall, 0);
3950   case X86::BI__builtin_ia32_tdpbssd:
3951   case X86::BI__builtin_ia32_tdpbsud:
3952   case X86::BI__builtin_ia32_tdpbusd:
3953   case X86::BI__builtin_ia32_tdpbuud:
3954   case X86::BI__builtin_ia32_tdpbf16ps:
3955     return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2});
3956   }
3957 }
3958 static bool isX86_32Builtin(unsigned BuiltinID) {
3959   // These builtins only work on x86-32 targets.
3960   switch (BuiltinID) {
3961   case X86::BI__builtin_ia32_readeflags_u32:
3962   case X86::BI__builtin_ia32_writeeflags_u32:
3963     return true;
3964   }
3965 
3966   return false;
3967 }
3968 
3969 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3970                                        CallExpr *TheCall) {
3971   if (BuiltinID == X86::BI__builtin_cpu_supports)
3972     return SemaBuiltinCpuSupports(*this, TI, TheCall);
3973 
3974   if (BuiltinID == X86::BI__builtin_cpu_is)
3975     return SemaBuiltinCpuIs(*this, TI, TheCall);
3976 
3977   // Check for 32-bit only builtins on a 64-bit target.
3978   const llvm::Triple &TT = TI.getTriple();
3979   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
3980     return Diag(TheCall->getCallee()->getBeginLoc(),
3981                 diag::err_32_bit_builtin_64_bit_tgt);
3982 
3983   // If the intrinsic has rounding or SAE make sure its valid.
3984   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
3985     return true;
3986 
3987   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
3988   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
3989     return true;
3990 
3991   // If the intrinsic has a tile arguments, make sure they are valid.
3992   if (CheckX86BuiltinTileArguments(BuiltinID, TheCall))
3993     return true;
3994 
3995   // For intrinsics which take an immediate value as part of the instruction,
3996   // range check them here.
3997   int i = 0, l = 0, u = 0;
3998   switch (BuiltinID) {
3999   default:
4000     return false;
4001   case X86::BI__builtin_ia32_vec_ext_v2si:
4002   case X86::BI__builtin_ia32_vec_ext_v2di:
4003   case X86::BI__builtin_ia32_vextractf128_pd256:
4004   case X86::BI__builtin_ia32_vextractf128_ps256:
4005   case X86::BI__builtin_ia32_vextractf128_si256:
4006   case X86::BI__builtin_ia32_extract128i256:
4007   case X86::BI__builtin_ia32_extractf64x4_mask:
4008   case X86::BI__builtin_ia32_extracti64x4_mask:
4009   case X86::BI__builtin_ia32_extractf32x8_mask:
4010   case X86::BI__builtin_ia32_extracti32x8_mask:
4011   case X86::BI__builtin_ia32_extractf64x2_256_mask:
4012   case X86::BI__builtin_ia32_extracti64x2_256_mask:
4013   case X86::BI__builtin_ia32_extractf32x4_256_mask:
4014   case X86::BI__builtin_ia32_extracti32x4_256_mask:
4015     i = 1; l = 0; u = 1;
4016     break;
4017   case X86::BI__builtin_ia32_vec_set_v2di:
4018   case X86::BI__builtin_ia32_vinsertf128_pd256:
4019   case X86::BI__builtin_ia32_vinsertf128_ps256:
4020   case X86::BI__builtin_ia32_vinsertf128_si256:
4021   case X86::BI__builtin_ia32_insert128i256:
4022   case X86::BI__builtin_ia32_insertf32x8:
4023   case X86::BI__builtin_ia32_inserti32x8:
4024   case X86::BI__builtin_ia32_insertf64x4:
4025   case X86::BI__builtin_ia32_inserti64x4:
4026   case X86::BI__builtin_ia32_insertf64x2_256:
4027   case X86::BI__builtin_ia32_inserti64x2_256:
4028   case X86::BI__builtin_ia32_insertf32x4_256:
4029   case X86::BI__builtin_ia32_inserti32x4_256:
4030     i = 2; l = 0; u = 1;
4031     break;
4032   case X86::BI__builtin_ia32_vpermilpd:
4033   case X86::BI__builtin_ia32_vec_ext_v4hi:
4034   case X86::BI__builtin_ia32_vec_ext_v4si:
4035   case X86::BI__builtin_ia32_vec_ext_v4sf:
4036   case X86::BI__builtin_ia32_vec_ext_v4di:
4037   case X86::BI__builtin_ia32_extractf32x4_mask:
4038   case X86::BI__builtin_ia32_extracti32x4_mask:
4039   case X86::BI__builtin_ia32_extractf64x2_512_mask:
4040   case X86::BI__builtin_ia32_extracti64x2_512_mask:
4041     i = 1; l = 0; u = 3;
4042     break;
4043   case X86::BI_mm_prefetch:
4044   case X86::BI__builtin_ia32_vec_ext_v8hi:
4045   case X86::BI__builtin_ia32_vec_ext_v8si:
4046     i = 1; l = 0; u = 7;
4047     break;
4048   case X86::BI__builtin_ia32_sha1rnds4:
4049   case X86::BI__builtin_ia32_blendpd:
4050   case X86::BI__builtin_ia32_shufpd:
4051   case X86::BI__builtin_ia32_vec_set_v4hi:
4052   case X86::BI__builtin_ia32_vec_set_v4si:
4053   case X86::BI__builtin_ia32_vec_set_v4di:
4054   case X86::BI__builtin_ia32_shuf_f32x4_256:
4055   case X86::BI__builtin_ia32_shuf_f64x2_256:
4056   case X86::BI__builtin_ia32_shuf_i32x4_256:
4057   case X86::BI__builtin_ia32_shuf_i64x2_256:
4058   case X86::BI__builtin_ia32_insertf64x2_512:
4059   case X86::BI__builtin_ia32_inserti64x2_512:
4060   case X86::BI__builtin_ia32_insertf32x4:
4061   case X86::BI__builtin_ia32_inserti32x4:
4062     i = 2; l = 0; u = 3;
4063     break;
4064   case X86::BI__builtin_ia32_vpermil2pd:
4065   case X86::BI__builtin_ia32_vpermil2pd256:
4066   case X86::BI__builtin_ia32_vpermil2ps:
4067   case X86::BI__builtin_ia32_vpermil2ps256:
4068     i = 3; l = 0; u = 3;
4069     break;
4070   case X86::BI__builtin_ia32_cmpb128_mask:
4071   case X86::BI__builtin_ia32_cmpw128_mask:
4072   case X86::BI__builtin_ia32_cmpd128_mask:
4073   case X86::BI__builtin_ia32_cmpq128_mask:
4074   case X86::BI__builtin_ia32_cmpb256_mask:
4075   case X86::BI__builtin_ia32_cmpw256_mask:
4076   case X86::BI__builtin_ia32_cmpd256_mask:
4077   case X86::BI__builtin_ia32_cmpq256_mask:
4078   case X86::BI__builtin_ia32_cmpb512_mask:
4079   case X86::BI__builtin_ia32_cmpw512_mask:
4080   case X86::BI__builtin_ia32_cmpd512_mask:
4081   case X86::BI__builtin_ia32_cmpq512_mask:
4082   case X86::BI__builtin_ia32_ucmpb128_mask:
4083   case X86::BI__builtin_ia32_ucmpw128_mask:
4084   case X86::BI__builtin_ia32_ucmpd128_mask:
4085   case X86::BI__builtin_ia32_ucmpq128_mask:
4086   case X86::BI__builtin_ia32_ucmpb256_mask:
4087   case X86::BI__builtin_ia32_ucmpw256_mask:
4088   case X86::BI__builtin_ia32_ucmpd256_mask:
4089   case X86::BI__builtin_ia32_ucmpq256_mask:
4090   case X86::BI__builtin_ia32_ucmpb512_mask:
4091   case X86::BI__builtin_ia32_ucmpw512_mask:
4092   case X86::BI__builtin_ia32_ucmpd512_mask:
4093   case X86::BI__builtin_ia32_ucmpq512_mask:
4094   case X86::BI__builtin_ia32_vpcomub:
4095   case X86::BI__builtin_ia32_vpcomuw:
4096   case X86::BI__builtin_ia32_vpcomud:
4097   case X86::BI__builtin_ia32_vpcomuq:
4098   case X86::BI__builtin_ia32_vpcomb:
4099   case X86::BI__builtin_ia32_vpcomw:
4100   case X86::BI__builtin_ia32_vpcomd:
4101   case X86::BI__builtin_ia32_vpcomq:
4102   case X86::BI__builtin_ia32_vec_set_v8hi:
4103   case X86::BI__builtin_ia32_vec_set_v8si:
4104     i = 2; l = 0; u = 7;
4105     break;
4106   case X86::BI__builtin_ia32_vpermilpd256:
4107   case X86::BI__builtin_ia32_roundps:
4108   case X86::BI__builtin_ia32_roundpd:
4109   case X86::BI__builtin_ia32_roundps256:
4110   case X86::BI__builtin_ia32_roundpd256:
4111   case X86::BI__builtin_ia32_getmantpd128_mask:
4112   case X86::BI__builtin_ia32_getmantpd256_mask:
4113   case X86::BI__builtin_ia32_getmantps128_mask:
4114   case X86::BI__builtin_ia32_getmantps256_mask:
4115   case X86::BI__builtin_ia32_getmantpd512_mask:
4116   case X86::BI__builtin_ia32_getmantps512_mask:
4117   case X86::BI__builtin_ia32_vec_ext_v16qi:
4118   case X86::BI__builtin_ia32_vec_ext_v16hi:
4119     i = 1; l = 0; u = 15;
4120     break;
4121   case X86::BI__builtin_ia32_pblendd128:
4122   case X86::BI__builtin_ia32_blendps:
4123   case X86::BI__builtin_ia32_blendpd256:
4124   case X86::BI__builtin_ia32_shufpd256:
4125   case X86::BI__builtin_ia32_roundss:
4126   case X86::BI__builtin_ia32_roundsd:
4127   case X86::BI__builtin_ia32_rangepd128_mask:
4128   case X86::BI__builtin_ia32_rangepd256_mask:
4129   case X86::BI__builtin_ia32_rangepd512_mask:
4130   case X86::BI__builtin_ia32_rangeps128_mask:
4131   case X86::BI__builtin_ia32_rangeps256_mask:
4132   case X86::BI__builtin_ia32_rangeps512_mask:
4133   case X86::BI__builtin_ia32_getmantsd_round_mask:
4134   case X86::BI__builtin_ia32_getmantss_round_mask:
4135   case X86::BI__builtin_ia32_vec_set_v16qi:
4136   case X86::BI__builtin_ia32_vec_set_v16hi:
4137     i = 2; l = 0; u = 15;
4138     break;
4139   case X86::BI__builtin_ia32_vec_ext_v32qi:
4140     i = 1; l = 0; u = 31;
4141     break;
4142   case X86::BI__builtin_ia32_cmpps:
4143   case X86::BI__builtin_ia32_cmpss:
4144   case X86::BI__builtin_ia32_cmppd:
4145   case X86::BI__builtin_ia32_cmpsd:
4146   case X86::BI__builtin_ia32_cmpps256:
4147   case X86::BI__builtin_ia32_cmppd256:
4148   case X86::BI__builtin_ia32_cmpps128_mask:
4149   case X86::BI__builtin_ia32_cmppd128_mask:
4150   case X86::BI__builtin_ia32_cmpps256_mask:
4151   case X86::BI__builtin_ia32_cmppd256_mask:
4152   case X86::BI__builtin_ia32_cmpps512_mask:
4153   case X86::BI__builtin_ia32_cmppd512_mask:
4154   case X86::BI__builtin_ia32_cmpsd_mask:
4155   case X86::BI__builtin_ia32_cmpss_mask:
4156   case X86::BI__builtin_ia32_vec_set_v32qi:
4157     i = 2; l = 0; u = 31;
4158     break;
4159   case X86::BI__builtin_ia32_permdf256:
4160   case X86::BI__builtin_ia32_permdi256:
4161   case X86::BI__builtin_ia32_permdf512:
4162   case X86::BI__builtin_ia32_permdi512:
4163   case X86::BI__builtin_ia32_vpermilps:
4164   case X86::BI__builtin_ia32_vpermilps256:
4165   case X86::BI__builtin_ia32_vpermilpd512:
4166   case X86::BI__builtin_ia32_vpermilps512:
4167   case X86::BI__builtin_ia32_pshufd:
4168   case X86::BI__builtin_ia32_pshufd256:
4169   case X86::BI__builtin_ia32_pshufd512:
4170   case X86::BI__builtin_ia32_pshufhw:
4171   case X86::BI__builtin_ia32_pshufhw256:
4172   case X86::BI__builtin_ia32_pshufhw512:
4173   case X86::BI__builtin_ia32_pshuflw:
4174   case X86::BI__builtin_ia32_pshuflw256:
4175   case X86::BI__builtin_ia32_pshuflw512:
4176   case X86::BI__builtin_ia32_vcvtps2ph:
4177   case X86::BI__builtin_ia32_vcvtps2ph_mask:
4178   case X86::BI__builtin_ia32_vcvtps2ph256:
4179   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
4180   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
4181   case X86::BI__builtin_ia32_rndscaleps_128_mask:
4182   case X86::BI__builtin_ia32_rndscalepd_128_mask:
4183   case X86::BI__builtin_ia32_rndscaleps_256_mask:
4184   case X86::BI__builtin_ia32_rndscalepd_256_mask:
4185   case X86::BI__builtin_ia32_rndscaleps_mask:
4186   case X86::BI__builtin_ia32_rndscalepd_mask:
4187   case X86::BI__builtin_ia32_reducepd128_mask:
4188   case X86::BI__builtin_ia32_reducepd256_mask:
4189   case X86::BI__builtin_ia32_reducepd512_mask:
4190   case X86::BI__builtin_ia32_reduceps128_mask:
4191   case X86::BI__builtin_ia32_reduceps256_mask:
4192   case X86::BI__builtin_ia32_reduceps512_mask:
4193   case X86::BI__builtin_ia32_prold512:
4194   case X86::BI__builtin_ia32_prolq512:
4195   case X86::BI__builtin_ia32_prold128:
4196   case X86::BI__builtin_ia32_prold256:
4197   case X86::BI__builtin_ia32_prolq128:
4198   case X86::BI__builtin_ia32_prolq256:
4199   case X86::BI__builtin_ia32_prord512:
4200   case X86::BI__builtin_ia32_prorq512:
4201   case X86::BI__builtin_ia32_prord128:
4202   case X86::BI__builtin_ia32_prord256:
4203   case X86::BI__builtin_ia32_prorq128:
4204   case X86::BI__builtin_ia32_prorq256:
4205   case X86::BI__builtin_ia32_fpclasspd128_mask:
4206   case X86::BI__builtin_ia32_fpclasspd256_mask:
4207   case X86::BI__builtin_ia32_fpclassps128_mask:
4208   case X86::BI__builtin_ia32_fpclassps256_mask:
4209   case X86::BI__builtin_ia32_fpclassps512_mask:
4210   case X86::BI__builtin_ia32_fpclasspd512_mask:
4211   case X86::BI__builtin_ia32_fpclasssd_mask:
4212   case X86::BI__builtin_ia32_fpclassss_mask:
4213   case X86::BI__builtin_ia32_pslldqi128_byteshift:
4214   case X86::BI__builtin_ia32_pslldqi256_byteshift:
4215   case X86::BI__builtin_ia32_pslldqi512_byteshift:
4216   case X86::BI__builtin_ia32_psrldqi128_byteshift:
4217   case X86::BI__builtin_ia32_psrldqi256_byteshift:
4218   case X86::BI__builtin_ia32_psrldqi512_byteshift:
4219   case X86::BI__builtin_ia32_kshiftliqi:
4220   case X86::BI__builtin_ia32_kshiftlihi:
4221   case X86::BI__builtin_ia32_kshiftlisi:
4222   case X86::BI__builtin_ia32_kshiftlidi:
4223   case X86::BI__builtin_ia32_kshiftriqi:
4224   case X86::BI__builtin_ia32_kshiftrihi:
4225   case X86::BI__builtin_ia32_kshiftrisi:
4226   case X86::BI__builtin_ia32_kshiftridi:
4227     i = 1; l = 0; u = 255;
4228     break;
4229   case X86::BI__builtin_ia32_vperm2f128_pd256:
4230   case X86::BI__builtin_ia32_vperm2f128_ps256:
4231   case X86::BI__builtin_ia32_vperm2f128_si256:
4232   case X86::BI__builtin_ia32_permti256:
4233   case X86::BI__builtin_ia32_pblendw128:
4234   case X86::BI__builtin_ia32_pblendw256:
4235   case X86::BI__builtin_ia32_blendps256:
4236   case X86::BI__builtin_ia32_pblendd256:
4237   case X86::BI__builtin_ia32_palignr128:
4238   case X86::BI__builtin_ia32_palignr256:
4239   case X86::BI__builtin_ia32_palignr512:
4240   case X86::BI__builtin_ia32_alignq512:
4241   case X86::BI__builtin_ia32_alignd512:
4242   case X86::BI__builtin_ia32_alignd128:
4243   case X86::BI__builtin_ia32_alignd256:
4244   case X86::BI__builtin_ia32_alignq128:
4245   case X86::BI__builtin_ia32_alignq256:
4246   case X86::BI__builtin_ia32_vcomisd:
4247   case X86::BI__builtin_ia32_vcomiss:
4248   case X86::BI__builtin_ia32_shuf_f32x4:
4249   case X86::BI__builtin_ia32_shuf_f64x2:
4250   case X86::BI__builtin_ia32_shuf_i32x4:
4251   case X86::BI__builtin_ia32_shuf_i64x2:
4252   case X86::BI__builtin_ia32_shufpd512:
4253   case X86::BI__builtin_ia32_shufps:
4254   case X86::BI__builtin_ia32_shufps256:
4255   case X86::BI__builtin_ia32_shufps512:
4256   case X86::BI__builtin_ia32_dbpsadbw128:
4257   case X86::BI__builtin_ia32_dbpsadbw256:
4258   case X86::BI__builtin_ia32_dbpsadbw512:
4259   case X86::BI__builtin_ia32_vpshldd128:
4260   case X86::BI__builtin_ia32_vpshldd256:
4261   case X86::BI__builtin_ia32_vpshldd512:
4262   case X86::BI__builtin_ia32_vpshldq128:
4263   case X86::BI__builtin_ia32_vpshldq256:
4264   case X86::BI__builtin_ia32_vpshldq512:
4265   case X86::BI__builtin_ia32_vpshldw128:
4266   case X86::BI__builtin_ia32_vpshldw256:
4267   case X86::BI__builtin_ia32_vpshldw512:
4268   case X86::BI__builtin_ia32_vpshrdd128:
4269   case X86::BI__builtin_ia32_vpshrdd256:
4270   case X86::BI__builtin_ia32_vpshrdd512:
4271   case X86::BI__builtin_ia32_vpshrdq128:
4272   case X86::BI__builtin_ia32_vpshrdq256:
4273   case X86::BI__builtin_ia32_vpshrdq512:
4274   case X86::BI__builtin_ia32_vpshrdw128:
4275   case X86::BI__builtin_ia32_vpshrdw256:
4276   case X86::BI__builtin_ia32_vpshrdw512:
4277     i = 2; l = 0; u = 255;
4278     break;
4279   case X86::BI__builtin_ia32_fixupimmpd512_mask:
4280   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
4281   case X86::BI__builtin_ia32_fixupimmps512_mask:
4282   case X86::BI__builtin_ia32_fixupimmps512_maskz:
4283   case X86::BI__builtin_ia32_fixupimmsd_mask:
4284   case X86::BI__builtin_ia32_fixupimmsd_maskz:
4285   case X86::BI__builtin_ia32_fixupimmss_mask:
4286   case X86::BI__builtin_ia32_fixupimmss_maskz:
4287   case X86::BI__builtin_ia32_fixupimmpd128_mask:
4288   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
4289   case X86::BI__builtin_ia32_fixupimmpd256_mask:
4290   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
4291   case X86::BI__builtin_ia32_fixupimmps128_mask:
4292   case X86::BI__builtin_ia32_fixupimmps128_maskz:
4293   case X86::BI__builtin_ia32_fixupimmps256_mask:
4294   case X86::BI__builtin_ia32_fixupimmps256_maskz:
4295   case X86::BI__builtin_ia32_pternlogd512_mask:
4296   case X86::BI__builtin_ia32_pternlogd512_maskz:
4297   case X86::BI__builtin_ia32_pternlogq512_mask:
4298   case X86::BI__builtin_ia32_pternlogq512_maskz:
4299   case X86::BI__builtin_ia32_pternlogd128_mask:
4300   case X86::BI__builtin_ia32_pternlogd128_maskz:
4301   case X86::BI__builtin_ia32_pternlogd256_mask:
4302   case X86::BI__builtin_ia32_pternlogd256_maskz:
4303   case X86::BI__builtin_ia32_pternlogq128_mask:
4304   case X86::BI__builtin_ia32_pternlogq128_maskz:
4305   case X86::BI__builtin_ia32_pternlogq256_mask:
4306   case X86::BI__builtin_ia32_pternlogq256_maskz:
4307     i = 3; l = 0; u = 255;
4308     break;
4309   case X86::BI__builtin_ia32_gatherpfdpd:
4310   case X86::BI__builtin_ia32_gatherpfdps:
4311   case X86::BI__builtin_ia32_gatherpfqpd:
4312   case X86::BI__builtin_ia32_gatherpfqps:
4313   case X86::BI__builtin_ia32_scatterpfdpd:
4314   case X86::BI__builtin_ia32_scatterpfdps:
4315   case X86::BI__builtin_ia32_scatterpfqpd:
4316   case X86::BI__builtin_ia32_scatterpfqps:
4317     i = 4; l = 2; u = 3;
4318     break;
4319   case X86::BI__builtin_ia32_reducesd_mask:
4320   case X86::BI__builtin_ia32_reducess_mask:
4321   case X86::BI__builtin_ia32_rndscalesd_round_mask:
4322   case X86::BI__builtin_ia32_rndscaless_round_mask:
4323     i = 4; l = 0; u = 255;
4324     break;
4325   }
4326 
4327   // Note that we don't force a hard error on the range check here, allowing
4328   // template-generated or macro-generated dead code to potentially have out-of-
4329   // range values. These need to code generate, but don't need to necessarily
4330   // make any sense. We use a warning that defaults to an error.
4331   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
4332 }
4333 
4334 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
4335 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
4336 /// Returns true when the format fits the function and the FormatStringInfo has
4337 /// been populated.
4338 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
4339                                FormatStringInfo *FSI) {
4340   FSI->HasVAListArg = Format->getFirstArg() == 0;
4341   FSI->FormatIdx = Format->getFormatIdx() - 1;
4342   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
4343 
4344   // The way the format attribute works in GCC, the implicit this argument
4345   // of member functions is counted. However, it doesn't appear in our own
4346   // lists, so decrement format_idx in that case.
4347   if (IsCXXMember) {
4348     if(FSI->FormatIdx == 0)
4349       return false;
4350     --FSI->FormatIdx;
4351     if (FSI->FirstDataArg != 0)
4352       --FSI->FirstDataArg;
4353   }
4354   return true;
4355 }
4356 
4357 /// Checks if a the given expression evaluates to null.
4358 ///
4359 /// Returns true if the value evaluates to null.
4360 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4361   // If the expression has non-null type, it doesn't evaluate to null.
4362   if (auto nullability
4363         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
4364     if (*nullability == NullabilityKind::NonNull)
4365       return false;
4366   }
4367 
4368   // As a special case, transparent unions initialized with zero are
4369   // considered null for the purposes of the nonnull attribute.
4370   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
4371     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
4372       if (const CompoundLiteralExpr *CLE =
4373           dyn_cast<CompoundLiteralExpr>(Expr))
4374         if (const InitListExpr *ILE =
4375             dyn_cast<InitListExpr>(CLE->getInitializer()))
4376           Expr = ILE->getInit(0);
4377   }
4378 
4379   bool Result;
4380   return (!Expr->isValueDependent() &&
4381           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
4382           !Result);
4383 }
4384 
4385 static void CheckNonNullArgument(Sema &S,
4386                                  const Expr *ArgExpr,
4387                                  SourceLocation CallSiteLoc) {
4388   if (CheckNonNullExpr(S, ArgExpr))
4389     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
4390                           S.PDiag(diag::warn_null_arg)
4391                               << ArgExpr->getSourceRange());
4392 }
4393 
4394 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
4395   FormatStringInfo FSI;
4396   if ((GetFormatStringType(Format) == FST_NSString) &&
4397       getFormatStringInfo(Format, false, &FSI)) {
4398     Idx = FSI.FormatIdx;
4399     return true;
4400   }
4401   return false;
4402 }
4403 
4404 /// Diagnose use of %s directive in an NSString which is being passed
4405 /// as formatting string to formatting method.
4406 static void
4407 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
4408                                         const NamedDecl *FDecl,
4409                                         Expr **Args,
4410                                         unsigned NumArgs) {
4411   unsigned Idx = 0;
4412   bool Format = false;
4413   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
4414   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
4415     Idx = 2;
4416     Format = true;
4417   }
4418   else
4419     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4420       if (S.GetFormatNSStringIdx(I, Idx)) {
4421         Format = true;
4422         break;
4423       }
4424     }
4425   if (!Format || NumArgs <= Idx)
4426     return;
4427   const Expr *FormatExpr = Args[Idx];
4428   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
4429     FormatExpr = CSCE->getSubExpr();
4430   const StringLiteral *FormatString;
4431   if (const ObjCStringLiteral *OSL =
4432       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
4433     FormatString = OSL->getString();
4434   else
4435     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
4436   if (!FormatString)
4437     return;
4438   if (S.FormatStringHasSArg(FormatString)) {
4439     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
4440       << "%s" << 1 << 1;
4441     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
4442       << FDecl->getDeclName();
4443   }
4444 }
4445 
4446 /// Determine whether the given type has a non-null nullability annotation.
4447 static bool isNonNullType(ASTContext &ctx, QualType type) {
4448   if (auto nullability = type->getNullability(ctx))
4449     return *nullability == NullabilityKind::NonNull;
4450 
4451   return false;
4452 }
4453 
4454 static void CheckNonNullArguments(Sema &S,
4455                                   const NamedDecl *FDecl,
4456                                   const FunctionProtoType *Proto,
4457                                   ArrayRef<const Expr *> Args,
4458                                   SourceLocation CallSiteLoc) {
4459   assert((FDecl || Proto) && "Need a function declaration or prototype");
4460 
4461   // Already checked by by constant evaluator.
4462   if (S.isConstantEvaluated())
4463     return;
4464   // Check the attributes attached to the method/function itself.
4465   llvm::SmallBitVector NonNullArgs;
4466   if (FDecl) {
4467     // Handle the nonnull attribute on the function/method declaration itself.
4468     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4469       if (!NonNull->args_size()) {
4470         // Easy case: all pointer arguments are nonnull.
4471         for (const auto *Arg : Args)
4472           if (S.isValidPointerAttrType(Arg->getType()))
4473             CheckNonNullArgument(S, Arg, CallSiteLoc);
4474         return;
4475       }
4476 
4477       for (const ParamIdx &Idx : NonNull->args()) {
4478         unsigned IdxAST = Idx.getASTIndex();
4479         if (IdxAST >= Args.size())
4480           continue;
4481         if (NonNullArgs.empty())
4482           NonNullArgs.resize(Args.size());
4483         NonNullArgs.set(IdxAST);
4484       }
4485     }
4486   }
4487 
4488   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4489     // Handle the nonnull attribute on the parameters of the
4490     // function/method.
4491     ArrayRef<ParmVarDecl*> parms;
4492     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4493       parms = FD->parameters();
4494     else
4495       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4496 
4497     unsigned ParamIndex = 0;
4498     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4499          I != E; ++I, ++ParamIndex) {
4500       const ParmVarDecl *PVD = *I;
4501       if (PVD->hasAttr<NonNullAttr>() ||
4502           isNonNullType(S.Context, PVD->getType())) {
4503         if (NonNullArgs.empty())
4504           NonNullArgs.resize(Args.size());
4505 
4506         NonNullArgs.set(ParamIndex);
4507       }
4508     }
4509   } else {
4510     // If we have a non-function, non-method declaration but no
4511     // function prototype, try to dig out the function prototype.
4512     if (!Proto) {
4513       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4514         QualType type = VD->getType().getNonReferenceType();
4515         if (auto pointerType = type->getAs<PointerType>())
4516           type = pointerType->getPointeeType();
4517         else if (auto blockType = type->getAs<BlockPointerType>())
4518           type = blockType->getPointeeType();
4519         // FIXME: data member pointers?
4520 
4521         // Dig out the function prototype, if there is one.
4522         Proto = type->getAs<FunctionProtoType>();
4523       }
4524     }
4525 
4526     // Fill in non-null argument information from the nullability
4527     // information on the parameter types (if we have them).
4528     if (Proto) {
4529       unsigned Index = 0;
4530       for (auto paramType : Proto->getParamTypes()) {
4531         if (isNonNullType(S.Context, paramType)) {
4532           if (NonNullArgs.empty())
4533             NonNullArgs.resize(Args.size());
4534 
4535           NonNullArgs.set(Index);
4536         }
4537 
4538         ++Index;
4539       }
4540     }
4541   }
4542 
4543   // Check for non-null arguments.
4544   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4545        ArgIndex != ArgIndexEnd; ++ArgIndex) {
4546     if (NonNullArgs[ArgIndex])
4547       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
4548   }
4549 }
4550 
4551 /// Warn if a pointer or reference argument passed to a function points to an
4552 /// object that is less aligned than the parameter. This can happen when
4553 /// creating a typedef with a lower alignment than the original type and then
4554 /// calling functions defined in terms of the original type.
4555 void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
4556                              StringRef ParamName, QualType ArgTy,
4557                              QualType ParamTy) {
4558 
4559   // If a function accepts a pointer or reference type
4560   if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
4561     return;
4562 
4563   // If the parameter is a pointer type, get the pointee type for the
4564   // argument too. If the parameter is a reference type, don't try to get
4565   // the pointee type for the argument.
4566   if (ParamTy->isPointerType())
4567     ArgTy = ArgTy->getPointeeType();
4568 
4569   // Remove reference or pointer
4570   ParamTy = ParamTy->getPointeeType();
4571 
4572   // Find expected alignment, and the actual alignment of the passed object.
4573   // getTypeAlignInChars requires complete types
4574   if (ArgTy.isNull() || ParamTy->isIncompleteType() ||
4575       ArgTy->isIncompleteType() || ParamTy->isUndeducedType() ||
4576       ArgTy->isUndeducedType())
4577     return;
4578 
4579   CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
4580   CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
4581 
4582   // If the argument is less aligned than the parameter, there is a
4583   // potential alignment issue.
4584   if (ArgAlign < ParamAlign)
4585     Diag(Loc, diag::warn_param_mismatched_alignment)
4586         << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
4587         << ParamName << FDecl;
4588 }
4589 
4590 /// Handles the checks for format strings, non-POD arguments to vararg
4591 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
4592 /// attributes.
4593 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
4594                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
4595                      bool IsMemberFunction, SourceLocation Loc,
4596                      SourceRange Range, VariadicCallType CallType) {
4597   // FIXME: We should check as much as we can in the template definition.
4598   if (CurContext->isDependentContext())
4599     return;
4600 
4601   // Printf and scanf checking.
4602   llvm::SmallBitVector CheckedVarArgs;
4603   if (FDecl) {
4604     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4605       // Only create vector if there are format attributes.
4606       CheckedVarArgs.resize(Args.size());
4607 
4608       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4609                            CheckedVarArgs);
4610     }
4611   }
4612 
4613   // Refuse POD arguments that weren't caught by the format string
4614   // checks above.
4615   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4616   if (CallType != VariadicDoesNotApply &&
4617       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4618     unsigned NumParams = Proto ? Proto->getNumParams()
4619                        : FDecl && isa<FunctionDecl>(FDecl)
4620                            ? cast<FunctionDecl>(FDecl)->getNumParams()
4621                        : FDecl && isa<ObjCMethodDecl>(FDecl)
4622                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
4623                        : 0;
4624 
4625     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4626       // Args[ArgIdx] can be null in malformed code.
4627       if (const Expr *Arg = Args[ArgIdx]) {
4628         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4629           checkVariadicArgument(Arg, CallType);
4630       }
4631     }
4632   }
4633 
4634   if (FDecl || Proto) {
4635     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4636 
4637     // Type safety checking.
4638     if (FDecl) {
4639       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4640         CheckArgumentWithTypeTag(I, Args, Loc);
4641     }
4642   }
4643 
4644   // Check that passed arguments match the alignment of original arguments.
4645   // Try to get the missing prototype from the declaration.
4646   if (!Proto && FDecl) {
4647     const auto *FT = FDecl->getFunctionType();
4648     if (isa_and_nonnull<FunctionProtoType>(FT))
4649       Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
4650   }
4651   if (Proto) {
4652     // For variadic functions, we may have more args than parameters.
4653     // For some K&R functions, we may have less args than parameters.
4654     const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
4655     for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
4656       // Args[ArgIdx] can be null in malformed code.
4657       if (const Expr *Arg = Args[ArgIdx]) {
4658         if (Arg->containsErrors())
4659           continue;
4660 
4661         QualType ParamTy = Proto->getParamType(ArgIdx);
4662         QualType ArgTy = Arg->getType();
4663         CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
4664                           ArgTy, ParamTy);
4665       }
4666     }
4667   }
4668 
4669   if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
4670     auto *AA = FDecl->getAttr<AllocAlignAttr>();
4671     const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
4672     if (!Arg->isValueDependent()) {
4673       Expr::EvalResult Align;
4674       if (Arg->EvaluateAsInt(Align, Context)) {
4675         const llvm::APSInt &I = Align.Val.getInt();
4676         if (!I.isPowerOf2())
4677           Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
4678               << Arg->getSourceRange();
4679 
4680         if (I > Sema::MaximumAlignment)
4681           Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
4682               << Arg->getSourceRange() << Sema::MaximumAlignment;
4683       }
4684     }
4685   }
4686 
4687   if (FD)
4688     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4689 }
4690 
4691 /// CheckConstructorCall - Check a constructor call for correctness and safety
4692 /// properties not enforced by the C type system.
4693 void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
4694                                 ArrayRef<const Expr *> Args,
4695                                 const FunctionProtoType *Proto,
4696                                 SourceLocation Loc) {
4697   VariadicCallType CallType =
4698       Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4699 
4700   auto *Ctor = cast<CXXConstructorDecl>(FDecl);
4701   CheckArgAlignment(Loc, FDecl, "'this'", Context.getPointerType(ThisType),
4702                     Context.getPointerType(Ctor->getThisObjectType()));
4703 
4704   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4705             Loc, SourceRange(), CallType);
4706 }
4707 
4708 /// CheckFunctionCall - Check a direct function call for various correctness
4709 /// and safety properties not strictly enforced by the C type system.
4710 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
4711                              const FunctionProtoType *Proto) {
4712   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4713                               isa<CXXMethodDecl>(FDecl);
4714   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4715                           IsMemberOperatorCall;
4716   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4717                                                   TheCall->getCallee());
4718   Expr** Args = TheCall->getArgs();
4719   unsigned NumArgs = TheCall->getNumArgs();
4720 
4721   Expr *ImplicitThis = nullptr;
4722   if (IsMemberOperatorCall) {
4723     // If this is a call to a member operator, hide the first argument
4724     // from checkCall.
4725     // FIXME: Our choice of AST representation here is less than ideal.
4726     ImplicitThis = Args[0];
4727     ++Args;
4728     --NumArgs;
4729   } else if (IsMemberFunction)
4730     ImplicitThis =
4731         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4732 
4733   if (ImplicitThis) {
4734     // ImplicitThis may or may not be a pointer, depending on whether . or -> is
4735     // used.
4736     QualType ThisType = ImplicitThis->getType();
4737     if (!ThisType->isPointerType()) {
4738       assert(!ThisType->isReferenceType());
4739       ThisType = Context.getPointerType(ThisType);
4740     }
4741 
4742     QualType ThisTypeFromDecl =
4743         Context.getPointerType(cast<CXXMethodDecl>(FDecl)->getThisObjectType());
4744 
4745     CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
4746                       ThisTypeFromDecl);
4747   }
4748 
4749   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
4750             IsMemberFunction, TheCall->getRParenLoc(),
4751             TheCall->getCallee()->getSourceRange(), CallType);
4752 
4753   IdentifierInfo *FnInfo = FDecl->getIdentifier();
4754   // None of the checks below are needed for functions that don't have
4755   // simple names (e.g., C++ conversion functions).
4756   if (!FnInfo)
4757     return false;
4758 
4759   CheckTCBEnforcement(TheCall, FDecl);
4760 
4761   CheckAbsoluteValueFunction(TheCall, FDecl);
4762   CheckMaxUnsignedZero(TheCall, FDecl);
4763 
4764   if (getLangOpts().ObjC)
4765     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
4766 
4767   unsigned CMId = FDecl->getMemoryFunctionKind();
4768 
4769   // Handle memory setting and copying functions.
4770   switch (CMId) {
4771   case 0:
4772     return false;
4773   case Builtin::BIstrlcpy: // fallthrough
4774   case Builtin::BIstrlcat:
4775     CheckStrlcpycatArguments(TheCall, FnInfo);
4776     break;
4777   case Builtin::BIstrncat:
4778     CheckStrncatArguments(TheCall, FnInfo);
4779     break;
4780   case Builtin::BIfree:
4781     CheckFreeArguments(TheCall);
4782     break;
4783   default:
4784     CheckMemaccessArguments(TheCall, CMId, FnInfo);
4785   }
4786 
4787   return false;
4788 }
4789 
4790 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
4791                                ArrayRef<const Expr *> Args) {
4792   VariadicCallType CallType =
4793       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
4794 
4795   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
4796             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
4797             CallType);
4798 
4799   return false;
4800 }
4801 
4802 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4803                             const FunctionProtoType *Proto) {
4804   QualType Ty;
4805   if (const auto *V = dyn_cast<VarDecl>(NDecl))
4806     Ty = V->getType().getNonReferenceType();
4807   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4808     Ty = F->getType().getNonReferenceType();
4809   else
4810     return false;
4811 
4812   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4813       !Ty->isFunctionProtoType())
4814     return false;
4815 
4816   VariadicCallType CallType;
4817   if (!Proto || !Proto->isVariadic()) {
4818     CallType = VariadicDoesNotApply;
4819   } else if (Ty->isBlockPointerType()) {
4820     CallType = VariadicBlock;
4821   } else { // Ty->isFunctionPointerType()
4822     CallType = VariadicFunction;
4823   }
4824 
4825   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4826             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4827             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4828             TheCall->getCallee()->getSourceRange(), CallType);
4829 
4830   return false;
4831 }
4832 
4833 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
4834 /// such as function pointers returned from functions.
4835 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4836   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4837                                                   TheCall->getCallee());
4838   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4839             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4840             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4841             TheCall->getCallee()->getSourceRange(), CallType);
4842 
4843   return false;
4844 }
4845 
4846 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4847   if (!llvm::isValidAtomicOrderingCABI(Ordering))
4848     return false;
4849 
4850   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4851   switch (Op) {
4852   case AtomicExpr::AO__c11_atomic_init:
4853   case AtomicExpr::AO__opencl_atomic_init:
4854     llvm_unreachable("There is no ordering argument for an init");
4855 
4856   case AtomicExpr::AO__c11_atomic_load:
4857   case AtomicExpr::AO__opencl_atomic_load:
4858   case AtomicExpr::AO__atomic_load_n:
4859   case AtomicExpr::AO__atomic_load:
4860     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4861            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4862 
4863   case AtomicExpr::AO__c11_atomic_store:
4864   case AtomicExpr::AO__opencl_atomic_store:
4865   case AtomicExpr::AO__atomic_store:
4866   case AtomicExpr::AO__atomic_store_n:
4867     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4868            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4869            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4870 
4871   default:
4872     return true;
4873   }
4874 }
4875 
4876 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
4877                                          AtomicExpr::AtomicOp Op) {
4878   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4879   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4880   MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
4881   return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
4882                          DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
4883                          Op);
4884 }
4885 
4886 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
4887                                  SourceLocation RParenLoc, MultiExprArg Args,
4888                                  AtomicExpr::AtomicOp Op,
4889                                  AtomicArgumentOrder ArgOrder) {
4890   // All the non-OpenCL operations take one of the following forms.
4891   // The OpenCL operations take the __c11 forms with one extra argument for
4892   // synchronization scope.
4893   enum {
4894     // C    __c11_atomic_init(A *, C)
4895     Init,
4896 
4897     // C    __c11_atomic_load(A *, int)
4898     Load,
4899 
4900     // void __atomic_load(A *, CP, int)
4901     LoadCopy,
4902 
4903     // void __atomic_store(A *, CP, int)
4904     Copy,
4905 
4906     // C    __c11_atomic_add(A *, M, int)
4907     Arithmetic,
4908 
4909     // C    __atomic_exchange_n(A *, CP, int)
4910     Xchg,
4911 
4912     // void __atomic_exchange(A *, C *, CP, int)
4913     GNUXchg,
4914 
4915     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4916     C11CmpXchg,
4917 
4918     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4919     GNUCmpXchg
4920   } Form = Init;
4921 
4922   const unsigned NumForm = GNUCmpXchg + 1;
4923   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
4924   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
4925   // where:
4926   //   C is an appropriate type,
4927   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4928   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4929   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4930   //   the int parameters are for orderings.
4931 
4932   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4933       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4934       "need to update code for modified forms");
4935   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
4936                     AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
4937                         AtomicExpr::AO__atomic_load,
4938                 "need to update code for modified C11 atomics");
4939   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
4940                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
4941   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
4942                Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
4943                IsOpenCL;
4944   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4945              Op == AtomicExpr::AO__atomic_store_n ||
4946              Op == AtomicExpr::AO__atomic_exchange_n ||
4947              Op == AtomicExpr::AO__atomic_compare_exchange_n;
4948   bool IsAddSub = false;
4949 
4950   switch (Op) {
4951   case AtomicExpr::AO__c11_atomic_init:
4952   case AtomicExpr::AO__opencl_atomic_init:
4953     Form = Init;
4954     break;
4955 
4956   case AtomicExpr::AO__c11_atomic_load:
4957   case AtomicExpr::AO__opencl_atomic_load:
4958   case AtomicExpr::AO__atomic_load_n:
4959     Form = Load;
4960     break;
4961 
4962   case AtomicExpr::AO__atomic_load:
4963     Form = LoadCopy;
4964     break;
4965 
4966   case AtomicExpr::AO__c11_atomic_store:
4967   case AtomicExpr::AO__opencl_atomic_store:
4968   case AtomicExpr::AO__atomic_store:
4969   case AtomicExpr::AO__atomic_store_n:
4970     Form = Copy;
4971     break;
4972 
4973   case AtomicExpr::AO__c11_atomic_fetch_add:
4974   case AtomicExpr::AO__c11_atomic_fetch_sub:
4975   case AtomicExpr::AO__opencl_atomic_fetch_add:
4976   case AtomicExpr::AO__opencl_atomic_fetch_sub:
4977   case AtomicExpr::AO__atomic_fetch_add:
4978   case AtomicExpr::AO__atomic_fetch_sub:
4979   case AtomicExpr::AO__atomic_add_fetch:
4980   case AtomicExpr::AO__atomic_sub_fetch:
4981     IsAddSub = true;
4982     Form = Arithmetic;
4983     break;
4984   case AtomicExpr::AO__c11_atomic_fetch_and:
4985   case AtomicExpr::AO__c11_atomic_fetch_or:
4986   case AtomicExpr::AO__c11_atomic_fetch_xor:
4987   case AtomicExpr::AO__opencl_atomic_fetch_and:
4988   case AtomicExpr::AO__opencl_atomic_fetch_or:
4989   case AtomicExpr::AO__opencl_atomic_fetch_xor:
4990   case AtomicExpr::AO__atomic_fetch_and:
4991   case AtomicExpr::AO__atomic_fetch_or:
4992   case AtomicExpr::AO__atomic_fetch_xor:
4993   case AtomicExpr::AO__atomic_fetch_nand:
4994   case AtomicExpr::AO__atomic_and_fetch:
4995   case AtomicExpr::AO__atomic_or_fetch:
4996   case AtomicExpr::AO__atomic_xor_fetch:
4997   case AtomicExpr::AO__atomic_nand_fetch:
4998     Form = Arithmetic;
4999     break;
5000   case AtomicExpr::AO__c11_atomic_fetch_min:
5001   case AtomicExpr::AO__c11_atomic_fetch_max:
5002   case AtomicExpr::AO__opencl_atomic_fetch_min:
5003   case AtomicExpr::AO__opencl_atomic_fetch_max:
5004   case AtomicExpr::AO__atomic_min_fetch:
5005   case AtomicExpr::AO__atomic_max_fetch:
5006   case AtomicExpr::AO__atomic_fetch_min:
5007   case AtomicExpr::AO__atomic_fetch_max:
5008     Form = Arithmetic;
5009     break;
5010 
5011   case AtomicExpr::AO__c11_atomic_exchange:
5012   case AtomicExpr::AO__opencl_atomic_exchange:
5013   case AtomicExpr::AO__atomic_exchange_n:
5014     Form = Xchg;
5015     break;
5016 
5017   case AtomicExpr::AO__atomic_exchange:
5018     Form = GNUXchg;
5019     break;
5020 
5021   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
5022   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
5023   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
5024   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
5025     Form = C11CmpXchg;
5026     break;
5027 
5028   case AtomicExpr::AO__atomic_compare_exchange:
5029   case AtomicExpr::AO__atomic_compare_exchange_n:
5030     Form = GNUCmpXchg;
5031     break;
5032   }
5033 
5034   unsigned AdjustedNumArgs = NumArgs[Form];
5035   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
5036     ++AdjustedNumArgs;
5037   // Check we have the right number of arguments.
5038   if (Args.size() < AdjustedNumArgs) {
5039     Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
5040         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5041         << ExprRange;
5042     return ExprError();
5043   } else if (Args.size() > AdjustedNumArgs) {
5044     Diag(Args[AdjustedNumArgs]->getBeginLoc(),
5045          diag::err_typecheck_call_too_many_args)
5046         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5047         << ExprRange;
5048     return ExprError();
5049   }
5050 
5051   // Inspect the first argument of the atomic operation.
5052   Expr *Ptr = Args[0];
5053   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
5054   if (ConvertedPtr.isInvalid())
5055     return ExprError();
5056 
5057   Ptr = ConvertedPtr.get();
5058   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
5059   if (!pointerType) {
5060     Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
5061         << Ptr->getType() << Ptr->getSourceRange();
5062     return ExprError();
5063   }
5064 
5065   // For a __c11 builtin, this should be a pointer to an _Atomic type.
5066   QualType AtomTy = pointerType->getPointeeType(); // 'A'
5067   QualType ValType = AtomTy; // 'C'
5068   if (IsC11) {
5069     if (!AtomTy->isAtomicType()) {
5070       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
5071           << Ptr->getType() << Ptr->getSourceRange();
5072       return ExprError();
5073     }
5074     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
5075         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
5076       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
5077           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
5078           << Ptr->getSourceRange();
5079       return ExprError();
5080     }
5081     ValType = AtomTy->castAs<AtomicType>()->getValueType();
5082   } else if (Form != Load && Form != LoadCopy) {
5083     if (ValType.isConstQualified()) {
5084       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
5085           << Ptr->getType() << Ptr->getSourceRange();
5086       return ExprError();
5087     }
5088   }
5089 
5090   // For an arithmetic operation, the implied arithmetic must be well-formed.
5091   if (Form == Arithmetic) {
5092     // gcc does not enforce these rules for GNU atomics, but we do so for
5093     // sanity.
5094     auto IsAllowedValueType = [&](QualType ValType) {
5095       if (ValType->isIntegerType())
5096         return true;
5097       if (ValType->isPointerType())
5098         return true;
5099       if (!ValType->isFloatingType())
5100         return false;
5101       // LLVM Parser does not allow atomicrmw with x86_fp80 type.
5102       if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
5103           &Context.getTargetInfo().getLongDoubleFormat() ==
5104               &llvm::APFloat::x87DoubleExtended())
5105         return false;
5106       return true;
5107     };
5108     if (IsAddSub && !IsAllowedValueType(ValType)) {
5109       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_ptr_or_fp)
5110           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5111       return ExprError();
5112     }
5113     if (!IsAddSub && !ValType->isIntegerType()) {
5114       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
5115           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5116       return ExprError();
5117     }
5118     if (IsC11 && ValType->isPointerType() &&
5119         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
5120                             diag::err_incomplete_type)) {
5121       return ExprError();
5122     }
5123   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
5124     // For __atomic_*_n operations, the value type must be a scalar integral or
5125     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
5126     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
5127         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5128     return ExprError();
5129   }
5130 
5131   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
5132       !AtomTy->isScalarType()) {
5133     // For GNU atomics, require a trivially-copyable type. This is not part of
5134     // the GNU atomics specification, but we enforce it for sanity.
5135     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
5136         << Ptr->getType() << Ptr->getSourceRange();
5137     return ExprError();
5138   }
5139 
5140   switch (ValType.getObjCLifetime()) {
5141   case Qualifiers::OCL_None:
5142   case Qualifiers::OCL_ExplicitNone:
5143     // okay
5144     break;
5145 
5146   case Qualifiers::OCL_Weak:
5147   case Qualifiers::OCL_Strong:
5148   case Qualifiers::OCL_Autoreleasing:
5149     // FIXME: Can this happen? By this point, ValType should be known
5150     // to be trivially copyable.
5151     Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
5152         << ValType << Ptr->getSourceRange();
5153     return ExprError();
5154   }
5155 
5156   // All atomic operations have an overload which takes a pointer to a volatile
5157   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
5158   // into the result or the other operands. Similarly atomic_load takes a
5159   // pointer to a const 'A'.
5160   ValType.removeLocalVolatile();
5161   ValType.removeLocalConst();
5162   QualType ResultType = ValType;
5163   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
5164       Form == Init)
5165     ResultType = Context.VoidTy;
5166   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
5167     ResultType = Context.BoolTy;
5168 
5169   // The type of a parameter passed 'by value'. In the GNU atomics, such
5170   // arguments are actually passed as pointers.
5171   QualType ByValType = ValType; // 'CP'
5172   bool IsPassedByAddress = false;
5173   if (!IsC11 && !IsN) {
5174     ByValType = Ptr->getType();
5175     IsPassedByAddress = true;
5176   }
5177 
5178   SmallVector<Expr *, 5> APIOrderedArgs;
5179   if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
5180     APIOrderedArgs.push_back(Args[0]);
5181     switch (Form) {
5182     case Init:
5183     case Load:
5184       APIOrderedArgs.push_back(Args[1]); // Val1/Order
5185       break;
5186     case LoadCopy:
5187     case Copy:
5188     case Arithmetic:
5189     case Xchg:
5190       APIOrderedArgs.push_back(Args[2]); // Val1
5191       APIOrderedArgs.push_back(Args[1]); // Order
5192       break;
5193     case GNUXchg:
5194       APIOrderedArgs.push_back(Args[2]); // Val1
5195       APIOrderedArgs.push_back(Args[3]); // Val2
5196       APIOrderedArgs.push_back(Args[1]); // Order
5197       break;
5198     case C11CmpXchg:
5199       APIOrderedArgs.push_back(Args[2]); // Val1
5200       APIOrderedArgs.push_back(Args[4]); // Val2
5201       APIOrderedArgs.push_back(Args[1]); // Order
5202       APIOrderedArgs.push_back(Args[3]); // OrderFail
5203       break;
5204     case GNUCmpXchg:
5205       APIOrderedArgs.push_back(Args[2]); // Val1
5206       APIOrderedArgs.push_back(Args[4]); // Val2
5207       APIOrderedArgs.push_back(Args[5]); // Weak
5208       APIOrderedArgs.push_back(Args[1]); // Order
5209       APIOrderedArgs.push_back(Args[3]); // OrderFail
5210       break;
5211     }
5212   } else
5213     APIOrderedArgs.append(Args.begin(), Args.end());
5214 
5215   // The first argument's non-CV pointer type is used to deduce the type of
5216   // subsequent arguments, except for:
5217   //  - weak flag (always converted to bool)
5218   //  - memory order (always converted to int)
5219   //  - scope  (always converted to int)
5220   for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
5221     QualType Ty;
5222     if (i < NumVals[Form] + 1) {
5223       switch (i) {
5224       case 0:
5225         // The first argument is always a pointer. It has a fixed type.
5226         // It is always dereferenced, a nullptr is undefined.
5227         CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5228         // Nothing else to do: we already know all we want about this pointer.
5229         continue;
5230       case 1:
5231         // The second argument is the non-atomic operand. For arithmetic, this
5232         // is always passed by value, and for a compare_exchange it is always
5233         // passed by address. For the rest, GNU uses by-address and C11 uses
5234         // by-value.
5235         assert(Form != Load);
5236         if (Form == Arithmetic && ValType->isPointerType())
5237           Ty = Context.getPointerDiffType();
5238         else if (Form == Init || Form == Arithmetic)
5239           Ty = ValType;
5240         else if (Form == Copy || Form == Xchg) {
5241           if (IsPassedByAddress) {
5242             // The value pointer is always dereferenced, a nullptr is undefined.
5243             CheckNonNullArgument(*this, APIOrderedArgs[i],
5244                                  ExprRange.getBegin());
5245           }
5246           Ty = ByValType;
5247         } else {
5248           Expr *ValArg = APIOrderedArgs[i];
5249           // The value pointer is always dereferenced, a nullptr is undefined.
5250           CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
5251           LangAS AS = LangAS::Default;
5252           // Keep address space of non-atomic pointer type.
5253           if (const PointerType *PtrTy =
5254                   ValArg->getType()->getAs<PointerType>()) {
5255             AS = PtrTy->getPointeeType().getAddressSpace();
5256           }
5257           Ty = Context.getPointerType(
5258               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
5259         }
5260         break;
5261       case 2:
5262         // The third argument to compare_exchange / GNU exchange is the desired
5263         // value, either by-value (for the C11 and *_n variant) or as a pointer.
5264         if (IsPassedByAddress)
5265           CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5266         Ty = ByValType;
5267         break;
5268       case 3:
5269         // The fourth argument to GNU compare_exchange is a 'weak' flag.
5270         Ty = Context.BoolTy;
5271         break;
5272       }
5273     } else {
5274       // The order(s) and scope are always converted to int.
5275       Ty = Context.IntTy;
5276     }
5277 
5278     InitializedEntity Entity =
5279         InitializedEntity::InitializeParameter(Context, Ty, false);
5280     ExprResult Arg = APIOrderedArgs[i];
5281     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5282     if (Arg.isInvalid())
5283       return true;
5284     APIOrderedArgs[i] = Arg.get();
5285   }
5286 
5287   // Permute the arguments into a 'consistent' order.
5288   SmallVector<Expr*, 5> SubExprs;
5289   SubExprs.push_back(Ptr);
5290   switch (Form) {
5291   case Init:
5292     // Note, AtomicExpr::getVal1() has a special case for this atomic.
5293     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5294     break;
5295   case Load:
5296     SubExprs.push_back(APIOrderedArgs[1]); // Order
5297     break;
5298   case LoadCopy:
5299   case Copy:
5300   case Arithmetic:
5301   case Xchg:
5302     SubExprs.push_back(APIOrderedArgs[2]); // Order
5303     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5304     break;
5305   case GNUXchg:
5306     // Note, AtomicExpr::getVal2() has a special case for this atomic.
5307     SubExprs.push_back(APIOrderedArgs[3]); // Order
5308     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5309     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5310     break;
5311   case C11CmpXchg:
5312     SubExprs.push_back(APIOrderedArgs[3]); // Order
5313     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5314     SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
5315     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5316     break;
5317   case GNUCmpXchg:
5318     SubExprs.push_back(APIOrderedArgs[4]); // Order
5319     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5320     SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
5321     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5322     SubExprs.push_back(APIOrderedArgs[3]); // Weak
5323     break;
5324   }
5325 
5326   if (SubExprs.size() >= 2 && Form != Init) {
5327     if (Optional<llvm::APSInt> Result =
5328             SubExprs[1]->getIntegerConstantExpr(Context))
5329       if (!isValidOrderingForOp(Result->getSExtValue(), Op))
5330         Diag(SubExprs[1]->getBeginLoc(),
5331              diag::warn_atomic_op_has_invalid_memory_order)
5332             << SubExprs[1]->getSourceRange();
5333   }
5334 
5335   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
5336     auto *Scope = Args[Args.size() - 1];
5337     if (Optional<llvm::APSInt> Result =
5338             Scope->getIntegerConstantExpr(Context)) {
5339       if (!ScopeModel->isValid(Result->getZExtValue()))
5340         Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
5341             << Scope->getSourceRange();
5342     }
5343     SubExprs.push_back(Scope);
5344   }
5345 
5346   AtomicExpr *AE = new (Context)
5347       AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
5348 
5349   if ((Op == AtomicExpr::AO__c11_atomic_load ||
5350        Op == AtomicExpr::AO__c11_atomic_store ||
5351        Op == AtomicExpr::AO__opencl_atomic_load ||
5352        Op == AtomicExpr::AO__opencl_atomic_store ) &&
5353       Context.AtomicUsesUnsupportedLibcall(AE))
5354     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
5355         << ((Op == AtomicExpr::AO__c11_atomic_load ||
5356              Op == AtomicExpr::AO__opencl_atomic_load)
5357                 ? 0
5358                 : 1);
5359 
5360   if (ValType->isExtIntType()) {
5361     Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_ext_int_prohibit);
5362     return ExprError();
5363   }
5364 
5365   return AE;
5366 }
5367 
5368 /// checkBuiltinArgument - Given a call to a builtin function, perform
5369 /// normal type-checking on the given argument, updating the call in
5370 /// place.  This is useful when a builtin function requires custom
5371 /// type-checking for some of its arguments but not necessarily all of
5372 /// them.
5373 ///
5374 /// Returns true on error.
5375 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
5376   FunctionDecl *Fn = E->getDirectCallee();
5377   assert(Fn && "builtin call without direct callee!");
5378 
5379   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
5380   InitializedEntity Entity =
5381     InitializedEntity::InitializeParameter(S.Context, Param);
5382 
5383   ExprResult Arg = E->getArg(0);
5384   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
5385   if (Arg.isInvalid())
5386     return true;
5387 
5388   E->setArg(ArgIndex, Arg.get());
5389   return false;
5390 }
5391 
5392 /// We have a call to a function like __sync_fetch_and_add, which is an
5393 /// overloaded function based on the pointer type of its first argument.
5394 /// The main BuildCallExpr routines have already promoted the types of
5395 /// arguments because all of these calls are prototyped as void(...).
5396 ///
5397 /// This function goes through and does final semantic checking for these
5398 /// builtins, as well as generating any warnings.
5399 ExprResult
5400 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
5401   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
5402   Expr *Callee = TheCall->getCallee();
5403   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
5404   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5405 
5406   // Ensure that we have at least one argument to do type inference from.
5407   if (TheCall->getNumArgs() < 1) {
5408     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5409         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
5410     return ExprError();
5411   }
5412 
5413   // Inspect the first argument of the atomic builtin.  This should always be
5414   // a pointer type, whose element is an integral scalar or pointer type.
5415   // Because it is a pointer type, we don't have to worry about any implicit
5416   // casts here.
5417   // FIXME: We don't allow floating point scalars as input.
5418   Expr *FirstArg = TheCall->getArg(0);
5419   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
5420   if (FirstArgResult.isInvalid())
5421     return ExprError();
5422   FirstArg = FirstArgResult.get();
5423   TheCall->setArg(0, FirstArg);
5424 
5425   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5426   if (!pointerType) {
5427     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
5428         << FirstArg->getType() << FirstArg->getSourceRange();
5429     return ExprError();
5430   }
5431 
5432   QualType ValType = pointerType->getPointeeType();
5433   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5434       !ValType->isBlockPointerType()) {
5435     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
5436         << FirstArg->getType() << FirstArg->getSourceRange();
5437     return ExprError();
5438   }
5439 
5440   if (ValType.isConstQualified()) {
5441     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
5442         << FirstArg->getType() << FirstArg->getSourceRange();
5443     return ExprError();
5444   }
5445 
5446   switch (ValType.getObjCLifetime()) {
5447   case Qualifiers::OCL_None:
5448   case Qualifiers::OCL_ExplicitNone:
5449     // okay
5450     break;
5451 
5452   case Qualifiers::OCL_Weak:
5453   case Qualifiers::OCL_Strong:
5454   case Qualifiers::OCL_Autoreleasing:
5455     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
5456         << ValType << FirstArg->getSourceRange();
5457     return ExprError();
5458   }
5459 
5460   // Strip any qualifiers off ValType.
5461   ValType = ValType.getUnqualifiedType();
5462 
5463   // The majority of builtins return a value, but a few have special return
5464   // types, so allow them to override appropriately below.
5465   QualType ResultType = ValType;
5466 
5467   // We need to figure out which concrete builtin this maps onto.  For example,
5468   // __sync_fetch_and_add with a 2 byte object turns into
5469   // __sync_fetch_and_add_2.
5470 #define BUILTIN_ROW(x) \
5471   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5472     Builtin::BI##x##_8, Builtin::BI##x##_16 }
5473 
5474   static const unsigned BuiltinIndices[][5] = {
5475     BUILTIN_ROW(__sync_fetch_and_add),
5476     BUILTIN_ROW(__sync_fetch_and_sub),
5477     BUILTIN_ROW(__sync_fetch_and_or),
5478     BUILTIN_ROW(__sync_fetch_and_and),
5479     BUILTIN_ROW(__sync_fetch_and_xor),
5480     BUILTIN_ROW(__sync_fetch_and_nand),
5481 
5482     BUILTIN_ROW(__sync_add_and_fetch),
5483     BUILTIN_ROW(__sync_sub_and_fetch),
5484     BUILTIN_ROW(__sync_and_and_fetch),
5485     BUILTIN_ROW(__sync_or_and_fetch),
5486     BUILTIN_ROW(__sync_xor_and_fetch),
5487     BUILTIN_ROW(__sync_nand_and_fetch),
5488 
5489     BUILTIN_ROW(__sync_val_compare_and_swap),
5490     BUILTIN_ROW(__sync_bool_compare_and_swap),
5491     BUILTIN_ROW(__sync_lock_test_and_set),
5492     BUILTIN_ROW(__sync_lock_release),
5493     BUILTIN_ROW(__sync_swap)
5494   };
5495 #undef BUILTIN_ROW
5496 
5497   // Determine the index of the size.
5498   unsigned SizeIndex;
5499   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
5500   case 1: SizeIndex = 0; break;
5501   case 2: SizeIndex = 1; break;
5502   case 4: SizeIndex = 2; break;
5503   case 8: SizeIndex = 3; break;
5504   case 16: SizeIndex = 4; break;
5505   default:
5506     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
5507         << FirstArg->getType() << FirstArg->getSourceRange();
5508     return ExprError();
5509   }
5510 
5511   // Each of these builtins has one pointer argument, followed by some number of
5512   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5513   // that we ignore.  Find out which row of BuiltinIndices to read from as well
5514   // as the number of fixed args.
5515   unsigned BuiltinID = FDecl->getBuiltinID();
5516   unsigned BuiltinIndex, NumFixed = 1;
5517   bool WarnAboutSemanticsChange = false;
5518   switch (BuiltinID) {
5519   default: llvm_unreachable("Unknown overloaded atomic builtin!");
5520   case Builtin::BI__sync_fetch_and_add:
5521   case Builtin::BI__sync_fetch_and_add_1:
5522   case Builtin::BI__sync_fetch_and_add_2:
5523   case Builtin::BI__sync_fetch_and_add_4:
5524   case Builtin::BI__sync_fetch_and_add_8:
5525   case Builtin::BI__sync_fetch_and_add_16:
5526     BuiltinIndex = 0;
5527     break;
5528 
5529   case Builtin::BI__sync_fetch_and_sub:
5530   case Builtin::BI__sync_fetch_and_sub_1:
5531   case Builtin::BI__sync_fetch_and_sub_2:
5532   case Builtin::BI__sync_fetch_and_sub_4:
5533   case Builtin::BI__sync_fetch_and_sub_8:
5534   case Builtin::BI__sync_fetch_and_sub_16:
5535     BuiltinIndex = 1;
5536     break;
5537 
5538   case Builtin::BI__sync_fetch_and_or:
5539   case Builtin::BI__sync_fetch_and_or_1:
5540   case Builtin::BI__sync_fetch_and_or_2:
5541   case Builtin::BI__sync_fetch_and_or_4:
5542   case Builtin::BI__sync_fetch_and_or_8:
5543   case Builtin::BI__sync_fetch_and_or_16:
5544     BuiltinIndex = 2;
5545     break;
5546 
5547   case Builtin::BI__sync_fetch_and_and:
5548   case Builtin::BI__sync_fetch_and_and_1:
5549   case Builtin::BI__sync_fetch_and_and_2:
5550   case Builtin::BI__sync_fetch_and_and_4:
5551   case Builtin::BI__sync_fetch_and_and_8:
5552   case Builtin::BI__sync_fetch_and_and_16:
5553     BuiltinIndex = 3;
5554     break;
5555 
5556   case Builtin::BI__sync_fetch_and_xor:
5557   case Builtin::BI__sync_fetch_and_xor_1:
5558   case Builtin::BI__sync_fetch_and_xor_2:
5559   case Builtin::BI__sync_fetch_and_xor_4:
5560   case Builtin::BI__sync_fetch_and_xor_8:
5561   case Builtin::BI__sync_fetch_and_xor_16:
5562     BuiltinIndex = 4;
5563     break;
5564 
5565   case Builtin::BI__sync_fetch_and_nand:
5566   case Builtin::BI__sync_fetch_and_nand_1:
5567   case Builtin::BI__sync_fetch_and_nand_2:
5568   case Builtin::BI__sync_fetch_and_nand_4:
5569   case Builtin::BI__sync_fetch_and_nand_8:
5570   case Builtin::BI__sync_fetch_and_nand_16:
5571     BuiltinIndex = 5;
5572     WarnAboutSemanticsChange = true;
5573     break;
5574 
5575   case Builtin::BI__sync_add_and_fetch:
5576   case Builtin::BI__sync_add_and_fetch_1:
5577   case Builtin::BI__sync_add_and_fetch_2:
5578   case Builtin::BI__sync_add_and_fetch_4:
5579   case Builtin::BI__sync_add_and_fetch_8:
5580   case Builtin::BI__sync_add_and_fetch_16:
5581     BuiltinIndex = 6;
5582     break;
5583 
5584   case Builtin::BI__sync_sub_and_fetch:
5585   case Builtin::BI__sync_sub_and_fetch_1:
5586   case Builtin::BI__sync_sub_and_fetch_2:
5587   case Builtin::BI__sync_sub_and_fetch_4:
5588   case Builtin::BI__sync_sub_and_fetch_8:
5589   case Builtin::BI__sync_sub_and_fetch_16:
5590     BuiltinIndex = 7;
5591     break;
5592 
5593   case Builtin::BI__sync_and_and_fetch:
5594   case Builtin::BI__sync_and_and_fetch_1:
5595   case Builtin::BI__sync_and_and_fetch_2:
5596   case Builtin::BI__sync_and_and_fetch_4:
5597   case Builtin::BI__sync_and_and_fetch_8:
5598   case Builtin::BI__sync_and_and_fetch_16:
5599     BuiltinIndex = 8;
5600     break;
5601 
5602   case Builtin::BI__sync_or_and_fetch:
5603   case Builtin::BI__sync_or_and_fetch_1:
5604   case Builtin::BI__sync_or_and_fetch_2:
5605   case Builtin::BI__sync_or_and_fetch_4:
5606   case Builtin::BI__sync_or_and_fetch_8:
5607   case Builtin::BI__sync_or_and_fetch_16:
5608     BuiltinIndex = 9;
5609     break;
5610 
5611   case Builtin::BI__sync_xor_and_fetch:
5612   case Builtin::BI__sync_xor_and_fetch_1:
5613   case Builtin::BI__sync_xor_and_fetch_2:
5614   case Builtin::BI__sync_xor_and_fetch_4:
5615   case Builtin::BI__sync_xor_and_fetch_8:
5616   case Builtin::BI__sync_xor_and_fetch_16:
5617     BuiltinIndex = 10;
5618     break;
5619 
5620   case Builtin::BI__sync_nand_and_fetch:
5621   case Builtin::BI__sync_nand_and_fetch_1:
5622   case Builtin::BI__sync_nand_and_fetch_2:
5623   case Builtin::BI__sync_nand_and_fetch_4:
5624   case Builtin::BI__sync_nand_and_fetch_8:
5625   case Builtin::BI__sync_nand_and_fetch_16:
5626     BuiltinIndex = 11;
5627     WarnAboutSemanticsChange = true;
5628     break;
5629 
5630   case Builtin::BI__sync_val_compare_and_swap:
5631   case Builtin::BI__sync_val_compare_and_swap_1:
5632   case Builtin::BI__sync_val_compare_and_swap_2:
5633   case Builtin::BI__sync_val_compare_and_swap_4:
5634   case Builtin::BI__sync_val_compare_and_swap_8:
5635   case Builtin::BI__sync_val_compare_and_swap_16:
5636     BuiltinIndex = 12;
5637     NumFixed = 2;
5638     break;
5639 
5640   case Builtin::BI__sync_bool_compare_and_swap:
5641   case Builtin::BI__sync_bool_compare_and_swap_1:
5642   case Builtin::BI__sync_bool_compare_and_swap_2:
5643   case Builtin::BI__sync_bool_compare_and_swap_4:
5644   case Builtin::BI__sync_bool_compare_and_swap_8:
5645   case Builtin::BI__sync_bool_compare_and_swap_16:
5646     BuiltinIndex = 13;
5647     NumFixed = 2;
5648     ResultType = Context.BoolTy;
5649     break;
5650 
5651   case Builtin::BI__sync_lock_test_and_set:
5652   case Builtin::BI__sync_lock_test_and_set_1:
5653   case Builtin::BI__sync_lock_test_and_set_2:
5654   case Builtin::BI__sync_lock_test_and_set_4:
5655   case Builtin::BI__sync_lock_test_and_set_8:
5656   case Builtin::BI__sync_lock_test_and_set_16:
5657     BuiltinIndex = 14;
5658     break;
5659 
5660   case Builtin::BI__sync_lock_release:
5661   case Builtin::BI__sync_lock_release_1:
5662   case Builtin::BI__sync_lock_release_2:
5663   case Builtin::BI__sync_lock_release_4:
5664   case Builtin::BI__sync_lock_release_8:
5665   case Builtin::BI__sync_lock_release_16:
5666     BuiltinIndex = 15;
5667     NumFixed = 0;
5668     ResultType = Context.VoidTy;
5669     break;
5670 
5671   case Builtin::BI__sync_swap:
5672   case Builtin::BI__sync_swap_1:
5673   case Builtin::BI__sync_swap_2:
5674   case Builtin::BI__sync_swap_4:
5675   case Builtin::BI__sync_swap_8:
5676   case Builtin::BI__sync_swap_16:
5677     BuiltinIndex = 16;
5678     break;
5679   }
5680 
5681   // Now that we know how many fixed arguments we expect, first check that we
5682   // have at least that many.
5683   if (TheCall->getNumArgs() < 1+NumFixed) {
5684     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5685         << 0 << 1 + NumFixed << TheCall->getNumArgs()
5686         << Callee->getSourceRange();
5687     return ExprError();
5688   }
5689 
5690   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5691       << Callee->getSourceRange();
5692 
5693   if (WarnAboutSemanticsChange) {
5694     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
5695         << Callee->getSourceRange();
5696   }
5697 
5698   // Get the decl for the concrete builtin from this, we can tell what the
5699   // concrete integer type we should convert to is.
5700   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5701   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
5702   FunctionDecl *NewBuiltinDecl;
5703   if (NewBuiltinID == BuiltinID)
5704     NewBuiltinDecl = FDecl;
5705   else {
5706     // Perform builtin lookup to avoid redeclaring it.
5707     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
5708     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5709     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5710     assert(Res.getFoundDecl());
5711     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
5712     if (!NewBuiltinDecl)
5713       return ExprError();
5714   }
5715 
5716   // The first argument --- the pointer --- has a fixed type; we
5717   // deduce the types of the rest of the arguments accordingly.  Walk
5718   // the remaining arguments, converting them to the deduced value type.
5719   for (unsigned i = 0; i != NumFixed; ++i) {
5720     ExprResult Arg = TheCall->getArg(i+1);
5721 
5722     // GCC does an implicit conversion to the pointer or integer ValType.  This
5723     // can fail in some cases (1i -> int**), check for this error case now.
5724     // Initialize the argument.
5725     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5726                                                    ValType, /*consume*/ false);
5727     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5728     if (Arg.isInvalid())
5729       return ExprError();
5730 
5731     // Okay, we have something that *can* be converted to the right type.  Check
5732     // to see if there is a potentially weird extension going on here.  This can
5733     // happen when you do an atomic operation on something like an char* and
5734     // pass in 42.  The 42 gets converted to char.  This is even more strange
5735     // for things like 45.123 -> char, etc.
5736     // FIXME: Do this check.
5737     TheCall->setArg(i+1, Arg.get());
5738   }
5739 
5740   // Create a new DeclRefExpr to refer to the new decl.
5741   DeclRefExpr *NewDRE = DeclRefExpr::Create(
5742       Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
5743       /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
5744       DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
5745 
5746   // Set the callee in the CallExpr.
5747   // FIXME: This loses syntactic information.
5748   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5749   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5750                                               CK_BuiltinFnToFnPtr);
5751   TheCall->setCallee(PromotedCall.get());
5752 
5753   // Change the result type of the call to match the original value type. This
5754   // is arbitrary, but the codegen for these builtins ins design to handle it
5755   // gracefully.
5756   TheCall->setType(ResultType);
5757 
5758   // Prohibit use of _ExtInt with atomic builtins.
5759   // The arguments would have already been converted to the first argument's
5760   // type, so only need to check the first argument.
5761   const auto *ExtIntValType = ValType->getAs<ExtIntType>();
5762   if (ExtIntValType && !llvm::isPowerOf2_64(ExtIntValType->getNumBits())) {
5763     Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
5764     return ExprError();
5765   }
5766 
5767   return TheCallResult;
5768 }
5769 
5770 /// SemaBuiltinNontemporalOverloaded - We have a call to
5771 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
5772 /// overloaded function based on the pointer type of its last argument.
5773 ///
5774 /// This function goes through and does final semantic checking for these
5775 /// builtins.
5776 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5777   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5778   DeclRefExpr *DRE =
5779       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5780   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5781   unsigned BuiltinID = FDecl->getBuiltinID();
5782   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5783           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5784          "Unexpected nontemporal load/store builtin!");
5785   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5786   unsigned numArgs = isStore ? 2 : 1;
5787 
5788   // Ensure that we have the proper number of arguments.
5789   if (checkArgCount(*this, TheCall, numArgs))
5790     return ExprError();
5791 
5792   // Inspect the last argument of the nontemporal builtin.  This should always
5793   // be a pointer type, from which we imply the type of the memory access.
5794   // Because it is a pointer type, we don't have to worry about any implicit
5795   // casts here.
5796   Expr *PointerArg = TheCall->getArg(numArgs - 1);
5797   ExprResult PointerArgResult =
5798       DefaultFunctionArrayLvalueConversion(PointerArg);
5799 
5800   if (PointerArgResult.isInvalid())
5801     return ExprError();
5802   PointerArg = PointerArgResult.get();
5803   TheCall->setArg(numArgs - 1, PointerArg);
5804 
5805   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5806   if (!pointerType) {
5807     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
5808         << PointerArg->getType() << PointerArg->getSourceRange();
5809     return ExprError();
5810   }
5811 
5812   QualType ValType = pointerType->getPointeeType();
5813 
5814   // Strip any qualifiers off ValType.
5815   ValType = ValType.getUnqualifiedType();
5816   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5817       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5818       !ValType->isVectorType()) {
5819     Diag(DRE->getBeginLoc(),
5820          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5821         << PointerArg->getType() << PointerArg->getSourceRange();
5822     return ExprError();
5823   }
5824 
5825   if (!isStore) {
5826     TheCall->setType(ValType);
5827     return TheCallResult;
5828   }
5829 
5830   ExprResult ValArg = TheCall->getArg(0);
5831   InitializedEntity Entity = InitializedEntity::InitializeParameter(
5832       Context, ValType, /*consume*/ false);
5833   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
5834   if (ValArg.isInvalid())
5835     return ExprError();
5836 
5837   TheCall->setArg(0, ValArg.get());
5838   TheCall->setType(Context.VoidTy);
5839   return TheCallResult;
5840 }
5841 
5842 /// CheckObjCString - Checks that the argument to the builtin
5843 /// CFString constructor is correct
5844 /// Note: It might also make sense to do the UTF-16 conversion here (would
5845 /// simplify the backend).
5846 bool Sema::CheckObjCString(Expr *Arg) {
5847   Arg = Arg->IgnoreParenCasts();
5848   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
5849 
5850   if (!Literal || !Literal->isAscii()) {
5851     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
5852         << Arg->getSourceRange();
5853     return true;
5854   }
5855 
5856   if (Literal->containsNonAsciiOrNull()) {
5857     StringRef String = Literal->getString();
5858     unsigned NumBytes = String.size();
5859     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
5860     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
5861     llvm::UTF16 *ToPtr = &ToBuf[0];
5862 
5863     llvm::ConversionResult Result =
5864         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
5865                                  ToPtr + NumBytes, llvm::strictConversion);
5866     // Check for conversion failure.
5867     if (Result != llvm::conversionOK)
5868       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
5869           << Arg->getSourceRange();
5870   }
5871   return false;
5872 }
5873 
5874 /// CheckObjCString - Checks that the format string argument to the os_log()
5875 /// and os_trace() functions is correct, and converts it to const char *.
5876 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5877   Arg = Arg->IgnoreParenCasts();
5878   auto *Literal = dyn_cast<StringLiteral>(Arg);
5879   if (!Literal) {
5880     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
5881       Literal = ObjcLiteral->getString();
5882     }
5883   }
5884 
5885   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
5886     return ExprError(
5887         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
5888         << Arg->getSourceRange());
5889   }
5890 
5891   ExprResult Result(Literal);
5892   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
5893   InitializedEntity Entity =
5894       InitializedEntity::InitializeParameter(Context, ResultTy, false);
5895   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
5896   return Result;
5897 }
5898 
5899 /// Check that the user is calling the appropriate va_start builtin for the
5900 /// target and calling convention.
5901 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5902   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5903   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
5904   bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
5905                     TT.getArch() == llvm::Triple::aarch64_32);
5906   bool IsWindows = TT.isOSWindows();
5907   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5908   if (IsX64 || IsAArch64) {
5909     CallingConv CC = CC_C;
5910     if (const FunctionDecl *FD = S.getCurFunctionDecl())
5911       CC = FD->getType()->castAs<FunctionType>()->getCallConv();
5912     if (IsMSVAStart) {
5913       // Don't allow this in System V ABI functions.
5914       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
5915         return S.Diag(Fn->getBeginLoc(),
5916                       diag::err_ms_va_start_used_in_sysv_function);
5917     } else {
5918       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
5919       // On x64 Windows, don't allow this in System V ABI functions.
5920       // (Yes, that means there's no corresponding way to support variadic
5921       // System V ABI functions on Windows.)
5922       if ((IsWindows && CC == CC_X86_64SysV) ||
5923           (!IsWindows && CC == CC_Win64))
5924         return S.Diag(Fn->getBeginLoc(),
5925                       diag::err_va_start_used_in_wrong_abi_function)
5926                << !IsWindows;
5927     }
5928     return false;
5929   }
5930 
5931   if (IsMSVAStart)
5932     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
5933   return false;
5934 }
5935 
5936 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
5937                                              ParmVarDecl **LastParam = nullptr) {
5938   // Determine whether the current function, block, or obj-c method is variadic
5939   // and get its parameter list.
5940   bool IsVariadic = false;
5941   ArrayRef<ParmVarDecl *> Params;
5942   DeclContext *Caller = S.CurContext;
5943   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
5944     IsVariadic = Block->isVariadic();
5945     Params = Block->parameters();
5946   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
5947     IsVariadic = FD->isVariadic();
5948     Params = FD->parameters();
5949   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
5950     IsVariadic = MD->isVariadic();
5951     // FIXME: This isn't correct for methods (results in bogus warning).
5952     Params = MD->parameters();
5953   } else if (isa<CapturedDecl>(Caller)) {
5954     // We don't support va_start in a CapturedDecl.
5955     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
5956     return true;
5957   } else {
5958     // This must be some other declcontext that parses exprs.
5959     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
5960     return true;
5961   }
5962 
5963   if (!IsVariadic) {
5964     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
5965     return true;
5966   }
5967 
5968   if (LastParam)
5969     *LastParam = Params.empty() ? nullptr : Params.back();
5970 
5971   return false;
5972 }
5973 
5974 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
5975 /// for validity.  Emit an error and return true on failure; return false
5976 /// on success.
5977 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5978   Expr *Fn = TheCall->getCallee();
5979 
5980   if (checkVAStartABI(*this, BuiltinID, Fn))
5981     return true;
5982 
5983   if (checkArgCount(*this, TheCall, 2))
5984     return true;
5985 
5986   // Type-check the first argument normally.
5987   if (checkBuiltinArgument(*this, TheCall, 0))
5988     return true;
5989 
5990   // Check that the current function is variadic, and get its last parameter.
5991   ParmVarDecl *LastParam;
5992   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
5993     return true;
5994 
5995   // Verify that the second argument to the builtin is the last argument of the
5996   // current function or method.
5997   bool SecondArgIsLastNamedArgument = false;
5998   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
5999 
6000   // These are valid if SecondArgIsLastNamedArgument is false after the next
6001   // block.
6002   QualType Type;
6003   SourceLocation ParamLoc;
6004   bool IsCRegister = false;
6005 
6006   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
6007     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
6008       SecondArgIsLastNamedArgument = PV == LastParam;
6009 
6010       Type = PV->getType();
6011       ParamLoc = PV->getLocation();
6012       IsCRegister =
6013           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
6014     }
6015   }
6016 
6017   if (!SecondArgIsLastNamedArgument)
6018     Diag(TheCall->getArg(1)->getBeginLoc(),
6019          diag::warn_second_arg_of_va_start_not_last_named_param);
6020   else if (IsCRegister || Type->isReferenceType() ||
6021            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
6022              // Promotable integers are UB, but enumerations need a bit of
6023              // extra checking to see what their promotable type actually is.
6024              if (!Type->isPromotableIntegerType())
6025                return false;
6026              if (!Type->isEnumeralType())
6027                return true;
6028              const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
6029              return !(ED &&
6030                       Context.typesAreCompatible(ED->getPromotionType(), Type));
6031            }()) {
6032     unsigned Reason = 0;
6033     if (Type->isReferenceType())  Reason = 1;
6034     else if (IsCRegister)         Reason = 2;
6035     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
6036     Diag(ParamLoc, diag::note_parameter_type) << Type;
6037   }
6038 
6039   TheCall->setType(Context.VoidTy);
6040   return false;
6041 }
6042 
6043 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
6044   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
6045   //                 const char *named_addr);
6046 
6047   Expr *Func = Call->getCallee();
6048 
6049   if (Call->getNumArgs() < 3)
6050     return Diag(Call->getEndLoc(),
6051                 diag::err_typecheck_call_too_few_args_at_least)
6052            << 0 /*function call*/ << 3 << Call->getNumArgs();
6053 
6054   // Type-check the first argument normally.
6055   if (checkBuiltinArgument(*this, Call, 0))
6056     return true;
6057 
6058   // Check that the current function is variadic.
6059   if (checkVAStartIsInVariadicFunction(*this, Func))
6060     return true;
6061 
6062   // __va_start on Windows does not validate the parameter qualifiers
6063 
6064   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
6065   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
6066 
6067   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
6068   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
6069 
6070   const QualType &ConstCharPtrTy =
6071       Context.getPointerType(Context.CharTy.withConst());
6072   if (!Arg1Ty->isPointerType() ||
6073       Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
6074     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6075         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
6076         << 0                                      /* qualifier difference */
6077         << 3                                      /* parameter mismatch */
6078         << 2 << Arg1->getType() << ConstCharPtrTy;
6079 
6080   const QualType SizeTy = Context.getSizeType();
6081   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
6082     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6083         << Arg2->getType() << SizeTy << 1 /* different class */
6084         << 0                              /* qualifier difference */
6085         << 3                              /* parameter mismatch */
6086         << 3 << Arg2->getType() << SizeTy;
6087 
6088   return false;
6089 }
6090 
6091 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
6092 /// friends.  This is declared to take (...), so we have to check everything.
6093 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
6094   if (checkArgCount(*this, TheCall, 2))
6095     return true;
6096 
6097   ExprResult OrigArg0 = TheCall->getArg(0);
6098   ExprResult OrigArg1 = TheCall->getArg(1);
6099 
6100   // Do standard promotions between the two arguments, returning their common
6101   // type.
6102   QualType Res = UsualArithmeticConversions(
6103       OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
6104   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
6105     return true;
6106 
6107   // Make sure any conversions are pushed back into the call; this is
6108   // type safe since unordered compare builtins are declared as "_Bool
6109   // foo(...)".
6110   TheCall->setArg(0, OrigArg0.get());
6111   TheCall->setArg(1, OrigArg1.get());
6112 
6113   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
6114     return false;
6115 
6116   // If the common type isn't a real floating type, then the arguments were
6117   // invalid for this operation.
6118   if (Res.isNull() || !Res->isRealFloatingType())
6119     return Diag(OrigArg0.get()->getBeginLoc(),
6120                 diag::err_typecheck_call_invalid_ordered_compare)
6121            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
6122            << SourceRange(OrigArg0.get()->getBeginLoc(),
6123                           OrigArg1.get()->getEndLoc());
6124 
6125   return false;
6126 }
6127 
6128 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
6129 /// __builtin_isnan and friends.  This is declared to take (...), so we have
6130 /// to check everything. We expect the last argument to be a floating point
6131 /// value.
6132 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
6133   if (checkArgCount(*this, TheCall, NumArgs))
6134     return true;
6135 
6136   // __builtin_fpclassify is the only case where NumArgs != 1, so we can count
6137   // on all preceding parameters just being int.  Try all of those.
6138   for (unsigned i = 0; i < NumArgs - 1; ++i) {
6139     Expr *Arg = TheCall->getArg(i);
6140 
6141     if (Arg->isTypeDependent())
6142       return false;
6143 
6144     ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);
6145 
6146     if (Res.isInvalid())
6147       return true;
6148     TheCall->setArg(i, Res.get());
6149   }
6150 
6151   Expr *OrigArg = TheCall->getArg(NumArgs-1);
6152 
6153   if (OrigArg->isTypeDependent())
6154     return false;
6155 
6156   // Usual Unary Conversions will convert half to float, which we want for
6157   // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
6158   // type how it is, but do normal L->Rvalue conversions.
6159   if (Context.getTargetInfo().useFP16ConversionIntrinsics())
6160     OrigArg = UsualUnaryConversions(OrigArg).get();
6161   else
6162     OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
6163   TheCall->setArg(NumArgs - 1, OrigArg);
6164 
6165   // This operation requires a non-_Complex floating-point number.
6166   if (!OrigArg->getType()->isRealFloatingType())
6167     return Diag(OrigArg->getBeginLoc(),
6168                 diag::err_typecheck_call_invalid_unary_fp)
6169            << OrigArg->getType() << OrigArg->getSourceRange();
6170 
6171   return false;
6172 }
6173 
6174 /// Perform semantic analysis for a call to __builtin_complex.
6175 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) {
6176   if (checkArgCount(*this, TheCall, 2))
6177     return true;
6178 
6179   bool Dependent = false;
6180   for (unsigned I = 0; I != 2; ++I) {
6181     Expr *Arg = TheCall->getArg(I);
6182     QualType T = Arg->getType();
6183     if (T->isDependentType()) {
6184       Dependent = true;
6185       continue;
6186     }
6187 
6188     // Despite supporting _Complex int, GCC requires a real floating point type
6189     // for the operands of __builtin_complex.
6190     if (!T->isRealFloatingType()) {
6191       return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
6192              << Arg->getType() << Arg->getSourceRange();
6193     }
6194 
6195     ExprResult Converted = DefaultLvalueConversion(Arg);
6196     if (Converted.isInvalid())
6197       return true;
6198     TheCall->setArg(I, Converted.get());
6199   }
6200 
6201   if (Dependent) {
6202     TheCall->setType(Context.DependentTy);
6203     return false;
6204   }
6205 
6206   Expr *Real = TheCall->getArg(0);
6207   Expr *Imag = TheCall->getArg(1);
6208   if (!Context.hasSameType(Real->getType(), Imag->getType())) {
6209     return Diag(Real->getBeginLoc(),
6210                 diag::err_typecheck_call_different_arg_types)
6211            << Real->getType() << Imag->getType()
6212            << Real->getSourceRange() << Imag->getSourceRange();
6213   }
6214 
6215   // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers;
6216   // don't allow this builtin to form those types either.
6217   // FIXME: Should we allow these types?
6218   if (Real->getType()->isFloat16Type())
6219     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6220            << "_Float16";
6221   if (Real->getType()->isHalfType())
6222     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6223            << "half";
6224 
6225   TheCall->setType(Context.getComplexType(Real->getType()));
6226   return false;
6227 }
6228 
6229 // Customized Sema Checking for VSX builtins that have the following signature:
6230 // vector [...] builtinName(vector [...], vector [...], const int);
6231 // Which takes the same type of vectors (any legal vector type) for the first
6232 // two arguments and takes compile time constant for the third argument.
6233 // Example builtins are :
6234 // vector double vec_xxpermdi(vector double, vector double, int);
6235 // vector short vec_xxsldwi(vector short, vector short, int);
6236 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
6237   unsigned ExpectedNumArgs = 3;
6238   if (checkArgCount(*this, TheCall, ExpectedNumArgs))
6239     return true;
6240 
6241   // Check the third argument is a compile time constant
6242   if (!TheCall->getArg(2)->isIntegerConstantExpr(Context))
6243     return Diag(TheCall->getBeginLoc(),
6244                 diag::err_vsx_builtin_nonconstant_argument)
6245            << 3 /* argument index */ << TheCall->getDirectCallee()
6246            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
6247                           TheCall->getArg(2)->getEndLoc());
6248 
6249   QualType Arg1Ty = TheCall->getArg(0)->getType();
6250   QualType Arg2Ty = TheCall->getArg(1)->getType();
6251 
6252   // Check the type of argument 1 and argument 2 are vectors.
6253   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
6254   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
6255       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
6256     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
6257            << TheCall->getDirectCallee()
6258            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6259                           TheCall->getArg(1)->getEndLoc());
6260   }
6261 
6262   // Check the first two arguments are the same type.
6263   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
6264     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
6265            << TheCall->getDirectCallee()
6266            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6267                           TheCall->getArg(1)->getEndLoc());
6268   }
6269 
6270   // When default clang type checking is turned off and the customized type
6271   // checking is used, the returning type of the function must be explicitly
6272   // set. Otherwise it is _Bool by default.
6273   TheCall->setType(Arg1Ty);
6274 
6275   return false;
6276 }
6277 
6278 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
6279 // This is declared to take (...), so we have to check everything.
6280 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
6281   if (TheCall->getNumArgs() < 2)
6282     return ExprError(Diag(TheCall->getEndLoc(),
6283                           diag::err_typecheck_call_too_few_args_at_least)
6284                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
6285                      << TheCall->getSourceRange());
6286 
6287   // Determine which of the following types of shufflevector we're checking:
6288   // 1) unary, vector mask: (lhs, mask)
6289   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
6290   QualType resType = TheCall->getArg(0)->getType();
6291   unsigned numElements = 0;
6292 
6293   if (!TheCall->getArg(0)->isTypeDependent() &&
6294       !TheCall->getArg(1)->isTypeDependent()) {
6295     QualType LHSType = TheCall->getArg(0)->getType();
6296     QualType RHSType = TheCall->getArg(1)->getType();
6297 
6298     if (!LHSType->isVectorType() || !RHSType->isVectorType())
6299       return ExprError(
6300           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
6301           << TheCall->getDirectCallee()
6302           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6303                          TheCall->getArg(1)->getEndLoc()));
6304 
6305     numElements = LHSType->castAs<VectorType>()->getNumElements();
6306     unsigned numResElements = TheCall->getNumArgs() - 2;
6307 
6308     // Check to see if we have a call with 2 vector arguments, the unary shuffle
6309     // with mask.  If so, verify that RHS is an integer vector type with the
6310     // same number of elts as lhs.
6311     if (TheCall->getNumArgs() == 2) {
6312       if (!RHSType->hasIntegerRepresentation() ||
6313           RHSType->castAs<VectorType>()->getNumElements() != numElements)
6314         return ExprError(Diag(TheCall->getBeginLoc(),
6315                               diag::err_vec_builtin_incompatible_vector)
6316                          << TheCall->getDirectCallee()
6317                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
6318                                         TheCall->getArg(1)->getEndLoc()));
6319     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
6320       return ExprError(Diag(TheCall->getBeginLoc(),
6321                             diag::err_vec_builtin_incompatible_vector)
6322                        << TheCall->getDirectCallee()
6323                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6324                                       TheCall->getArg(1)->getEndLoc()));
6325     } else if (numElements != numResElements) {
6326       QualType eltType = LHSType->castAs<VectorType>()->getElementType();
6327       resType = Context.getVectorType(eltType, numResElements,
6328                                       VectorType::GenericVector);
6329     }
6330   }
6331 
6332   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
6333     if (TheCall->getArg(i)->isTypeDependent() ||
6334         TheCall->getArg(i)->isValueDependent())
6335       continue;
6336 
6337     Optional<llvm::APSInt> Result;
6338     if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context)))
6339       return ExprError(Diag(TheCall->getBeginLoc(),
6340                             diag::err_shufflevector_nonconstant_argument)
6341                        << TheCall->getArg(i)->getSourceRange());
6342 
6343     // Allow -1 which will be translated to undef in the IR.
6344     if (Result->isSigned() && Result->isAllOnesValue())
6345       continue;
6346 
6347     if (Result->getActiveBits() > 64 ||
6348         Result->getZExtValue() >= numElements * 2)
6349       return ExprError(Diag(TheCall->getBeginLoc(),
6350                             diag::err_shufflevector_argument_too_large)
6351                        << TheCall->getArg(i)->getSourceRange());
6352   }
6353 
6354   SmallVector<Expr*, 32> exprs;
6355 
6356   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
6357     exprs.push_back(TheCall->getArg(i));
6358     TheCall->setArg(i, nullptr);
6359   }
6360 
6361   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
6362                                          TheCall->getCallee()->getBeginLoc(),
6363                                          TheCall->getRParenLoc());
6364 }
6365 
6366 /// SemaConvertVectorExpr - Handle __builtin_convertvector
6367 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
6368                                        SourceLocation BuiltinLoc,
6369                                        SourceLocation RParenLoc) {
6370   ExprValueKind VK = VK_PRValue;
6371   ExprObjectKind OK = OK_Ordinary;
6372   QualType DstTy = TInfo->getType();
6373   QualType SrcTy = E->getType();
6374 
6375   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
6376     return ExprError(Diag(BuiltinLoc,
6377                           diag::err_convertvector_non_vector)
6378                      << E->getSourceRange());
6379   if (!DstTy->isVectorType() && !DstTy->isDependentType())
6380     return ExprError(Diag(BuiltinLoc,
6381                           diag::err_convertvector_non_vector_type));
6382 
6383   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
6384     unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
6385     unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
6386     if (SrcElts != DstElts)
6387       return ExprError(Diag(BuiltinLoc,
6388                             diag::err_convertvector_incompatible_vector)
6389                        << E->getSourceRange());
6390   }
6391 
6392   return new (Context)
6393       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
6394 }
6395 
6396 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
6397 // This is declared to take (const void*, ...) and can take two
6398 // optional constant int args.
6399 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
6400   unsigned NumArgs = TheCall->getNumArgs();
6401 
6402   if (NumArgs > 3)
6403     return Diag(TheCall->getEndLoc(),
6404                 diag::err_typecheck_call_too_many_args_at_most)
6405            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6406 
6407   // Argument 0 is checked for us and the remaining arguments must be
6408   // constant integers.
6409   for (unsigned i = 1; i != NumArgs; ++i)
6410     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
6411       return true;
6412 
6413   return false;
6414 }
6415 
6416 /// SemaBuiltinAssume - Handle __assume (MS Extension).
6417 // __assume does not evaluate its arguments, and should warn if its argument
6418 // has side effects.
6419 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
6420   Expr *Arg = TheCall->getArg(0);
6421   if (Arg->isInstantiationDependent()) return false;
6422 
6423   if (Arg->HasSideEffects(Context))
6424     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
6425         << Arg->getSourceRange()
6426         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
6427 
6428   return false;
6429 }
6430 
6431 /// Handle __builtin_alloca_with_align. This is declared
6432 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
6433 /// than 8.
6434 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
6435   // The alignment must be a constant integer.
6436   Expr *Arg = TheCall->getArg(1);
6437 
6438   // We can't check the value of a dependent argument.
6439   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6440     if (const auto *UE =
6441             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
6442       if (UE->getKind() == UETT_AlignOf ||
6443           UE->getKind() == UETT_PreferredAlignOf)
6444         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
6445             << Arg->getSourceRange();
6446 
6447     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
6448 
6449     if (!Result.isPowerOf2())
6450       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6451              << Arg->getSourceRange();
6452 
6453     if (Result < Context.getCharWidth())
6454       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
6455              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6456 
6457     if (Result > std::numeric_limits<int32_t>::max())
6458       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
6459              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6460   }
6461 
6462   return false;
6463 }
6464 
6465 /// Handle __builtin_assume_aligned. This is declared
6466 /// as (const void*, size_t, ...) and can take one optional constant int arg.
6467 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
6468   unsigned NumArgs = TheCall->getNumArgs();
6469 
6470   if (NumArgs > 3)
6471     return Diag(TheCall->getEndLoc(),
6472                 diag::err_typecheck_call_too_many_args_at_most)
6473            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6474 
6475   // The alignment must be a constant integer.
6476   Expr *Arg = TheCall->getArg(1);
6477 
6478   // We can't check the value of a dependent argument.
6479   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6480     llvm::APSInt Result;
6481     if (SemaBuiltinConstantArg(TheCall, 1, Result))
6482       return true;
6483 
6484     if (!Result.isPowerOf2())
6485       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6486              << Arg->getSourceRange();
6487 
6488     if (Result > Sema::MaximumAlignment)
6489       Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
6490           << Arg->getSourceRange() << Sema::MaximumAlignment;
6491   }
6492 
6493   if (NumArgs > 2) {
6494     ExprResult Arg(TheCall->getArg(2));
6495     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6496       Context.getSizeType(), false);
6497     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6498     if (Arg.isInvalid()) return true;
6499     TheCall->setArg(2, Arg.get());
6500   }
6501 
6502   return false;
6503 }
6504 
6505 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
6506   unsigned BuiltinID =
6507       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
6508   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6509 
6510   unsigned NumArgs = TheCall->getNumArgs();
6511   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6512   if (NumArgs < NumRequiredArgs) {
6513     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
6514            << 0 /* function call */ << NumRequiredArgs << NumArgs
6515            << TheCall->getSourceRange();
6516   }
6517   if (NumArgs >= NumRequiredArgs + 0x100) {
6518     return Diag(TheCall->getEndLoc(),
6519                 diag::err_typecheck_call_too_many_args_at_most)
6520            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6521            << TheCall->getSourceRange();
6522   }
6523   unsigned i = 0;
6524 
6525   // For formatting call, check buffer arg.
6526   if (!IsSizeCall) {
6527     ExprResult Arg(TheCall->getArg(i));
6528     InitializedEntity Entity = InitializedEntity::InitializeParameter(
6529         Context, Context.VoidPtrTy, false);
6530     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6531     if (Arg.isInvalid())
6532       return true;
6533     TheCall->setArg(i, Arg.get());
6534     i++;
6535   }
6536 
6537   // Check string literal arg.
6538   unsigned FormatIdx = i;
6539   {
6540     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
6541     if (Arg.isInvalid())
6542       return true;
6543     TheCall->setArg(i, Arg.get());
6544     i++;
6545   }
6546 
6547   // Make sure variadic args are scalar.
6548   unsigned FirstDataArg = i;
6549   while (i < NumArgs) {
6550     ExprResult Arg = DefaultVariadicArgumentPromotion(
6551         TheCall->getArg(i), VariadicFunction, nullptr);
6552     if (Arg.isInvalid())
6553       return true;
6554     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
6555     if (ArgSize.getQuantity() >= 0x100) {
6556       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
6557              << i << (int)ArgSize.getQuantity() << 0xff
6558              << TheCall->getSourceRange();
6559     }
6560     TheCall->setArg(i, Arg.get());
6561     i++;
6562   }
6563 
6564   // Check formatting specifiers. NOTE: We're only doing this for the non-size
6565   // call to avoid duplicate diagnostics.
6566   if (!IsSizeCall) {
6567     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6568     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6569     bool Success = CheckFormatArguments(
6570         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
6571         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
6572         CheckedVarArgs);
6573     if (!Success)
6574       return true;
6575   }
6576 
6577   if (IsSizeCall) {
6578     TheCall->setType(Context.getSizeType());
6579   } else {
6580     TheCall->setType(Context.VoidPtrTy);
6581   }
6582   return false;
6583 }
6584 
6585 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
6586 /// TheCall is a constant expression.
6587 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
6588                                   llvm::APSInt &Result) {
6589   Expr *Arg = TheCall->getArg(ArgNum);
6590   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6591   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6592 
6593   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
6594 
6595   Optional<llvm::APSInt> R;
6596   if (!(R = Arg->getIntegerConstantExpr(Context)))
6597     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6598            << FDecl->getDeclName() << Arg->getSourceRange();
6599   Result = *R;
6600   return false;
6601 }
6602 
6603 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
6604 /// TheCall is a constant expression in the range [Low, High].
6605 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
6606                                        int Low, int High, bool RangeIsError) {
6607   if (isConstantEvaluated())
6608     return false;
6609   llvm::APSInt Result;
6610 
6611   // We can't check the value of a dependent argument.
6612   Expr *Arg = TheCall->getArg(ArgNum);
6613   if (Arg->isTypeDependent() || Arg->isValueDependent())
6614     return false;
6615 
6616   // Check constant-ness first.
6617   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6618     return true;
6619 
6620   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6621     if (RangeIsError)
6622       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
6623              << toString(Result, 10) << Low << High << Arg->getSourceRange();
6624     else
6625       // Defer the warning until we know if the code will be emitted so that
6626       // dead code can ignore this.
6627       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6628                           PDiag(diag::warn_argument_invalid_range)
6629                               << toString(Result, 10) << Low << High
6630                               << Arg->getSourceRange());
6631   }
6632 
6633   return false;
6634 }
6635 
6636 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
6637 /// TheCall is a constant expression is a multiple of Num..
6638 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
6639                                           unsigned Num) {
6640   llvm::APSInt Result;
6641 
6642   // We can't check the value of a dependent argument.
6643   Expr *Arg = TheCall->getArg(ArgNum);
6644   if (Arg->isTypeDependent() || Arg->isValueDependent())
6645     return false;
6646 
6647   // Check constant-ness first.
6648   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6649     return true;
6650 
6651   if (Result.getSExtValue() % Num != 0)
6652     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6653            << Num << Arg->getSourceRange();
6654 
6655   return false;
6656 }
6657 
6658 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
6659 /// constant expression representing a power of 2.
6660 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
6661   llvm::APSInt Result;
6662 
6663   // We can't check the value of a dependent argument.
6664   Expr *Arg = TheCall->getArg(ArgNum);
6665   if (Arg->isTypeDependent() || Arg->isValueDependent())
6666     return false;
6667 
6668   // Check constant-ness first.
6669   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6670     return true;
6671 
6672   // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
6673   // and only if x is a power of 2.
6674   if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
6675     return false;
6676 
6677   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
6678          << Arg->getSourceRange();
6679 }
6680 
6681 static bool IsShiftedByte(llvm::APSInt Value) {
6682   if (Value.isNegative())
6683     return false;
6684 
6685   // Check if it's a shifted byte, by shifting it down
6686   while (true) {
6687     // If the value fits in the bottom byte, the check passes.
6688     if (Value < 0x100)
6689       return true;
6690 
6691     // Otherwise, if the value has _any_ bits in the bottom byte, the check
6692     // fails.
6693     if ((Value & 0xFF) != 0)
6694       return false;
6695 
6696     // If the bottom 8 bits are all 0, but something above that is nonzero,
6697     // then shifting the value right by 8 bits won't affect whether it's a
6698     // shifted byte or not. So do that, and go round again.
6699     Value >>= 8;
6700   }
6701 }
6702 
6703 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
6704 /// a constant expression representing an arbitrary byte value shifted left by
6705 /// a multiple of 8 bits.
6706 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
6707                                              unsigned ArgBits) {
6708   llvm::APSInt Result;
6709 
6710   // We can't check the value of a dependent argument.
6711   Expr *Arg = TheCall->getArg(ArgNum);
6712   if (Arg->isTypeDependent() || Arg->isValueDependent())
6713     return false;
6714 
6715   // Check constant-ness first.
6716   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6717     return true;
6718 
6719   // Truncate to the given size.
6720   Result = Result.getLoBits(ArgBits);
6721   Result.setIsUnsigned(true);
6722 
6723   if (IsShiftedByte(Result))
6724     return false;
6725 
6726   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
6727          << Arg->getSourceRange();
6728 }
6729 
6730 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
6731 /// TheCall is a constant expression representing either a shifted byte value,
6732 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
6733 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
6734 /// Arm MVE intrinsics.
6735 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
6736                                                    int ArgNum,
6737                                                    unsigned ArgBits) {
6738   llvm::APSInt Result;
6739 
6740   // We can't check the value of a dependent argument.
6741   Expr *Arg = TheCall->getArg(ArgNum);
6742   if (Arg->isTypeDependent() || Arg->isValueDependent())
6743     return false;
6744 
6745   // Check constant-ness first.
6746   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6747     return true;
6748 
6749   // Truncate to the given size.
6750   Result = Result.getLoBits(ArgBits);
6751   Result.setIsUnsigned(true);
6752 
6753   // Check to see if it's in either of the required forms.
6754   if (IsShiftedByte(Result) ||
6755       (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
6756     return false;
6757 
6758   return Diag(TheCall->getBeginLoc(),
6759               diag::err_argument_not_shifted_byte_or_xxff)
6760          << Arg->getSourceRange();
6761 }
6762 
6763 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
6764 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
6765   if (BuiltinID == AArch64::BI__builtin_arm_irg) {
6766     if (checkArgCount(*this, TheCall, 2))
6767       return true;
6768     Expr *Arg0 = TheCall->getArg(0);
6769     Expr *Arg1 = TheCall->getArg(1);
6770 
6771     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6772     if (FirstArg.isInvalid())
6773       return true;
6774     QualType FirstArgType = FirstArg.get()->getType();
6775     if (!FirstArgType->isAnyPointerType())
6776       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6777                << "first" << FirstArgType << Arg0->getSourceRange();
6778     TheCall->setArg(0, FirstArg.get());
6779 
6780     ExprResult SecArg = DefaultLvalueConversion(Arg1);
6781     if (SecArg.isInvalid())
6782       return true;
6783     QualType SecArgType = SecArg.get()->getType();
6784     if (!SecArgType->isIntegerType())
6785       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6786                << "second" << SecArgType << Arg1->getSourceRange();
6787 
6788     // Derive the return type from the pointer argument.
6789     TheCall->setType(FirstArgType);
6790     return false;
6791   }
6792 
6793   if (BuiltinID == AArch64::BI__builtin_arm_addg) {
6794     if (checkArgCount(*this, TheCall, 2))
6795       return true;
6796 
6797     Expr *Arg0 = TheCall->getArg(0);
6798     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6799     if (FirstArg.isInvalid())
6800       return true;
6801     QualType FirstArgType = FirstArg.get()->getType();
6802     if (!FirstArgType->isAnyPointerType())
6803       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6804                << "first" << FirstArgType << Arg0->getSourceRange();
6805     TheCall->setArg(0, FirstArg.get());
6806 
6807     // Derive the return type from the pointer argument.
6808     TheCall->setType(FirstArgType);
6809 
6810     // Second arg must be an constant in range [0,15]
6811     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6812   }
6813 
6814   if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
6815     if (checkArgCount(*this, TheCall, 2))
6816       return true;
6817     Expr *Arg0 = TheCall->getArg(0);
6818     Expr *Arg1 = TheCall->getArg(1);
6819 
6820     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6821     if (FirstArg.isInvalid())
6822       return true;
6823     QualType FirstArgType = FirstArg.get()->getType();
6824     if (!FirstArgType->isAnyPointerType())
6825       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6826                << "first" << FirstArgType << Arg0->getSourceRange();
6827 
6828     QualType SecArgType = Arg1->getType();
6829     if (!SecArgType->isIntegerType())
6830       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6831                << "second" << SecArgType << Arg1->getSourceRange();
6832     TheCall->setType(Context.IntTy);
6833     return false;
6834   }
6835 
6836   if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
6837       BuiltinID == AArch64::BI__builtin_arm_stg) {
6838     if (checkArgCount(*this, TheCall, 1))
6839       return true;
6840     Expr *Arg0 = TheCall->getArg(0);
6841     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6842     if (FirstArg.isInvalid())
6843       return true;
6844 
6845     QualType FirstArgType = FirstArg.get()->getType();
6846     if (!FirstArgType->isAnyPointerType())
6847       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6848                << "first" << FirstArgType << Arg0->getSourceRange();
6849     TheCall->setArg(0, FirstArg.get());
6850 
6851     // Derive the return type from the pointer argument.
6852     if (BuiltinID == AArch64::BI__builtin_arm_ldg)
6853       TheCall->setType(FirstArgType);
6854     return false;
6855   }
6856 
6857   if (BuiltinID == AArch64::BI__builtin_arm_subp) {
6858     Expr *ArgA = TheCall->getArg(0);
6859     Expr *ArgB = TheCall->getArg(1);
6860 
6861     ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
6862     ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
6863 
6864     if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
6865       return true;
6866 
6867     QualType ArgTypeA = ArgExprA.get()->getType();
6868     QualType ArgTypeB = ArgExprB.get()->getType();
6869 
6870     auto isNull = [&] (Expr *E) -> bool {
6871       return E->isNullPointerConstant(
6872                         Context, Expr::NPC_ValueDependentIsNotNull); };
6873 
6874     // argument should be either a pointer or null
6875     if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
6876       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6877         << "first" << ArgTypeA << ArgA->getSourceRange();
6878 
6879     if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
6880       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6881         << "second" << ArgTypeB << ArgB->getSourceRange();
6882 
6883     // Ensure Pointee types are compatible
6884     if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
6885         ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
6886       QualType pointeeA = ArgTypeA->getPointeeType();
6887       QualType pointeeB = ArgTypeB->getPointeeType();
6888       if (!Context.typesAreCompatible(
6889              Context.getCanonicalType(pointeeA).getUnqualifiedType(),
6890              Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
6891         return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
6892           << ArgTypeA <<  ArgTypeB << ArgA->getSourceRange()
6893           << ArgB->getSourceRange();
6894       }
6895     }
6896 
6897     // at least one argument should be pointer type
6898     if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
6899       return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
6900         <<  ArgTypeA << ArgTypeB << ArgA->getSourceRange();
6901 
6902     if (isNull(ArgA)) // adopt type of the other pointer
6903       ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
6904 
6905     if (isNull(ArgB))
6906       ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
6907 
6908     TheCall->setArg(0, ArgExprA.get());
6909     TheCall->setArg(1, ArgExprB.get());
6910     TheCall->setType(Context.LongLongTy);
6911     return false;
6912   }
6913   assert(false && "Unhandled ARM MTE intrinsic");
6914   return true;
6915 }
6916 
6917 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
6918 /// TheCall is an ARM/AArch64 special register string literal.
6919 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
6920                                     int ArgNum, unsigned ExpectedFieldNum,
6921                                     bool AllowName) {
6922   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
6923                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
6924                       BuiltinID == ARM::BI__builtin_arm_rsr ||
6925                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
6926                       BuiltinID == ARM::BI__builtin_arm_wsr ||
6927                       BuiltinID == ARM::BI__builtin_arm_wsrp;
6928   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
6929                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
6930                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
6931                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
6932                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
6933                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
6934   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
6935 
6936   // We can't check the value of a dependent argument.
6937   Expr *Arg = TheCall->getArg(ArgNum);
6938   if (Arg->isTypeDependent() || Arg->isValueDependent())
6939     return false;
6940 
6941   // Check if the argument is a string literal.
6942   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
6943     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
6944            << Arg->getSourceRange();
6945 
6946   // Check the type of special register given.
6947   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
6948   SmallVector<StringRef, 6> Fields;
6949   Reg.split(Fields, ":");
6950 
6951   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
6952     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6953            << Arg->getSourceRange();
6954 
6955   // If the string is the name of a register then we cannot check that it is
6956   // valid here but if the string is of one the forms described in ACLE then we
6957   // can check that the supplied fields are integers and within the valid
6958   // ranges.
6959   if (Fields.size() > 1) {
6960     bool FiveFields = Fields.size() == 5;
6961 
6962     bool ValidString = true;
6963     if (IsARMBuiltin) {
6964       ValidString &= Fields[0].startswith_lower("cp") ||
6965                      Fields[0].startswith_lower("p");
6966       if (ValidString)
6967         Fields[0] =
6968           Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
6969 
6970       ValidString &= Fields[2].startswith_lower("c");
6971       if (ValidString)
6972         Fields[2] = Fields[2].drop_front(1);
6973 
6974       if (FiveFields) {
6975         ValidString &= Fields[3].startswith_lower("c");
6976         if (ValidString)
6977           Fields[3] = Fields[3].drop_front(1);
6978       }
6979     }
6980 
6981     SmallVector<int, 5> Ranges;
6982     if (FiveFields)
6983       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
6984     else
6985       Ranges.append({15, 7, 15});
6986 
6987     for (unsigned i=0; i<Fields.size(); ++i) {
6988       int IntField;
6989       ValidString &= !Fields[i].getAsInteger(10, IntField);
6990       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
6991     }
6992 
6993     if (!ValidString)
6994       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6995              << Arg->getSourceRange();
6996   } else if (IsAArch64Builtin && Fields.size() == 1) {
6997     // If the register name is one of those that appear in the condition below
6998     // and the special register builtin being used is one of the write builtins,
6999     // then we require that the argument provided for writing to the register
7000     // is an integer constant expression. This is because it will be lowered to
7001     // an MSR (immediate) instruction, so we need to know the immediate at
7002     // compile time.
7003     if (TheCall->getNumArgs() != 2)
7004       return false;
7005 
7006     std::string RegLower = Reg.lower();
7007     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
7008         RegLower != "pan" && RegLower != "uao")
7009       return false;
7010 
7011     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
7012   }
7013 
7014   return false;
7015 }
7016 
7017 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity.
7018 /// Emit an error and return true on failure; return false on success.
7019 /// TypeStr is a string containing the type descriptor of the value returned by
7020 /// the builtin and the descriptors of the expected type of the arguments.
7021 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, const char *TypeStr) {
7022 
7023   assert((TypeStr[0] != '\0') &&
7024          "Invalid types in PPC MMA builtin declaration");
7025 
7026   unsigned Mask = 0;
7027   unsigned ArgNum = 0;
7028 
7029   // The first type in TypeStr is the type of the value returned by the
7030   // builtin. So we first read that type and change the type of TheCall.
7031   QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7032   TheCall->setType(type);
7033 
7034   while (*TypeStr != '\0') {
7035     Mask = 0;
7036     QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7037     if (ArgNum >= TheCall->getNumArgs()) {
7038       ArgNum++;
7039       break;
7040     }
7041 
7042     Expr *Arg = TheCall->getArg(ArgNum);
7043     QualType ArgType = Arg->getType();
7044 
7045     if ((ExpectedType->isVoidPointerType() && !ArgType->isPointerType()) ||
7046         (!ExpectedType->isVoidPointerType() &&
7047            ArgType.getCanonicalType() != ExpectedType))
7048       return Diag(Arg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
7049              << ArgType << ExpectedType << 1 << 0 << 0;
7050 
7051     // If the value of the Mask is not 0, we have a constraint in the size of
7052     // the integer argument so here we ensure the argument is a constant that
7053     // is in the valid range.
7054     if (Mask != 0 &&
7055         SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true))
7056       return true;
7057 
7058     ArgNum++;
7059   }
7060 
7061   // In case we exited early from the previous loop, there are other types to
7062   // read from TypeStr. So we need to read them all to ensure we have the right
7063   // number of arguments in TheCall and if it is not the case, to display a
7064   // better error message.
7065   while (*TypeStr != '\0') {
7066     (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7067     ArgNum++;
7068   }
7069   if (checkArgCount(*this, TheCall, ArgNum))
7070     return true;
7071 
7072   return false;
7073 }
7074 
7075 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
7076 /// This checks that the target supports __builtin_longjmp and
7077 /// that val is a constant 1.
7078 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
7079   if (!Context.getTargetInfo().hasSjLjLowering())
7080     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
7081            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7082 
7083   Expr *Arg = TheCall->getArg(1);
7084   llvm::APSInt Result;
7085 
7086   // TODO: This is less than ideal. Overload this to take a value.
7087   if (SemaBuiltinConstantArg(TheCall, 1, Result))
7088     return true;
7089 
7090   if (Result != 1)
7091     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
7092            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
7093 
7094   return false;
7095 }
7096 
7097 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
7098 /// This checks that the target supports __builtin_setjmp.
7099 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
7100   if (!Context.getTargetInfo().hasSjLjLowering())
7101     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
7102            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7103   return false;
7104 }
7105 
7106 namespace {
7107 
7108 class UncoveredArgHandler {
7109   enum { Unknown = -1, AllCovered = -2 };
7110 
7111   signed FirstUncoveredArg = Unknown;
7112   SmallVector<const Expr *, 4> DiagnosticExprs;
7113 
7114 public:
7115   UncoveredArgHandler() = default;
7116 
7117   bool hasUncoveredArg() const {
7118     return (FirstUncoveredArg >= 0);
7119   }
7120 
7121   unsigned getUncoveredArg() const {
7122     assert(hasUncoveredArg() && "no uncovered argument");
7123     return FirstUncoveredArg;
7124   }
7125 
7126   void setAllCovered() {
7127     // A string has been found with all arguments covered, so clear out
7128     // the diagnostics.
7129     DiagnosticExprs.clear();
7130     FirstUncoveredArg = AllCovered;
7131   }
7132 
7133   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
7134     assert(NewFirstUncoveredArg >= 0 && "Outside range");
7135 
7136     // Don't update if a previous string covers all arguments.
7137     if (FirstUncoveredArg == AllCovered)
7138       return;
7139 
7140     // UncoveredArgHandler tracks the highest uncovered argument index
7141     // and with it all the strings that match this index.
7142     if (NewFirstUncoveredArg == FirstUncoveredArg)
7143       DiagnosticExprs.push_back(StrExpr);
7144     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
7145       DiagnosticExprs.clear();
7146       DiagnosticExprs.push_back(StrExpr);
7147       FirstUncoveredArg = NewFirstUncoveredArg;
7148     }
7149   }
7150 
7151   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
7152 };
7153 
7154 enum StringLiteralCheckType {
7155   SLCT_NotALiteral,
7156   SLCT_UncheckedLiteral,
7157   SLCT_CheckedLiteral
7158 };
7159 
7160 } // namespace
7161 
7162 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
7163                                      BinaryOperatorKind BinOpKind,
7164                                      bool AddendIsRight) {
7165   unsigned BitWidth = Offset.getBitWidth();
7166   unsigned AddendBitWidth = Addend.getBitWidth();
7167   // There might be negative interim results.
7168   if (Addend.isUnsigned()) {
7169     Addend = Addend.zext(++AddendBitWidth);
7170     Addend.setIsSigned(true);
7171   }
7172   // Adjust the bit width of the APSInts.
7173   if (AddendBitWidth > BitWidth) {
7174     Offset = Offset.sext(AddendBitWidth);
7175     BitWidth = AddendBitWidth;
7176   } else if (BitWidth > AddendBitWidth) {
7177     Addend = Addend.sext(BitWidth);
7178   }
7179 
7180   bool Ov = false;
7181   llvm::APSInt ResOffset = Offset;
7182   if (BinOpKind == BO_Add)
7183     ResOffset = Offset.sadd_ov(Addend, Ov);
7184   else {
7185     assert(AddendIsRight && BinOpKind == BO_Sub &&
7186            "operator must be add or sub with addend on the right");
7187     ResOffset = Offset.ssub_ov(Addend, Ov);
7188   }
7189 
7190   // We add an offset to a pointer here so we should support an offset as big as
7191   // possible.
7192   if (Ov) {
7193     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
7194            "index (intermediate) result too big");
7195     Offset = Offset.sext(2 * BitWidth);
7196     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
7197     return;
7198   }
7199 
7200   Offset = ResOffset;
7201 }
7202 
7203 namespace {
7204 
7205 // This is a wrapper class around StringLiteral to support offsetted string
7206 // literals as format strings. It takes the offset into account when returning
7207 // the string and its length or the source locations to display notes correctly.
7208 class FormatStringLiteral {
7209   const StringLiteral *FExpr;
7210   int64_t Offset;
7211 
7212  public:
7213   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
7214       : FExpr(fexpr), Offset(Offset) {}
7215 
7216   StringRef getString() const {
7217     return FExpr->getString().drop_front(Offset);
7218   }
7219 
7220   unsigned getByteLength() const {
7221     return FExpr->getByteLength() - getCharByteWidth() * Offset;
7222   }
7223 
7224   unsigned getLength() const { return FExpr->getLength() - Offset; }
7225   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
7226 
7227   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
7228 
7229   QualType getType() const { return FExpr->getType(); }
7230 
7231   bool isAscii() const { return FExpr->isAscii(); }
7232   bool isWide() const { return FExpr->isWide(); }
7233   bool isUTF8() const { return FExpr->isUTF8(); }
7234   bool isUTF16() const { return FExpr->isUTF16(); }
7235   bool isUTF32() const { return FExpr->isUTF32(); }
7236   bool isPascal() const { return FExpr->isPascal(); }
7237 
7238   SourceLocation getLocationOfByte(
7239       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
7240       const TargetInfo &Target, unsigned *StartToken = nullptr,
7241       unsigned *StartTokenByteOffset = nullptr) const {
7242     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
7243                                     StartToken, StartTokenByteOffset);
7244   }
7245 
7246   SourceLocation getBeginLoc() const LLVM_READONLY {
7247     return FExpr->getBeginLoc().getLocWithOffset(Offset);
7248   }
7249 
7250   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
7251 };
7252 
7253 }  // namespace
7254 
7255 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
7256                               const Expr *OrigFormatExpr,
7257                               ArrayRef<const Expr *> Args,
7258                               bool HasVAListArg, unsigned format_idx,
7259                               unsigned firstDataArg,
7260                               Sema::FormatStringType Type,
7261                               bool inFunctionCall,
7262                               Sema::VariadicCallType CallType,
7263                               llvm::SmallBitVector &CheckedVarArgs,
7264                               UncoveredArgHandler &UncoveredArg,
7265                               bool IgnoreStringsWithoutSpecifiers);
7266 
7267 // Determine if an expression is a string literal or constant string.
7268 // If this function returns false on the arguments to a function expecting a
7269 // format string, we will usually need to emit a warning.
7270 // True string literals are then checked by CheckFormatString.
7271 static StringLiteralCheckType
7272 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
7273                       bool HasVAListArg, unsigned format_idx,
7274                       unsigned firstDataArg, Sema::FormatStringType Type,
7275                       Sema::VariadicCallType CallType, bool InFunctionCall,
7276                       llvm::SmallBitVector &CheckedVarArgs,
7277                       UncoveredArgHandler &UncoveredArg,
7278                       llvm::APSInt Offset,
7279                       bool IgnoreStringsWithoutSpecifiers = false) {
7280   if (S.isConstantEvaluated())
7281     return SLCT_NotALiteral;
7282  tryAgain:
7283   assert(Offset.isSigned() && "invalid offset");
7284 
7285   if (E->isTypeDependent() || E->isValueDependent())
7286     return SLCT_NotALiteral;
7287 
7288   E = E->IgnoreParenCasts();
7289 
7290   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
7291     // Technically -Wformat-nonliteral does not warn about this case.
7292     // The behavior of printf and friends in this case is implementation
7293     // dependent.  Ideally if the format string cannot be null then
7294     // it should have a 'nonnull' attribute in the function prototype.
7295     return SLCT_UncheckedLiteral;
7296 
7297   switch (E->getStmtClass()) {
7298   case Stmt::BinaryConditionalOperatorClass:
7299   case Stmt::ConditionalOperatorClass: {
7300     // The expression is a literal if both sub-expressions were, and it was
7301     // completely checked only if both sub-expressions were checked.
7302     const AbstractConditionalOperator *C =
7303         cast<AbstractConditionalOperator>(E);
7304 
7305     // Determine whether it is necessary to check both sub-expressions, for
7306     // example, because the condition expression is a constant that can be
7307     // evaluated at compile time.
7308     bool CheckLeft = true, CheckRight = true;
7309 
7310     bool Cond;
7311     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
7312                                                  S.isConstantEvaluated())) {
7313       if (Cond)
7314         CheckRight = false;
7315       else
7316         CheckLeft = false;
7317     }
7318 
7319     // We need to maintain the offsets for the right and the left hand side
7320     // separately to check if every possible indexed expression is a valid
7321     // string literal. They might have different offsets for different string
7322     // literals in the end.
7323     StringLiteralCheckType Left;
7324     if (!CheckLeft)
7325       Left = SLCT_UncheckedLiteral;
7326     else {
7327       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
7328                                    HasVAListArg, format_idx, firstDataArg,
7329                                    Type, CallType, InFunctionCall,
7330                                    CheckedVarArgs, UncoveredArg, Offset,
7331                                    IgnoreStringsWithoutSpecifiers);
7332       if (Left == SLCT_NotALiteral || !CheckRight) {
7333         return Left;
7334       }
7335     }
7336 
7337     StringLiteralCheckType Right = checkFormatStringExpr(
7338         S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
7339         Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7340         IgnoreStringsWithoutSpecifiers);
7341 
7342     return (CheckLeft && Left < Right) ? Left : Right;
7343   }
7344 
7345   case Stmt::ImplicitCastExprClass:
7346     E = cast<ImplicitCastExpr>(E)->getSubExpr();
7347     goto tryAgain;
7348 
7349   case Stmt::OpaqueValueExprClass:
7350     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
7351       E = src;
7352       goto tryAgain;
7353     }
7354     return SLCT_NotALiteral;
7355 
7356   case Stmt::PredefinedExprClass:
7357     // While __func__, etc., are technically not string literals, they
7358     // cannot contain format specifiers and thus are not a security
7359     // liability.
7360     return SLCT_UncheckedLiteral;
7361 
7362   case Stmt::DeclRefExprClass: {
7363     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7364 
7365     // As an exception, do not flag errors for variables binding to
7366     // const string literals.
7367     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
7368       bool isConstant = false;
7369       QualType T = DR->getType();
7370 
7371       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
7372         isConstant = AT->getElementType().isConstant(S.Context);
7373       } else if (const PointerType *PT = T->getAs<PointerType>()) {
7374         isConstant = T.isConstant(S.Context) &&
7375                      PT->getPointeeType().isConstant(S.Context);
7376       } else if (T->isObjCObjectPointerType()) {
7377         // In ObjC, there is usually no "const ObjectPointer" type,
7378         // so don't check if the pointee type is constant.
7379         isConstant = T.isConstant(S.Context);
7380       }
7381 
7382       if (isConstant) {
7383         if (const Expr *Init = VD->getAnyInitializer()) {
7384           // Look through initializers like const char c[] = { "foo" }
7385           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
7386             if (InitList->isStringLiteralInit())
7387               Init = InitList->getInit(0)->IgnoreParenImpCasts();
7388           }
7389           return checkFormatStringExpr(S, Init, Args,
7390                                        HasVAListArg, format_idx,
7391                                        firstDataArg, Type, CallType,
7392                                        /*InFunctionCall*/ false, CheckedVarArgs,
7393                                        UncoveredArg, Offset);
7394         }
7395       }
7396 
7397       // For vprintf* functions (i.e., HasVAListArg==true), we add a
7398       // special check to see if the format string is a function parameter
7399       // of the function calling the printf function.  If the function
7400       // has an attribute indicating it is a printf-like function, then we
7401       // should suppress warnings concerning non-literals being used in a call
7402       // to a vprintf function.  For example:
7403       //
7404       // void
7405       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
7406       //      va_list ap;
7407       //      va_start(ap, fmt);
7408       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
7409       //      ...
7410       // }
7411       if (HasVAListArg) {
7412         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
7413           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
7414             int PVIndex = PV->getFunctionScopeIndex() + 1;
7415             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
7416               // adjust for implicit parameter
7417               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
7418                 if (MD->isInstance())
7419                   ++PVIndex;
7420               // We also check if the formats are compatible.
7421               // We can't pass a 'scanf' string to a 'printf' function.
7422               if (PVIndex == PVFormat->getFormatIdx() &&
7423                   Type == S.GetFormatStringType(PVFormat))
7424                 return SLCT_UncheckedLiteral;
7425             }
7426           }
7427         }
7428       }
7429     }
7430 
7431     return SLCT_NotALiteral;
7432   }
7433 
7434   case Stmt::CallExprClass:
7435   case Stmt::CXXMemberCallExprClass: {
7436     const CallExpr *CE = cast<CallExpr>(E);
7437     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
7438       bool IsFirst = true;
7439       StringLiteralCheckType CommonResult;
7440       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
7441         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
7442         StringLiteralCheckType Result = checkFormatStringExpr(
7443             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7444             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7445             IgnoreStringsWithoutSpecifiers);
7446         if (IsFirst) {
7447           CommonResult = Result;
7448           IsFirst = false;
7449         }
7450       }
7451       if (!IsFirst)
7452         return CommonResult;
7453 
7454       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
7455         unsigned BuiltinID = FD->getBuiltinID();
7456         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
7457             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
7458           const Expr *Arg = CE->getArg(0);
7459           return checkFormatStringExpr(S, Arg, Args,
7460                                        HasVAListArg, format_idx,
7461                                        firstDataArg, Type, CallType,
7462                                        InFunctionCall, CheckedVarArgs,
7463                                        UncoveredArg, Offset,
7464                                        IgnoreStringsWithoutSpecifiers);
7465         }
7466       }
7467     }
7468 
7469     return SLCT_NotALiteral;
7470   }
7471   case Stmt::ObjCMessageExprClass: {
7472     const auto *ME = cast<ObjCMessageExpr>(E);
7473     if (const auto *MD = ME->getMethodDecl()) {
7474       if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
7475         // As a special case heuristic, if we're using the method -[NSBundle
7476         // localizedStringForKey:value:table:], ignore any key strings that lack
7477         // format specifiers. The idea is that if the key doesn't have any
7478         // format specifiers then its probably just a key to map to the
7479         // localized strings. If it does have format specifiers though, then its
7480         // likely that the text of the key is the format string in the
7481         // programmer's language, and should be checked.
7482         const ObjCInterfaceDecl *IFace;
7483         if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
7484             IFace->getIdentifier()->isStr("NSBundle") &&
7485             MD->getSelector().isKeywordSelector(
7486                 {"localizedStringForKey", "value", "table"})) {
7487           IgnoreStringsWithoutSpecifiers = true;
7488         }
7489 
7490         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
7491         return checkFormatStringExpr(
7492             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7493             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7494             IgnoreStringsWithoutSpecifiers);
7495       }
7496     }
7497 
7498     return SLCT_NotALiteral;
7499   }
7500   case Stmt::ObjCStringLiteralClass:
7501   case Stmt::StringLiteralClass: {
7502     const StringLiteral *StrE = nullptr;
7503 
7504     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
7505       StrE = ObjCFExpr->getString();
7506     else
7507       StrE = cast<StringLiteral>(E);
7508 
7509     if (StrE) {
7510       if (Offset.isNegative() || Offset > StrE->getLength()) {
7511         // TODO: It would be better to have an explicit warning for out of
7512         // bounds literals.
7513         return SLCT_NotALiteral;
7514       }
7515       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
7516       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
7517                         firstDataArg, Type, InFunctionCall, CallType,
7518                         CheckedVarArgs, UncoveredArg,
7519                         IgnoreStringsWithoutSpecifiers);
7520       return SLCT_CheckedLiteral;
7521     }
7522 
7523     return SLCT_NotALiteral;
7524   }
7525   case Stmt::BinaryOperatorClass: {
7526     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
7527 
7528     // A string literal + an int offset is still a string literal.
7529     if (BinOp->isAdditiveOp()) {
7530       Expr::EvalResult LResult, RResult;
7531 
7532       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
7533           LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7534       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
7535           RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7536 
7537       if (LIsInt != RIsInt) {
7538         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
7539 
7540         if (LIsInt) {
7541           if (BinOpKind == BO_Add) {
7542             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
7543             E = BinOp->getRHS();
7544             goto tryAgain;
7545           }
7546         } else {
7547           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
7548           E = BinOp->getLHS();
7549           goto tryAgain;
7550         }
7551       }
7552     }
7553 
7554     return SLCT_NotALiteral;
7555   }
7556   case Stmt::UnaryOperatorClass: {
7557     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
7558     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
7559     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
7560       Expr::EvalResult IndexResult;
7561       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
7562                                        Expr::SE_NoSideEffects,
7563                                        S.isConstantEvaluated())) {
7564         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
7565                    /*RHS is int*/ true);
7566         E = ASE->getBase();
7567         goto tryAgain;
7568       }
7569     }
7570 
7571     return SLCT_NotALiteral;
7572   }
7573 
7574   default:
7575     return SLCT_NotALiteral;
7576   }
7577 }
7578 
7579 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
7580   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
7581       .Case("scanf", FST_Scanf)
7582       .Cases("printf", "printf0", FST_Printf)
7583       .Cases("NSString", "CFString", FST_NSString)
7584       .Case("strftime", FST_Strftime)
7585       .Case("strfmon", FST_Strfmon)
7586       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
7587       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
7588       .Case("os_trace", FST_OSLog)
7589       .Case("os_log", FST_OSLog)
7590       .Default(FST_Unknown);
7591 }
7592 
7593 /// CheckFormatArguments - Check calls to printf and scanf (and similar
7594 /// functions) for correct use of format strings.
7595 /// Returns true if a format string has been fully checked.
7596 bool Sema::CheckFormatArguments(const FormatAttr *Format,
7597                                 ArrayRef<const Expr *> Args,
7598                                 bool IsCXXMember,
7599                                 VariadicCallType CallType,
7600                                 SourceLocation Loc, SourceRange Range,
7601                                 llvm::SmallBitVector &CheckedVarArgs) {
7602   FormatStringInfo FSI;
7603   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
7604     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
7605                                 FSI.FirstDataArg, GetFormatStringType(Format),
7606                                 CallType, Loc, Range, CheckedVarArgs);
7607   return false;
7608 }
7609 
7610 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
7611                                 bool HasVAListArg, unsigned format_idx,
7612                                 unsigned firstDataArg, FormatStringType Type,
7613                                 VariadicCallType CallType,
7614                                 SourceLocation Loc, SourceRange Range,
7615                                 llvm::SmallBitVector &CheckedVarArgs) {
7616   // CHECK: printf/scanf-like function is called with no format string.
7617   if (format_idx >= Args.size()) {
7618     Diag(Loc, diag::warn_missing_format_string) << Range;
7619     return false;
7620   }
7621 
7622   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
7623 
7624   // CHECK: format string is not a string literal.
7625   //
7626   // Dynamically generated format strings are difficult to
7627   // automatically vet at compile time.  Requiring that format strings
7628   // are string literals: (1) permits the checking of format strings by
7629   // the compiler and thereby (2) can practically remove the source of
7630   // many format string exploits.
7631 
7632   // Format string can be either ObjC string (e.g. @"%d") or
7633   // C string (e.g. "%d")
7634   // ObjC string uses the same format specifiers as C string, so we can use
7635   // the same format string checking logic for both ObjC and C strings.
7636   UncoveredArgHandler UncoveredArg;
7637   StringLiteralCheckType CT =
7638       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
7639                             format_idx, firstDataArg, Type, CallType,
7640                             /*IsFunctionCall*/ true, CheckedVarArgs,
7641                             UncoveredArg,
7642                             /*no string offset*/ llvm::APSInt(64, false) = 0);
7643 
7644   // Generate a diagnostic where an uncovered argument is detected.
7645   if (UncoveredArg.hasUncoveredArg()) {
7646     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
7647     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
7648     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
7649   }
7650 
7651   if (CT != SLCT_NotALiteral)
7652     // Literal format string found, check done!
7653     return CT == SLCT_CheckedLiteral;
7654 
7655   // Strftime is particular as it always uses a single 'time' argument,
7656   // so it is safe to pass a non-literal string.
7657   if (Type == FST_Strftime)
7658     return false;
7659 
7660   // Do not emit diag when the string param is a macro expansion and the
7661   // format is either NSString or CFString. This is a hack to prevent
7662   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
7663   // which are usually used in place of NS and CF string literals.
7664   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
7665   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
7666     return false;
7667 
7668   // If there are no arguments specified, warn with -Wformat-security, otherwise
7669   // warn only with -Wformat-nonliteral.
7670   if (Args.size() == firstDataArg) {
7671     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
7672       << OrigFormatExpr->getSourceRange();
7673     switch (Type) {
7674     default:
7675       break;
7676     case FST_Kprintf:
7677     case FST_FreeBSDKPrintf:
7678     case FST_Printf:
7679       Diag(FormatLoc, diag::note_format_security_fixit)
7680         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
7681       break;
7682     case FST_NSString:
7683       Diag(FormatLoc, diag::note_format_security_fixit)
7684         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
7685       break;
7686     }
7687   } else {
7688     Diag(FormatLoc, diag::warn_format_nonliteral)
7689       << OrigFormatExpr->getSourceRange();
7690   }
7691   return false;
7692 }
7693 
7694 namespace {
7695 
7696 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
7697 protected:
7698   Sema &S;
7699   const FormatStringLiteral *FExpr;
7700   const Expr *OrigFormatExpr;
7701   const Sema::FormatStringType FSType;
7702   const unsigned FirstDataArg;
7703   const unsigned NumDataArgs;
7704   const char *Beg; // Start of format string.
7705   const bool HasVAListArg;
7706   ArrayRef<const Expr *> Args;
7707   unsigned FormatIdx;
7708   llvm::SmallBitVector CoveredArgs;
7709   bool usesPositionalArgs = false;
7710   bool atFirstArg = true;
7711   bool inFunctionCall;
7712   Sema::VariadicCallType CallType;
7713   llvm::SmallBitVector &CheckedVarArgs;
7714   UncoveredArgHandler &UncoveredArg;
7715 
7716 public:
7717   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
7718                      const Expr *origFormatExpr,
7719                      const Sema::FormatStringType type, unsigned firstDataArg,
7720                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
7721                      ArrayRef<const Expr *> Args, unsigned formatIdx,
7722                      bool inFunctionCall, Sema::VariadicCallType callType,
7723                      llvm::SmallBitVector &CheckedVarArgs,
7724                      UncoveredArgHandler &UncoveredArg)
7725       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
7726         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
7727         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
7728         inFunctionCall(inFunctionCall), CallType(callType),
7729         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
7730     CoveredArgs.resize(numDataArgs);
7731     CoveredArgs.reset();
7732   }
7733 
7734   void DoneProcessing();
7735 
7736   void HandleIncompleteSpecifier(const char *startSpecifier,
7737                                  unsigned specifierLen) override;
7738 
7739   void HandleInvalidLengthModifier(
7740                            const analyze_format_string::FormatSpecifier &FS,
7741                            const analyze_format_string::ConversionSpecifier &CS,
7742                            const char *startSpecifier, unsigned specifierLen,
7743                            unsigned DiagID);
7744 
7745   void HandleNonStandardLengthModifier(
7746                     const analyze_format_string::FormatSpecifier &FS,
7747                     const char *startSpecifier, unsigned specifierLen);
7748 
7749   void HandleNonStandardConversionSpecifier(
7750                     const analyze_format_string::ConversionSpecifier &CS,
7751                     const char *startSpecifier, unsigned specifierLen);
7752 
7753   void HandlePosition(const char *startPos, unsigned posLen) override;
7754 
7755   void HandleInvalidPosition(const char *startSpecifier,
7756                              unsigned specifierLen,
7757                              analyze_format_string::PositionContext p) override;
7758 
7759   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
7760 
7761   void HandleNullChar(const char *nullCharacter) override;
7762 
7763   template <typename Range>
7764   static void
7765   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
7766                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
7767                        bool IsStringLocation, Range StringRange,
7768                        ArrayRef<FixItHint> Fixit = None);
7769 
7770 protected:
7771   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
7772                                         const char *startSpec,
7773                                         unsigned specifierLen,
7774                                         const char *csStart, unsigned csLen);
7775 
7776   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
7777                                          const char *startSpec,
7778                                          unsigned specifierLen);
7779 
7780   SourceRange getFormatStringRange();
7781   CharSourceRange getSpecifierRange(const char *startSpecifier,
7782                                     unsigned specifierLen);
7783   SourceLocation getLocationOfByte(const char *x);
7784 
7785   const Expr *getDataArg(unsigned i) const;
7786 
7787   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
7788                     const analyze_format_string::ConversionSpecifier &CS,
7789                     const char *startSpecifier, unsigned specifierLen,
7790                     unsigned argIndex);
7791 
7792   template <typename Range>
7793   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
7794                             bool IsStringLocation, Range StringRange,
7795                             ArrayRef<FixItHint> Fixit = None);
7796 };
7797 
7798 } // namespace
7799 
7800 SourceRange CheckFormatHandler::getFormatStringRange() {
7801   return OrigFormatExpr->getSourceRange();
7802 }
7803 
7804 CharSourceRange CheckFormatHandler::
7805 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
7806   SourceLocation Start = getLocationOfByte(startSpecifier);
7807   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
7808 
7809   // Advance the end SourceLocation by one due to half-open ranges.
7810   End = End.getLocWithOffset(1);
7811 
7812   return CharSourceRange::getCharRange(Start, End);
7813 }
7814 
7815 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
7816   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
7817                                   S.getLangOpts(), S.Context.getTargetInfo());
7818 }
7819 
7820 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
7821                                                    unsigned specifierLen){
7822   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
7823                        getLocationOfByte(startSpecifier),
7824                        /*IsStringLocation*/true,
7825                        getSpecifierRange(startSpecifier, specifierLen));
7826 }
7827 
7828 void CheckFormatHandler::HandleInvalidLengthModifier(
7829     const analyze_format_string::FormatSpecifier &FS,
7830     const analyze_format_string::ConversionSpecifier &CS,
7831     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
7832   using namespace analyze_format_string;
7833 
7834   const LengthModifier &LM = FS.getLengthModifier();
7835   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7836 
7837   // See if we know how to fix this length modifier.
7838   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7839   if (FixedLM) {
7840     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7841                          getLocationOfByte(LM.getStart()),
7842                          /*IsStringLocation*/true,
7843                          getSpecifierRange(startSpecifier, specifierLen));
7844 
7845     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7846       << FixedLM->toString()
7847       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7848 
7849   } else {
7850     FixItHint Hint;
7851     if (DiagID == diag::warn_format_nonsensical_length)
7852       Hint = FixItHint::CreateRemoval(LMRange);
7853 
7854     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7855                          getLocationOfByte(LM.getStart()),
7856                          /*IsStringLocation*/true,
7857                          getSpecifierRange(startSpecifier, specifierLen),
7858                          Hint);
7859   }
7860 }
7861 
7862 void CheckFormatHandler::HandleNonStandardLengthModifier(
7863     const analyze_format_string::FormatSpecifier &FS,
7864     const char *startSpecifier, unsigned specifierLen) {
7865   using namespace analyze_format_string;
7866 
7867   const LengthModifier &LM = FS.getLengthModifier();
7868   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7869 
7870   // See if we know how to fix this length modifier.
7871   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7872   if (FixedLM) {
7873     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7874                            << LM.toString() << 0,
7875                          getLocationOfByte(LM.getStart()),
7876                          /*IsStringLocation*/true,
7877                          getSpecifierRange(startSpecifier, specifierLen));
7878 
7879     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7880       << FixedLM->toString()
7881       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7882 
7883   } else {
7884     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7885                            << LM.toString() << 0,
7886                          getLocationOfByte(LM.getStart()),
7887                          /*IsStringLocation*/true,
7888                          getSpecifierRange(startSpecifier, specifierLen));
7889   }
7890 }
7891 
7892 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
7893     const analyze_format_string::ConversionSpecifier &CS,
7894     const char *startSpecifier, unsigned specifierLen) {
7895   using namespace analyze_format_string;
7896 
7897   // See if we know how to fix this conversion specifier.
7898   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
7899   if (FixedCS) {
7900     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7901                           << CS.toString() << /*conversion specifier*/1,
7902                          getLocationOfByte(CS.getStart()),
7903                          /*IsStringLocation*/true,
7904                          getSpecifierRange(startSpecifier, specifierLen));
7905 
7906     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
7907     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
7908       << FixedCS->toString()
7909       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
7910   } else {
7911     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7912                           << CS.toString() << /*conversion specifier*/1,
7913                          getLocationOfByte(CS.getStart()),
7914                          /*IsStringLocation*/true,
7915                          getSpecifierRange(startSpecifier, specifierLen));
7916   }
7917 }
7918 
7919 void CheckFormatHandler::HandlePosition(const char *startPos,
7920                                         unsigned posLen) {
7921   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
7922                                getLocationOfByte(startPos),
7923                                /*IsStringLocation*/true,
7924                                getSpecifierRange(startPos, posLen));
7925 }
7926 
7927 void
7928 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
7929                                      analyze_format_string::PositionContext p) {
7930   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
7931                          << (unsigned) p,
7932                        getLocationOfByte(startPos), /*IsStringLocation*/true,
7933                        getSpecifierRange(startPos, posLen));
7934 }
7935 
7936 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
7937                                             unsigned posLen) {
7938   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
7939                                getLocationOfByte(startPos),
7940                                /*IsStringLocation*/true,
7941                                getSpecifierRange(startPos, posLen));
7942 }
7943 
7944 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
7945   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
7946     // The presence of a null character is likely an error.
7947     EmitFormatDiagnostic(
7948       S.PDiag(diag::warn_printf_format_string_contains_null_char),
7949       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
7950       getFormatStringRange());
7951   }
7952 }
7953 
7954 // Note that this may return NULL if there was an error parsing or building
7955 // one of the argument expressions.
7956 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
7957   return Args[FirstDataArg + i];
7958 }
7959 
7960 void CheckFormatHandler::DoneProcessing() {
7961   // Does the number of data arguments exceed the number of
7962   // format conversions in the format string?
7963   if (!HasVAListArg) {
7964       // Find any arguments that weren't covered.
7965     CoveredArgs.flip();
7966     signed notCoveredArg = CoveredArgs.find_first();
7967     if (notCoveredArg >= 0) {
7968       assert((unsigned)notCoveredArg < NumDataArgs);
7969       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
7970     } else {
7971       UncoveredArg.setAllCovered();
7972     }
7973   }
7974 }
7975 
7976 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
7977                                    const Expr *ArgExpr) {
7978   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
7979          "Invalid state");
7980 
7981   if (!ArgExpr)
7982     return;
7983 
7984   SourceLocation Loc = ArgExpr->getBeginLoc();
7985 
7986   if (S.getSourceManager().isInSystemMacro(Loc))
7987     return;
7988 
7989   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
7990   for (auto E : DiagnosticExprs)
7991     PDiag << E->getSourceRange();
7992 
7993   CheckFormatHandler::EmitFormatDiagnostic(
7994                                   S, IsFunctionCall, DiagnosticExprs[0],
7995                                   PDiag, Loc, /*IsStringLocation*/false,
7996                                   DiagnosticExprs[0]->getSourceRange());
7997 }
7998 
7999 bool
8000 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
8001                                                      SourceLocation Loc,
8002                                                      const char *startSpec,
8003                                                      unsigned specifierLen,
8004                                                      const char *csStart,
8005                                                      unsigned csLen) {
8006   bool keepGoing = true;
8007   if (argIndex < NumDataArgs) {
8008     // Consider the argument coverered, even though the specifier doesn't
8009     // make sense.
8010     CoveredArgs.set(argIndex);
8011   }
8012   else {
8013     // If argIndex exceeds the number of data arguments we
8014     // don't issue a warning because that is just a cascade of warnings (and
8015     // they may have intended '%%' anyway). We don't want to continue processing
8016     // the format string after this point, however, as we will like just get
8017     // gibberish when trying to match arguments.
8018     keepGoing = false;
8019   }
8020 
8021   StringRef Specifier(csStart, csLen);
8022 
8023   // If the specifier in non-printable, it could be the first byte of a UTF-8
8024   // sequence. In that case, print the UTF-8 code point. If not, print the byte
8025   // hex value.
8026   std::string CodePointStr;
8027   if (!llvm::sys::locale::isPrint(*csStart)) {
8028     llvm::UTF32 CodePoint;
8029     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
8030     const llvm::UTF8 *E =
8031         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
8032     llvm::ConversionResult Result =
8033         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
8034 
8035     if (Result != llvm::conversionOK) {
8036       unsigned char FirstChar = *csStart;
8037       CodePoint = (llvm::UTF32)FirstChar;
8038     }
8039 
8040     llvm::raw_string_ostream OS(CodePointStr);
8041     if (CodePoint < 256)
8042       OS << "\\x" << llvm::format("%02x", CodePoint);
8043     else if (CodePoint <= 0xFFFF)
8044       OS << "\\u" << llvm::format("%04x", CodePoint);
8045     else
8046       OS << "\\U" << llvm::format("%08x", CodePoint);
8047     OS.flush();
8048     Specifier = CodePointStr;
8049   }
8050 
8051   EmitFormatDiagnostic(
8052       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
8053       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
8054 
8055   return keepGoing;
8056 }
8057 
8058 void
8059 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
8060                                                       const char *startSpec,
8061                                                       unsigned specifierLen) {
8062   EmitFormatDiagnostic(
8063     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
8064     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
8065 }
8066 
8067 bool
8068 CheckFormatHandler::CheckNumArgs(
8069   const analyze_format_string::FormatSpecifier &FS,
8070   const analyze_format_string::ConversionSpecifier &CS,
8071   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
8072 
8073   if (argIndex >= NumDataArgs) {
8074     PartialDiagnostic PDiag = FS.usesPositionalArg()
8075       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
8076            << (argIndex+1) << NumDataArgs)
8077       : S.PDiag(diag::warn_printf_insufficient_data_args);
8078     EmitFormatDiagnostic(
8079       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
8080       getSpecifierRange(startSpecifier, specifierLen));
8081 
8082     // Since more arguments than conversion tokens are given, by extension
8083     // all arguments are covered, so mark this as so.
8084     UncoveredArg.setAllCovered();
8085     return false;
8086   }
8087   return true;
8088 }
8089 
8090 template<typename Range>
8091 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
8092                                               SourceLocation Loc,
8093                                               bool IsStringLocation,
8094                                               Range StringRange,
8095                                               ArrayRef<FixItHint> FixIt) {
8096   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
8097                        Loc, IsStringLocation, StringRange, FixIt);
8098 }
8099 
8100 /// If the format string is not within the function call, emit a note
8101 /// so that the function call and string are in diagnostic messages.
8102 ///
8103 /// \param InFunctionCall if true, the format string is within the function
8104 /// call and only one diagnostic message will be produced.  Otherwise, an
8105 /// extra note will be emitted pointing to location of the format string.
8106 ///
8107 /// \param ArgumentExpr the expression that is passed as the format string
8108 /// argument in the function call.  Used for getting locations when two
8109 /// diagnostics are emitted.
8110 ///
8111 /// \param PDiag the callee should already have provided any strings for the
8112 /// diagnostic message.  This function only adds locations and fixits
8113 /// to diagnostics.
8114 ///
8115 /// \param Loc primary location for diagnostic.  If two diagnostics are
8116 /// required, one will be at Loc and a new SourceLocation will be created for
8117 /// the other one.
8118 ///
8119 /// \param IsStringLocation if true, Loc points to the format string should be
8120 /// used for the note.  Otherwise, Loc points to the argument list and will
8121 /// be used with PDiag.
8122 ///
8123 /// \param StringRange some or all of the string to highlight.  This is
8124 /// templated so it can accept either a CharSourceRange or a SourceRange.
8125 ///
8126 /// \param FixIt optional fix it hint for the format string.
8127 template <typename Range>
8128 void CheckFormatHandler::EmitFormatDiagnostic(
8129     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
8130     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
8131     Range StringRange, ArrayRef<FixItHint> FixIt) {
8132   if (InFunctionCall) {
8133     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
8134     D << StringRange;
8135     D << FixIt;
8136   } else {
8137     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
8138       << ArgumentExpr->getSourceRange();
8139 
8140     const Sema::SemaDiagnosticBuilder &Note =
8141       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
8142              diag::note_format_string_defined);
8143 
8144     Note << StringRange;
8145     Note << FixIt;
8146   }
8147 }
8148 
8149 //===--- CHECK: Printf format string checking ------------------------------===//
8150 
8151 namespace {
8152 
8153 class CheckPrintfHandler : public CheckFormatHandler {
8154 public:
8155   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8156                      const Expr *origFormatExpr,
8157                      const Sema::FormatStringType type, unsigned firstDataArg,
8158                      unsigned numDataArgs, bool isObjC, const char *beg,
8159                      bool hasVAListArg, ArrayRef<const Expr *> Args,
8160                      unsigned formatIdx, bool inFunctionCall,
8161                      Sema::VariadicCallType CallType,
8162                      llvm::SmallBitVector &CheckedVarArgs,
8163                      UncoveredArgHandler &UncoveredArg)
8164       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8165                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
8166                            inFunctionCall, CallType, CheckedVarArgs,
8167                            UncoveredArg) {}
8168 
8169   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
8170 
8171   /// Returns true if '%@' specifiers are allowed in the format string.
8172   bool allowsObjCArg() const {
8173     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
8174            FSType == Sema::FST_OSTrace;
8175   }
8176 
8177   bool HandleInvalidPrintfConversionSpecifier(
8178                                       const analyze_printf::PrintfSpecifier &FS,
8179                                       const char *startSpecifier,
8180                                       unsigned specifierLen) override;
8181 
8182   void handleInvalidMaskType(StringRef MaskType) override;
8183 
8184   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8185                              const char *startSpecifier,
8186                              unsigned specifierLen) override;
8187   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8188                        const char *StartSpecifier,
8189                        unsigned SpecifierLen,
8190                        const Expr *E);
8191 
8192   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
8193                     const char *startSpecifier, unsigned specifierLen);
8194   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
8195                            const analyze_printf::OptionalAmount &Amt,
8196                            unsigned type,
8197                            const char *startSpecifier, unsigned specifierLen);
8198   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8199                   const analyze_printf::OptionalFlag &flag,
8200                   const char *startSpecifier, unsigned specifierLen);
8201   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
8202                          const analyze_printf::OptionalFlag &ignoredFlag,
8203                          const analyze_printf::OptionalFlag &flag,
8204                          const char *startSpecifier, unsigned specifierLen);
8205   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
8206                            const Expr *E);
8207 
8208   void HandleEmptyObjCModifierFlag(const char *startFlag,
8209                                    unsigned flagLen) override;
8210 
8211   void HandleInvalidObjCModifierFlag(const char *startFlag,
8212                                             unsigned flagLen) override;
8213 
8214   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
8215                                            const char *flagsEnd,
8216                                            const char *conversionPosition)
8217                                              override;
8218 };
8219 
8220 } // namespace
8221 
8222 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
8223                                       const analyze_printf::PrintfSpecifier &FS,
8224                                       const char *startSpecifier,
8225                                       unsigned specifierLen) {
8226   const analyze_printf::PrintfConversionSpecifier &CS =
8227     FS.getConversionSpecifier();
8228 
8229   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8230                                           getLocationOfByte(CS.getStart()),
8231                                           startSpecifier, specifierLen,
8232                                           CS.getStart(), CS.getLength());
8233 }
8234 
8235 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
8236   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
8237 }
8238 
8239 bool CheckPrintfHandler::HandleAmount(
8240                                const analyze_format_string::OptionalAmount &Amt,
8241                                unsigned k, const char *startSpecifier,
8242                                unsigned specifierLen) {
8243   if (Amt.hasDataArgument()) {
8244     if (!HasVAListArg) {
8245       unsigned argIndex = Amt.getArgIndex();
8246       if (argIndex >= NumDataArgs) {
8247         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
8248                                << k,
8249                              getLocationOfByte(Amt.getStart()),
8250                              /*IsStringLocation*/true,
8251                              getSpecifierRange(startSpecifier, specifierLen));
8252         // Don't do any more checking.  We will just emit
8253         // spurious errors.
8254         return false;
8255       }
8256 
8257       // Type check the data argument.  It should be an 'int'.
8258       // Although not in conformance with C99, we also allow the argument to be
8259       // an 'unsigned int' as that is a reasonably safe case.  GCC also
8260       // doesn't emit a warning for that case.
8261       CoveredArgs.set(argIndex);
8262       const Expr *Arg = getDataArg(argIndex);
8263       if (!Arg)
8264         return false;
8265 
8266       QualType T = Arg->getType();
8267 
8268       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
8269       assert(AT.isValid());
8270 
8271       if (!AT.matchesType(S.Context, T)) {
8272         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
8273                                << k << AT.getRepresentativeTypeName(S.Context)
8274                                << T << Arg->getSourceRange(),
8275                              getLocationOfByte(Amt.getStart()),
8276                              /*IsStringLocation*/true,
8277                              getSpecifierRange(startSpecifier, specifierLen));
8278         // Don't do any more checking.  We will just emit
8279         // spurious errors.
8280         return false;
8281       }
8282     }
8283   }
8284   return true;
8285 }
8286 
8287 void CheckPrintfHandler::HandleInvalidAmount(
8288                                       const analyze_printf::PrintfSpecifier &FS,
8289                                       const analyze_printf::OptionalAmount &Amt,
8290                                       unsigned type,
8291                                       const char *startSpecifier,
8292                                       unsigned specifierLen) {
8293   const analyze_printf::PrintfConversionSpecifier &CS =
8294     FS.getConversionSpecifier();
8295 
8296   FixItHint fixit =
8297     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
8298       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
8299                                  Amt.getConstantLength()))
8300       : FixItHint();
8301 
8302   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
8303                          << type << CS.toString(),
8304                        getLocationOfByte(Amt.getStart()),
8305                        /*IsStringLocation*/true,
8306                        getSpecifierRange(startSpecifier, specifierLen),
8307                        fixit);
8308 }
8309 
8310 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8311                                     const analyze_printf::OptionalFlag &flag,
8312                                     const char *startSpecifier,
8313                                     unsigned specifierLen) {
8314   // Warn about pointless flag with a fixit removal.
8315   const analyze_printf::PrintfConversionSpecifier &CS =
8316     FS.getConversionSpecifier();
8317   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
8318                          << flag.toString() << CS.toString(),
8319                        getLocationOfByte(flag.getPosition()),
8320                        /*IsStringLocation*/true,
8321                        getSpecifierRange(startSpecifier, specifierLen),
8322                        FixItHint::CreateRemoval(
8323                          getSpecifierRange(flag.getPosition(), 1)));
8324 }
8325 
8326 void CheckPrintfHandler::HandleIgnoredFlag(
8327                                 const analyze_printf::PrintfSpecifier &FS,
8328                                 const analyze_printf::OptionalFlag &ignoredFlag,
8329                                 const analyze_printf::OptionalFlag &flag,
8330                                 const char *startSpecifier,
8331                                 unsigned specifierLen) {
8332   // Warn about ignored flag with a fixit removal.
8333   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
8334                          << ignoredFlag.toString() << flag.toString(),
8335                        getLocationOfByte(ignoredFlag.getPosition()),
8336                        /*IsStringLocation*/true,
8337                        getSpecifierRange(startSpecifier, specifierLen),
8338                        FixItHint::CreateRemoval(
8339                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
8340 }
8341 
8342 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
8343                                                      unsigned flagLen) {
8344   // Warn about an empty flag.
8345   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
8346                        getLocationOfByte(startFlag),
8347                        /*IsStringLocation*/true,
8348                        getSpecifierRange(startFlag, flagLen));
8349 }
8350 
8351 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
8352                                                        unsigned flagLen) {
8353   // Warn about an invalid flag.
8354   auto Range = getSpecifierRange(startFlag, flagLen);
8355   StringRef flag(startFlag, flagLen);
8356   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
8357                       getLocationOfByte(startFlag),
8358                       /*IsStringLocation*/true,
8359                       Range, FixItHint::CreateRemoval(Range));
8360 }
8361 
8362 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
8363     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
8364     // Warn about using '[...]' without a '@' conversion.
8365     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
8366     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
8367     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
8368                          getLocationOfByte(conversionPosition),
8369                          /*IsStringLocation*/true,
8370                          Range, FixItHint::CreateRemoval(Range));
8371 }
8372 
8373 // Determines if the specified is a C++ class or struct containing
8374 // a member with the specified name and kind (e.g. a CXXMethodDecl named
8375 // "c_str()").
8376 template<typename MemberKind>
8377 static llvm::SmallPtrSet<MemberKind*, 1>
8378 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
8379   const RecordType *RT = Ty->getAs<RecordType>();
8380   llvm::SmallPtrSet<MemberKind*, 1> Results;
8381 
8382   if (!RT)
8383     return Results;
8384   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
8385   if (!RD || !RD->getDefinition())
8386     return Results;
8387 
8388   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
8389                  Sema::LookupMemberName);
8390   R.suppressDiagnostics();
8391 
8392   // We just need to include all members of the right kind turned up by the
8393   // filter, at this point.
8394   if (S.LookupQualifiedName(R, RT->getDecl()))
8395     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8396       NamedDecl *decl = (*I)->getUnderlyingDecl();
8397       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
8398         Results.insert(FK);
8399     }
8400   return Results;
8401 }
8402 
8403 /// Check if we could call '.c_str()' on an object.
8404 ///
8405 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
8406 /// allow the call, or if it would be ambiguous).
8407 bool Sema::hasCStrMethod(const Expr *E) {
8408   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8409 
8410   MethodSet Results =
8411       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
8412   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8413        MI != ME; ++MI)
8414     if ((*MI)->getMinRequiredArguments() == 0)
8415       return true;
8416   return false;
8417 }
8418 
8419 // Check if a (w)string was passed when a (w)char* was needed, and offer a
8420 // better diagnostic if so. AT is assumed to be valid.
8421 // Returns true when a c_str() conversion method is found.
8422 bool CheckPrintfHandler::checkForCStrMembers(
8423     const analyze_printf::ArgType &AT, const Expr *E) {
8424   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8425 
8426   MethodSet Results =
8427       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
8428 
8429   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8430        MI != ME; ++MI) {
8431     const CXXMethodDecl *Method = *MI;
8432     if (Method->getMinRequiredArguments() == 0 &&
8433         AT.matchesType(S.Context, Method->getReturnType())) {
8434       // FIXME: Suggest parens if the expression needs them.
8435       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
8436       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
8437           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
8438       return true;
8439     }
8440   }
8441 
8442   return false;
8443 }
8444 
8445 bool
8446 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
8447                                             &FS,
8448                                           const char *startSpecifier,
8449                                           unsigned specifierLen) {
8450   using namespace analyze_format_string;
8451   using namespace analyze_printf;
8452 
8453   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
8454 
8455   if (FS.consumesDataArgument()) {
8456     if (atFirstArg) {
8457         atFirstArg = false;
8458         usesPositionalArgs = FS.usesPositionalArg();
8459     }
8460     else if (usesPositionalArgs != FS.usesPositionalArg()) {
8461       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8462                                         startSpecifier, specifierLen);
8463       return false;
8464     }
8465   }
8466 
8467   // First check if the field width, precision, and conversion specifier
8468   // have matching data arguments.
8469   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
8470                     startSpecifier, specifierLen)) {
8471     return false;
8472   }
8473 
8474   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
8475                     startSpecifier, specifierLen)) {
8476     return false;
8477   }
8478 
8479   if (!CS.consumesDataArgument()) {
8480     // FIXME: Technically specifying a precision or field width here
8481     // makes no sense.  Worth issuing a warning at some point.
8482     return true;
8483   }
8484 
8485   // Consume the argument.
8486   unsigned argIndex = FS.getArgIndex();
8487   if (argIndex < NumDataArgs) {
8488     // The check to see if the argIndex is valid will come later.
8489     // We set the bit here because we may exit early from this
8490     // function if we encounter some other error.
8491     CoveredArgs.set(argIndex);
8492   }
8493 
8494   // FreeBSD kernel extensions.
8495   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
8496       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
8497     // We need at least two arguments.
8498     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
8499       return false;
8500 
8501     // Claim the second argument.
8502     CoveredArgs.set(argIndex + 1);
8503 
8504     // Type check the first argument (int for %b, pointer for %D)
8505     const Expr *Ex = getDataArg(argIndex);
8506     const analyze_printf::ArgType &AT =
8507       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
8508         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
8509     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
8510       EmitFormatDiagnostic(
8511           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8512               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
8513               << false << Ex->getSourceRange(),
8514           Ex->getBeginLoc(), /*IsStringLocation*/ false,
8515           getSpecifierRange(startSpecifier, specifierLen));
8516 
8517     // Type check the second argument (char * for both %b and %D)
8518     Ex = getDataArg(argIndex + 1);
8519     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
8520     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
8521       EmitFormatDiagnostic(
8522           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8523               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
8524               << false << Ex->getSourceRange(),
8525           Ex->getBeginLoc(), /*IsStringLocation*/ false,
8526           getSpecifierRange(startSpecifier, specifierLen));
8527 
8528      return true;
8529   }
8530 
8531   // Check for using an Objective-C specific conversion specifier
8532   // in a non-ObjC literal.
8533   if (!allowsObjCArg() && CS.isObjCArg()) {
8534     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8535                                                   specifierLen);
8536   }
8537 
8538   // %P can only be used with os_log.
8539   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
8540     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8541                                                   specifierLen);
8542   }
8543 
8544   // %n is not allowed with os_log.
8545   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
8546     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
8547                          getLocationOfByte(CS.getStart()),
8548                          /*IsStringLocation*/ false,
8549                          getSpecifierRange(startSpecifier, specifierLen));
8550 
8551     return true;
8552   }
8553 
8554   // Only scalars are allowed for os_trace.
8555   if (FSType == Sema::FST_OSTrace &&
8556       (CS.getKind() == ConversionSpecifier::PArg ||
8557        CS.getKind() == ConversionSpecifier::sArg ||
8558        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
8559     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8560                                                   specifierLen);
8561   }
8562 
8563   // Check for use of public/private annotation outside of os_log().
8564   if (FSType != Sema::FST_OSLog) {
8565     if (FS.isPublic().isSet()) {
8566       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8567                                << "public",
8568                            getLocationOfByte(FS.isPublic().getPosition()),
8569                            /*IsStringLocation*/ false,
8570                            getSpecifierRange(startSpecifier, specifierLen));
8571     }
8572     if (FS.isPrivate().isSet()) {
8573       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8574                                << "private",
8575                            getLocationOfByte(FS.isPrivate().getPosition()),
8576                            /*IsStringLocation*/ false,
8577                            getSpecifierRange(startSpecifier, specifierLen));
8578     }
8579   }
8580 
8581   // Check for invalid use of field width
8582   if (!FS.hasValidFieldWidth()) {
8583     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
8584         startSpecifier, specifierLen);
8585   }
8586 
8587   // Check for invalid use of precision
8588   if (!FS.hasValidPrecision()) {
8589     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
8590         startSpecifier, specifierLen);
8591   }
8592 
8593   // Precision is mandatory for %P specifier.
8594   if (CS.getKind() == ConversionSpecifier::PArg &&
8595       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
8596     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
8597                          getLocationOfByte(startSpecifier),
8598                          /*IsStringLocation*/ false,
8599                          getSpecifierRange(startSpecifier, specifierLen));
8600   }
8601 
8602   // Check each flag does not conflict with any other component.
8603   if (!FS.hasValidThousandsGroupingPrefix())
8604     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
8605   if (!FS.hasValidLeadingZeros())
8606     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
8607   if (!FS.hasValidPlusPrefix())
8608     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
8609   if (!FS.hasValidSpacePrefix())
8610     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
8611   if (!FS.hasValidAlternativeForm())
8612     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
8613   if (!FS.hasValidLeftJustified())
8614     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
8615 
8616   // Check that flags are not ignored by another flag
8617   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
8618     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
8619         startSpecifier, specifierLen);
8620   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
8621     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
8622             startSpecifier, specifierLen);
8623 
8624   // Check the length modifier is valid with the given conversion specifier.
8625   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8626                                  S.getLangOpts()))
8627     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8628                                 diag::warn_format_nonsensical_length);
8629   else if (!FS.hasStandardLengthModifier())
8630     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8631   else if (!FS.hasStandardLengthConversionCombination())
8632     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8633                                 diag::warn_format_non_standard_conversion_spec);
8634 
8635   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8636     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8637 
8638   // The remaining checks depend on the data arguments.
8639   if (HasVAListArg)
8640     return true;
8641 
8642   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8643     return false;
8644 
8645   const Expr *Arg = getDataArg(argIndex);
8646   if (!Arg)
8647     return true;
8648 
8649   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
8650 }
8651 
8652 static bool requiresParensToAddCast(const Expr *E) {
8653   // FIXME: We should have a general way to reason about operator
8654   // precedence and whether parens are actually needed here.
8655   // Take care of a few common cases where they aren't.
8656   const Expr *Inside = E->IgnoreImpCasts();
8657   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
8658     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
8659 
8660   switch (Inside->getStmtClass()) {
8661   case Stmt::ArraySubscriptExprClass:
8662   case Stmt::CallExprClass:
8663   case Stmt::CharacterLiteralClass:
8664   case Stmt::CXXBoolLiteralExprClass:
8665   case Stmt::DeclRefExprClass:
8666   case Stmt::FloatingLiteralClass:
8667   case Stmt::IntegerLiteralClass:
8668   case Stmt::MemberExprClass:
8669   case Stmt::ObjCArrayLiteralClass:
8670   case Stmt::ObjCBoolLiteralExprClass:
8671   case Stmt::ObjCBoxedExprClass:
8672   case Stmt::ObjCDictionaryLiteralClass:
8673   case Stmt::ObjCEncodeExprClass:
8674   case Stmt::ObjCIvarRefExprClass:
8675   case Stmt::ObjCMessageExprClass:
8676   case Stmt::ObjCPropertyRefExprClass:
8677   case Stmt::ObjCStringLiteralClass:
8678   case Stmt::ObjCSubscriptRefExprClass:
8679   case Stmt::ParenExprClass:
8680   case Stmt::StringLiteralClass:
8681   case Stmt::UnaryOperatorClass:
8682     return false;
8683   default:
8684     return true;
8685   }
8686 }
8687 
8688 static std::pair<QualType, StringRef>
8689 shouldNotPrintDirectly(const ASTContext &Context,
8690                        QualType IntendedTy,
8691                        const Expr *E) {
8692   // Use a 'while' to peel off layers of typedefs.
8693   QualType TyTy = IntendedTy;
8694   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
8695     StringRef Name = UserTy->getDecl()->getName();
8696     QualType CastTy = llvm::StringSwitch<QualType>(Name)
8697       .Case("CFIndex", Context.getNSIntegerType())
8698       .Case("NSInteger", Context.getNSIntegerType())
8699       .Case("NSUInteger", Context.getNSUIntegerType())
8700       .Case("SInt32", Context.IntTy)
8701       .Case("UInt32", Context.UnsignedIntTy)
8702       .Default(QualType());
8703 
8704     if (!CastTy.isNull())
8705       return std::make_pair(CastTy, Name);
8706 
8707     TyTy = UserTy->desugar();
8708   }
8709 
8710   // Strip parens if necessary.
8711   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
8712     return shouldNotPrintDirectly(Context,
8713                                   PE->getSubExpr()->getType(),
8714                                   PE->getSubExpr());
8715 
8716   // If this is a conditional expression, then its result type is constructed
8717   // via usual arithmetic conversions and thus there might be no necessary
8718   // typedef sugar there.  Recurse to operands to check for NSInteger &
8719   // Co. usage condition.
8720   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8721     QualType TrueTy, FalseTy;
8722     StringRef TrueName, FalseName;
8723 
8724     std::tie(TrueTy, TrueName) =
8725       shouldNotPrintDirectly(Context,
8726                              CO->getTrueExpr()->getType(),
8727                              CO->getTrueExpr());
8728     std::tie(FalseTy, FalseName) =
8729       shouldNotPrintDirectly(Context,
8730                              CO->getFalseExpr()->getType(),
8731                              CO->getFalseExpr());
8732 
8733     if (TrueTy == FalseTy)
8734       return std::make_pair(TrueTy, TrueName);
8735     else if (TrueTy.isNull())
8736       return std::make_pair(FalseTy, FalseName);
8737     else if (FalseTy.isNull())
8738       return std::make_pair(TrueTy, TrueName);
8739   }
8740 
8741   return std::make_pair(QualType(), StringRef());
8742 }
8743 
8744 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
8745 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
8746 /// type do not count.
8747 static bool
8748 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
8749   QualType From = ICE->getSubExpr()->getType();
8750   QualType To = ICE->getType();
8751   // It's an integer promotion if the destination type is the promoted
8752   // source type.
8753   if (ICE->getCastKind() == CK_IntegralCast &&
8754       From->isPromotableIntegerType() &&
8755       S.Context.getPromotedIntegerType(From) == To)
8756     return true;
8757   // Look through vector types, since we do default argument promotion for
8758   // those in OpenCL.
8759   if (const auto *VecTy = From->getAs<ExtVectorType>())
8760     From = VecTy->getElementType();
8761   if (const auto *VecTy = To->getAs<ExtVectorType>())
8762     To = VecTy->getElementType();
8763   // It's a floating promotion if the source type is a lower rank.
8764   return ICE->getCastKind() == CK_FloatingCast &&
8765          S.Context.getFloatingTypeOrder(From, To) < 0;
8766 }
8767 
8768 bool
8769 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8770                                     const char *StartSpecifier,
8771                                     unsigned SpecifierLen,
8772                                     const Expr *E) {
8773   using namespace analyze_format_string;
8774   using namespace analyze_printf;
8775 
8776   // Now type check the data expression that matches the
8777   // format specifier.
8778   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
8779   if (!AT.isValid())
8780     return true;
8781 
8782   QualType ExprTy = E->getType();
8783   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
8784     ExprTy = TET->getUnderlyingExpr()->getType();
8785   }
8786 
8787   // Diagnose attempts to print a boolean value as a character. Unlike other
8788   // -Wformat diagnostics, this is fine from a type perspective, but it still
8789   // doesn't make sense.
8790   if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
8791       E->isKnownToHaveBooleanValue()) {
8792     const CharSourceRange &CSR =
8793         getSpecifierRange(StartSpecifier, SpecifierLen);
8794     SmallString<4> FSString;
8795     llvm::raw_svector_ostream os(FSString);
8796     FS.toString(os);
8797     EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
8798                              << FSString,
8799                          E->getExprLoc(), false, CSR);
8800     return true;
8801   }
8802 
8803   analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
8804   if (Match == analyze_printf::ArgType::Match)
8805     return true;
8806 
8807   // Look through argument promotions for our error message's reported type.
8808   // This includes the integral and floating promotions, but excludes array
8809   // and function pointer decay (seeing that an argument intended to be a
8810   // string has type 'char [6]' is probably more confusing than 'char *') and
8811   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
8812   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8813     if (isArithmeticArgumentPromotion(S, ICE)) {
8814       E = ICE->getSubExpr();
8815       ExprTy = E->getType();
8816 
8817       // Check if we didn't match because of an implicit cast from a 'char'
8818       // or 'short' to an 'int'.  This is done because printf is a varargs
8819       // function.
8820       if (ICE->getType() == S.Context.IntTy ||
8821           ICE->getType() == S.Context.UnsignedIntTy) {
8822         // All further checking is done on the subexpression
8823         const analyze_printf::ArgType::MatchKind ImplicitMatch =
8824             AT.matchesType(S.Context, ExprTy);
8825         if (ImplicitMatch == analyze_printf::ArgType::Match)
8826           return true;
8827         if (ImplicitMatch == ArgType::NoMatchPedantic ||
8828             ImplicitMatch == ArgType::NoMatchTypeConfusion)
8829           Match = ImplicitMatch;
8830       }
8831     }
8832   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
8833     // Special case for 'a', which has type 'int' in C.
8834     // Note, however, that we do /not/ want to treat multibyte constants like
8835     // 'MooV' as characters! This form is deprecated but still exists. In
8836     // addition, don't treat expressions as of type 'char' if one byte length
8837     // modifier is provided.
8838     if (ExprTy == S.Context.IntTy &&
8839         FS.getLengthModifier().getKind() != LengthModifier::AsChar)
8840       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
8841         ExprTy = S.Context.CharTy;
8842   }
8843 
8844   // Look through enums to their underlying type.
8845   bool IsEnum = false;
8846   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
8847     ExprTy = EnumTy->getDecl()->getIntegerType();
8848     IsEnum = true;
8849   }
8850 
8851   // %C in an Objective-C context prints a unichar, not a wchar_t.
8852   // If the argument is an integer of some kind, believe the %C and suggest
8853   // a cast instead of changing the conversion specifier.
8854   QualType IntendedTy = ExprTy;
8855   if (isObjCContext() &&
8856       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
8857     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
8858         !ExprTy->isCharType()) {
8859       // 'unichar' is defined as a typedef of unsigned short, but we should
8860       // prefer using the typedef if it is visible.
8861       IntendedTy = S.Context.UnsignedShortTy;
8862 
8863       // While we are here, check if the value is an IntegerLiteral that happens
8864       // to be within the valid range.
8865       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
8866         const llvm::APInt &V = IL->getValue();
8867         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
8868           return true;
8869       }
8870 
8871       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
8872                           Sema::LookupOrdinaryName);
8873       if (S.LookupName(Result, S.getCurScope())) {
8874         NamedDecl *ND = Result.getFoundDecl();
8875         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
8876           if (TD->getUnderlyingType() == IntendedTy)
8877             IntendedTy = S.Context.getTypedefType(TD);
8878       }
8879     }
8880   }
8881 
8882   // Special-case some of Darwin's platform-independence types by suggesting
8883   // casts to primitive types that are known to be large enough.
8884   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
8885   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
8886     QualType CastTy;
8887     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
8888     if (!CastTy.isNull()) {
8889       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
8890       // (long in ASTContext). Only complain to pedants.
8891       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
8892           (AT.isSizeT() || AT.isPtrdiffT()) &&
8893           AT.matchesType(S.Context, CastTy))
8894         Match = ArgType::NoMatchPedantic;
8895       IntendedTy = CastTy;
8896       ShouldNotPrintDirectly = true;
8897     }
8898   }
8899 
8900   // We may be able to offer a FixItHint if it is a supported type.
8901   PrintfSpecifier fixedFS = FS;
8902   bool Success =
8903       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
8904 
8905   if (Success) {
8906     // Get the fix string from the fixed format specifier
8907     SmallString<16> buf;
8908     llvm::raw_svector_ostream os(buf);
8909     fixedFS.toString(os);
8910 
8911     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
8912 
8913     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
8914       unsigned Diag;
8915       switch (Match) {
8916       case ArgType::Match: llvm_unreachable("expected non-matching");
8917       case ArgType::NoMatchPedantic:
8918         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8919         break;
8920       case ArgType::NoMatchTypeConfusion:
8921         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8922         break;
8923       case ArgType::NoMatch:
8924         Diag = diag::warn_format_conversion_argument_type_mismatch;
8925         break;
8926       }
8927 
8928       // In this case, the specifier is wrong and should be changed to match
8929       // the argument.
8930       EmitFormatDiagnostic(S.PDiag(Diag)
8931                                << AT.getRepresentativeTypeName(S.Context)
8932                                << IntendedTy << IsEnum << E->getSourceRange(),
8933                            E->getBeginLoc(),
8934                            /*IsStringLocation*/ false, SpecRange,
8935                            FixItHint::CreateReplacement(SpecRange, os.str()));
8936     } else {
8937       // The canonical type for formatting this value is different from the
8938       // actual type of the expression. (This occurs, for example, with Darwin's
8939       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
8940       // should be printed as 'long' for 64-bit compatibility.)
8941       // Rather than emitting a normal format/argument mismatch, we want to
8942       // add a cast to the recommended type (and correct the format string
8943       // if necessary).
8944       SmallString<16> CastBuf;
8945       llvm::raw_svector_ostream CastFix(CastBuf);
8946       CastFix << "(";
8947       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
8948       CastFix << ")";
8949 
8950       SmallVector<FixItHint,4> Hints;
8951       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
8952         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
8953 
8954       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
8955         // If there's already a cast present, just replace it.
8956         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
8957         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
8958 
8959       } else if (!requiresParensToAddCast(E)) {
8960         // If the expression has high enough precedence,
8961         // just write the C-style cast.
8962         Hints.push_back(
8963             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8964       } else {
8965         // Otherwise, add parens around the expression as well as the cast.
8966         CastFix << "(";
8967         Hints.push_back(
8968             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8969 
8970         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
8971         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
8972       }
8973 
8974       if (ShouldNotPrintDirectly) {
8975         // The expression has a type that should not be printed directly.
8976         // We extract the name from the typedef because we don't want to show
8977         // the underlying type in the diagnostic.
8978         StringRef Name;
8979         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
8980           Name = TypedefTy->getDecl()->getName();
8981         else
8982           Name = CastTyName;
8983         unsigned Diag = Match == ArgType::NoMatchPedantic
8984                             ? diag::warn_format_argument_needs_cast_pedantic
8985                             : diag::warn_format_argument_needs_cast;
8986         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
8987                                            << E->getSourceRange(),
8988                              E->getBeginLoc(), /*IsStringLocation=*/false,
8989                              SpecRange, Hints);
8990       } else {
8991         // In this case, the expression could be printed using a different
8992         // specifier, but we've decided that the specifier is probably correct
8993         // and we should cast instead. Just use the normal warning message.
8994         EmitFormatDiagnostic(
8995             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8996                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
8997                 << E->getSourceRange(),
8998             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
8999       }
9000     }
9001   } else {
9002     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
9003                                                    SpecifierLen);
9004     // Since the warning for passing non-POD types to variadic functions
9005     // was deferred until now, we emit a warning for non-POD
9006     // arguments here.
9007     switch (S.isValidVarArgType(ExprTy)) {
9008     case Sema::VAK_Valid:
9009     case Sema::VAK_ValidInCXX11: {
9010       unsigned Diag;
9011       switch (Match) {
9012       case ArgType::Match: llvm_unreachable("expected non-matching");
9013       case ArgType::NoMatchPedantic:
9014         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9015         break;
9016       case ArgType::NoMatchTypeConfusion:
9017         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9018         break;
9019       case ArgType::NoMatch:
9020         Diag = diag::warn_format_conversion_argument_type_mismatch;
9021         break;
9022       }
9023 
9024       EmitFormatDiagnostic(
9025           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
9026                         << IsEnum << CSR << E->getSourceRange(),
9027           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9028       break;
9029     }
9030     case Sema::VAK_Undefined:
9031     case Sema::VAK_MSVCUndefined:
9032       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
9033                                << S.getLangOpts().CPlusPlus11 << ExprTy
9034                                << CallType
9035                                << AT.getRepresentativeTypeName(S.Context) << CSR
9036                                << E->getSourceRange(),
9037                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9038       checkForCStrMembers(AT, E);
9039       break;
9040 
9041     case Sema::VAK_Invalid:
9042       if (ExprTy->isObjCObjectType())
9043         EmitFormatDiagnostic(
9044             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
9045                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9046                 << AT.getRepresentativeTypeName(S.Context) << CSR
9047                 << E->getSourceRange(),
9048             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9049       else
9050         // FIXME: If this is an initializer list, suggest removing the braces
9051         // or inserting a cast to the target type.
9052         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
9053             << isa<InitListExpr>(E) << ExprTy << CallType
9054             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
9055       break;
9056     }
9057 
9058     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
9059            "format string specifier index out of range");
9060     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
9061   }
9062 
9063   return true;
9064 }
9065 
9066 //===--- CHECK: Scanf format string checking ------------------------------===//
9067 
9068 namespace {
9069 
9070 class CheckScanfHandler : public CheckFormatHandler {
9071 public:
9072   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
9073                     const Expr *origFormatExpr, Sema::FormatStringType type,
9074                     unsigned firstDataArg, unsigned numDataArgs,
9075                     const char *beg, bool hasVAListArg,
9076                     ArrayRef<const Expr *> Args, unsigned formatIdx,
9077                     bool inFunctionCall, Sema::VariadicCallType CallType,
9078                     llvm::SmallBitVector &CheckedVarArgs,
9079                     UncoveredArgHandler &UncoveredArg)
9080       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
9081                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
9082                            inFunctionCall, CallType, CheckedVarArgs,
9083                            UncoveredArg) {}
9084 
9085   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
9086                             const char *startSpecifier,
9087                             unsigned specifierLen) override;
9088 
9089   bool HandleInvalidScanfConversionSpecifier(
9090           const analyze_scanf::ScanfSpecifier &FS,
9091           const char *startSpecifier,
9092           unsigned specifierLen) override;
9093 
9094   void HandleIncompleteScanList(const char *start, const char *end) override;
9095 };
9096 
9097 } // namespace
9098 
9099 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
9100                                                  const char *end) {
9101   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
9102                        getLocationOfByte(end), /*IsStringLocation*/true,
9103                        getSpecifierRange(start, end - start));
9104 }
9105 
9106 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
9107                                         const analyze_scanf::ScanfSpecifier &FS,
9108                                         const char *startSpecifier,
9109                                         unsigned specifierLen) {
9110   const analyze_scanf::ScanfConversionSpecifier &CS =
9111     FS.getConversionSpecifier();
9112 
9113   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
9114                                           getLocationOfByte(CS.getStart()),
9115                                           startSpecifier, specifierLen,
9116                                           CS.getStart(), CS.getLength());
9117 }
9118 
9119 bool CheckScanfHandler::HandleScanfSpecifier(
9120                                        const analyze_scanf::ScanfSpecifier &FS,
9121                                        const char *startSpecifier,
9122                                        unsigned specifierLen) {
9123   using namespace analyze_scanf;
9124   using namespace analyze_format_string;
9125 
9126   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
9127 
9128   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
9129   // be used to decide if we are using positional arguments consistently.
9130   if (FS.consumesDataArgument()) {
9131     if (atFirstArg) {
9132       atFirstArg = false;
9133       usesPositionalArgs = FS.usesPositionalArg();
9134     }
9135     else if (usesPositionalArgs != FS.usesPositionalArg()) {
9136       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9137                                         startSpecifier, specifierLen);
9138       return false;
9139     }
9140   }
9141 
9142   // Check if the field with is non-zero.
9143   const OptionalAmount &Amt = FS.getFieldWidth();
9144   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
9145     if (Amt.getConstantAmount() == 0) {
9146       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
9147                                                    Amt.getConstantLength());
9148       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
9149                            getLocationOfByte(Amt.getStart()),
9150                            /*IsStringLocation*/true, R,
9151                            FixItHint::CreateRemoval(R));
9152     }
9153   }
9154 
9155   if (!FS.consumesDataArgument()) {
9156     // FIXME: Technically specifying a precision or field width here
9157     // makes no sense.  Worth issuing a warning at some point.
9158     return true;
9159   }
9160 
9161   // Consume the argument.
9162   unsigned argIndex = FS.getArgIndex();
9163   if (argIndex < NumDataArgs) {
9164       // The check to see if the argIndex is valid will come later.
9165       // We set the bit here because we may exit early from this
9166       // function if we encounter some other error.
9167     CoveredArgs.set(argIndex);
9168   }
9169 
9170   // Check the length modifier is valid with the given conversion specifier.
9171   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
9172                                  S.getLangOpts()))
9173     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9174                                 diag::warn_format_nonsensical_length);
9175   else if (!FS.hasStandardLengthModifier())
9176     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9177   else if (!FS.hasStandardLengthConversionCombination())
9178     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9179                                 diag::warn_format_non_standard_conversion_spec);
9180 
9181   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
9182     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9183 
9184   // The remaining checks depend on the data arguments.
9185   if (HasVAListArg)
9186     return true;
9187 
9188   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9189     return false;
9190 
9191   // Check that the argument type matches the format specifier.
9192   const Expr *Ex = getDataArg(argIndex);
9193   if (!Ex)
9194     return true;
9195 
9196   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
9197 
9198   if (!AT.isValid()) {
9199     return true;
9200   }
9201 
9202   analyze_format_string::ArgType::MatchKind Match =
9203       AT.matchesType(S.Context, Ex->getType());
9204   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
9205   if (Match == analyze_format_string::ArgType::Match)
9206     return true;
9207 
9208   ScanfSpecifier fixedFS = FS;
9209   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
9210                                  S.getLangOpts(), S.Context);
9211 
9212   unsigned Diag =
9213       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9214                : diag::warn_format_conversion_argument_type_mismatch;
9215 
9216   if (Success) {
9217     // Get the fix string from the fixed format specifier.
9218     SmallString<128> buf;
9219     llvm::raw_svector_ostream os(buf);
9220     fixedFS.toString(os);
9221 
9222     EmitFormatDiagnostic(
9223         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
9224                       << Ex->getType() << false << Ex->getSourceRange(),
9225         Ex->getBeginLoc(),
9226         /*IsStringLocation*/ false,
9227         getSpecifierRange(startSpecifier, specifierLen),
9228         FixItHint::CreateReplacement(
9229             getSpecifierRange(startSpecifier, specifierLen), os.str()));
9230   } else {
9231     EmitFormatDiagnostic(S.PDiag(Diag)
9232                              << AT.getRepresentativeTypeName(S.Context)
9233                              << Ex->getType() << false << Ex->getSourceRange(),
9234                          Ex->getBeginLoc(),
9235                          /*IsStringLocation*/ false,
9236                          getSpecifierRange(startSpecifier, specifierLen));
9237   }
9238 
9239   return true;
9240 }
9241 
9242 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
9243                               const Expr *OrigFormatExpr,
9244                               ArrayRef<const Expr *> Args,
9245                               bool HasVAListArg, unsigned format_idx,
9246                               unsigned firstDataArg,
9247                               Sema::FormatStringType Type,
9248                               bool inFunctionCall,
9249                               Sema::VariadicCallType CallType,
9250                               llvm::SmallBitVector &CheckedVarArgs,
9251                               UncoveredArgHandler &UncoveredArg,
9252                               bool IgnoreStringsWithoutSpecifiers) {
9253   // CHECK: is the format string a wide literal?
9254   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
9255     CheckFormatHandler::EmitFormatDiagnostic(
9256         S, inFunctionCall, Args[format_idx],
9257         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
9258         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9259     return;
9260   }
9261 
9262   // Str - The format string.  NOTE: this is NOT null-terminated!
9263   StringRef StrRef = FExpr->getString();
9264   const char *Str = StrRef.data();
9265   // Account for cases where the string literal is truncated in a declaration.
9266   const ConstantArrayType *T =
9267     S.Context.getAsConstantArrayType(FExpr->getType());
9268   assert(T && "String literal not of constant array type!");
9269   size_t TypeSize = T->getSize().getZExtValue();
9270   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9271   const unsigned numDataArgs = Args.size() - firstDataArg;
9272 
9273   if (IgnoreStringsWithoutSpecifiers &&
9274       !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
9275           Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
9276     return;
9277 
9278   // Emit a warning if the string literal is truncated and does not contain an
9279   // embedded null character.
9280   if (TypeSize <= StrRef.size() &&
9281       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
9282     CheckFormatHandler::EmitFormatDiagnostic(
9283         S, inFunctionCall, Args[format_idx],
9284         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
9285         FExpr->getBeginLoc(),
9286         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
9287     return;
9288   }
9289 
9290   // CHECK: empty format string?
9291   if (StrLen == 0 && numDataArgs > 0) {
9292     CheckFormatHandler::EmitFormatDiagnostic(
9293         S, inFunctionCall, Args[format_idx],
9294         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
9295         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9296     return;
9297   }
9298 
9299   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
9300       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
9301       Type == Sema::FST_OSTrace) {
9302     CheckPrintfHandler H(
9303         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
9304         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
9305         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
9306         CheckedVarArgs, UncoveredArg);
9307 
9308     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
9309                                                   S.getLangOpts(),
9310                                                   S.Context.getTargetInfo(),
9311                                             Type == Sema::FST_FreeBSDKPrintf))
9312       H.DoneProcessing();
9313   } else if (Type == Sema::FST_Scanf) {
9314     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9315                         numDataArgs, Str, HasVAListArg, Args, format_idx,
9316                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
9317 
9318     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
9319                                                  S.getLangOpts(),
9320                                                  S.Context.getTargetInfo()))
9321       H.DoneProcessing();
9322   } // TODO: handle other formats
9323 }
9324 
9325 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
9326   // Str - The format string.  NOTE: this is NOT null-terminated!
9327   StringRef StrRef = FExpr->getString();
9328   const char *Str = StrRef.data();
9329   // Account for cases where the string literal is truncated in a declaration.
9330   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
9331   assert(T && "String literal not of constant array type!");
9332   size_t TypeSize = T->getSize().getZExtValue();
9333   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9334   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
9335                                                          getLangOpts(),
9336                                                          Context.getTargetInfo());
9337 }
9338 
9339 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
9340 
9341 // Returns the related absolute value function that is larger, of 0 if one
9342 // does not exist.
9343 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
9344   switch (AbsFunction) {
9345   default:
9346     return 0;
9347 
9348   case Builtin::BI__builtin_abs:
9349     return Builtin::BI__builtin_labs;
9350   case Builtin::BI__builtin_labs:
9351     return Builtin::BI__builtin_llabs;
9352   case Builtin::BI__builtin_llabs:
9353     return 0;
9354 
9355   case Builtin::BI__builtin_fabsf:
9356     return Builtin::BI__builtin_fabs;
9357   case Builtin::BI__builtin_fabs:
9358     return Builtin::BI__builtin_fabsl;
9359   case Builtin::BI__builtin_fabsl:
9360     return 0;
9361 
9362   case Builtin::BI__builtin_cabsf:
9363     return Builtin::BI__builtin_cabs;
9364   case Builtin::BI__builtin_cabs:
9365     return Builtin::BI__builtin_cabsl;
9366   case Builtin::BI__builtin_cabsl:
9367     return 0;
9368 
9369   case Builtin::BIabs:
9370     return Builtin::BIlabs;
9371   case Builtin::BIlabs:
9372     return Builtin::BIllabs;
9373   case Builtin::BIllabs:
9374     return 0;
9375 
9376   case Builtin::BIfabsf:
9377     return Builtin::BIfabs;
9378   case Builtin::BIfabs:
9379     return Builtin::BIfabsl;
9380   case Builtin::BIfabsl:
9381     return 0;
9382 
9383   case Builtin::BIcabsf:
9384    return Builtin::BIcabs;
9385   case Builtin::BIcabs:
9386     return Builtin::BIcabsl;
9387   case Builtin::BIcabsl:
9388     return 0;
9389   }
9390 }
9391 
9392 // Returns the argument type of the absolute value function.
9393 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
9394                                              unsigned AbsType) {
9395   if (AbsType == 0)
9396     return QualType();
9397 
9398   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
9399   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
9400   if (Error != ASTContext::GE_None)
9401     return QualType();
9402 
9403   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
9404   if (!FT)
9405     return QualType();
9406 
9407   if (FT->getNumParams() != 1)
9408     return QualType();
9409 
9410   return FT->getParamType(0);
9411 }
9412 
9413 // Returns the best absolute value function, or zero, based on type and
9414 // current absolute value function.
9415 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
9416                                    unsigned AbsFunctionKind) {
9417   unsigned BestKind = 0;
9418   uint64_t ArgSize = Context.getTypeSize(ArgType);
9419   for (unsigned Kind = AbsFunctionKind; Kind != 0;
9420        Kind = getLargerAbsoluteValueFunction(Kind)) {
9421     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
9422     if (Context.getTypeSize(ParamType) >= ArgSize) {
9423       if (BestKind == 0)
9424         BestKind = Kind;
9425       else if (Context.hasSameType(ParamType, ArgType)) {
9426         BestKind = Kind;
9427         break;
9428       }
9429     }
9430   }
9431   return BestKind;
9432 }
9433 
9434 enum AbsoluteValueKind {
9435   AVK_Integer,
9436   AVK_Floating,
9437   AVK_Complex
9438 };
9439 
9440 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
9441   if (T->isIntegralOrEnumerationType())
9442     return AVK_Integer;
9443   if (T->isRealFloatingType())
9444     return AVK_Floating;
9445   if (T->isAnyComplexType())
9446     return AVK_Complex;
9447 
9448   llvm_unreachable("Type not integer, floating, or complex");
9449 }
9450 
9451 // Changes the absolute value function to a different type.  Preserves whether
9452 // the function is a builtin.
9453 static unsigned changeAbsFunction(unsigned AbsKind,
9454                                   AbsoluteValueKind ValueKind) {
9455   switch (ValueKind) {
9456   case AVK_Integer:
9457     switch (AbsKind) {
9458     default:
9459       return 0;
9460     case Builtin::BI__builtin_fabsf:
9461     case Builtin::BI__builtin_fabs:
9462     case Builtin::BI__builtin_fabsl:
9463     case Builtin::BI__builtin_cabsf:
9464     case Builtin::BI__builtin_cabs:
9465     case Builtin::BI__builtin_cabsl:
9466       return Builtin::BI__builtin_abs;
9467     case Builtin::BIfabsf:
9468     case Builtin::BIfabs:
9469     case Builtin::BIfabsl:
9470     case Builtin::BIcabsf:
9471     case Builtin::BIcabs:
9472     case Builtin::BIcabsl:
9473       return Builtin::BIabs;
9474     }
9475   case AVK_Floating:
9476     switch (AbsKind) {
9477     default:
9478       return 0;
9479     case Builtin::BI__builtin_abs:
9480     case Builtin::BI__builtin_labs:
9481     case Builtin::BI__builtin_llabs:
9482     case Builtin::BI__builtin_cabsf:
9483     case Builtin::BI__builtin_cabs:
9484     case Builtin::BI__builtin_cabsl:
9485       return Builtin::BI__builtin_fabsf;
9486     case Builtin::BIabs:
9487     case Builtin::BIlabs:
9488     case Builtin::BIllabs:
9489     case Builtin::BIcabsf:
9490     case Builtin::BIcabs:
9491     case Builtin::BIcabsl:
9492       return Builtin::BIfabsf;
9493     }
9494   case AVK_Complex:
9495     switch (AbsKind) {
9496     default:
9497       return 0;
9498     case Builtin::BI__builtin_abs:
9499     case Builtin::BI__builtin_labs:
9500     case Builtin::BI__builtin_llabs:
9501     case Builtin::BI__builtin_fabsf:
9502     case Builtin::BI__builtin_fabs:
9503     case Builtin::BI__builtin_fabsl:
9504       return Builtin::BI__builtin_cabsf;
9505     case Builtin::BIabs:
9506     case Builtin::BIlabs:
9507     case Builtin::BIllabs:
9508     case Builtin::BIfabsf:
9509     case Builtin::BIfabs:
9510     case Builtin::BIfabsl:
9511       return Builtin::BIcabsf;
9512     }
9513   }
9514   llvm_unreachable("Unable to convert function");
9515 }
9516 
9517 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
9518   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
9519   if (!FnInfo)
9520     return 0;
9521 
9522   switch (FDecl->getBuiltinID()) {
9523   default:
9524     return 0;
9525   case Builtin::BI__builtin_abs:
9526   case Builtin::BI__builtin_fabs:
9527   case Builtin::BI__builtin_fabsf:
9528   case Builtin::BI__builtin_fabsl:
9529   case Builtin::BI__builtin_labs:
9530   case Builtin::BI__builtin_llabs:
9531   case Builtin::BI__builtin_cabs:
9532   case Builtin::BI__builtin_cabsf:
9533   case Builtin::BI__builtin_cabsl:
9534   case Builtin::BIabs:
9535   case Builtin::BIlabs:
9536   case Builtin::BIllabs:
9537   case Builtin::BIfabs:
9538   case Builtin::BIfabsf:
9539   case Builtin::BIfabsl:
9540   case Builtin::BIcabs:
9541   case Builtin::BIcabsf:
9542   case Builtin::BIcabsl:
9543     return FDecl->getBuiltinID();
9544   }
9545   llvm_unreachable("Unknown Builtin type");
9546 }
9547 
9548 // If the replacement is valid, emit a note with replacement function.
9549 // Additionally, suggest including the proper header if not already included.
9550 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
9551                             unsigned AbsKind, QualType ArgType) {
9552   bool EmitHeaderHint = true;
9553   const char *HeaderName = nullptr;
9554   const char *FunctionName = nullptr;
9555   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
9556     FunctionName = "std::abs";
9557     if (ArgType->isIntegralOrEnumerationType()) {
9558       HeaderName = "cstdlib";
9559     } else if (ArgType->isRealFloatingType()) {
9560       HeaderName = "cmath";
9561     } else {
9562       llvm_unreachable("Invalid Type");
9563     }
9564 
9565     // Lookup all std::abs
9566     if (NamespaceDecl *Std = S.getStdNamespace()) {
9567       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
9568       R.suppressDiagnostics();
9569       S.LookupQualifiedName(R, Std);
9570 
9571       for (const auto *I : R) {
9572         const FunctionDecl *FDecl = nullptr;
9573         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
9574           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
9575         } else {
9576           FDecl = dyn_cast<FunctionDecl>(I);
9577         }
9578         if (!FDecl)
9579           continue;
9580 
9581         // Found std::abs(), check that they are the right ones.
9582         if (FDecl->getNumParams() != 1)
9583           continue;
9584 
9585         // Check that the parameter type can handle the argument.
9586         QualType ParamType = FDecl->getParamDecl(0)->getType();
9587         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
9588             S.Context.getTypeSize(ArgType) <=
9589                 S.Context.getTypeSize(ParamType)) {
9590           // Found a function, don't need the header hint.
9591           EmitHeaderHint = false;
9592           break;
9593         }
9594       }
9595     }
9596   } else {
9597     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
9598     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
9599 
9600     if (HeaderName) {
9601       DeclarationName DN(&S.Context.Idents.get(FunctionName));
9602       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
9603       R.suppressDiagnostics();
9604       S.LookupName(R, S.getCurScope());
9605 
9606       if (R.isSingleResult()) {
9607         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
9608         if (FD && FD->getBuiltinID() == AbsKind) {
9609           EmitHeaderHint = false;
9610         } else {
9611           return;
9612         }
9613       } else if (!R.empty()) {
9614         return;
9615       }
9616     }
9617   }
9618 
9619   S.Diag(Loc, diag::note_replace_abs_function)
9620       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
9621 
9622   if (!HeaderName)
9623     return;
9624 
9625   if (!EmitHeaderHint)
9626     return;
9627 
9628   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
9629                                                     << FunctionName;
9630 }
9631 
9632 template <std::size_t StrLen>
9633 static bool IsStdFunction(const FunctionDecl *FDecl,
9634                           const char (&Str)[StrLen]) {
9635   if (!FDecl)
9636     return false;
9637   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
9638     return false;
9639   if (!FDecl->isInStdNamespace())
9640     return false;
9641 
9642   return true;
9643 }
9644 
9645 // Warn when using the wrong abs() function.
9646 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
9647                                       const FunctionDecl *FDecl) {
9648   if (Call->getNumArgs() != 1)
9649     return;
9650 
9651   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
9652   bool IsStdAbs = IsStdFunction(FDecl, "abs");
9653   if (AbsKind == 0 && !IsStdAbs)
9654     return;
9655 
9656   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9657   QualType ParamType = Call->getArg(0)->getType();
9658 
9659   // Unsigned types cannot be negative.  Suggest removing the absolute value
9660   // function call.
9661   if (ArgType->isUnsignedIntegerType()) {
9662     const char *FunctionName =
9663         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
9664     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
9665     Diag(Call->getExprLoc(), diag::note_remove_abs)
9666         << FunctionName
9667         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
9668     return;
9669   }
9670 
9671   // Taking the absolute value of a pointer is very suspicious, they probably
9672   // wanted to index into an array, dereference a pointer, call a function, etc.
9673   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
9674     unsigned DiagType = 0;
9675     if (ArgType->isFunctionType())
9676       DiagType = 1;
9677     else if (ArgType->isArrayType())
9678       DiagType = 2;
9679 
9680     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
9681     return;
9682   }
9683 
9684   // std::abs has overloads which prevent most of the absolute value problems
9685   // from occurring.
9686   if (IsStdAbs)
9687     return;
9688 
9689   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
9690   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
9691 
9692   // The argument and parameter are the same kind.  Check if they are the right
9693   // size.
9694   if (ArgValueKind == ParamValueKind) {
9695     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
9696       return;
9697 
9698     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
9699     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
9700         << FDecl << ArgType << ParamType;
9701 
9702     if (NewAbsKind == 0)
9703       return;
9704 
9705     emitReplacement(*this, Call->getExprLoc(),
9706                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9707     return;
9708   }
9709 
9710   // ArgValueKind != ParamValueKind
9711   // The wrong type of absolute value function was used.  Attempt to find the
9712   // proper one.
9713   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
9714   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
9715   if (NewAbsKind == 0)
9716     return;
9717 
9718   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
9719       << FDecl << ParamValueKind << ArgValueKind;
9720 
9721   emitReplacement(*this, Call->getExprLoc(),
9722                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9723 }
9724 
9725 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
9726 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
9727                                 const FunctionDecl *FDecl) {
9728   if (!Call || !FDecl) return;
9729 
9730   // Ignore template specializations and macros.
9731   if (inTemplateInstantiation()) return;
9732   if (Call->getExprLoc().isMacroID()) return;
9733 
9734   // Only care about the one template argument, two function parameter std::max
9735   if (Call->getNumArgs() != 2) return;
9736   if (!IsStdFunction(FDecl, "max")) return;
9737   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
9738   if (!ArgList) return;
9739   if (ArgList->size() != 1) return;
9740 
9741   // Check that template type argument is unsigned integer.
9742   const auto& TA = ArgList->get(0);
9743   if (TA.getKind() != TemplateArgument::Type) return;
9744   QualType ArgType = TA.getAsType();
9745   if (!ArgType->isUnsignedIntegerType()) return;
9746 
9747   // See if either argument is a literal zero.
9748   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
9749     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
9750     if (!MTE) return false;
9751     const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
9752     if (!Num) return false;
9753     if (Num->getValue() != 0) return false;
9754     return true;
9755   };
9756 
9757   const Expr *FirstArg = Call->getArg(0);
9758   const Expr *SecondArg = Call->getArg(1);
9759   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
9760   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
9761 
9762   // Only warn when exactly one argument is zero.
9763   if (IsFirstArgZero == IsSecondArgZero) return;
9764 
9765   SourceRange FirstRange = FirstArg->getSourceRange();
9766   SourceRange SecondRange = SecondArg->getSourceRange();
9767 
9768   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
9769 
9770   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
9771       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
9772 
9773   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
9774   SourceRange RemovalRange;
9775   if (IsFirstArgZero) {
9776     RemovalRange = SourceRange(FirstRange.getBegin(),
9777                                SecondRange.getBegin().getLocWithOffset(-1));
9778   } else {
9779     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
9780                                SecondRange.getEnd());
9781   }
9782 
9783   Diag(Call->getExprLoc(), diag::note_remove_max_call)
9784         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
9785         << FixItHint::CreateRemoval(RemovalRange);
9786 }
9787 
9788 //===--- CHECK: Standard memory functions ---------------------------------===//
9789 
9790 /// Takes the expression passed to the size_t parameter of functions
9791 /// such as memcmp, strncat, etc and warns if it's a comparison.
9792 ///
9793 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
9794 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
9795                                            IdentifierInfo *FnName,
9796                                            SourceLocation FnLoc,
9797                                            SourceLocation RParenLoc) {
9798   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
9799   if (!Size)
9800     return false;
9801 
9802   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
9803   if (!Size->isComparisonOp() && !Size->isLogicalOp())
9804     return false;
9805 
9806   SourceRange SizeRange = Size->getSourceRange();
9807   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
9808       << SizeRange << FnName;
9809   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
9810       << FnName
9811       << FixItHint::CreateInsertion(
9812              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
9813       << FixItHint::CreateRemoval(RParenLoc);
9814   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
9815       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
9816       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
9817                                     ")");
9818 
9819   return true;
9820 }
9821 
9822 /// Determine whether the given type is or contains a dynamic class type
9823 /// (e.g., whether it has a vtable).
9824 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
9825                                                      bool &IsContained) {
9826   // Look through array types while ignoring qualifiers.
9827   const Type *Ty = T->getBaseElementTypeUnsafe();
9828   IsContained = false;
9829 
9830   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
9831   RD = RD ? RD->getDefinition() : nullptr;
9832   if (!RD || RD->isInvalidDecl())
9833     return nullptr;
9834 
9835   if (RD->isDynamicClass())
9836     return RD;
9837 
9838   // Check all the fields.  If any bases were dynamic, the class is dynamic.
9839   // It's impossible for a class to transitively contain itself by value, so
9840   // infinite recursion is impossible.
9841   for (auto *FD : RD->fields()) {
9842     bool SubContained;
9843     if (const CXXRecordDecl *ContainedRD =
9844             getContainedDynamicClass(FD->getType(), SubContained)) {
9845       IsContained = true;
9846       return ContainedRD;
9847     }
9848   }
9849 
9850   return nullptr;
9851 }
9852 
9853 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
9854   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
9855     if (Unary->getKind() == UETT_SizeOf)
9856       return Unary;
9857   return nullptr;
9858 }
9859 
9860 /// If E is a sizeof expression, returns its argument expression,
9861 /// otherwise returns NULL.
9862 static const Expr *getSizeOfExprArg(const Expr *E) {
9863   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9864     if (!SizeOf->isArgumentType())
9865       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
9866   return nullptr;
9867 }
9868 
9869 /// If E is a sizeof expression, returns its argument type.
9870 static QualType getSizeOfArgType(const Expr *E) {
9871   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9872     return SizeOf->getTypeOfArgument();
9873   return QualType();
9874 }
9875 
9876 namespace {
9877 
9878 struct SearchNonTrivialToInitializeField
9879     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
9880   using Super =
9881       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
9882 
9883   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
9884 
9885   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
9886                      SourceLocation SL) {
9887     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9888       asDerived().visitArray(PDIK, AT, SL);
9889       return;
9890     }
9891 
9892     Super::visitWithKind(PDIK, FT, SL);
9893   }
9894 
9895   void visitARCStrong(QualType FT, SourceLocation SL) {
9896     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9897   }
9898   void visitARCWeak(QualType FT, SourceLocation SL) {
9899     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9900   }
9901   void visitStruct(QualType FT, SourceLocation SL) {
9902     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9903       visit(FD->getType(), FD->getLocation());
9904   }
9905   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
9906                   const ArrayType *AT, SourceLocation SL) {
9907     visit(getContext().getBaseElementType(AT), SL);
9908   }
9909   void visitTrivial(QualType FT, SourceLocation SL) {}
9910 
9911   static void diag(QualType RT, const Expr *E, Sema &S) {
9912     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
9913   }
9914 
9915   ASTContext &getContext() { return S.getASTContext(); }
9916 
9917   const Expr *E;
9918   Sema &S;
9919 };
9920 
9921 struct SearchNonTrivialToCopyField
9922     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
9923   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
9924 
9925   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
9926 
9927   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
9928                      SourceLocation SL) {
9929     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9930       asDerived().visitArray(PCK, AT, SL);
9931       return;
9932     }
9933 
9934     Super::visitWithKind(PCK, FT, SL);
9935   }
9936 
9937   void visitARCStrong(QualType FT, SourceLocation SL) {
9938     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9939   }
9940   void visitARCWeak(QualType FT, SourceLocation SL) {
9941     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9942   }
9943   void visitStruct(QualType FT, SourceLocation SL) {
9944     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9945       visit(FD->getType(), FD->getLocation());
9946   }
9947   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
9948                   SourceLocation SL) {
9949     visit(getContext().getBaseElementType(AT), SL);
9950   }
9951   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
9952                 SourceLocation SL) {}
9953   void visitTrivial(QualType FT, SourceLocation SL) {}
9954   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
9955 
9956   static void diag(QualType RT, const Expr *E, Sema &S) {
9957     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
9958   }
9959 
9960   ASTContext &getContext() { return S.getASTContext(); }
9961 
9962   const Expr *E;
9963   Sema &S;
9964 };
9965 
9966 }
9967 
9968 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
9969 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
9970   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
9971 
9972   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
9973     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
9974       return false;
9975 
9976     return doesExprLikelyComputeSize(BO->getLHS()) ||
9977            doesExprLikelyComputeSize(BO->getRHS());
9978   }
9979 
9980   return getAsSizeOfExpr(SizeofExpr) != nullptr;
9981 }
9982 
9983 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
9984 ///
9985 /// \code
9986 ///   #define MACRO 0
9987 ///   foo(MACRO);
9988 ///   foo(0);
9989 /// \endcode
9990 ///
9991 /// This should return true for the first call to foo, but not for the second
9992 /// (regardless of whether foo is a macro or function).
9993 static bool isArgumentExpandedFromMacro(SourceManager &SM,
9994                                         SourceLocation CallLoc,
9995                                         SourceLocation ArgLoc) {
9996   if (!CallLoc.isMacroID())
9997     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
9998 
9999   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
10000          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
10001 }
10002 
10003 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
10004 /// last two arguments transposed.
10005 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
10006   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
10007     return;
10008 
10009   const Expr *SizeArg =
10010     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
10011 
10012   auto isLiteralZero = [](const Expr *E) {
10013     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
10014   };
10015 
10016   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
10017   SourceLocation CallLoc = Call->getRParenLoc();
10018   SourceManager &SM = S.getSourceManager();
10019   if (isLiteralZero(SizeArg) &&
10020       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
10021 
10022     SourceLocation DiagLoc = SizeArg->getExprLoc();
10023 
10024     // Some platforms #define bzero to __builtin_memset. See if this is the
10025     // case, and if so, emit a better diagnostic.
10026     if (BId == Builtin::BIbzero ||
10027         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
10028                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
10029       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
10030       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
10031     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
10032       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
10033       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
10034     }
10035     return;
10036   }
10037 
10038   // If the second argument to a memset is a sizeof expression and the third
10039   // isn't, this is also likely an error. This should catch
10040   // 'memset(buf, sizeof(buf), 0xff)'.
10041   if (BId == Builtin::BImemset &&
10042       doesExprLikelyComputeSize(Call->getArg(1)) &&
10043       !doesExprLikelyComputeSize(Call->getArg(2))) {
10044     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
10045     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
10046     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
10047     return;
10048   }
10049 }
10050 
10051 /// Check for dangerous or invalid arguments to memset().
10052 ///
10053 /// This issues warnings on known problematic, dangerous or unspecified
10054 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
10055 /// function calls.
10056 ///
10057 /// \param Call The call expression to diagnose.
10058 void Sema::CheckMemaccessArguments(const CallExpr *Call,
10059                                    unsigned BId,
10060                                    IdentifierInfo *FnName) {
10061   assert(BId != 0);
10062 
10063   // It is possible to have a non-standard definition of memset.  Validate
10064   // we have enough arguments, and if not, abort further checking.
10065   unsigned ExpectedNumArgs =
10066       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
10067   if (Call->getNumArgs() < ExpectedNumArgs)
10068     return;
10069 
10070   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
10071                       BId == Builtin::BIstrndup ? 1 : 2);
10072   unsigned LenArg =
10073       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
10074   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
10075 
10076   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
10077                                      Call->getBeginLoc(), Call->getRParenLoc()))
10078     return;
10079 
10080   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
10081   CheckMemaccessSize(*this, BId, Call);
10082 
10083   // We have special checking when the length is a sizeof expression.
10084   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
10085   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
10086   llvm::FoldingSetNodeID SizeOfArgID;
10087 
10088   // Although widely used, 'bzero' is not a standard function. Be more strict
10089   // with the argument types before allowing diagnostics and only allow the
10090   // form bzero(ptr, sizeof(...)).
10091   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10092   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
10093     return;
10094 
10095   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
10096     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
10097     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
10098 
10099     QualType DestTy = Dest->getType();
10100     QualType PointeeTy;
10101     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
10102       PointeeTy = DestPtrTy->getPointeeType();
10103 
10104       // Never warn about void type pointers. This can be used to suppress
10105       // false positives.
10106       if (PointeeTy->isVoidType())
10107         continue;
10108 
10109       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
10110       // actually comparing the expressions for equality. Because computing the
10111       // expression IDs can be expensive, we only do this if the diagnostic is
10112       // enabled.
10113       if (SizeOfArg &&
10114           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
10115                            SizeOfArg->getExprLoc())) {
10116         // We only compute IDs for expressions if the warning is enabled, and
10117         // cache the sizeof arg's ID.
10118         if (SizeOfArgID == llvm::FoldingSetNodeID())
10119           SizeOfArg->Profile(SizeOfArgID, Context, true);
10120         llvm::FoldingSetNodeID DestID;
10121         Dest->Profile(DestID, Context, true);
10122         if (DestID == SizeOfArgID) {
10123           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
10124           //       over sizeof(src) as well.
10125           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
10126           StringRef ReadableName = FnName->getName();
10127 
10128           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
10129             if (UnaryOp->getOpcode() == UO_AddrOf)
10130               ActionIdx = 1; // If its an address-of operator, just remove it.
10131           if (!PointeeTy->isIncompleteType() &&
10132               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
10133             ActionIdx = 2; // If the pointee's size is sizeof(char),
10134                            // suggest an explicit length.
10135 
10136           // If the function is defined as a builtin macro, do not show macro
10137           // expansion.
10138           SourceLocation SL = SizeOfArg->getExprLoc();
10139           SourceRange DSR = Dest->getSourceRange();
10140           SourceRange SSR = SizeOfArg->getSourceRange();
10141           SourceManager &SM = getSourceManager();
10142 
10143           if (SM.isMacroArgExpansion(SL)) {
10144             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
10145             SL = SM.getSpellingLoc(SL);
10146             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
10147                              SM.getSpellingLoc(DSR.getEnd()));
10148             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
10149                              SM.getSpellingLoc(SSR.getEnd()));
10150           }
10151 
10152           DiagRuntimeBehavior(SL, SizeOfArg,
10153                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
10154                                 << ReadableName
10155                                 << PointeeTy
10156                                 << DestTy
10157                                 << DSR
10158                                 << SSR);
10159           DiagRuntimeBehavior(SL, SizeOfArg,
10160                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
10161                                 << ActionIdx
10162                                 << SSR);
10163 
10164           break;
10165         }
10166       }
10167 
10168       // Also check for cases where the sizeof argument is the exact same
10169       // type as the memory argument, and where it points to a user-defined
10170       // record type.
10171       if (SizeOfArgTy != QualType()) {
10172         if (PointeeTy->isRecordType() &&
10173             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
10174           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
10175                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
10176                                 << FnName << SizeOfArgTy << ArgIdx
10177                                 << PointeeTy << Dest->getSourceRange()
10178                                 << LenExpr->getSourceRange());
10179           break;
10180         }
10181       }
10182     } else if (DestTy->isArrayType()) {
10183       PointeeTy = DestTy;
10184     }
10185 
10186     if (PointeeTy == QualType())
10187       continue;
10188 
10189     // Always complain about dynamic classes.
10190     bool IsContained;
10191     if (const CXXRecordDecl *ContainedRD =
10192             getContainedDynamicClass(PointeeTy, IsContained)) {
10193 
10194       unsigned OperationType = 0;
10195       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
10196       // "overwritten" if we're warning about the destination for any call
10197       // but memcmp; otherwise a verb appropriate to the call.
10198       if (ArgIdx != 0 || IsCmp) {
10199         if (BId == Builtin::BImemcpy)
10200           OperationType = 1;
10201         else if(BId == Builtin::BImemmove)
10202           OperationType = 2;
10203         else if (IsCmp)
10204           OperationType = 3;
10205       }
10206 
10207       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10208                           PDiag(diag::warn_dyn_class_memaccess)
10209                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
10210                               << IsContained << ContainedRD << OperationType
10211                               << Call->getCallee()->getSourceRange());
10212     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
10213              BId != Builtin::BImemset)
10214       DiagRuntimeBehavior(
10215         Dest->getExprLoc(), Dest,
10216         PDiag(diag::warn_arc_object_memaccess)
10217           << ArgIdx << FnName << PointeeTy
10218           << Call->getCallee()->getSourceRange());
10219     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
10220       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10221           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
10222         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10223                             PDiag(diag::warn_cstruct_memaccess)
10224                                 << ArgIdx << FnName << PointeeTy << 0);
10225         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
10226       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10227                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
10228         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10229                             PDiag(diag::warn_cstruct_memaccess)
10230                                 << ArgIdx << FnName << PointeeTy << 1);
10231         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
10232       } else {
10233         continue;
10234       }
10235     } else
10236       continue;
10237 
10238     DiagRuntimeBehavior(
10239       Dest->getExprLoc(), Dest,
10240       PDiag(diag::note_bad_memaccess_silence)
10241         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
10242     break;
10243   }
10244 }
10245 
10246 // A little helper routine: ignore addition and subtraction of integer literals.
10247 // This intentionally does not ignore all integer constant expressions because
10248 // we don't want to remove sizeof().
10249 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
10250   Ex = Ex->IgnoreParenCasts();
10251 
10252   while (true) {
10253     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
10254     if (!BO || !BO->isAdditiveOp())
10255       break;
10256 
10257     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
10258     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
10259 
10260     if (isa<IntegerLiteral>(RHS))
10261       Ex = LHS;
10262     else if (isa<IntegerLiteral>(LHS))
10263       Ex = RHS;
10264     else
10265       break;
10266   }
10267 
10268   return Ex;
10269 }
10270 
10271 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
10272                                                       ASTContext &Context) {
10273   // Only handle constant-sized or VLAs, but not flexible members.
10274   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
10275     // Only issue the FIXIT for arrays of size > 1.
10276     if (CAT->getSize().getSExtValue() <= 1)
10277       return false;
10278   } else if (!Ty->isVariableArrayType()) {
10279     return false;
10280   }
10281   return true;
10282 }
10283 
10284 // Warn if the user has made the 'size' argument to strlcpy or strlcat
10285 // be the size of the source, instead of the destination.
10286 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
10287                                     IdentifierInfo *FnName) {
10288 
10289   // Don't crash if the user has the wrong number of arguments
10290   unsigned NumArgs = Call->getNumArgs();
10291   if ((NumArgs != 3) && (NumArgs != 4))
10292     return;
10293 
10294   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
10295   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
10296   const Expr *CompareWithSrc = nullptr;
10297 
10298   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
10299                                      Call->getBeginLoc(), Call->getRParenLoc()))
10300     return;
10301 
10302   // Look for 'strlcpy(dst, x, sizeof(x))'
10303   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
10304     CompareWithSrc = Ex;
10305   else {
10306     // Look for 'strlcpy(dst, x, strlen(x))'
10307     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
10308       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
10309           SizeCall->getNumArgs() == 1)
10310         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
10311     }
10312   }
10313 
10314   if (!CompareWithSrc)
10315     return;
10316 
10317   // Determine if the argument to sizeof/strlen is equal to the source
10318   // argument.  In principle there's all kinds of things you could do
10319   // here, for instance creating an == expression and evaluating it with
10320   // EvaluateAsBooleanCondition, but this uses a more direct technique:
10321   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
10322   if (!SrcArgDRE)
10323     return;
10324 
10325   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
10326   if (!CompareWithSrcDRE ||
10327       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
10328     return;
10329 
10330   const Expr *OriginalSizeArg = Call->getArg(2);
10331   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
10332       << OriginalSizeArg->getSourceRange() << FnName;
10333 
10334   // Output a FIXIT hint if the destination is an array (rather than a
10335   // pointer to an array).  This could be enhanced to handle some
10336   // pointers if we know the actual size, like if DstArg is 'array+2'
10337   // we could say 'sizeof(array)-2'.
10338   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
10339   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
10340     return;
10341 
10342   SmallString<128> sizeString;
10343   llvm::raw_svector_ostream OS(sizeString);
10344   OS << "sizeof(";
10345   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10346   OS << ")";
10347 
10348   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
10349       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
10350                                       OS.str());
10351 }
10352 
10353 /// Check if two expressions refer to the same declaration.
10354 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
10355   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
10356     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
10357       return D1->getDecl() == D2->getDecl();
10358   return false;
10359 }
10360 
10361 static const Expr *getStrlenExprArg(const Expr *E) {
10362   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10363     const FunctionDecl *FD = CE->getDirectCallee();
10364     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
10365       return nullptr;
10366     return CE->getArg(0)->IgnoreParenCasts();
10367   }
10368   return nullptr;
10369 }
10370 
10371 // Warn on anti-patterns as the 'size' argument to strncat.
10372 // The correct size argument should look like following:
10373 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
10374 void Sema::CheckStrncatArguments(const CallExpr *CE,
10375                                  IdentifierInfo *FnName) {
10376   // Don't crash if the user has the wrong number of arguments.
10377   if (CE->getNumArgs() < 3)
10378     return;
10379   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
10380   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
10381   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
10382 
10383   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
10384                                      CE->getRParenLoc()))
10385     return;
10386 
10387   // Identify common expressions, which are wrongly used as the size argument
10388   // to strncat and may lead to buffer overflows.
10389   unsigned PatternType = 0;
10390   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
10391     // - sizeof(dst)
10392     if (referToTheSameDecl(SizeOfArg, DstArg))
10393       PatternType = 1;
10394     // - sizeof(src)
10395     else if (referToTheSameDecl(SizeOfArg, SrcArg))
10396       PatternType = 2;
10397   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
10398     if (BE->getOpcode() == BO_Sub) {
10399       const Expr *L = BE->getLHS()->IgnoreParenCasts();
10400       const Expr *R = BE->getRHS()->IgnoreParenCasts();
10401       // - sizeof(dst) - strlen(dst)
10402       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
10403           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
10404         PatternType = 1;
10405       // - sizeof(src) - (anything)
10406       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
10407         PatternType = 2;
10408     }
10409   }
10410 
10411   if (PatternType == 0)
10412     return;
10413 
10414   // Generate the diagnostic.
10415   SourceLocation SL = LenArg->getBeginLoc();
10416   SourceRange SR = LenArg->getSourceRange();
10417   SourceManager &SM = getSourceManager();
10418 
10419   // If the function is defined as a builtin macro, do not show macro expansion.
10420   if (SM.isMacroArgExpansion(SL)) {
10421     SL = SM.getSpellingLoc(SL);
10422     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
10423                      SM.getSpellingLoc(SR.getEnd()));
10424   }
10425 
10426   // Check if the destination is an array (rather than a pointer to an array).
10427   QualType DstTy = DstArg->getType();
10428   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
10429                                                                     Context);
10430   if (!isKnownSizeArray) {
10431     if (PatternType == 1)
10432       Diag(SL, diag::warn_strncat_wrong_size) << SR;
10433     else
10434       Diag(SL, diag::warn_strncat_src_size) << SR;
10435     return;
10436   }
10437 
10438   if (PatternType == 1)
10439     Diag(SL, diag::warn_strncat_large_size) << SR;
10440   else
10441     Diag(SL, diag::warn_strncat_src_size) << SR;
10442 
10443   SmallString<128> sizeString;
10444   llvm::raw_svector_ostream OS(sizeString);
10445   OS << "sizeof(";
10446   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10447   OS << ") - ";
10448   OS << "strlen(";
10449   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10450   OS << ") - 1";
10451 
10452   Diag(SL, diag::note_strncat_wrong_size)
10453     << FixItHint::CreateReplacement(SR, OS.str());
10454 }
10455 
10456 namespace {
10457 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
10458                                 const UnaryOperator *UnaryExpr, const Decl *D) {
10459   if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) {
10460     S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
10461         << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
10462     return;
10463   }
10464 }
10465 
10466 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
10467                                  const UnaryOperator *UnaryExpr) {
10468   if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
10469     const Decl *D = Lvalue->getDecl();
10470     if (isa<VarDecl, FunctionDecl>(D))
10471       return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
10472   }
10473 
10474   if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
10475     return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
10476                                       Lvalue->getMemberDecl());
10477 }
10478 
10479 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
10480                             const UnaryOperator *UnaryExpr) {
10481   const auto *Lambda = dyn_cast<LambdaExpr>(
10482       UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens());
10483   if (!Lambda)
10484     return;
10485 
10486   S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
10487       << CalleeName << 2 /*object: lambda expression*/;
10488 }
10489 
10490 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
10491                                   const DeclRefExpr *Lvalue) {
10492   const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
10493   if (Var == nullptr)
10494     return;
10495 
10496   S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
10497       << CalleeName << 0 /*object: */ << Var;
10498 }
10499 
10500 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
10501                             const CastExpr *Cast) {
10502   SmallString<128> SizeString;
10503   llvm::raw_svector_ostream OS(SizeString);
10504 
10505   clang::CastKind Kind = Cast->getCastKind();
10506   if (Kind == clang::CK_BitCast &&
10507       !Cast->getSubExpr()->getType()->isFunctionPointerType())
10508     return;
10509   if (Kind == clang::CK_IntegralToPointer &&
10510       !isa<IntegerLiteral>(
10511           Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
10512     return;
10513 
10514   switch (Cast->getCastKind()) {
10515   case clang::CK_BitCast:
10516   case clang::CK_IntegralToPointer:
10517   case clang::CK_FunctionToPointerDecay:
10518     OS << '\'';
10519     Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
10520     OS << '\'';
10521     break;
10522   default:
10523     return;
10524   }
10525 
10526   S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
10527       << CalleeName << 0 /*object: */ << OS.str();
10528 }
10529 } // namespace
10530 
10531 /// Alerts the user that they are attempting to free a non-malloc'd object.
10532 void Sema::CheckFreeArguments(const CallExpr *E) {
10533   const std::string CalleeName =
10534       dyn_cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
10535 
10536   { // Prefer something that doesn't involve a cast to make things simpler.
10537     const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
10538     if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
10539       switch (UnaryExpr->getOpcode()) {
10540       case UnaryOperator::Opcode::UO_AddrOf:
10541         return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
10542       case UnaryOperator::Opcode::UO_Plus:
10543         return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
10544       default:
10545         break;
10546       }
10547 
10548     if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
10549       if (Lvalue->getType()->isArrayType())
10550         return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
10551 
10552     if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
10553       Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
10554           << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
10555       return;
10556     }
10557 
10558     if (isa<BlockExpr>(Arg)) {
10559       Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
10560           << CalleeName << 1 /*object: block*/;
10561       return;
10562     }
10563   }
10564   // Maybe the cast was important, check after the other cases.
10565   if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
10566     return CheckFreeArgumentsCast(*this, CalleeName, Cast);
10567 }
10568 
10569 void
10570 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
10571                          SourceLocation ReturnLoc,
10572                          bool isObjCMethod,
10573                          const AttrVec *Attrs,
10574                          const FunctionDecl *FD) {
10575   // Check if the return value is null but should not be.
10576   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
10577        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
10578       CheckNonNullExpr(*this, RetValExp))
10579     Diag(ReturnLoc, diag::warn_null_ret)
10580       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
10581 
10582   // C++11 [basic.stc.dynamic.allocation]p4:
10583   //   If an allocation function declared with a non-throwing
10584   //   exception-specification fails to allocate storage, it shall return
10585   //   a null pointer. Any other allocation function that fails to allocate
10586   //   storage shall indicate failure only by throwing an exception [...]
10587   if (FD) {
10588     OverloadedOperatorKind Op = FD->getOverloadedOperator();
10589     if (Op == OO_New || Op == OO_Array_New) {
10590       const FunctionProtoType *Proto
10591         = FD->getType()->castAs<FunctionProtoType>();
10592       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
10593           CheckNonNullExpr(*this, RetValExp))
10594         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
10595           << FD << getLangOpts().CPlusPlus11;
10596     }
10597   }
10598 
10599   // PPC MMA non-pointer types are not allowed as return type. Checking the type
10600   // here prevent the user from using a PPC MMA type as trailing return type.
10601   if (Context.getTargetInfo().getTriple().isPPC64())
10602     CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
10603 }
10604 
10605 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
10606 
10607 /// Check for comparisons of floating point operands using != and ==.
10608 /// Issue a warning if these are no self-comparisons, as they are not likely
10609 /// to do what the programmer intended.
10610 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
10611   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
10612   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
10613 
10614   // Special case: check for x == x (which is OK).
10615   // Do not emit warnings for such cases.
10616   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
10617     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
10618       if (DRL->getDecl() == DRR->getDecl())
10619         return;
10620 
10621   // Special case: check for comparisons against literals that can be exactly
10622   //  represented by APFloat.  In such cases, do not emit a warning.  This
10623   //  is a heuristic: often comparison against such literals are used to
10624   //  detect if a value in a variable has not changed.  This clearly can
10625   //  lead to false negatives.
10626   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
10627     if (FLL->isExact())
10628       return;
10629   } else
10630     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
10631       if (FLR->isExact())
10632         return;
10633 
10634   // Check for comparisons with builtin types.
10635   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
10636     if (CL->getBuiltinCallee())
10637       return;
10638 
10639   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
10640     if (CR->getBuiltinCallee())
10641       return;
10642 
10643   // Emit the diagnostic.
10644   Diag(Loc, diag::warn_floatingpoint_eq)
10645     << LHS->getSourceRange() << RHS->getSourceRange();
10646 }
10647 
10648 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
10649 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
10650 
10651 namespace {
10652 
10653 /// Structure recording the 'active' range of an integer-valued
10654 /// expression.
10655 struct IntRange {
10656   /// The number of bits active in the int. Note that this includes exactly one
10657   /// sign bit if !NonNegative.
10658   unsigned Width;
10659 
10660   /// True if the int is known not to have negative values. If so, all leading
10661   /// bits before Width are known zero, otherwise they are known to be the
10662   /// same as the MSB within Width.
10663   bool NonNegative;
10664 
10665   IntRange(unsigned Width, bool NonNegative)
10666       : Width(Width), NonNegative(NonNegative) {}
10667 
10668   /// Number of bits excluding the sign bit.
10669   unsigned valueBits() const {
10670     return NonNegative ? Width : Width - 1;
10671   }
10672 
10673   /// Returns the range of the bool type.
10674   static IntRange forBoolType() {
10675     return IntRange(1, true);
10676   }
10677 
10678   /// Returns the range of an opaque value of the given integral type.
10679   static IntRange forValueOfType(ASTContext &C, QualType T) {
10680     return forValueOfCanonicalType(C,
10681                           T->getCanonicalTypeInternal().getTypePtr());
10682   }
10683 
10684   /// Returns the range of an opaque value of a canonical integral type.
10685   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
10686     assert(T->isCanonicalUnqualified());
10687 
10688     if (const VectorType *VT = dyn_cast<VectorType>(T))
10689       T = VT->getElementType().getTypePtr();
10690     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
10691       T = CT->getElementType().getTypePtr();
10692     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
10693       T = AT->getValueType().getTypePtr();
10694 
10695     if (!C.getLangOpts().CPlusPlus) {
10696       // For enum types in C code, use the underlying datatype.
10697       if (const EnumType *ET = dyn_cast<EnumType>(T))
10698         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
10699     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
10700       // For enum types in C++, use the known bit width of the enumerators.
10701       EnumDecl *Enum = ET->getDecl();
10702       // In C++11, enums can have a fixed underlying type. Use this type to
10703       // compute the range.
10704       if (Enum->isFixed()) {
10705         return IntRange(C.getIntWidth(QualType(T, 0)),
10706                         !ET->isSignedIntegerOrEnumerationType());
10707       }
10708 
10709       unsigned NumPositive = Enum->getNumPositiveBits();
10710       unsigned NumNegative = Enum->getNumNegativeBits();
10711 
10712       if (NumNegative == 0)
10713         return IntRange(NumPositive, true/*NonNegative*/);
10714       else
10715         return IntRange(std::max(NumPositive + 1, NumNegative),
10716                         false/*NonNegative*/);
10717     }
10718 
10719     if (const auto *EIT = dyn_cast<ExtIntType>(T))
10720       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
10721 
10722     const BuiltinType *BT = cast<BuiltinType>(T);
10723     assert(BT->isInteger());
10724 
10725     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10726   }
10727 
10728   /// Returns the "target" range of a canonical integral type, i.e.
10729   /// the range of values expressible in the type.
10730   ///
10731   /// This matches forValueOfCanonicalType except that enums have the
10732   /// full range of their type, not the range of their enumerators.
10733   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
10734     assert(T->isCanonicalUnqualified());
10735 
10736     if (const VectorType *VT = dyn_cast<VectorType>(T))
10737       T = VT->getElementType().getTypePtr();
10738     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
10739       T = CT->getElementType().getTypePtr();
10740     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
10741       T = AT->getValueType().getTypePtr();
10742     if (const EnumType *ET = dyn_cast<EnumType>(T))
10743       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
10744 
10745     if (const auto *EIT = dyn_cast<ExtIntType>(T))
10746       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
10747 
10748     const BuiltinType *BT = cast<BuiltinType>(T);
10749     assert(BT->isInteger());
10750 
10751     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10752   }
10753 
10754   /// Returns the supremum of two ranges: i.e. their conservative merge.
10755   static IntRange join(IntRange L, IntRange R) {
10756     bool Unsigned = L.NonNegative && R.NonNegative;
10757     return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
10758                     L.NonNegative && R.NonNegative);
10759   }
10760 
10761   /// Return the range of a bitwise-AND of the two ranges.
10762   static IntRange bit_and(IntRange L, IntRange R) {
10763     unsigned Bits = std::max(L.Width, R.Width);
10764     bool NonNegative = false;
10765     if (L.NonNegative) {
10766       Bits = std::min(Bits, L.Width);
10767       NonNegative = true;
10768     }
10769     if (R.NonNegative) {
10770       Bits = std::min(Bits, R.Width);
10771       NonNegative = true;
10772     }
10773     return IntRange(Bits, NonNegative);
10774   }
10775 
10776   /// Return the range of a sum of the two ranges.
10777   static IntRange sum(IntRange L, IntRange R) {
10778     bool Unsigned = L.NonNegative && R.NonNegative;
10779     return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
10780                     Unsigned);
10781   }
10782 
10783   /// Return the range of a difference of the two ranges.
10784   static IntRange difference(IntRange L, IntRange R) {
10785     // We need a 1-bit-wider range if:
10786     //   1) LHS can be negative: least value can be reduced.
10787     //   2) RHS can be negative: greatest value can be increased.
10788     bool CanWiden = !L.NonNegative || !R.NonNegative;
10789     bool Unsigned = L.NonNegative && R.Width == 0;
10790     return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
10791                         !Unsigned,
10792                     Unsigned);
10793   }
10794 
10795   /// Return the range of a product of the two ranges.
10796   static IntRange product(IntRange L, IntRange R) {
10797     // If both LHS and RHS can be negative, we can form
10798     //   -2^L * -2^R = 2^(L + R)
10799     // which requires L + R + 1 value bits to represent.
10800     bool CanWiden = !L.NonNegative && !R.NonNegative;
10801     bool Unsigned = L.NonNegative && R.NonNegative;
10802     return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
10803                     Unsigned);
10804   }
10805 
10806   /// Return the range of a remainder operation between the two ranges.
10807   static IntRange rem(IntRange L, IntRange R) {
10808     // The result of a remainder can't be larger than the result of
10809     // either side. The sign of the result is the sign of the LHS.
10810     bool Unsigned = L.NonNegative;
10811     return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
10812                     Unsigned);
10813   }
10814 };
10815 
10816 } // namespace
10817 
10818 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
10819                               unsigned MaxWidth) {
10820   if (value.isSigned() && value.isNegative())
10821     return IntRange(value.getMinSignedBits(), false);
10822 
10823   if (value.getBitWidth() > MaxWidth)
10824     value = value.trunc(MaxWidth);
10825 
10826   // isNonNegative() just checks the sign bit without considering
10827   // signedness.
10828   return IntRange(value.getActiveBits(), true);
10829 }
10830 
10831 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
10832                               unsigned MaxWidth) {
10833   if (result.isInt())
10834     return GetValueRange(C, result.getInt(), MaxWidth);
10835 
10836   if (result.isVector()) {
10837     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
10838     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
10839       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
10840       R = IntRange::join(R, El);
10841     }
10842     return R;
10843   }
10844 
10845   if (result.isComplexInt()) {
10846     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
10847     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
10848     return IntRange::join(R, I);
10849   }
10850 
10851   // This can happen with lossless casts to intptr_t of "based" lvalues.
10852   // Assume it might use arbitrary bits.
10853   // FIXME: The only reason we need to pass the type in here is to get
10854   // the sign right on this one case.  It would be nice if APValue
10855   // preserved this.
10856   assert(result.isLValue() || result.isAddrLabelDiff());
10857   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
10858 }
10859 
10860 static QualType GetExprType(const Expr *E) {
10861   QualType Ty = E->getType();
10862   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
10863     Ty = AtomicRHS->getValueType();
10864   return Ty;
10865 }
10866 
10867 /// Pseudo-evaluate the given integer expression, estimating the
10868 /// range of values it might take.
10869 ///
10870 /// \param MaxWidth The width to which the value will be truncated.
10871 /// \param Approximate If \c true, return a likely range for the result: in
10872 ///        particular, assume that aritmetic on narrower types doesn't leave
10873 ///        those types. If \c false, return a range including all possible
10874 ///        result values.
10875 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
10876                              bool InConstantContext, bool Approximate) {
10877   E = E->IgnoreParens();
10878 
10879   // Try a full evaluation first.
10880   Expr::EvalResult result;
10881   if (E->EvaluateAsRValue(result, C, InConstantContext))
10882     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
10883 
10884   // I think we only want to look through implicit casts here; if the
10885   // user has an explicit widening cast, we should treat the value as
10886   // being of the new, wider type.
10887   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
10888     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
10889       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
10890                           Approximate);
10891 
10892     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
10893 
10894     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
10895                          CE->getCastKind() == CK_BooleanToSignedIntegral;
10896 
10897     // Assume that non-integer casts can span the full range of the type.
10898     if (!isIntegerCast)
10899       return OutputTypeRange;
10900 
10901     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
10902                                      std::min(MaxWidth, OutputTypeRange.Width),
10903                                      InConstantContext, Approximate);
10904 
10905     // Bail out if the subexpr's range is as wide as the cast type.
10906     if (SubRange.Width >= OutputTypeRange.Width)
10907       return OutputTypeRange;
10908 
10909     // Otherwise, we take the smaller width, and we're non-negative if
10910     // either the output type or the subexpr is.
10911     return IntRange(SubRange.Width,
10912                     SubRange.NonNegative || OutputTypeRange.NonNegative);
10913   }
10914 
10915   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
10916     // If we can fold the condition, just take that operand.
10917     bool CondResult;
10918     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
10919       return GetExprRange(C,
10920                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
10921                           MaxWidth, InConstantContext, Approximate);
10922 
10923     // Otherwise, conservatively merge.
10924     // GetExprRange requires an integer expression, but a throw expression
10925     // results in a void type.
10926     Expr *E = CO->getTrueExpr();
10927     IntRange L = E->getType()->isVoidType()
10928                      ? IntRange{0, true}
10929                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
10930     E = CO->getFalseExpr();
10931     IntRange R = E->getType()->isVoidType()
10932                      ? IntRange{0, true}
10933                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
10934     return IntRange::join(L, R);
10935   }
10936 
10937   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
10938     IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
10939 
10940     switch (BO->getOpcode()) {
10941     case BO_Cmp:
10942       llvm_unreachable("builtin <=> should have class type");
10943 
10944     // Boolean-valued operations are single-bit and positive.
10945     case BO_LAnd:
10946     case BO_LOr:
10947     case BO_LT:
10948     case BO_GT:
10949     case BO_LE:
10950     case BO_GE:
10951     case BO_EQ:
10952     case BO_NE:
10953       return IntRange::forBoolType();
10954 
10955     // The type of the assignments is the type of the LHS, so the RHS
10956     // is not necessarily the same type.
10957     case BO_MulAssign:
10958     case BO_DivAssign:
10959     case BO_RemAssign:
10960     case BO_AddAssign:
10961     case BO_SubAssign:
10962     case BO_XorAssign:
10963     case BO_OrAssign:
10964       // TODO: bitfields?
10965       return IntRange::forValueOfType(C, GetExprType(E));
10966 
10967     // Simple assignments just pass through the RHS, which will have
10968     // been coerced to the LHS type.
10969     case BO_Assign:
10970       // TODO: bitfields?
10971       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
10972                           Approximate);
10973 
10974     // Operations with opaque sources are black-listed.
10975     case BO_PtrMemD:
10976     case BO_PtrMemI:
10977       return IntRange::forValueOfType(C, GetExprType(E));
10978 
10979     // Bitwise-and uses the *infinum* of the two source ranges.
10980     case BO_And:
10981     case BO_AndAssign:
10982       Combine = IntRange::bit_and;
10983       break;
10984 
10985     // Left shift gets black-listed based on a judgement call.
10986     case BO_Shl:
10987       // ...except that we want to treat '1 << (blah)' as logically
10988       // positive.  It's an important idiom.
10989       if (IntegerLiteral *I
10990             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
10991         if (I->getValue() == 1) {
10992           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
10993           return IntRange(R.Width, /*NonNegative*/ true);
10994         }
10995       }
10996       LLVM_FALLTHROUGH;
10997 
10998     case BO_ShlAssign:
10999       return IntRange::forValueOfType(C, GetExprType(E));
11000 
11001     // Right shift by a constant can narrow its left argument.
11002     case BO_Shr:
11003     case BO_ShrAssign: {
11004       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext,
11005                                 Approximate);
11006 
11007       // If the shift amount is a positive constant, drop the width by
11008       // that much.
11009       if (Optional<llvm::APSInt> shift =
11010               BO->getRHS()->getIntegerConstantExpr(C)) {
11011         if (shift->isNonNegative()) {
11012           unsigned zext = shift->getZExtValue();
11013           if (zext >= L.Width)
11014             L.Width = (L.NonNegative ? 0 : 1);
11015           else
11016             L.Width -= zext;
11017         }
11018       }
11019 
11020       return L;
11021     }
11022 
11023     // Comma acts as its right operand.
11024     case BO_Comma:
11025       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11026                           Approximate);
11027 
11028     case BO_Add:
11029       if (!Approximate)
11030         Combine = IntRange::sum;
11031       break;
11032 
11033     case BO_Sub:
11034       if (BO->getLHS()->getType()->isPointerType())
11035         return IntRange::forValueOfType(C, GetExprType(E));
11036       if (!Approximate)
11037         Combine = IntRange::difference;
11038       break;
11039 
11040     case BO_Mul:
11041       if (!Approximate)
11042         Combine = IntRange::product;
11043       break;
11044 
11045     // The width of a division result is mostly determined by the size
11046     // of the LHS.
11047     case BO_Div: {
11048       // Don't 'pre-truncate' the operands.
11049       unsigned opWidth = C.getIntWidth(GetExprType(E));
11050       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext,
11051                                 Approximate);
11052 
11053       // If the divisor is constant, use that.
11054       if (Optional<llvm::APSInt> divisor =
11055               BO->getRHS()->getIntegerConstantExpr(C)) {
11056         unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
11057         if (log2 >= L.Width)
11058           L.Width = (L.NonNegative ? 0 : 1);
11059         else
11060           L.Width = std::min(L.Width - log2, MaxWidth);
11061         return L;
11062       }
11063 
11064       // Otherwise, just use the LHS's width.
11065       // FIXME: This is wrong if the LHS could be its minimal value and the RHS
11066       // could be -1.
11067       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext,
11068                                 Approximate);
11069       return IntRange(L.Width, L.NonNegative && R.NonNegative);
11070     }
11071 
11072     case BO_Rem:
11073       Combine = IntRange::rem;
11074       break;
11075 
11076     // The default behavior is okay for these.
11077     case BO_Xor:
11078     case BO_Or:
11079       break;
11080     }
11081 
11082     // Combine the two ranges, but limit the result to the type in which we
11083     // performed the computation.
11084     QualType T = GetExprType(E);
11085     unsigned opWidth = C.getIntWidth(T);
11086     IntRange L =
11087         GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate);
11088     IntRange R =
11089         GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate);
11090     IntRange C = Combine(L, R);
11091     C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
11092     C.Width = std::min(C.Width, MaxWidth);
11093     return C;
11094   }
11095 
11096   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
11097     switch (UO->getOpcode()) {
11098     // Boolean-valued operations are white-listed.
11099     case UO_LNot:
11100       return IntRange::forBoolType();
11101 
11102     // Operations with opaque sources are black-listed.
11103     case UO_Deref:
11104     case UO_AddrOf: // should be impossible
11105       return IntRange::forValueOfType(C, GetExprType(E));
11106 
11107     default:
11108       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11109                           Approximate);
11110     }
11111   }
11112 
11113   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
11114     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
11115                         Approximate);
11116 
11117   if (const auto *BitField = E->getSourceBitField())
11118     return IntRange(BitField->getBitWidthValue(C),
11119                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
11120 
11121   return IntRange::forValueOfType(C, GetExprType(E));
11122 }
11123 
11124 static IntRange GetExprRange(ASTContext &C, const Expr *E,
11125                              bool InConstantContext, bool Approximate) {
11126   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
11127                       Approximate);
11128 }
11129 
11130 /// Checks whether the given value, which currently has the given
11131 /// source semantics, has the same value when coerced through the
11132 /// target semantics.
11133 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
11134                                  const llvm::fltSemantics &Src,
11135                                  const llvm::fltSemantics &Tgt) {
11136   llvm::APFloat truncated = value;
11137 
11138   bool ignored;
11139   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
11140   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
11141 
11142   return truncated.bitwiseIsEqual(value);
11143 }
11144 
11145 /// Checks whether the given value, which currently has the given
11146 /// source semantics, has the same value when coerced through the
11147 /// target semantics.
11148 ///
11149 /// The value might be a vector of floats (or a complex number).
11150 static bool IsSameFloatAfterCast(const APValue &value,
11151                                  const llvm::fltSemantics &Src,
11152                                  const llvm::fltSemantics &Tgt) {
11153   if (value.isFloat())
11154     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
11155 
11156   if (value.isVector()) {
11157     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
11158       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
11159         return false;
11160     return true;
11161   }
11162 
11163   assert(value.isComplexFloat());
11164   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
11165           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
11166 }
11167 
11168 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
11169                                        bool IsListInit = false);
11170 
11171 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
11172   // Suppress cases where we are comparing against an enum constant.
11173   if (const DeclRefExpr *DR =
11174       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
11175     if (isa<EnumConstantDecl>(DR->getDecl()))
11176       return true;
11177 
11178   // Suppress cases where the value is expanded from a macro, unless that macro
11179   // is how a language represents a boolean literal. This is the case in both C
11180   // and Objective-C.
11181   SourceLocation BeginLoc = E->getBeginLoc();
11182   if (BeginLoc.isMacroID()) {
11183     StringRef MacroName = Lexer::getImmediateMacroName(
11184         BeginLoc, S.getSourceManager(), S.getLangOpts());
11185     return MacroName != "YES" && MacroName != "NO" &&
11186            MacroName != "true" && MacroName != "false";
11187   }
11188 
11189   return false;
11190 }
11191 
11192 static bool isKnownToHaveUnsignedValue(Expr *E) {
11193   return E->getType()->isIntegerType() &&
11194          (!E->getType()->isSignedIntegerType() ||
11195           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
11196 }
11197 
11198 namespace {
11199 /// The promoted range of values of a type. In general this has the
11200 /// following structure:
11201 ///
11202 ///     |-----------| . . . |-----------|
11203 ///     ^           ^       ^           ^
11204 ///    Min       HoleMin  HoleMax      Max
11205 ///
11206 /// ... where there is only a hole if a signed type is promoted to unsigned
11207 /// (in which case Min and Max are the smallest and largest representable
11208 /// values).
11209 struct PromotedRange {
11210   // Min, or HoleMax if there is a hole.
11211   llvm::APSInt PromotedMin;
11212   // Max, or HoleMin if there is a hole.
11213   llvm::APSInt PromotedMax;
11214 
11215   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
11216     if (R.Width == 0)
11217       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
11218     else if (R.Width >= BitWidth && !Unsigned) {
11219       // Promotion made the type *narrower*. This happens when promoting
11220       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
11221       // Treat all values of 'signed int' as being in range for now.
11222       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
11223       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
11224     } else {
11225       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
11226                         .extOrTrunc(BitWidth);
11227       PromotedMin.setIsUnsigned(Unsigned);
11228 
11229       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
11230                         .extOrTrunc(BitWidth);
11231       PromotedMax.setIsUnsigned(Unsigned);
11232     }
11233   }
11234 
11235   // Determine whether this range is contiguous (has no hole).
11236   bool isContiguous() const { return PromotedMin <= PromotedMax; }
11237 
11238   // Where a constant value is within the range.
11239   enum ComparisonResult {
11240     LT = 0x1,
11241     LE = 0x2,
11242     GT = 0x4,
11243     GE = 0x8,
11244     EQ = 0x10,
11245     NE = 0x20,
11246     InRangeFlag = 0x40,
11247 
11248     Less = LE | LT | NE,
11249     Min = LE | InRangeFlag,
11250     InRange = InRangeFlag,
11251     Max = GE | InRangeFlag,
11252     Greater = GE | GT | NE,
11253 
11254     OnlyValue = LE | GE | EQ | InRangeFlag,
11255     InHole = NE
11256   };
11257 
11258   ComparisonResult compare(const llvm::APSInt &Value) const {
11259     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
11260            Value.isUnsigned() == PromotedMin.isUnsigned());
11261     if (!isContiguous()) {
11262       assert(Value.isUnsigned() && "discontiguous range for signed compare");
11263       if (Value.isMinValue()) return Min;
11264       if (Value.isMaxValue()) return Max;
11265       if (Value >= PromotedMin) return InRange;
11266       if (Value <= PromotedMax) return InRange;
11267       return InHole;
11268     }
11269 
11270     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
11271     case -1: return Less;
11272     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
11273     case 1:
11274       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
11275       case -1: return InRange;
11276       case 0: return Max;
11277       case 1: return Greater;
11278       }
11279     }
11280 
11281     llvm_unreachable("impossible compare result");
11282   }
11283 
11284   static llvm::Optional<StringRef>
11285   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
11286     if (Op == BO_Cmp) {
11287       ComparisonResult LTFlag = LT, GTFlag = GT;
11288       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
11289 
11290       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
11291       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
11292       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
11293       return llvm::None;
11294     }
11295 
11296     ComparisonResult TrueFlag, FalseFlag;
11297     if (Op == BO_EQ) {
11298       TrueFlag = EQ;
11299       FalseFlag = NE;
11300     } else if (Op == BO_NE) {
11301       TrueFlag = NE;
11302       FalseFlag = EQ;
11303     } else {
11304       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
11305         TrueFlag = LT;
11306         FalseFlag = GE;
11307       } else {
11308         TrueFlag = GT;
11309         FalseFlag = LE;
11310       }
11311       if (Op == BO_GE || Op == BO_LE)
11312         std::swap(TrueFlag, FalseFlag);
11313     }
11314     if (R & TrueFlag)
11315       return StringRef("true");
11316     if (R & FalseFlag)
11317       return StringRef("false");
11318     return llvm::None;
11319   }
11320 };
11321 }
11322 
11323 static bool HasEnumType(Expr *E) {
11324   // Strip off implicit integral promotions.
11325   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
11326     if (ICE->getCastKind() != CK_IntegralCast &&
11327         ICE->getCastKind() != CK_NoOp)
11328       break;
11329     E = ICE->getSubExpr();
11330   }
11331 
11332   return E->getType()->isEnumeralType();
11333 }
11334 
11335 static int classifyConstantValue(Expr *Constant) {
11336   // The values of this enumeration are used in the diagnostics
11337   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
11338   enum ConstantValueKind {
11339     Miscellaneous = 0,
11340     LiteralTrue,
11341     LiteralFalse
11342   };
11343   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
11344     return BL->getValue() ? ConstantValueKind::LiteralTrue
11345                           : ConstantValueKind::LiteralFalse;
11346   return ConstantValueKind::Miscellaneous;
11347 }
11348 
11349 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
11350                                         Expr *Constant, Expr *Other,
11351                                         const llvm::APSInt &Value,
11352                                         bool RhsConstant) {
11353   if (S.inTemplateInstantiation())
11354     return false;
11355 
11356   Expr *OriginalOther = Other;
11357 
11358   Constant = Constant->IgnoreParenImpCasts();
11359   Other = Other->IgnoreParenImpCasts();
11360 
11361   // Suppress warnings on tautological comparisons between values of the same
11362   // enumeration type. There are only two ways we could warn on this:
11363   //  - If the constant is outside the range of representable values of
11364   //    the enumeration. In such a case, we should warn about the cast
11365   //    to enumeration type, not about the comparison.
11366   //  - If the constant is the maximum / minimum in-range value. For an
11367   //    enumeratin type, such comparisons can be meaningful and useful.
11368   if (Constant->getType()->isEnumeralType() &&
11369       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
11370     return false;
11371 
11372   IntRange OtherValueRange = GetExprRange(
11373       S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false);
11374 
11375   QualType OtherT = Other->getType();
11376   if (const auto *AT = OtherT->getAs<AtomicType>())
11377     OtherT = AT->getValueType();
11378   IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
11379 
11380   // Special case for ObjC BOOL on targets where its a typedef for a signed char
11381   // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
11382   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
11383                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
11384                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
11385 
11386   // Whether we're treating Other as being a bool because of the form of
11387   // expression despite it having another type (typically 'int' in C).
11388   bool OtherIsBooleanDespiteType =
11389       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
11390   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
11391     OtherTypeRange = OtherValueRange = IntRange::forBoolType();
11392 
11393   // Check if all values in the range of possible values of this expression
11394   // lead to the same comparison outcome.
11395   PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(),
11396                                         Value.isUnsigned());
11397   auto Cmp = OtherPromotedValueRange.compare(Value);
11398   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
11399   if (!Result)
11400     return false;
11401 
11402   // Also consider the range determined by the type alone. This allows us to
11403   // classify the warning under the proper diagnostic group.
11404   bool TautologicalTypeCompare = false;
11405   {
11406     PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
11407                                          Value.isUnsigned());
11408     auto TypeCmp = OtherPromotedTypeRange.compare(Value);
11409     if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
11410                                                        RhsConstant)) {
11411       TautologicalTypeCompare = true;
11412       Cmp = TypeCmp;
11413       Result = TypeResult;
11414     }
11415   }
11416 
11417   // Don't warn if the non-constant operand actually always evaluates to the
11418   // same value.
11419   if (!TautologicalTypeCompare && OtherValueRange.Width == 0)
11420     return false;
11421 
11422   // Suppress the diagnostic for an in-range comparison if the constant comes
11423   // from a macro or enumerator. We don't want to diagnose
11424   //
11425   //   some_long_value <= INT_MAX
11426   //
11427   // when sizeof(int) == sizeof(long).
11428   bool InRange = Cmp & PromotedRange::InRangeFlag;
11429   if (InRange && IsEnumConstOrFromMacro(S, Constant))
11430     return false;
11431 
11432   // A comparison of an unsigned bit-field against 0 is really a type problem,
11433   // even though at the type level the bit-field might promote to 'signed int'.
11434   if (Other->refersToBitField() && InRange && Value == 0 &&
11435       Other->getType()->isUnsignedIntegerOrEnumerationType())
11436     TautologicalTypeCompare = true;
11437 
11438   // If this is a comparison to an enum constant, include that
11439   // constant in the diagnostic.
11440   const EnumConstantDecl *ED = nullptr;
11441   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
11442     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
11443 
11444   // Should be enough for uint128 (39 decimal digits)
11445   SmallString<64> PrettySourceValue;
11446   llvm::raw_svector_ostream OS(PrettySourceValue);
11447   if (ED) {
11448     OS << '\'' << *ED << "' (" << Value << ")";
11449   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
11450                Constant->IgnoreParenImpCasts())) {
11451     OS << (BL->getValue() ? "YES" : "NO");
11452   } else {
11453     OS << Value;
11454   }
11455 
11456   if (!TautologicalTypeCompare) {
11457     S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
11458         << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative
11459         << E->getOpcodeStr() << OS.str() << *Result
11460         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11461     return true;
11462   }
11463 
11464   if (IsObjCSignedCharBool) {
11465     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
11466                           S.PDiag(diag::warn_tautological_compare_objc_bool)
11467                               << OS.str() << *Result);
11468     return true;
11469   }
11470 
11471   // FIXME: We use a somewhat different formatting for the in-range cases and
11472   // cases involving boolean values for historical reasons. We should pick a
11473   // consistent way of presenting these diagnostics.
11474   if (!InRange || Other->isKnownToHaveBooleanValue()) {
11475 
11476     S.DiagRuntimeBehavior(
11477         E->getOperatorLoc(), E,
11478         S.PDiag(!InRange ? diag::warn_out_of_range_compare
11479                          : diag::warn_tautological_bool_compare)
11480             << OS.str() << classifyConstantValue(Constant) << OtherT
11481             << OtherIsBooleanDespiteType << *Result
11482             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
11483   } else {
11484     bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
11485     unsigned Diag =
11486         (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
11487             ? (HasEnumType(OriginalOther)
11488                    ? diag::warn_unsigned_enum_always_true_comparison
11489                    : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
11490                               : diag::warn_unsigned_always_true_comparison)
11491             : diag::warn_tautological_constant_compare;
11492 
11493     S.Diag(E->getOperatorLoc(), Diag)
11494         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
11495         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11496   }
11497 
11498   return true;
11499 }
11500 
11501 /// Analyze the operands of the given comparison.  Implements the
11502 /// fallback case from AnalyzeComparison.
11503 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
11504   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11505   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11506 }
11507 
11508 /// Implements -Wsign-compare.
11509 ///
11510 /// \param E the binary operator to check for warnings
11511 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
11512   // The type the comparison is being performed in.
11513   QualType T = E->getLHS()->getType();
11514 
11515   // Only analyze comparison operators where both sides have been converted to
11516   // the same type.
11517   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
11518     return AnalyzeImpConvsInComparison(S, E);
11519 
11520   // Don't analyze value-dependent comparisons directly.
11521   if (E->isValueDependent())
11522     return AnalyzeImpConvsInComparison(S, E);
11523 
11524   Expr *LHS = E->getLHS();
11525   Expr *RHS = E->getRHS();
11526 
11527   if (T->isIntegralType(S.Context)) {
11528     Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context);
11529     Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context);
11530 
11531     // We don't care about expressions whose result is a constant.
11532     if (RHSValue && LHSValue)
11533       return AnalyzeImpConvsInComparison(S, E);
11534 
11535     // We only care about expressions where just one side is literal
11536     if ((bool)RHSValue ^ (bool)LHSValue) {
11537       // Is the constant on the RHS or LHS?
11538       const bool RhsConstant = (bool)RHSValue;
11539       Expr *Const = RhsConstant ? RHS : LHS;
11540       Expr *Other = RhsConstant ? LHS : RHS;
11541       const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
11542 
11543       // Check whether an integer constant comparison results in a value
11544       // of 'true' or 'false'.
11545       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
11546         return AnalyzeImpConvsInComparison(S, E);
11547     }
11548   }
11549 
11550   if (!T->hasUnsignedIntegerRepresentation()) {
11551     // We don't do anything special if this isn't an unsigned integral
11552     // comparison:  we're only interested in integral comparisons, and
11553     // signed comparisons only happen in cases we don't care to warn about.
11554     return AnalyzeImpConvsInComparison(S, E);
11555   }
11556 
11557   LHS = LHS->IgnoreParenImpCasts();
11558   RHS = RHS->IgnoreParenImpCasts();
11559 
11560   if (!S.getLangOpts().CPlusPlus) {
11561     // Avoid warning about comparison of integers with different signs when
11562     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
11563     // the type of `E`.
11564     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
11565       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11566     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
11567       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11568   }
11569 
11570   // Check to see if one of the (unmodified) operands is of different
11571   // signedness.
11572   Expr *signedOperand, *unsignedOperand;
11573   if (LHS->getType()->hasSignedIntegerRepresentation()) {
11574     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
11575            "unsigned comparison between two signed integer expressions?");
11576     signedOperand = LHS;
11577     unsignedOperand = RHS;
11578   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
11579     signedOperand = RHS;
11580     unsignedOperand = LHS;
11581   } else {
11582     return AnalyzeImpConvsInComparison(S, E);
11583   }
11584 
11585   // Otherwise, calculate the effective range of the signed operand.
11586   IntRange signedRange = GetExprRange(
11587       S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true);
11588 
11589   // Go ahead and analyze implicit conversions in the operands.  Note
11590   // that we skip the implicit conversions on both sides.
11591   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
11592   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
11593 
11594   // If the signed range is non-negative, -Wsign-compare won't fire.
11595   if (signedRange.NonNegative)
11596     return;
11597 
11598   // For (in)equality comparisons, if the unsigned operand is a
11599   // constant which cannot collide with a overflowed signed operand,
11600   // then reinterpreting the signed operand as unsigned will not
11601   // change the result of the comparison.
11602   if (E->isEqualityOp()) {
11603     unsigned comparisonWidth = S.Context.getIntWidth(T);
11604     IntRange unsignedRange =
11605         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(),
11606                      /*Approximate*/ true);
11607 
11608     // We should never be unable to prove that the unsigned operand is
11609     // non-negative.
11610     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
11611 
11612     if (unsignedRange.Width < comparisonWidth)
11613       return;
11614   }
11615 
11616   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
11617                         S.PDiag(diag::warn_mixed_sign_comparison)
11618                             << LHS->getType() << RHS->getType()
11619                             << LHS->getSourceRange() << RHS->getSourceRange());
11620 }
11621 
11622 /// Analyzes an attempt to assign the given value to a bitfield.
11623 ///
11624 /// Returns true if there was something fishy about the attempt.
11625 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
11626                                       SourceLocation InitLoc) {
11627   assert(Bitfield->isBitField());
11628   if (Bitfield->isInvalidDecl())
11629     return false;
11630 
11631   // White-list bool bitfields.
11632   QualType BitfieldType = Bitfield->getType();
11633   if (BitfieldType->isBooleanType())
11634      return false;
11635 
11636   if (BitfieldType->isEnumeralType()) {
11637     EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
11638     // If the underlying enum type was not explicitly specified as an unsigned
11639     // type and the enum contain only positive values, MSVC++ will cause an
11640     // inconsistency by storing this as a signed type.
11641     if (S.getLangOpts().CPlusPlus11 &&
11642         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
11643         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
11644         BitfieldEnumDecl->getNumNegativeBits() == 0) {
11645       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
11646           << BitfieldEnumDecl;
11647     }
11648   }
11649 
11650   if (Bitfield->getType()->isBooleanType())
11651     return false;
11652 
11653   // Ignore value- or type-dependent expressions.
11654   if (Bitfield->getBitWidth()->isValueDependent() ||
11655       Bitfield->getBitWidth()->isTypeDependent() ||
11656       Init->isValueDependent() ||
11657       Init->isTypeDependent())
11658     return false;
11659 
11660   Expr *OriginalInit = Init->IgnoreParenImpCasts();
11661   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
11662 
11663   Expr::EvalResult Result;
11664   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
11665                                    Expr::SE_AllowSideEffects)) {
11666     // The RHS is not constant.  If the RHS has an enum type, make sure the
11667     // bitfield is wide enough to hold all the values of the enum without
11668     // truncation.
11669     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
11670       EnumDecl *ED = EnumTy->getDecl();
11671       bool SignedBitfield = BitfieldType->isSignedIntegerType();
11672 
11673       // Enum types are implicitly signed on Windows, so check if there are any
11674       // negative enumerators to see if the enum was intended to be signed or
11675       // not.
11676       bool SignedEnum = ED->getNumNegativeBits() > 0;
11677 
11678       // Check for surprising sign changes when assigning enum values to a
11679       // bitfield of different signedness.  If the bitfield is signed and we
11680       // have exactly the right number of bits to store this unsigned enum,
11681       // suggest changing the enum to an unsigned type. This typically happens
11682       // on Windows where unfixed enums always use an underlying type of 'int'.
11683       unsigned DiagID = 0;
11684       if (SignedEnum && !SignedBitfield) {
11685         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
11686       } else if (SignedBitfield && !SignedEnum &&
11687                  ED->getNumPositiveBits() == FieldWidth) {
11688         DiagID = diag::warn_signed_bitfield_enum_conversion;
11689       }
11690 
11691       if (DiagID) {
11692         S.Diag(InitLoc, DiagID) << Bitfield << ED;
11693         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
11694         SourceRange TypeRange =
11695             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
11696         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
11697             << SignedEnum << TypeRange;
11698       }
11699 
11700       // Compute the required bitwidth. If the enum has negative values, we need
11701       // one more bit than the normal number of positive bits to represent the
11702       // sign bit.
11703       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
11704                                                   ED->getNumNegativeBits())
11705                                        : ED->getNumPositiveBits();
11706 
11707       // Check the bitwidth.
11708       if (BitsNeeded > FieldWidth) {
11709         Expr *WidthExpr = Bitfield->getBitWidth();
11710         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
11711             << Bitfield << ED;
11712         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
11713             << BitsNeeded << ED << WidthExpr->getSourceRange();
11714       }
11715     }
11716 
11717     return false;
11718   }
11719 
11720   llvm::APSInt Value = Result.Val.getInt();
11721 
11722   unsigned OriginalWidth = Value.getBitWidth();
11723 
11724   if (!Value.isSigned() || Value.isNegative())
11725     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
11726       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
11727         OriginalWidth = Value.getMinSignedBits();
11728 
11729   if (OriginalWidth <= FieldWidth)
11730     return false;
11731 
11732   // Compute the value which the bitfield will contain.
11733   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
11734   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
11735 
11736   // Check whether the stored value is equal to the original value.
11737   TruncatedValue = TruncatedValue.extend(OriginalWidth);
11738   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
11739     return false;
11740 
11741   // Special-case bitfields of width 1: booleans are naturally 0/1, and
11742   // therefore don't strictly fit into a signed bitfield of width 1.
11743   if (FieldWidth == 1 && Value == 1)
11744     return false;
11745 
11746   std::string PrettyValue = toString(Value, 10);
11747   std::string PrettyTrunc = toString(TruncatedValue, 10);
11748 
11749   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
11750     << PrettyValue << PrettyTrunc << OriginalInit->getType()
11751     << Init->getSourceRange();
11752 
11753   return true;
11754 }
11755 
11756 /// Analyze the given simple or compound assignment for warning-worthy
11757 /// operations.
11758 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
11759   // Just recurse on the LHS.
11760   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11761 
11762   // We want to recurse on the RHS as normal unless we're assigning to
11763   // a bitfield.
11764   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
11765     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
11766                                   E->getOperatorLoc())) {
11767       // Recurse, ignoring any implicit conversions on the RHS.
11768       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
11769                                         E->getOperatorLoc());
11770     }
11771   }
11772 
11773   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11774 
11775   // Diagnose implicitly sequentially-consistent atomic assignment.
11776   if (E->getLHS()->getType()->isAtomicType())
11777     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
11778 }
11779 
11780 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
11781 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
11782                             SourceLocation CContext, unsigned diag,
11783                             bool pruneControlFlow = false) {
11784   if (pruneControlFlow) {
11785     S.DiagRuntimeBehavior(E->getExprLoc(), E,
11786                           S.PDiag(diag)
11787                               << SourceType << T << E->getSourceRange()
11788                               << SourceRange(CContext));
11789     return;
11790   }
11791   S.Diag(E->getExprLoc(), diag)
11792     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
11793 }
11794 
11795 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
11796 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
11797                             SourceLocation CContext,
11798                             unsigned diag, bool pruneControlFlow = false) {
11799   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
11800 }
11801 
11802 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
11803   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
11804       S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
11805 }
11806 
11807 static void adornObjCBoolConversionDiagWithTernaryFixit(
11808     Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
11809   Expr *Ignored = SourceExpr->IgnoreImplicit();
11810   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
11811     Ignored = OVE->getSourceExpr();
11812   bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
11813                      isa<BinaryOperator>(Ignored) ||
11814                      isa<CXXOperatorCallExpr>(Ignored);
11815   SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
11816   if (NeedsParens)
11817     Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
11818             << FixItHint::CreateInsertion(EndLoc, ")");
11819   Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
11820 }
11821 
11822 /// Diagnose an implicit cast from a floating point value to an integer value.
11823 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
11824                                     SourceLocation CContext) {
11825   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
11826   const bool PruneWarnings = S.inTemplateInstantiation();
11827 
11828   Expr *InnerE = E->IgnoreParenImpCasts();
11829   // We also want to warn on, e.g., "int i = -1.234"
11830   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
11831     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
11832       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
11833 
11834   const bool IsLiteral =
11835       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
11836 
11837   llvm::APFloat Value(0.0);
11838   bool IsConstant =
11839     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
11840   if (!IsConstant) {
11841     if (isObjCSignedCharBool(S, T)) {
11842       return adornObjCBoolConversionDiagWithTernaryFixit(
11843           S, E,
11844           S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
11845               << E->getType());
11846     }
11847 
11848     return DiagnoseImpCast(S, E, T, CContext,
11849                            diag::warn_impcast_float_integer, PruneWarnings);
11850   }
11851 
11852   bool isExact = false;
11853 
11854   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
11855                             T->hasUnsignedIntegerRepresentation());
11856   llvm::APFloat::opStatus Result = Value.convertToInteger(
11857       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
11858 
11859   // FIXME: Force the precision of the source value down so we don't print
11860   // digits which are usually useless (we don't really care here if we
11861   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
11862   // would automatically print the shortest representation, but it's a bit
11863   // tricky to implement.
11864   SmallString<16> PrettySourceValue;
11865   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
11866   precision = (precision * 59 + 195) / 196;
11867   Value.toString(PrettySourceValue, precision);
11868 
11869   if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
11870     return adornObjCBoolConversionDiagWithTernaryFixit(
11871         S, E,
11872         S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
11873             << PrettySourceValue);
11874   }
11875 
11876   if (Result == llvm::APFloat::opOK && isExact) {
11877     if (IsLiteral) return;
11878     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
11879                            PruneWarnings);
11880   }
11881 
11882   // Conversion of a floating-point value to a non-bool integer where the
11883   // integral part cannot be represented by the integer type is undefined.
11884   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
11885     return DiagnoseImpCast(
11886         S, E, T, CContext,
11887         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
11888                   : diag::warn_impcast_float_to_integer_out_of_range,
11889         PruneWarnings);
11890 
11891   unsigned DiagID = 0;
11892   if (IsLiteral) {
11893     // Warn on floating point literal to integer.
11894     DiagID = diag::warn_impcast_literal_float_to_integer;
11895   } else if (IntegerValue == 0) {
11896     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
11897       return DiagnoseImpCast(S, E, T, CContext,
11898                              diag::warn_impcast_float_integer, PruneWarnings);
11899     }
11900     // Warn on non-zero to zero conversion.
11901     DiagID = diag::warn_impcast_float_to_integer_zero;
11902   } else {
11903     if (IntegerValue.isUnsigned()) {
11904       if (!IntegerValue.isMaxValue()) {
11905         return DiagnoseImpCast(S, E, T, CContext,
11906                                diag::warn_impcast_float_integer, PruneWarnings);
11907       }
11908     } else {  // IntegerValue.isSigned()
11909       if (!IntegerValue.isMaxSignedValue() &&
11910           !IntegerValue.isMinSignedValue()) {
11911         return DiagnoseImpCast(S, E, T, CContext,
11912                                diag::warn_impcast_float_integer, PruneWarnings);
11913       }
11914     }
11915     // Warn on evaluatable floating point expression to integer conversion.
11916     DiagID = diag::warn_impcast_float_to_integer;
11917   }
11918 
11919   SmallString<16> PrettyTargetValue;
11920   if (IsBool)
11921     PrettyTargetValue = Value.isZero() ? "false" : "true";
11922   else
11923     IntegerValue.toString(PrettyTargetValue);
11924 
11925   if (PruneWarnings) {
11926     S.DiagRuntimeBehavior(E->getExprLoc(), E,
11927                           S.PDiag(DiagID)
11928                               << E->getType() << T.getUnqualifiedType()
11929                               << PrettySourceValue << PrettyTargetValue
11930                               << E->getSourceRange() << SourceRange(CContext));
11931   } else {
11932     S.Diag(E->getExprLoc(), DiagID)
11933         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
11934         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
11935   }
11936 }
11937 
11938 /// Analyze the given compound assignment for the possible losing of
11939 /// floating-point precision.
11940 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
11941   assert(isa<CompoundAssignOperator>(E) &&
11942          "Must be compound assignment operation");
11943   // Recurse on the LHS and RHS in here
11944   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11945   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11946 
11947   if (E->getLHS()->getType()->isAtomicType())
11948     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
11949 
11950   // Now check the outermost expression
11951   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
11952   const auto *RBT = cast<CompoundAssignOperator>(E)
11953                         ->getComputationResultType()
11954                         ->getAs<BuiltinType>();
11955 
11956   // The below checks assume source is floating point.
11957   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
11958 
11959   // If source is floating point but target is an integer.
11960   if (ResultBT->isInteger())
11961     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
11962                            E->getExprLoc(), diag::warn_impcast_float_integer);
11963 
11964   if (!ResultBT->isFloatingPoint())
11965     return;
11966 
11967   // If both source and target are floating points, warn about losing precision.
11968   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
11969       QualType(ResultBT, 0), QualType(RBT, 0));
11970   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
11971     // warn about dropping FP rank.
11972     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
11973                     diag::warn_impcast_float_result_precision);
11974 }
11975 
11976 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
11977                                       IntRange Range) {
11978   if (!Range.Width) return "0";
11979 
11980   llvm::APSInt ValueInRange = Value;
11981   ValueInRange.setIsSigned(!Range.NonNegative);
11982   ValueInRange = ValueInRange.trunc(Range.Width);
11983   return toString(ValueInRange, 10);
11984 }
11985 
11986 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
11987   if (!isa<ImplicitCastExpr>(Ex))
11988     return false;
11989 
11990   Expr *InnerE = Ex->IgnoreParenImpCasts();
11991   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
11992   const Type *Source =
11993     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
11994   if (Target->isDependentType())
11995     return false;
11996 
11997   const BuiltinType *FloatCandidateBT =
11998     dyn_cast<BuiltinType>(ToBool ? Source : Target);
11999   const Type *BoolCandidateType = ToBool ? Target : Source;
12000 
12001   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
12002           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
12003 }
12004 
12005 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
12006                                              SourceLocation CC) {
12007   unsigned NumArgs = TheCall->getNumArgs();
12008   for (unsigned i = 0; i < NumArgs; ++i) {
12009     Expr *CurrA = TheCall->getArg(i);
12010     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
12011       continue;
12012 
12013     bool IsSwapped = ((i > 0) &&
12014         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
12015     IsSwapped |= ((i < (NumArgs - 1)) &&
12016         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
12017     if (IsSwapped) {
12018       // Warn on this floating-point to bool conversion.
12019       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
12020                       CurrA->getType(), CC,
12021                       diag::warn_impcast_floating_point_to_bool);
12022     }
12023   }
12024 }
12025 
12026 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
12027                                    SourceLocation CC) {
12028   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
12029                         E->getExprLoc()))
12030     return;
12031 
12032   // Don't warn on functions which have return type nullptr_t.
12033   if (isa<CallExpr>(E))
12034     return;
12035 
12036   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
12037   const Expr::NullPointerConstantKind NullKind =
12038       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
12039   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
12040     return;
12041 
12042   // Return if target type is a safe conversion.
12043   if (T->isAnyPointerType() || T->isBlockPointerType() ||
12044       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
12045     return;
12046 
12047   SourceLocation Loc = E->getSourceRange().getBegin();
12048 
12049   // Venture through the macro stacks to get to the source of macro arguments.
12050   // The new location is a better location than the complete location that was
12051   // passed in.
12052   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
12053   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
12054 
12055   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
12056   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
12057     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
12058         Loc, S.SourceMgr, S.getLangOpts());
12059     if (MacroName == "NULL")
12060       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
12061   }
12062 
12063   // Only warn if the null and context location are in the same macro expansion.
12064   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
12065     return;
12066 
12067   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
12068       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
12069       << FixItHint::CreateReplacement(Loc,
12070                                       S.getFixItZeroLiteralForType(T, Loc));
12071 }
12072 
12073 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12074                                   ObjCArrayLiteral *ArrayLiteral);
12075 
12076 static void
12077 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12078                            ObjCDictionaryLiteral *DictionaryLiteral);
12079 
12080 /// Check a single element within a collection literal against the
12081 /// target element type.
12082 static void checkObjCCollectionLiteralElement(Sema &S,
12083                                               QualType TargetElementType,
12084                                               Expr *Element,
12085                                               unsigned ElementKind) {
12086   // Skip a bitcast to 'id' or qualified 'id'.
12087   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
12088     if (ICE->getCastKind() == CK_BitCast &&
12089         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
12090       Element = ICE->getSubExpr();
12091   }
12092 
12093   QualType ElementType = Element->getType();
12094   ExprResult ElementResult(Element);
12095   if (ElementType->getAs<ObjCObjectPointerType>() &&
12096       S.CheckSingleAssignmentConstraints(TargetElementType,
12097                                          ElementResult,
12098                                          false, false)
12099         != Sema::Compatible) {
12100     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
12101         << ElementType << ElementKind << TargetElementType
12102         << Element->getSourceRange();
12103   }
12104 
12105   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
12106     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
12107   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
12108     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
12109 }
12110 
12111 /// Check an Objective-C array literal being converted to the given
12112 /// target type.
12113 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12114                                   ObjCArrayLiteral *ArrayLiteral) {
12115   if (!S.NSArrayDecl)
12116     return;
12117 
12118   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12119   if (!TargetObjCPtr)
12120     return;
12121 
12122   if (TargetObjCPtr->isUnspecialized() ||
12123       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12124         != S.NSArrayDecl->getCanonicalDecl())
12125     return;
12126 
12127   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12128   if (TypeArgs.size() != 1)
12129     return;
12130 
12131   QualType TargetElementType = TypeArgs[0];
12132   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
12133     checkObjCCollectionLiteralElement(S, TargetElementType,
12134                                       ArrayLiteral->getElement(I),
12135                                       0);
12136   }
12137 }
12138 
12139 /// Check an Objective-C dictionary literal being converted to the given
12140 /// target type.
12141 static void
12142 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12143                            ObjCDictionaryLiteral *DictionaryLiteral) {
12144   if (!S.NSDictionaryDecl)
12145     return;
12146 
12147   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12148   if (!TargetObjCPtr)
12149     return;
12150 
12151   if (TargetObjCPtr->isUnspecialized() ||
12152       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12153         != S.NSDictionaryDecl->getCanonicalDecl())
12154     return;
12155 
12156   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12157   if (TypeArgs.size() != 2)
12158     return;
12159 
12160   QualType TargetKeyType = TypeArgs[0];
12161   QualType TargetObjectType = TypeArgs[1];
12162   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
12163     auto Element = DictionaryLiteral->getKeyValueElement(I);
12164     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
12165     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
12166   }
12167 }
12168 
12169 // Helper function to filter out cases for constant width constant conversion.
12170 // Don't warn on char array initialization or for non-decimal values.
12171 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
12172                                           SourceLocation CC) {
12173   // If initializing from a constant, and the constant starts with '0',
12174   // then it is a binary, octal, or hexadecimal.  Allow these constants
12175   // to fill all the bits, even if there is a sign change.
12176   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
12177     const char FirstLiteralCharacter =
12178         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
12179     if (FirstLiteralCharacter == '0')
12180       return false;
12181   }
12182 
12183   // If the CC location points to a '{', and the type is char, then assume
12184   // assume it is an array initialization.
12185   if (CC.isValid() && T->isCharType()) {
12186     const char FirstContextCharacter =
12187         S.getSourceManager().getCharacterData(CC)[0];
12188     if (FirstContextCharacter == '{')
12189       return false;
12190   }
12191 
12192   return true;
12193 }
12194 
12195 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
12196   const auto *IL = dyn_cast<IntegerLiteral>(E);
12197   if (!IL) {
12198     if (auto *UO = dyn_cast<UnaryOperator>(E)) {
12199       if (UO->getOpcode() == UO_Minus)
12200         return dyn_cast<IntegerLiteral>(UO->getSubExpr());
12201     }
12202   }
12203 
12204   return IL;
12205 }
12206 
12207 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
12208   E = E->IgnoreParenImpCasts();
12209   SourceLocation ExprLoc = E->getExprLoc();
12210 
12211   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
12212     BinaryOperator::Opcode Opc = BO->getOpcode();
12213     Expr::EvalResult Result;
12214     // Do not diagnose unsigned shifts.
12215     if (Opc == BO_Shl) {
12216       const auto *LHS = getIntegerLiteral(BO->getLHS());
12217       const auto *RHS = getIntegerLiteral(BO->getRHS());
12218       if (LHS && LHS->getValue() == 0)
12219         S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
12220       else if (!E->isValueDependent() && LHS && RHS &&
12221                RHS->getValue().isNonNegative() &&
12222                E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
12223         S.Diag(ExprLoc, diag::warn_left_shift_always)
12224             << (Result.Val.getInt() != 0);
12225       else if (E->getType()->isSignedIntegerType())
12226         S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
12227     }
12228   }
12229 
12230   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
12231     const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
12232     const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
12233     if (!LHS || !RHS)
12234       return;
12235     if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
12236         (RHS->getValue() == 0 || RHS->getValue() == 1))
12237       // Do not diagnose common idioms.
12238       return;
12239     if (LHS->getValue() != 0 && RHS->getValue() != 0)
12240       S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
12241   }
12242 }
12243 
12244 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
12245                                     SourceLocation CC,
12246                                     bool *ICContext = nullptr,
12247                                     bool IsListInit = false) {
12248   if (E->isTypeDependent() || E->isValueDependent()) return;
12249 
12250   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
12251   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
12252   if (Source == Target) return;
12253   if (Target->isDependentType()) return;
12254 
12255   // If the conversion context location is invalid don't complain. We also
12256   // don't want to emit a warning if the issue occurs from the expansion of
12257   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
12258   // delay this check as long as possible. Once we detect we are in that
12259   // scenario, we just return.
12260   if (CC.isInvalid())
12261     return;
12262 
12263   if (Source->isAtomicType())
12264     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
12265 
12266   // Diagnose implicit casts to bool.
12267   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
12268     if (isa<StringLiteral>(E))
12269       // Warn on string literal to bool.  Checks for string literals in logical
12270       // and expressions, for instance, assert(0 && "error here"), are
12271       // prevented by a check in AnalyzeImplicitConversions().
12272       return DiagnoseImpCast(S, E, T, CC,
12273                              diag::warn_impcast_string_literal_to_bool);
12274     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
12275         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
12276       // This covers the literal expressions that evaluate to Objective-C
12277       // objects.
12278       return DiagnoseImpCast(S, E, T, CC,
12279                              diag::warn_impcast_objective_c_literal_to_bool);
12280     }
12281     if (Source->isPointerType() || Source->canDecayToPointerType()) {
12282       // Warn on pointer to bool conversion that is always true.
12283       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
12284                                      SourceRange(CC));
12285     }
12286   }
12287 
12288   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
12289   // is a typedef for signed char (macOS), then that constant value has to be 1
12290   // or 0.
12291   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
12292     Expr::EvalResult Result;
12293     if (E->EvaluateAsInt(Result, S.getASTContext(),
12294                          Expr::SE_AllowSideEffects)) {
12295       if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
12296         adornObjCBoolConversionDiagWithTernaryFixit(
12297             S, E,
12298             S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
12299                 << toString(Result.Val.getInt(), 10));
12300       }
12301       return;
12302     }
12303   }
12304 
12305   // Check implicit casts from Objective-C collection literals to specialized
12306   // collection types, e.g., NSArray<NSString *> *.
12307   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
12308     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
12309   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
12310     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
12311 
12312   // Strip vector types.
12313   if (const auto *SourceVT = dyn_cast<VectorType>(Source)) {
12314     if (Target->isVLSTBuiltinType()) {
12315       auto SourceVectorKind = SourceVT->getVectorKind();
12316       if (SourceVectorKind == VectorType::SveFixedLengthDataVector ||
12317           SourceVectorKind == VectorType::SveFixedLengthPredicateVector ||
12318           (SourceVectorKind == VectorType::GenericVector &&
12319            S.Context.getTypeSize(Source) == S.getLangOpts().ArmSveVectorBits))
12320         return;
12321     }
12322 
12323     if (!isa<VectorType>(Target)) {
12324       if (S.SourceMgr.isInSystemMacro(CC))
12325         return;
12326       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
12327     }
12328 
12329     // If the vector cast is cast between two vectors of the same size, it is
12330     // a bitcast, not a conversion.
12331     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
12332       return;
12333 
12334     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
12335     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
12336   }
12337   if (auto VecTy = dyn_cast<VectorType>(Target))
12338     Target = VecTy->getElementType().getTypePtr();
12339 
12340   // Strip complex types.
12341   if (isa<ComplexType>(Source)) {
12342     if (!isa<ComplexType>(Target)) {
12343       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
12344         return;
12345 
12346       return DiagnoseImpCast(S, E, T, CC,
12347                              S.getLangOpts().CPlusPlus
12348                                  ? diag::err_impcast_complex_scalar
12349                                  : diag::warn_impcast_complex_scalar);
12350     }
12351 
12352     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
12353     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
12354   }
12355 
12356   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
12357   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
12358 
12359   // If the source is floating point...
12360   if (SourceBT && SourceBT->isFloatingPoint()) {
12361     // ...and the target is floating point...
12362     if (TargetBT && TargetBT->isFloatingPoint()) {
12363       // ...then warn if we're dropping FP rank.
12364 
12365       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12366           QualType(SourceBT, 0), QualType(TargetBT, 0));
12367       if (Order > 0) {
12368         // Don't warn about float constants that are precisely
12369         // representable in the target type.
12370         Expr::EvalResult result;
12371         if (E->EvaluateAsRValue(result, S.Context)) {
12372           // Value might be a float, a float vector, or a float complex.
12373           if (IsSameFloatAfterCast(result.Val,
12374                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
12375                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
12376             return;
12377         }
12378 
12379         if (S.SourceMgr.isInSystemMacro(CC))
12380           return;
12381 
12382         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
12383       }
12384       // ... or possibly if we're increasing rank, too
12385       else if (Order < 0) {
12386         if (S.SourceMgr.isInSystemMacro(CC))
12387           return;
12388 
12389         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
12390       }
12391       return;
12392     }
12393 
12394     // If the target is integral, always warn.
12395     if (TargetBT && TargetBT->isInteger()) {
12396       if (S.SourceMgr.isInSystemMacro(CC))
12397         return;
12398 
12399       DiagnoseFloatingImpCast(S, E, T, CC);
12400     }
12401 
12402     // Detect the case where a call result is converted from floating-point to
12403     // to bool, and the final argument to the call is converted from bool, to
12404     // discover this typo:
12405     //
12406     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
12407     //
12408     // FIXME: This is an incredibly special case; is there some more general
12409     // way to detect this class of misplaced-parentheses bug?
12410     if (Target->isBooleanType() && isa<CallExpr>(E)) {
12411       // Check last argument of function call to see if it is an
12412       // implicit cast from a type matching the type the result
12413       // is being cast to.
12414       CallExpr *CEx = cast<CallExpr>(E);
12415       if (unsigned NumArgs = CEx->getNumArgs()) {
12416         Expr *LastA = CEx->getArg(NumArgs - 1);
12417         Expr *InnerE = LastA->IgnoreParenImpCasts();
12418         if (isa<ImplicitCastExpr>(LastA) &&
12419             InnerE->getType()->isBooleanType()) {
12420           // Warn on this floating-point to bool conversion
12421           DiagnoseImpCast(S, E, T, CC,
12422                           diag::warn_impcast_floating_point_to_bool);
12423         }
12424       }
12425     }
12426     return;
12427   }
12428 
12429   // Valid casts involving fixed point types should be accounted for here.
12430   if (Source->isFixedPointType()) {
12431     if (Target->isUnsaturatedFixedPointType()) {
12432       Expr::EvalResult Result;
12433       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
12434                                   S.isConstantEvaluated())) {
12435         llvm::APFixedPoint Value = Result.Val.getFixedPoint();
12436         llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
12437         llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T);
12438         if (Value > MaxVal || Value < MinVal) {
12439           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12440                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12441                                     << Value.toString() << T
12442                                     << E->getSourceRange()
12443                                     << clang::SourceRange(CC));
12444           return;
12445         }
12446       }
12447     } else if (Target->isIntegerType()) {
12448       Expr::EvalResult Result;
12449       if (!S.isConstantEvaluated() &&
12450           E->EvaluateAsFixedPoint(Result, S.Context,
12451                                   Expr::SE_AllowSideEffects)) {
12452         llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
12453 
12454         bool Overflowed;
12455         llvm::APSInt IntResult = FXResult.convertToInt(
12456             S.Context.getIntWidth(T),
12457             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
12458 
12459         if (Overflowed) {
12460           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12461                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12462                                     << FXResult.toString() << T
12463                                     << E->getSourceRange()
12464                                     << clang::SourceRange(CC));
12465           return;
12466         }
12467       }
12468     }
12469   } else if (Target->isUnsaturatedFixedPointType()) {
12470     if (Source->isIntegerType()) {
12471       Expr::EvalResult Result;
12472       if (!S.isConstantEvaluated() &&
12473           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
12474         llvm::APSInt Value = Result.Val.getInt();
12475 
12476         bool Overflowed;
12477         llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
12478             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
12479 
12480         if (Overflowed) {
12481           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12482                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12483                                     << toString(Value, /*Radix=*/10) << T
12484                                     << E->getSourceRange()
12485                                     << clang::SourceRange(CC));
12486           return;
12487         }
12488       }
12489     }
12490   }
12491 
12492   // If we are casting an integer type to a floating point type without
12493   // initialization-list syntax, we might lose accuracy if the floating
12494   // point type has a narrower significand than the integer type.
12495   if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
12496       TargetBT->isFloatingType() && !IsListInit) {
12497     // Determine the number of precision bits in the source integer type.
12498     IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(),
12499                                         /*Approximate*/ true);
12500     unsigned int SourcePrecision = SourceRange.Width;
12501 
12502     // Determine the number of precision bits in the
12503     // target floating point type.
12504     unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
12505         S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12506 
12507     if (SourcePrecision > 0 && TargetPrecision > 0 &&
12508         SourcePrecision > TargetPrecision) {
12509 
12510       if (Optional<llvm::APSInt> SourceInt =
12511               E->getIntegerConstantExpr(S.Context)) {
12512         // If the source integer is a constant, convert it to the target
12513         // floating point type. Issue a warning if the value changes
12514         // during the whole conversion.
12515         llvm::APFloat TargetFloatValue(
12516             S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12517         llvm::APFloat::opStatus ConversionStatus =
12518             TargetFloatValue.convertFromAPInt(
12519                 *SourceInt, SourceBT->isSignedInteger(),
12520                 llvm::APFloat::rmNearestTiesToEven);
12521 
12522         if (ConversionStatus != llvm::APFloat::opOK) {
12523           SmallString<32> PrettySourceValue;
12524           SourceInt->toString(PrettySourceValue, 10);
12525           SmallString<32> PrettyTargetValue;
12526           TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
12527 
12528           S.DiagRuntimeBehavior(
12529               E->getExprLoc(), E,
12530               S.PDiag(diag::warn_impcast_integer_float_precision_constant)
12531                   << PrettySourceValue << PrettyTargetValue << E->getType() << T
12532                   << E->getSourceRange() << clang::SourceRange(CC));
12533         }
12534       } else {
12535         // Otherwise, the implicit conversion may lose precision.
12536         DiagnoseImpCast(S, E, T, CC,
12537                         diag::warn_impcast_integer_float_precision);
12538       }
12539     }
12540   }
12541 
12542   DiagnoseNullConversion(S, E, T, CC);
12543 
12544   S.DiscardMisalignedMemberAddress(Target, E);
12545 
12546   if (Target->isBooleanType())
12547     DiagnoseIntInBoolContext(S, E);
12548 
12549   if (!Source->isIntegerType() || !Target->isIntegerType())
12550     return;
12551 
12552   // TODO: remove this early return once the false positives for constant->bool
12553   // in templates, macros, etc, are reduced or removed.
12554   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
12555     return;
12556 
12557   if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
12558       !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
12559     return adornObjCBoolConversionDiagWithTernaryFixit(
12560         S, E,
12561         S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
12562             << E->getType());
12563   }
12564 
12565   IntRange SourceTypeRange =
12566       IntRange::forTargetOfCanonicalType(S.Context, Source);
12567   IntRange LikelySourceRange =
12568       GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true);
12569   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
12570 
12571   if (LikelySourceRange.Width > TargetRange.Width) {
12572     // If the source is a constant, use a default-on diagnostic.
12573     // TODO: this should happen for bitfield stores, too.
12574     Expr::EvalResult Result;
12575     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
12576                          S.isConstantEvaluated())) {
12577       llvm::APSInt Value(32);
12578       Value = Result.Val.getInt();
12579 
12580       if (S.SourceMgr.isInSystemMacro(CC))
12581         return;
12582 
12583       std::string PrettySourceValue = toString(Value, 10);
12584       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
12585 
12586       S.DiagRuntimeBehavior(
12587           E->getExprLoc(), E,
12588           S.PDiag(diag::warn_impcast_integer_precision_constant)
12589               << PrettySourceValue << PrettyTargetValue << E->getType() << T
12590               << E->getSourceRange() << SourceRange(CC));
12591       return;
12592     }
12593 
12594     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
12595     if (S.SourceMgr.isInSystemMacro(CC))
12596       return;
12597 
12598     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
12599       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
12600                              /* pruneControlFlow */ true);
12601     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
12602   }
12603 
12604   if (TargetRange.Width > SourceTypeRange.Width) {
12605     if (auto *UO = dyn_cast<UnaryOperator>(E))
12606       if (UO->getOpcode() == UO_Minus)
12607         if (Source->isUnsignedIntegerType()) {
12608           if (Target->isUnsignedIntegerType())
12609             return DiagnoseImpCast(S, E, T, CC,
12610                                    diag::warn_impcast_high_order_zero_bits);
12611           if (Target->isSignedIntegerType())
12612             return DiagnoseImpCast(S, E, T, CC,
12613                                    diag::warn_impcast_nonnegative_result);
12614         }
12615   }
12616 
12617   if (TargetRange.Width == LikelySourceRange.Width &&
12618       !TargetRange.NonNegative && LikelySourceRange.NonNegative &&
12619       Source->isSignedIntegerType()) {
12620     // Warn when doing a signed to signed conversion, warn if the positive
12621     // source value is exactly the width of the target type, which will
12622     // cause a negative value to be stored.
12623 
12624     Expr::EvalResult Result;
12625     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
12626         !S.SourceMgr.isInSystemMacro(CC)) {
12627       llvm::APSInt Value = Result.Val.getInt();
12628       if (isSameWidthConstantConversion(S, E, T, CC)) {
12629         std::string PrettySourceValue = toString(Value, 10);
12630         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
12631 
12632         S.DiagRuntimeBehavior(
12633             E->getExprLoc(), E,
12634             S.PDiag(diag::warn_impcast_integer_precision_constant)
12635                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
12636                 << E->getSourceRange() << SourceRange(CC));
12637         return;
12638       }
12639     }
12640 
12641     // Fall through for non-constants to give a sign conversion warning.
12642   }
12643 
12644   if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) ||
12645       (!TargetRange.NonNegative && LikelySourceRange.NonNegative &&
12646        LikelySourceRange.Width == TargetRange.Width)) {
12647     if (S.SourceMgr.isInSystemMacro(CC))
12648       return;
12649 
12650     unsigned DiagID = diag::warn_impcast_integer_sign;
12651 
12652     // Traditionally, gcc has warned about this under -Wsign-compare.
12653     // We also want to warn about it in -Wconversion.
12654     // So if -Wconversion is off, use a completely identical diagnostic
12655     // in the sign-compare group.
12656     // The conditional-checking code will
12657     if (ICContext) {
12658       DiagID = diag::warn_impcast_integer_sign_conditional;
12659       *ICContext = true;
12660     }
12661 
12662     return DiagnoseImpCast(S, E, T, CC, DiagID);
12663   }
12664 
12665   // Diagnose conversions between different enumeration types.
12666   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
12667   // type, to give us better diagnostics.
12668   QualType SourceType = E->getType();
12669   if (!S.getLangOpts().CPlusPlus) {
12670     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12671       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
12672         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
12673         SourceType = S.Context.getTypeDeclType(Enum);
12674         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
12675       }
12676   }
12677 
12678   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
12679     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
12680       if (SourceEnum->getDecl()->hasNameForLinkage() &&
12681           TargetEnum->getDecl()->hasNameForLinkage() &&
12682           SourceEnum != TargetEnum) {
12683         if (S.SourceMgr.isInSystemMacro(CC))
12684           return;
12685 
12686         return DiagnoseImpCast(S, E, SourceType, T, CC,
12687                                diag::warn_impcast_different_enum_types);
12688       }
12689 }
12690 
12691 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
12692                                      SourceLocation CC, QualType T);
12693 
12694 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
12695                                     SourceLocation CC, bool &ICContext) {
12696   E = E->IgnoreParenImpCasts();
12697 
12698   if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
12699     return CheckConditionalOperator(S, CO, CC, T);
12700 
12701   AnalyzeImplicitConversions(S, E, CC);
12702   if (E->getType() != T)
12703     return CheckImplicitConversion(S, E, T, CC, &ICContext);
12704 }
12705 
12706 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
12707                                      SourceLocation CC, QualType T) {
12708   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
12709 
12710   Expr *TrueExpr = E->getTrueExpr();
12711   if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
12712     TrueExpr = BCO->getCommon();
12713 
12714   bool Suspicious = false;
12715   CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
12716   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
12717 
12718   if (T->isBooleanType())
12719     DiagnoseIntInBoolContext(S, E);
12720 
12721   // If -Wconversion would have warned about either of the candidates
12722   // for a signedness conversion to the context type...
12723   if (!Suspicious) return;
12724 
12725   // ...but it's currently ignored...
12726   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
12727     return;
12728 
12729   // ...then check whether it would have warned about either of the
12730   // candidates for a signedness conversion to the condition type.
12731   if (E->getType() == T) return;
12732 
12733   Suspicious = false;
12734   CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(),
12735                           E->getType(), CC, &Suspicious);
12736   if (!Suspicious)
12737     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
12738                             E->getType(), CC, &Suspicious);
12739 }
12740 
12741 /// Check conversion of given expression to boolean.
12742 /// Input argument E is a logical expression.
12743 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
12744   if (S.getLangOpts().Bool)
12745     return;
12746   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
12747     return;
12748   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
12749 }
12750 
12751 namespace {
12752 struct AnalyzeImplicitConversionsWorkItem {
12753   Expr *E;
12754   SourceLocation CC;
12755   bool IsListInit;
12756 };
12757 }
12758 
12759 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
12760 /// that should be visited are added to WorkList.
12761 static void AnalyzeImplicitConversions(
12762     Sema &S, AnalyzeImplicitConversionsWorkItem Item,
12763     llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
12764   Expr *OrigE = Item.E;
12765   SourceLocation CC = Item.CC;
12766 
12767   QualType T = OrigE->getType();
12768   Expr *E = OrigE->IgnoreParenImpCasts();
12769 
12770   // Propagate whether we are in a C++ list initialization expression.
12771   // If so, we do not issue warnings for implicit int-float conversion
12772   // precision loss, because C++11 narrowing already handles it.
12773   bool IsListInit = Item.IsListInit ||
12774                     (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
12775 
12776   if (E->isTypeDependent() || E->isValueDependent())
12777     return;
12778 
12779   Expr *SourceExpr = E;
12780   // Examine, but don't traverse into the source expression of an
12781   // OpaqueValueExpr, since it may have multiple parents and we don't want to
12782   // emit duplicate diagnostics. Its fine to examine the form or attempt to
12783   // evaluate it in the context of checking the specific conversion to T though.
12784   if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
12785     if (auto *Src = OVE->getSourceExpr())
12786       SourceExpr = Src;
12787 
12788   if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
12789     if (UO->getOpcode() == UO_Not &&
12790         UO->getSubExpr()->isKnownToHaveBooleanValue())
12791       S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
12792           << OrigE->getSourceRange() << T->isBooleanType()
12793           << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
12794 
12795   // For conditional operators, we analyze the arguments as if they
12796   // were being fed directly into the output.
12797   if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
12798     CheckConditionalOperator(S, CO, CC, T);
12799     return;
12800   }
12801 
12802   // Check implicit argument conversions for function calls.
12803   if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
12804     CheckImplicitArgumentConversions(S, Call, CC);
12805 
12806   // Go ahead and check any implicit conversions we might have skipped.
12807   // The non-canonical typecheck is just an optimization;
12808   // CheckImplicitConversion will filter out dead implicit conversions.
12809   if (SourceExpr->getType() != T)
12810     CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit);
12811 
12812   // Now continue drilling into this expression.
12813 
12814   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
12815     // The bound subexpressions in a PseudoObjectExpr are not reachable
12816     // as transitive children.
12817     // FIXME: Use a more uniform representation for this.
12818     for (auto *SE : POE->semantics())
12819       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
12820         WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
12821   }
12822 
12823   // Skip past explicit casts.
12824   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
12825     E = CE->getSubExpr()->IgnoreParenImpCasts();
12826     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
12827       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12828     WorkList.push_back({E, CC, IsListInit});
12829     return;
12830   }
12831 
12832   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12833     // Do a somewhat different check with comparison operators.
12834     if (BO->isComparisonOp())
12835       return AnalyzeComparison(S, BO);
12836 
12837     // And with simple assignments.
12838     if (BO->getOpcode() == BO_Assign)
12839       return AnalyzeAssignment(S, BO);
12840     // And with compound assignments.
12841     if (BO->isAssignmentOp())
12842       return AnalyzeCompoundAssignment(S, BO);
12843   }
12844 
12845   // These break the otherwise-useful invariant below.  Fortunately,
12846   // we don't really need to recurse into them, because any internal
12847   // expressions should have been analyzed already when they were
12848   // built into statements.
12849   if (isa<StmtExpr>(E)) return;
12850 
12851   // Don't descend into unevaluated contexts.
12852   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
12853 
12854   // Now just recurse over the expression's children.
12855   CC = E->getExprLoc();
12856   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
12857   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
12858   for (Stmt *SubStmt : E->children()) {
12859     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
12860     if (!ChildExpr)
12861       continue;
12862 
12863     if (IsLogicalAndOperator &&
12864         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
12865       // Ignore checking string literals that are in logical and operators.
12866       // This is a common pattern for asserts.
12867       continue;
12868     WorkList.push_back({ChildExpr, CC, IsListInit});
12869   }
12870 
12871   if (BO && BO->isLogicalOp()) {
12872     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
12873     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
12874       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
12875 
12876     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
12877     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
12878       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
12879   }
12880 
12881   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
12882     if (U->getOpcode() == UO_LNot) {
12883       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
12884     } else if (U->getOpcode() != UO_AddrOf) {
12885       if (U->getSubExpr()->getType()->isAtomicType())
12886         S.Diag(U->getSubExpr()->getBeginLoc(),
12887                diag::warn_atomic_implicit_seq_cst);
12888     }
12889   }
12890 }
12891 
12892 /// AnalyzeImplicitConversions - Find and report any interesting
12893 /// implicit conversions in the given expression.  There are a couple
12894 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
12895 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
12896                                        bool IsListInit/*= false*/) {
12897   llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
12898   WorkList.push_back({OrigE, CC, IsListInit});
12899   while (!WorkList.empty())
12900     AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
12901 }
12902 
12903 /// Diagnose integer type and any valid implicit conversion to it.
12904 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
12905   // Taking into account implicit conversions,
12906   // allow any integer.
12907   if (!E->getType()->isIntegerType()) {
12908     S.Diag(E->getBeginLoc(),
12909            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
12910     return true;
12911   }
12912   // Potentially emit standard warnings for implicit conversions if enabled
12913   // using -Wconversion.
12914   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
12915   return false;
12916 }
12917 
12918 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
12919 // Returns true when emitting a warning about taking the address of a reference.
12920 static bool CheckForReference(Sema &SemaRef, const Expr *E,
12921                               const PartialDiagnostic &PD) {
12922   E = E->IgnoreParenImpCasts();
12923 
12924   const FunctionDecl *FD = nullptr;
12925 
12926   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12927     if (!DRE->getDecl()->getType()->isReferenceType())
12928       return false;
12929   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
12930     if (!M->getMemberDecl()->getType()->isReferenceType())
12931       return false;
12932   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
12933     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
12934       return false;
12935     FD = Call->getDirectCallee();
12936   } else {
12937     return false;
12938   }
12939 
12940   SemaRef.Diag(E->getExprLoc(), PD);
12941 
12942   // If possible, point to location of function.
12943   if (FD) {
12944     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
12945   }
12946 
12947   return true;
12948 }
12949 
12950 // Returns true if the SourceLocation is expanded from any macro body.
12951 // Returns false if the SourceLocation is invalid, is from not in a macro
12952 // expansion, or is from expanded from a top-level macro argument.
12953 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
12954   if (Loc.isInvalid())
12955     return false;
12956 
12957   while (Loc.isMacroID()) {
12958     if (SM.isMacroBodyExpansion(Loc))
12959       return true;
12960     Loc = SM.getImmediateMacroCallerLoc(Loc);
12961   }
12962 
12963   return false;
12964 }
12965 
12966 /// Diagnose pointers that are always non-null.
12967 /// \param E the expression containing the pointer
12968 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
12969 /// compared to a null pointer
12970 /// \param IsEqual True when the comparison is equal to a null pointer
12971 /// \param Range Extra SourceRange to highlight in the diagnostic
12972 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
12973                                         Expr::NullPointerConstantKind NullKind,
12974                                         bool IsEqual, SourceRange Range) {
12975   if (!E)
12976     return;
12977 
12978   // Don't warn inside macros.
12979   if (E->getExprLoc().isMacroID()) {
12980     const SourceManager &SM = getSourceManager();
12981     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
12982         IsInAnyMacroBody(SM, Range.getBegin()))
12983       return;
12984   }
12985   E = E->IgnoreImpCasts();
12986 
12987   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
12988 
12989   if (isa<CXXThisExpr>(E)) {
12990     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
12991                                 : diag::warn_this_bool_conversion;
12992     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
12993     return;
12994   }
12995 
12996   bool IsAddressOf = false;
12997 
12998   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
12999     if (UO->getOpcode() != UO_AddrOf)
13000       return;
13001     IsAddressOf = true;
13002     E = UO->getSubExpr();
13003   }
13004 
13005   if (IsAddressOf) {
13006     unsigned DiagID = IsCompare
13007                           ? diag::warn_address_of_reference_null_compare
13008                           : diag::warn_address_of_reference_bool_conversion;
13009     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
13010                                          << IsEqual;
13011     if (CheckForReference(*this, E, PD)) {
13012       return;
13013     }
13014   }
13015 
13016   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
13017     bool IsParam = isa<NonNullAttr>(NonnullAttr);
13018     std::string Str;
13019     llvm::raw_string_ostream S(Str);
13020     E->printPretty(S, nullptr, getPrintingPolicy());
13021     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
13022                                 : diag::warn_cast_nonnull_to_bool;
13023     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
13024       << E->getSourceRange() << Range << IsEqual;
13025     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
13026   };
13027 
13028   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
13029   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
13030     if (auto *Callee = Call->getDirectCallee()) {
13031       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
13032         ComplainAboutNonnullParamOrCall(A);
13033         return;
13034       }
13035     }
13036   }
13037 
13038   // Expect to find a single Decl.  Skip anything more complicated.
13039   ValueDecl *D = nullptr;
13040   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
13041     D = R->getDecl();
13042   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13043     D = M->getMemberDecl();
13044   }
13045 
13046   // Weak Decls can be null.
13047   if (!D || D->isWeak())
13048     return;
13049 
13050   // Check for parameter decl with nonnull attribute
13051   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
13052     if (getCurFunction() &&
13053         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
13054       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
13055         ComplainAboutNonnullParamOrCall(A);
13056         return;
13057       }
13058 
13059       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
13060         // Skip function template not specialized yet.
13061         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
13062           return;
13063         auto ParamIter = llvm::find(FD->parameters(), PV);
13064         assert(ParamIter != FD->param_end());
13065         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
13066 
13067         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
13068           if (!NonNull->args_size()) {
13069               ComplainAboutNonnullParamOrCall(NonNull);
13070               return;
13071           }
13072 
13073           for (const ParamIdx &ArgNo : NonNull->args()) {
13074             if (ArgNo.getASTIndex() == ParamNo) {
13075               ComplainAboutNonnullParamOrCall(NonNull);
13076               return;
13077             }
13078           }
13079         }
13080       }
13081     }
13082   }
13083 
13084   QualType T = D->getType();
13085   const bool IsArray = T->isArrayType();
13086   const bool IsFunction = T->isFunctionType();
13087 
13088   // Address of function is used to silence the function warning.
13089   if (IsAddressOf && IsFunction) {
13090     return;
13091   }
13092 
13093   // Found nothing.
13094   if (!IsAddressOf && !IsFunction && !IsArray)
13095     return;
13096 
13097   // Pretty print the expression for the diagnostic.
13098   std::string Str;
13099   llvm::raw_string_ostream S(Str);
13100   E->printPretty(S, nullptr, getPrintingPolicy());
13101 
13102   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
13103                               : diag::warn_impcast_pointer_to_bool;
13104   enum {
13105     AddressOf,
13106     FunctionPointer,
13107     ArrayPointer
13108   } DiagType;
13109   if (IsAddressOf)
13110     DiagType = AddressOf;
13111   else if (IsFunction)
13112     DiagType = FunctionPointer;
13113   else if (IsArray)
13114     DiagType = ArrayPointer;
13115   else
13116     llvm_unreachable("Could not determine diagnostic.");
13117   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
13118                                 << Range << IsEqual;
13119 
13120   if (!IsFunction)
13121     return;
13122 
13123   // Suggest '&' to silence the function warning.
13124   Diag(E->getExprLoc(), diag::note_function_warning_silence)
13125       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
13126 
13127   // Check to see if '()' fixit should be emitted.
13128   QualType ReturnType;
13129   UnresolvedSet<4> NonTemplateOverloads;
13130   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
13131   if (ReturnType.isNull())
13132     return;
13133 
13134   if (IsCompare) {
13135     // There are two cases here.  If there is null constant, the only suggest
13136     // for a pointer return type.  If the null is 0, then suggest if the return
13137     // type is a pointer or an integer type.
13138     if (!ReturnType->isPointerType()) {
13139       if (NullKind == Expr::NPCK_ZeroExpression ||
13140           NullKind == Expr::NPCK_ZeroLiteral) {
13141         if (!ReturnType->isIntegerType())
13142           return;
13143       } else {
13144         return;
13145       }
13146     }
13147   } else { // !IsCompare
13148     // For function to bool, only suggest if the function pointer has bool
13149     // return type.
13150     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
13151       return;
13152   }
13153   Diag(E->getExprLoc(), diag::note_function_to_function_call)
13154       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
13155 }
13156 
13157 /// Diagnoses "dangerous" implicit conversions within the given
13158 /// expression (which is a full expression).  Implements -Wconversion
13159 /// and -Wsign-compare.
13160 ///
13161 /// \param CC the "context" location of the implicit conversion, i.e.
13162 ///   the most location of the syntactic entity requiring the implicit
13163 ///   conversion
13164 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
13165   // Don't diagnose in unevaluated contexts.
13166   if (isUnevaluatedContext())
13167     return;
13168 
13169   // Don't diagnose for value- or type-dependent expressions.
13170   if (E->isTypeDependent() || E->isValueDependent())
13171     return;
13172 
13173   // Check for array bounds violations in cases where the check isn't triggered
13174   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
13175   // ArraySubscriptExpr is on the RHS of a variable initialization.
13176   CheckArrayAccess(E);
13177 
13178   // This is not the right CC for (e.g.) a variable initialization.
13179   AnalyzeImplicitConversions(*this, E, CC);
13180 }
13181 
13182 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
13183 /// Input argument E is a logical expression.
13184 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
13185   ::CheckBoolLikeConversion(*this, E, CC);
13186 }
13187 
13188 /// Diagnose when expression is an integer constant expression and its evaluation
13189 /// results in integer overflow
13190 void Sema::CheckForIntOverflow (Expr *E) {
13191   // Use a work list to deal with nested struct initializers.
13192   SmallVector<Expr *, 2> Exprs(1, E);
13193 
13194   do {
13195     Expr *OriginalE = Exprs.pop_back_val();
13196     Expr *E = OriginalE->IgnoreParenCasts();
13197 
13198     if (isa<BinaryOperator>(E)) {
13199       E->EvaluateForOverflow(Context);
13200       continue;
13201     }
13202 
13203     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
13204       Exprs.append(InitList->inits().begin(), InitList->inits().end());
13205     else if (isa<ObjCBoxedExpr>(OriginalE))
13206       E->EvaluateForOverflow(Context);
13207     else if (auto Call = dyn_cast<CallExpr>(E))
13208       Exprs.append(Call->arg_begin(), Call->arg_end());
13209     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
13210       Exprs.append(Message->arg_begin(), Message->arg_end());
13211   } while (!Exprs.empty());
13212 }
13213 
13214 namespace {
13215 
13216 /// Visitor for expressions which looks for unsequenced operations on the
13217 /// same object.
13218 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
13219   using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
13220 
13221   /// A tree of sequenced regions within an expression. Two regions are
13222   /// unsequenced if one is an ancestor or a descendent of the other. When we
13223   /// finish processing an expression with sequencing, such as a comma
13224   /// expression, we fold its tree nodes into its parent, since they are
13225   /// unsequenced with respect to nodes we will visit later.
13226   class SequenceTree {
13227     struct Value {
13228       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
13229       unsigned Parent : 31;
13230       unsigned Merged : 1;
13231     };
13232     SmallVector<Value, 8> Values;
13233 
13234   public:
13235     /// A region within an expression which may be sequenced with respect
13236     /// to some other region.
13237     class Seq {
13238       friend class SequenceTree;
13239 
13240       unsigned Index;
13241 
13242       explicit Seq(unsigned N) : Index(N) {}
13243 
13244     public:
13245       Seq() : Index(0) {}
13246     };
13247 
13248     SequenceTree() { Values.push_back(Value(0)); }
13249     Seq root() const { return Seq(0); }
13250 
13251     /// Create a new sequence of operations, which is an unsequenced
13252     /// subset of \p Parent. This sequence of operations is sequenced with
13253     /// respect to other children of \p Parent.
13254     Seq allocate(Seq Parent) {
13255       Values.push_back(Value(Parent.Index));
13256       return Seq(Values.size() - 1);
13257     }
13258 
13259     /// Merge a sequence of operations into its parent.
13260     void merge(Seq S) {
13261       Values[S.Index].Merged = true;
13262     }
13263 
13264     /// Determine whether two operations are unsequenced. This operation
13265     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
13266     /// should have been merged into its parent as appropriate.
13267     bool isUnsequenced(Seq Cur, Seq Old) {
13268       unsigned C = representative(Cur.Index);
13269       unsigned Target = representative(Old.Index);
13270       while (C >= Target) {
13271         if (C == Target)
13272           return true;
13273         C = Values[C].Parent;
13274       }
13275       return false;
13276     }
13277 
13278   private:
13279     /// Pick a representative for a sequence.
13280     unsigned representative(unsigned K) {
13281       if (Values[K].Merged)
13282         // Perform path compression as we go.
13283         return Values[K].Parent = representative(Values[K].Parent);
13284       return K;
13285     }
13286   };
13287 
13288   /// An object for which we can track unsequenced uses.
13289   using Object = const NamedDecl *;
13290 
13291   /// Different flavors of object usage which we track. We only track the
13292   /// least-sequenced usage of each kind.
13293   enum UsageKind {
13294     /// A read of an object. Multiple unsequenced reads are OK.
13295     UK_Use,
13296 
13297     /// A modification of an object which is sequenced before the value
13298     /// computation of the expression, such as ++n in C++.
13299     UK_ModAsValue,
13300 
13301     /// A modification of an object which is not sequenced before the value
13302     /// computation of the expression, such as n++.
13303     UK_ModAsSideEffect,
13304 
13305     UK_Count = UK_ModAsSideEffect + 1
13306   };
13307 
13308   /// Bundle together a sequencing region and the expression corresponding
13309   /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
13310   struct Usage {
13311     const Expr *UsageExpr;
13312     SequenceTree::Seq Seq;
13313 
13314     Usage() : UsageExpr(nullptr), Seq() {}
13315   };
13316 
13317   struct UsageInfo {
13318     Usage Uses[UK_Count];
13319 
13320     /// Have we issued a diagnostic for this object already?
13321     bool Diagnosed;
13322 
13323     UsageInfo() : Uses(), Diagnosed(false) {}
13324   };
13325   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
13326 
13327   Sema &SemaRef;
13328 
13329   /// Sequenced regions within the expression.
13330   SequenceTree Tree;
13331 
13332   /// Declaration modifications and references which we have seen.
13333   UsageInfoMap UsageMap;
13334 
13335   /// The region we are currently within.
13336   SequenceTree::Seq Region;
13337 
13338   /// Filled in with declarations which were modified as a side-effect
13339   /// (that is, post-increment operations).
13340   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
13341 
13342   /// Expressions to check later. We defer checking these to reduce
13343   /// stack usage.
13344   SmallVectorImpl<const Expr *> &WorkList;
13345 
13346   /// RAII object wrapping the visitation of a sequenced subexpression of an
13347   /// expression. At the end of this process, the side-effects of the evaluation
13348   /// become sequenced with respect to the value computation of the result, so
13349   /// we downgrade any UK_ModAsSideEffect within the evaluation to
13350   /// UK_ModAsValue.
13351   struct SequencedSubexpression {
13352     SequencedSubexpression(SequenceChecker &Self)
13353       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
13354       Self.ModAsSideEffect = &ModAsSideEffect;
13355     }
13356 
13357     ~SequencedSubexpression() {
13358       for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
13359         // Add a new usage with usage kind UK_ModAsValue, and then restore
13360         // the previous usage with UK_ModAsSideEffect (thus clearing it if
13361         // the previous one was empty).
13362         UsageInfo &UI = Self.UsageMap[M.first];
13363         auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
13364         Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
13365         SideEffectUsage = M.second;
13366       }
13367       Self.ModAsSideEffect = OldModAsSideEffect;
13368     }
13369 
13370     SequenceChecker &Self;
13371     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
13372     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
13373   };
13374 
13375   /// RAII object wrapping the visitation of a subexpression which we might
13376   /// choose to evaluate as a constant. If any subexpression is evaluated and
13377   /// found to be non-constant, this allows us to suppress the evaluation of
13378   /// the outer expression.
13379   class EvaluationTracker {
13380   public:
13381     EvaluationTracker(SequenceChecker &Self)
13382         : Self(Self), Prev(Self.EvalTracker) {
13383       Self.EvalTracker = this;
13384     }
13385 
13386     ~EvaluationTracker() {
13387       Self.EvalTracker = Prev;
13388       if (Prev)
13389         Prev->EvalOK &= EvalOK;
13390     }
13391 
13392     bool evaluate(const Expr *E, bool &Result) {
13393       if (!EvalOK || E->isValueDependent())
13394         return false;
13395       EvalOK = E->EvaluateAsBooleanCondition(
13396           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
13397       return EvalOK;
13398     }
13399 
13400   private:
13401     SequenceChecker &Self;
13402     EvaluationTracker *Prev;
13403     bool EvalOK = true;
13404   } *EvalTracker = nullptr;
13405 
13406   /// Find the object which is produced by the specified expression,
13407   /// if any.
13408   Object getObject(const Expr *E, bool Mod) const {
13409     E = E->IgnoreParenCasts();
13410     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13411       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
13412         return getObject(UO->getSubExpr(), Mod);
13413     } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13414       if (BO->getOpcode() == BO_Comma)
13415         return getObject(BO->getRHS(), Mod);
13416       if (Mod && BO->isAssignmentOp())
13417         return getObject(BO->getLHS(), Mod);
13418     } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13419       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
13420       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
13421         return ME->getMemberDecl();
13422     } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13423       // FIXME: If this is a reference, map through to its value.
13424       return DRE->getDecl();
13425     return nullptr;
13426   }
13427 
13428   /// Note that an object \p O was modified or used by an expression
13429   /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
13430   /// the object \p O as obtained via the \p UsageMap.
13431   void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
13432     // Get the old usage for the given object and usage kind.
13433     Usage &U = UI.Uses[UK];
13434     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
13435       // If we have a modification as side effect and are in a sequenced
13436       // subexpression, save the old Usage so that we can restore it later
13437       // in SequencedSubexpression::~SequencedSubexpression.
13438       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
13439         ModAsSideEffect->push_back(std::make_pair(O, U));
13440       // Then record the new usage with the current sequencing region.
13441       U.UsageExpr = UsageExpr;
13442       U.Seq = Region;
13443     }
13444   }
13445 
13446   /// Check whether a modification or use of an object \p O in an expression
13447   /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
13448   /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
13449   /// \p IsModMod is true when we are checking for a mod-mod unsequenced
13450   /// usage and false we are checking for a mod-use unsequenced usage.
13451   void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
13452                   UsageKind OtherKind, bool IsModMod) {
13453     if (UI.Diagnosed)
13454       return;
13455 
13456     const Usage &U = UI.Uses[OtherKind];
13457     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
13458       return;
13459 
13460     const Expr *Mod = U.UsageExpr;
13461     const Expr *ModOrUse = UsageExpr;
13462     if (OtherKind == UK_Use)
13463       std::swap(Mod, ModOrUse);
13464 
13465     SemaRef.DiagRuntimeBehavior(
13466         Mod->getExprLoc(), {Mod, ModOrUse},
13467         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
13468                                : diag::warn_unsequenced_mod_use)
13469             << O << SourceRange(ModOrUse->getExprLoc()));
13470     UI.Diagnosed = true;
13471   }
13472 
13473   // A note on note{Pre, Post}{Use, Mod}:
13474   //
13475   // (It helps to follow the algorithm with an expression such as
13476   //  "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
13477   //  operations before C++17 and both are well-defined in C++17).
13478   //
13479   // When visiting a node which uses/modify an object we first call notePreUse
13480   // or notePreMod before visiting its sub-expression(s). At this point the
13481   // children of the current node have not yet been visited and so the eventual
13482   // uses/modifications resulting from the children of the current node have not
13483   // been recorded yet.
13484   //
13485   // We then visit the children of the current node. After that notePostUse or
13486   // notePostMod is called. These will 1) detect an unsequenced modification
13487   // as side effect (as in "k++ + k") and 2) add a new usage with the
13488   // appropriate usage kind.
13489   //
13490   // We also have to be careful that some operation sequences modification as
13491   // side effect as well (for example: || or ,). To account for this we wrap
13492   // the visitation of such a sub-expression (for example: the LHS of || or ,)
13493   // with SequencedSubexpression. SequencedSubexpression is an RAII object
13494   // which record usages which are modifications as side effect, and then
13495   // downgrade them (or more accurately restore the previous usage which was a
13496   // modification as side effect) when exiting the scope of the sequenced
13497   // subexpression.
13498 
13499   void notePreUse(Object O, const Expr *UseExpr) {
13500     UsageInfo &UI = UsageMap[O];
13501     // Uses conflict with other modifications.
13502     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
13503   }
13504 
13505   void notePostUse(Object O, const Expr *UseExpr) {
13506     UsageInfo &UI = UsageMap[O];
13507     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
13508                /*IsModMod=*/false);
13509     addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
13510   }
13511 
13512   void notePreMod(Object O, const Expr *ModExpr) {
13513     UsageInfo &UI = UsageMap[O];
13514     // Modifications conflict with other modifications and with uses.
13515     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
13516     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
13517   }
13518 
13519   void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
13520     UsageInfo &UI = UsageMap[O];
13521     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
13522                /*IsModMod=*/true);
13523     addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
13524   }
13525 
13526 public:
13527   SequenceChecker(Sema &S, const Expr *E,
13528                   SmallVectorImpl<const Expr *> &WorkList)
13529       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
13530     Visit(E);
13531     // Silence a -Wunused-private-field since WorkList is now unused.
13532     // TODO: Evaluate if it can be used, and if not remove it.
13533     (void)this->WorkList;
13534   }
13535 
13536   void VisitStmt(const Stmt *S) {
13537     // Skip all statements which aren't expressions for now.
13538   }
13539 
13540   void VisitExpr(const Expr *E) {
13541     // By default, just recurse to evaluated subexpressions.
13542     Base::VisitStmt(E);
13543   }
13544 
13545   void VisitCastExpr(const CastExpr *E) {
13546     Object O = Object();
13547     if (E->getCastKind() == CK_LValueToRValue)
13548       O = getObject(E->getSubExpr(), false);
13549 
13550     if (O)
13551       notePreUse(O, E);
13552     VisitExpr(E);
13553     if (O)
13554       notePostUse(O, E);
13555   }
13556 
13557   void VisitSequencedExpressions(const Expr *SequencedBefore,
13558                                  const Expr *SequencedAfter) {
13559     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
13560     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
13561     SequenceTree::Seq OldRegion = Region;
13562 
13563     {
13564       SequencedSubexpression SeqBefore(*this);
13565       Region = BeforeRegion;
13566       Visit(SequencedBefore);
13567     }
13568 
13569     Region = AfterRegion;
13570     Visit(SequencedAfter);
13571 
13572     Region = OldRegion;
13573 
13574     Tree.merge(BeforeRegion);
13575     Tree.merge(AfterRegion);
13576   }
13577 
13578   void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
13579     // C++17 [expr.sub]p1:
13580     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
13581     //   expression E1 is sequenced before the expression E2.
13582     if (SemaRef.getLangOpts().CPlusPlus17)
13583       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
13584     else {
13585       Visit(ASE->getLHS());
13586       Visit(ASE->getRHS());
13587     }
13588   }
13589 
13590   void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
13591   void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
13592   void VisitBinPtrMem(const BinaryOperator *BO) {
13593     // C++17 [expr.mptr.oper]p4:
13594     //  Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
13595     //  the expression E1 is sequenced before the expression E2.
13596     if (SemaRef.getLangOpts().CPlusPlus17)
13597       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13598     else {
13599       Visit(BO->getLHS());
13600       Visit(BO->getRHS());
13601     }
13602   }
13603 
13604   void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
13605   void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
13606   void VisitBinShlShr(const BinaryOperator *BO) {
13607     // C++17 [expr.shift]p4:
13608     //  The expression E1 is sequenced before the expression E2.
13609     if (SemaRef.getLangOpts().CPlusPlus17)
13610       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13611     else {
13612       Visit(BO->getLHS());
13613       Visit(BO->getRHS());
13614     }
13615   }
13616 
13617   void VisitBinComma(const BinaryOperator *BO) {
13618     // C++11 [expr.comma]p1:
13619     //   Every value computation and side effect associated with the left
13620     //   expression is sequenced before every value computation and side
13621     //   effect associated with the right expression.
13622     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13623   }
13624 
13625   void VisitBinAssign(const BinaryOperator *BO) {
13626     SequenceTree::Seq RHSRegion;
13627     SequenceTree::Seq LHSRegion;
13628     if (SemaRef.getLangOpts().CPlusPlus17) {
13629       RHSRegion = Tree.allocate(Region);
13630       LHSRegion = Tree.allocate(Region);
13631     } else {
13632       RHSRegion = Region;
13633       LHSRegion = Region;
13634     }
13635     SequenceTree::Seq OldRegion = Region;
13636 
13637     // C++11 [expr.ass]p1:
13638     //  [...] the assignment is sequenced after the value computation
13639     //  of the right and left operands, [...]
13640     //
13641     // so check it before inspecting the operands and update the
13642     // map afterwards.
13643     Object O = getObject(BO->getLHS(), /*Mod=*/true);
13644     if (O)
13645       notePreMod(O, BO);
13646 
13647     if (SemaRef.getLangOpts().CPlusPlus17) {
13648       // C++17 [expr.ass]p1:
13649       //  [...] The right operand is sequenced before the left operand. [...]
13650       {
13651         SequencedSubexpression SeqBefore(*this);
13652         Region = RHSRegion;
13653         Visit(BO->getRHS());
13654       }
13655 
13656       Region = LHSRegion;
13657       Visit(BO->getLHS());
13658 
13659       if (O && isa<CompoundAssignOperator>(BO))
13660         notePostUse(O, BO);
13661 
13662     } else {
13663       // C++11 does not specify any sequencing between the LHS and RHS.
13664       Region = LHSRegion;
13665       Visit(BO->getLHS());
13666 
13667       if (O && isa<CompoundAssignOperator>(BO))
13668         notePostUse(O, BO);
13669 
13670       Region = RHSRegion;
13671       Visit(BO->getRHS());
13672     }
13673 
13674     // C++11 [expr.ass]p1:
13675     //  the assignment is sequenced [...] before the value computation of the
13676     //  assignment expression.
13677     // C11 6.5.16/3 has no such rule.
13678     Region = OldRegion;
13679     if (O)
13680       notePostMod(O, BO,
13681                   SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
13682                                                   : UK_ModAsSideEffect);
13683     if (SemaRef.getLangOpts().CPlusPlus17) {
13684       Tree.merge(RHSRegion);
13685       Tree.merge(LHSRegion);
13686     }
13687   }
13688 
13689   void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
13690     VisitBinAssign(CAO);
13691   }
13692 
13693   void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
13694   void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
13695   void VisitUnaryPreIncDec(const UnaryOperator *UO) {
13696     Object O = getObject(UO->getSubExpr(), true);
13697     if (!O)
13698       return VisitExpr(UO);
13699 
13700     notePreMod(O, UO);
13701     Visit(UO->getSubExpr());
13702     // C++11 [expr.pre.incr]p1:
13703     //   the expression ++x is equivalent to x+=1
13704     notePostMod(O, UO,
13705                 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
13706                                                 : UK_ModAsSideEffect);
13707   }
13708 
13709   void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
13710   void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
13711   void VisitUnaryPostIncDec(const UnaryOperator *UO) {
13712     Object O = getObject(UO->getSubExpr(), true);
13713     if (!O)
13714       return VisitExpr(UO);
13715 
13716     notePreMod(O, UO);
13717     Visit(UO->getSubExpr());
13718     notePostMod(O, UO, UK_ModAsSideEffect);
13719   }
13720 
13721   void VisitBinLOr(const BinaryOperator *BO) {
13722     // C++11 [expr.log.or]p2:
13723     //  If the second expression is evaluated, every value computation and
13724     //  side effect associated with the first expression is sequenced before
13725     //  every value computation and side effect associated with the
13726     //  second expression.
13727     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
13728     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
13729     SequenceTree::Seq OldRegion = Region;
13730 
13731     EvaluationTracker Eval(*this);
13732     {
13733       SequencedSubexpression Sequenced(*this);
13734       Region = LHSRegion;
13735       Visit(BO->getLHS());
13736     }
13737 
13738     // C++11 [expr.log.or]p1:
13739     //  [...] the second operand is not evaluated if the first operand
13740     //  evaluates to true.
13741     bool EvalResult = false;
13742     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
13743     bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
13744     if (ShouldVisitRHS) {
13745       Region = RHSRegion;
13746       Visit(BO->getRHS());
13747     }
13748 
13749     Region = OldRegion;
13750     Tree.merge(LHSRegion);
13751     Tree.merge(RHSRegion);
13752   }
13753 
13754   void VisitBinLAnd(const BinaryOperator *BO) {
13755     // C++11 [expr.log.and]p2:
13756     //  If the second expression is evaluated, every value computation and
13757     //  side effect associated with the first expression is sequenced before
13758     //  every value computation and side effect associated with the
13759     //  second expression.
13760     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
13761     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
13762     SequenceTree::Seq OldRegion = Region;
13763 
13764     EvaluationTracker Eval(*this);
13765     {
13766       SequencedSubexpression Sequenced(*this);
13767       Region = LHSRegion;
13768       Visit(BO->getLHS());
13769     }
13770 
13771     // C++11 [expr.log.and]p1:
13772     //  [...] the second operand is not evaluated if the first operand is false.
13773     bool EvalResult = false;
13774     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
13775     bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
13776     if (ShouldVisitRHS) {
13777       Region = RHSRegion;
13778       Visit(BO->getRHS());
13779     }
13780 
13781     Region = OldRegion;
13782     Tree.merge(LHSRegion);
13783     Tree.merge(RHSRegion);
13784   }
13785 
13786   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
13787     // C++11 [expr.cond]p1:
13788     //  [...] Every value computation and side effect associated with the first
13789     //  expression is sequenced before every value computation and side effect
13790     //  associated with the second or third expression.
13791     SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
13792 
13793     // No sequencing is specified between the true and false expression.
13794     // However since exactly one of both is going to be evaluated we can
13795     // consider them to be sequenced. This is needed to avoid warning on
13796     // something like "x ? y+= 1 : y += 2;" in the case where we will visit
13797     // both the true and false expressions because we can't evaluate x.
13798     // This will still allow us to detect an expression like (pre C++17)
13799     // "(x ? y += 1 : y += 2) = y".
13800     //
13801     // We don't wrap the visitation of the true and false expression with
13802     // SequencedSubexpression because we don't want to downgrade modifications
13803     // as side effect in the true and false expressions after the visition
13804     // is done. (for example in the expression "(x ? y++ : y++) + y" we should
13805     // not warn between the two "y++", but we should warn between the "y++"
13806     // and the "y".
13807     SequenceTree::Seq TrueRegion = Tree.allocate(Region);
13808     SequenceTree::Seq FalseRegion = Tree.allocate(Region);
13809     SequenceTree::Seq OldRegion = Region;
13810 
13811     EvaluationTracker Eval(*this);
13812     {
13813       SequencedSubexpression Sequenced(*this);
13814       Region = ConditionRegion;
13815       Visit(CO->getCond());
13816     }
13817 
13818     // C++11 [expr.cond]p1:
13819     // [...] The first expression is contextually converted to bool (Clause 4).
13820     // It is evaluated and if it is true, the result of the conditional
13821     // expression is the value of the second expression, otherwise that of the
13822     // third expression. Only one of the second and third expressions is
13823     // evaluated. [...]
13824     bool EvalResult = false;
13825     bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
13826     bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
13827     bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
13828     if (ShouldVisitTrueExpr) {
13829       Region = TrueRegion;
13830       Visit(CO->getTrueExpr());
13831     }
13832     if (ShouldVisitFalseExpr) {
13833       Region = FalseRegion;
13834       Visit(CO->getFalseExpr());
13835     }
13836 
13837     Region = OldRegion;
13838     Tree.merge(ConditionRegion);
13839     Tree.merge(TrueRegion);
13840     Tree.merge(FalseRegion);
13841   }
13842 
13843   void VisitCallExpr(const CallExpr *CE) {
13844     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
13845 
13846     if (CE->isUnevaluatedBuiltinCall(Context))
13847       return;
13848 
13849     // C++11 [intro.execution]p15:
13850     //   When calling a function [...], every value computation and side effect
13851     //   associated with any argument expression, or with the postfix expression
13852     //   designating the called function, is sequenced before execution of every
13853     //   expression or statement in the body of the function [and thus before
13854     //   the value computation of its result].
13855     SequencedSubexpression Sequenced(*this);
13856     SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
13857       // C++17 [expr.call]p5
13858       //   The postfix-expression is sequenced before each expression in the
13859       //   expression-list and any default argument. [...]
13860       SequenceTree::Seq CalleeRegion;
13861       SequenceTree::Seq OtherRegion;
13862       if (SemaRef.getLangOpts().CPlusPlus17) {
13863         CalleeRegion = Tree.allocate(Region);
13864         OtherRegion = Tree.allocate(Region);
13865       } else {
13866         CalleeRegion = Region;
13867         OtherRegion = Region;
13868       }
13869       SequenceTree::Seq OldRegion = Region;
13870 
13871       // Visit the callee expression first.
13872       Region = CalleeRegion;
13873       if (SemaRef.getLangOpts().CPlusPlus17) {
13874         SequencedSubexpression Sequenced(*this);
13875         Visit(CE->getCallee());
13876       } else {
13877         Visit(CE->getCallee());
13878       }
13879 
13880       // Then visit the argument expressions.
13881       Region = OtherRegion;
13882       for (const Expr *Argument : CE->arguments())
13883         Visit(Argument);
13884 
13885       Region = OldRegion;
13886       if (SemaRef.getLangOpts().CPlusPlus17) {
13887         Tree.merge(CalleeRegion);
13888         Tree.merge(OtherRegion);
13889       }
13890     });
13891   }
13892 
13893   void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
13894     // C++17 [over.match.oper]p2:
13895     //   [...] the operator notation is first transformed to the equivalent
13896     //   function-call notation as summarized in Table 12 (where @ denotes one
13897     //   of the operators covered in the specified subclause). However, the
13898     //   operands are sequenced in the order prescribed for the built-in
13899     //   operator (Clause 8).
13900     //
13901     // From the above only overloaded binary operators and overloaded call
13902     // operators have sequencing rules in C++17 that we need to handle
13903     // separately.
13904     if (!SemaRef.getLangOpts().CPlusPlus17 ||
13905         (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
13906       return VisitCallExpr(CXXOCE);
13907 
13908     enum {
13909       NoSequencing,
13910       LHSBeforeRHS,
13911       RHSBeforeLHS,
13912       LHSBeforeRest
13913     } SequencingKind;
13914     switch (CXXOCE->getOperator()) {
13915     case OO_Equal:
13916     case OO_PlusEqual:
13917     case OO_MinusEqual:
13918     case OO_StarEqual:
13919     case OO_SlashEqual:
13920     case OO_PercentEqual:
13921     case OO_CaretEqual:
13922     case OO_AmpEqual:
13923     case OO_PipeEqual:
13924     case OO_LessLessEqual:
13925     case OO_GreaterGreaterEqual:
13926       SequencingKind = RHSBeforeLHS;
13927       break;
13928 
13929     case OO_LessLess:
13930     case OO_GreaterGreater:
13931     case OO_AmpAmp:
13932     case OO_PipePipe:
13933     case OO_Comma:
13934     case OO_ArrowStar:
13935     case OO_Subscript:
13936       SequencingKind = LHSBeforeRHS;
13937       break;
13938 
13939     case OO_Call:
13940       SequencingKind = LHSBeforeRest;
13941       break;
13942 
13943     default:
13944       SequencingKind = NoSequencing;
13945       break;
13946     }
13947 
13948     if (SequencingKind == NoSequencing)
13949       return VisitCallExpr(CXXOCE);
13950 
13951     // This is a call, so all subexpressions are sequenced before the result.
13952     SequencedSubexpression Sequenced(*this);
13953 
13954     SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
13955       assert(SemaRef.getLangOpts().CPlusPlus17 &&
13956              "Should only get there with C++17 and above!");
13957       assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
13958              "Should only get there with an overloaded binary operator"
13959              " or an overloaded call operator!");
13960 
13961       if (SequencingKind == LHSBeforeRest) {
13962         assert(CXXOCE->getOperator() == OO_Call &&
13963                "We should only have an overloaded call operator here!");
13964 
13965         // This is very similar to VisitCallExpr, except that we only have the
13966         // C++17 case. The postfix-expression is the first argument of the
13967         // CXXOperatorCallExpr. The expressions in the expression-list, if any,
13968         // are in the following arguments.
13969         //
13970         // Note that we intentionally do not visit the callee expression since
13971         // it is just a decayed reference to a function.
13972         SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
13973         SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
13974         SequenceTree::Seq OldRegion = Region;
13975 
13976         assert(CXXOCE->getNumArgs() >= 1 &&
13977                "An overloaded call operator must have at least one argument"
13978                " for the postfix-expression!");
13979         const Expr *PostfixExpr = CXXOCE->getArgs()[0];
13980         llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
13981                                           CXXOCE->getNumArgs() - 1);
13982 
13983         // Visit the postfix-expression first.
13984         {
13985           Region = PostfixExprRegion;
13986           SequencedSubexpression Sequenced(*this);
13987           Visit(PostfixExpr);
13988         }
13989 
13990         // Then visit the argument expressions.
13991         Region = ArgsRegion;
13992         for (const Expr *Arg : Args)
13993           Visit(Arg);
13994 
13995         Region = OldRegion;
13996         Tree.merge(PostfixExprRegion);
13997         Tree.merge(ArgsRegion);
13998       } else {
13999         assert(CXXOCE->getNumArgs() == 2 &&
14000                "Should only have two arguments here!");
14001         assert((SequencingKind == LHSBeforeRHS ||
14002                 SequencingKind == RHSBeforeLHS) &&
14003                "Unexpected sequencing kind!");
14004 
14005         // We do not visit the callee expression since it is just a decayed
14006         // reference to a function.
14007         const Expr *E1 = CXXOCE->getArg(0);
14008         const Expr *E2 = CXXOCE->getArg(1);
14009         if (SequencingKind == RHSBeforeLHS)
14010           std::swap(E1, E2);
14011 
14012         return VisitSequencedExpressions(E1, E2);
14013       }
14014     });
14015   }
14016 
14017   void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
14018     // This is a call, so all subexpressions are sequenced before the result.
14019     SequencedSubexpression Sequenced(*this);
14020 
14021     if (!CCE->isListInitialization())
14022       return VisitExpr(CCE);
14023 
14024     // In C++11, list initializations are sequenced.
14025     SmallVector<SequenceTree::Seq, 32> Elts;
14026     SequenceTree::Seq Parent = Region;
14027     for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
14028                                               E = CCE->arg_end();
14029          I != E; ++I) {
14030       Region = Tree.allocate(Parent);
14031       Elts.push_back(Region);
14032       Visit(*I);
14033     }
14034 
14035     // Forget that the initializers are sequenced.
14036     Region = Parent;
14037     for (unsigned I = 0; I < Elts.size(); ++I)
14038       Tree.merge(Elts[I]);
14039   }
14040 
14041   void VisitInitListExpr(const InitListExpr *ILE) {
14042     if (!SemaRef.getLangOpts().CPlusPlus11)
14043       return VisitExpr(ILE);
14044 
14045     // In C++11, list initializations are sequenced.
14046     SmallVector<SequenceTree::Seq, 32> Elts;
14047     SequenceTree::Seq Parent = Region;
14048     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
14049       const Expr *E = ILE->getInit(I);
14050       if (!E)
14051         continue;
14052       Region = Tree.allocate(Parent);
14053       Elts.push_back(Region);
14054       Visit(E);
14055     }
14056 
14057     // Forget that the initializers are sequenced.
14058     Region = Parent;
14059     for (unsigned I = 0; I < Elts.size(); ++I)
14060       Tree.merge(Elts[I]);
14061   }
14062 };
14063 
14064 } // namespace
14065 
14066 void Sema::CheckUnsequencedOperations(const Expr *E) {
14067   SmallVector<const Expr *, 8> WorkList;
14068   WorkList.push_back(E);
14069   while (!WorkList.empty()) {
14070     const Expr *Item = WorkList.pop_back_val();
14071     SequenceChecker(*this, Item, WorkList);
14072   }
14073 }
14074 
14075 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
14076                               bool IsConstexpr) {
14077   llvm::SaveAndRestore<bool> ConstantContext(
14078       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
14079   CheckImplicitConversions(E, CheckLoc);
14080   if (!E->isInstantiationDependent())
14081     CheckUnsequencedOperations(E);
14082   if (!IsConstexpr && !E->isValueDependent())
14083     CheckForIntOverflow(E);
14084   DiagnoseMisalignedMembers();
14085 }
14086 
14087 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
14088                                        FieldDecl *BitField,
14089                                        Expr *Init) {
14090   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
14091 }
14092 
14093 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
14094                                          SourceLocation Loc) {
14095   if (!PType->isVariablyModifiedType())
14096     return;
14097   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
14098     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
14099     return;
14100   }
14101   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
14102     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
14103     return;
14104   }
14105   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
14106     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
14107     return;
14108   }
14109 
14110   const ArrayType *AT = S.Context.getAsArrayType(PType);
14111   if (!AT)
14112     return;
14113 
14114   if (AT->getSizeModifier() != ArrayType::Star) {
14115     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
14116     return;
14117   }
14118 
14119   S.Diag(Loc, diag::err_array_star_in_function_definition);
14120 }
14121 
14122 /// CheckParmsForFunctionDef - Check that the parameters of the given
14123 /// function are appropriate for the definition of a function. This
14124 /// takes care of any checks that cannot be performed on the
14125 /// declaration itself, e.g., that the types of each of the function
14126 /// parameters are complete.
14127 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
14128                                     bool CheckParameterNames) {
14129   bool HasInvalidParm = false;
14130   for (ParmVarDecl *Param : Parameters) {
14131     // C99 6.7.5.3p4: the parameters in a parameter type list in a
14132     // function declarator that is part of a function definition of
14133     // that function shall not have incomplete type.
14134     //
14135     // This is also C++ [dcl.fct]p6.
14136     if (!Param->isInvalidDecl() &&
14137         RequireCompleteType(Param->getLocation(), Param->getType(),
14138                             diag::err_typecheck_decl_incomplete_type)) {
14139       Param->setInvalidDecl();
14140       HasInvalidParm = true;
14141     }
14142 
14143     // C99 6.9.1p5: If the declarator includes a parameter type list, the
14144     // declaration of each parameter shall include an identifier.
14145     if (CheckParameterNames && Param->getIdentifier() == nullptr &&
14146         !Param->isImplicit() && !getLangOpts().CPlusPlus) {
14147       // Diagnose this as an extension in C17 and earlier.
14148       if (!getLangOpts().C2x)
14149         Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
14150     }
14151 
14152     // C99 6.7.5.3p12:
14153     //   If the function declarator is not part of a definition of that
14154     //   function, parameters may have incomplete type and may use the [*]
14155     //   notation in their sequences of declarator specifiers to specify
14156     //   variable length array types.
14157     QualType PType = Param->getOriginalType();
14158     // FIXME: This diagnostic should point the '[*]' if source-location
14159     // information is added for it.
14160     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
14161 
14162     // If the parameter is a c++ class type and it has to be destructed in the
14163     // callee function, declare the destructor so that it can be called by the
14164     // callee function. Do not perform any direct access check on the dtor here.
14165     if (!Param->isInvalidDecl()) {
14166       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
14167         if (!ClassDecl->isInvalidDecl() &&
14168             !ClassDecl->hasIrrelevantDestructor() &&
14169             !ClassDecl->isDependentContext() &&
14170             ClassDecl->isParamDestroyedInCallee()) {
14171           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
14172           MarkFunctionReferenced(Param->getLocation(), Destructor);
14173           DiagnoseUseOfDecl(Destructor, Param->getLocation());
14174         }
14175       }
14176     }
14177 
14178     // Parameters with the pass_object_size attribute only need to be marked
14179     // constant at function definitions. Because we lack information about
14180     // whether we're on a declaration or definition when we're instantiating the
14181     // attribute, we need to check for constness here.
14182     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
14183       if (!Param->getType().isConstQualified())
14184         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
14185             << Attr->getSpelling() << 1;
14186 
14187     // Check for parameter names shadowing fields from the class.
14188     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
14189       // The owning context for the parameter should be the function, but we
14190       // want to see if this function's declaration context is a record.
14191       DeclContext *DC = Param->getDeclContext();
14192       if (DC && DC->isFunctionOrMethod()) {
14193         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
14194           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
14195                                      RD, /*DeclIsField*/ false);
14196       }
14197     }
14198   }
14199 
14200   return HasInvalidParm;
14201 }
14202 
14203 Optional<std::pair<CharUnits, CharUnits>>
14204 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx);
14205 
14206 /// Compute the alignment and offset of the base class object given the
14207 /// derived-to-base cast expression and the alignment and offset of the derived
14208 /// class object.
14209 static std::pair<CharUnits, CharUnits>
14210 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
14211                                    CharUnits BaseAlignment, CharUnits Offset,
14212                                    ASTContext &Ctx) {
14213   for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
14214        ++PathI) {
14215     const CXXBaseSpecifier *Base = *PathI;
14216     const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
14217     if (Base->isVirtual()) {
14218       // The complete object may have a lower alignment than the non-virtual
14219       // alignment of the base, in which case the base may be misaligned. Choose
14220       // the smaller of the non-virtual alignment and BaseAlignment, which is a
14221       // conservative lower bound of the complete object alignment.
14222       CharUnits NonVirtualAlignment =
14223           Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment();
14224       BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
14225       Offset = CharUnits::Zero();
14226     } else {
14227       const ASTRecordLayout &RL =
14228           Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
14229       Offset += RL.getBaseClassOffset(BaseDecl);
14230     }
14231     DerivedType = Base->getType();
14232   }
14233 
14234   return std::make_pair(BaseAlignment, Offset);
14235 }
14236 
14237 /// Compute the alignment and offset of a binary additive operator.
14238 static Optional<std::pair<CharUnits, CharUnits>>
14239 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
14240                                      bool IsSub, ASTContext &Ctx) {
14241   QualType PointeeType = PtrE->getType()->getPointeeType();
14242 
14243   if (!PointeeType->isConstantSizeType())
14244     return llvm::None;
14245 
14246   auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
14247 
14248   if (!P)
14249     return llvm::None;
14250 
14251   CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
14252   if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
14253     CharUnits Offset = EltSize * IdxRes->getExtValue();
14254     if (IsSub)
14255       Offset = -Offset;
14256     return std::make_pair(P->first, P->second + Offset);
14257   }
14258 
14259   // If the integer expression isn't a constant expression, compute the lower
14260   // bound of the alignment using the alignment and offset of the pointer
14261   // expression and the element size.
14262   return std::make_pair(
14263       P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
14264       CharUnits::Zero());
14265 }
14266 
14267 /// This helper function takes an lvalue expression and returns the alignment of
14268 /// a VarDecl and a constant offset from the VarDecl.
14269 Optional<std::pair<CharUnits, CharUnits>>
14270 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) {
14271   E = E->IgnoreParens();
14272   switch (E->getStmtClass()) {
14273   default:
14274     break;
14275   case Stmt::CStyleCastExprClass:
14276   case Stmt::CXXStaticCastExprClass:
14277   case Stmt::ImplicitCastExprClass: {
14278     auto *CE = cast<CastExpr>(E);
14279     const Expr *From = CE->getSubExpr();
14280     switch (CE->getCastKind()) {
14281     default:
14282       break;
14283     case CK_NoOp:
14284       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14285     case CK_UncheckedDerivedToBase:
14286     case CK_DerivedToBase: {
14287       auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14288       if (!P)
14289         break;
14290       return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
14291                                                 P->second, Ctx);
14292     }
14293     }
14294     break;
14295   }
14296   case Stmt::ArraySubscriptExprClass: {
14297     auto *ASE = cast<ArraySubscriptExpr>(E);
14298     return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(),
14299                                                 false, Ctx);
14300   }
14301   case Stmt::DeclRefExprClass: {
14302     if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
14303       // FIXME: If VD is captured by copy or is an escaping __block variable,
14304       // use the alignment of VD's type.
14305       if (!VD->getType()->isReferenceType())
14306         return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
14307       if (VD->hasInit())
14308         return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
14309     }
14310     break;
14311   }
14312   case Stmt::MemberExprClass: {
14313     auto *ME = cast<MemberExpr>(E);
14314     auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
14315     if (!FD || FD->getType()->isReferenceType())
14316       break;
14317     Optional<std::pair<CharUnits, CharUnits>> P;
14318     if (ME->isArrow())
14319       P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
14320     else
14321       P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
14322     if (!P)
14323       break;
14324     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
14325     uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
14326     return std::make_pair(P->first,
14327                           P->second + CharUnits::fromQuantity(Offset));
14328   }
14329   case Stmt::UnaryOperatorClass: {
14330     auto *UO = cast<UnaryOperator>(E);
14331     switch (UO->getOpcode()) {
14332     default:
14333       break;
14334     case UO_Deref:
14335       return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx);
14336     }
14337     break;
14338   }
14339   case Stmt::BinaryOperatorClass: {
14340     auto *BO = cast<BinaryOperator>(E);
14341     auto Opcode = BO->getOpcode();
14342     switch (Opcode) {
14343     default:
14344       break;
14345     case BO_Comma:
14346       return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx);
14347     }
14348     break;
14349   }
14350   }
14351   return llvm::None;
14352 }
14353 
14354 /// This helper function takes a pointer expression and returns the alignment of
14355 /// a VarDecl and a constant offset from the VarDecl.
14356 Optional<std::pair<CharUnits, CharUnits>>
14357 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) {
14358   E = E->IgnoreParens();
14359   switch (E->getStmtClass()) {
14360   default:
14361     break;
14362   case Stmt::CStyleCastExprClass:
14363   case Stmt::CXXStaticCastExprClass:
14364   case Stmt::ImplicitCastExprClass: {
14365     auto *CE = cast<CastExpr>(E);
14366     const Expr *From = CE->getSubExpr();
14367     switch (CE->getCastKind()) {
14368     default:
14369       break;
14370     case CK_NoOp:
14371       return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14372     case CK_ArrayToPointerDecay:
14373       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14374     case CK_UncheckedDerivedToBase:
14375     case CK_DerivedToBase: {
14376       auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14377       if (!P)
14378         break;
14379       return getDerivedToBaseAlignmentAndOffset(
14380           CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
14381     }
14382     }
14383     break;
14384   }
14385   case Stmt::CXXThisExprClass: {
14386     auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
14387     CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment();
14388     return std::make_pair(Alignment, CharUnits::Zero());
14389   }
14390   case Stmt::UnaryOperatorClass: {
14391     auto *UO = cast<UnaryOperator>(E);
14392     if (UO->getOpcode() == UO_AddrOf)
14393       return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx);
14394     break;
14395   }
14396   case Stmt::BinaryOperatorClass: {
14397     auto *BO = cast<BinaryOperator>(E);
14398     auto Opcode = BO->getOpcode();
14399     switch (Opcode) {
14400     default:
14401       break;
14402     case BO_Add:
14403     case BO_Sub: {
14404       const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
14405       if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
14406         std::swap(LHS, RHS);
14407       return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
14408                                                   Ctx);
14409     }
14410     case BO_Comma:
14411       return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
14412     }
14413     break;
14414   }
14415   }
14416   return llvm::None;
14417 }
14418 
14419 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
14420   // See if we can compute the alignment of a VarDecl and an offset from it.
14421   Optional<std::pair<CharUnits, CharUnits>> P =
14422       getBaseAlignmentAndOffsetFromPtr(E, S.Context);
14423 
14424   if (P)
14425     return P->first.alignmentAtOffset(P->second);
14426 
14427   // If that failed, return the type's alignment.
14428   return S.Context.getTypeAlignInChars(E->getType()->getPointeeType());
14429 }
14430 
14431 /// CheckCastAlign - Implements -Wcast-align, which warns when a
14432 /// pointer cast increases the alignment requirements.
14433 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
14434   // This is actually a lot of work to potentially be doing on every
14435   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
14436   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
14437     return;
14438 
14439   // Ignore dependent types.
14440   if (T->isDependentType() || Op->getType()->isDependentType())
14441     return;
14442 
14443   // Require that the destination be a pointer type.
14444   const PointerType *DestPtr = T->getAs<PointerType>();
14445   if (!DestPtr) return;
14446 
14447   // If the destination has alignment 1, we're done.
14448   QualType DestPointee = DestPtr->getPointeeType();
14449   if (DestPointee->isIncompleteType()) return;
14450   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
14451   if (DestAlign.isOne()) return;
14452 
14453   // Require that the source be a pointer type.
14454   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
14455   if (!SrcPtr) return;
14456   QualType SrcPointee = SrcPtr->getPointeeType();
14457 
14458   // Explicitly allow casts from cv void*.  We already implicitly
14459   // allowed casts to cv void*, since they have alignment 1.
14460   // Also allow casts involving incomplete types, which implicitly
14461   // includes 'void'.
14462   if (SrcPointee->isIncompleteType()) return;
14463 
14464   CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
14465 
14466   if (SrcAlign >= DestAlign) return;
14467 
14468   Diag(TRange.getBegin(), diag::warn_cast_align)
14469     << Op->getType() << T
14470     << static_cast<unsigned>(SrcAlign.getQuantity())
14471     << static_cast<unsigned>(DestAlign.getQuantity())
14472     << TRange << Op->getSourceRange();
14473 }
14474 
14475 /// Check whether this array fits the idiom of a size-one tail padded
14476 /// array member of a struct.
14477 ///
14478 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
14479 /// commonly used to emulate flexible arrays in C89 code.
14480 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
14481                                     const NamedDecl *ND) {
14482   if (Size != 1 || !ND) return false;
14483 
14484   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
14485   if (!FD) return false;
14486 
14487   // Don't consider sizes resulting from macro expansions or template argument
14488   // substitution to form C89 tail-padded arrays.
14489 
14490   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
14491   while (TInfo) {
14492     TypeLoc TL = TInfo->getTypeLoc();
14493     // Look through typedefs.
14494     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
14495       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
14496       TInfo = TDL->getTypeSourceInfo();
14497       continue;
14498     }
14499     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
14500       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
14501       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
14502         return false;
14503     }
14504     break;
14505   }
14506 
14507   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
14508   if (!RD) return false;
14509   if (RD->isUnion()) return false;
14510   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
14511     if (!CRD->isStandardLayout()) return false;
14512   }
14513 
14514   // See if this is the last field decl in the record.
14515   const Decl *D = FD;
14516   while ((D = D->getNextDeclInContext()))
14517     if (isa<FieldDecl>(D))
14518       return false;
14519   return true;
14520 }
14521 
14522 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
14523                             const ArraySubscriptExpr *ASE,
14524                             bool AllowOnePastEnd, bool IndexNegated) {
14525   // Already diagnosed by the constant evaluator.
14526   if (isConstantEvaluated())
14527     return;
14528 
14529   IndexExpr = IndexExpr->IgnoreParenImpCasts();
14530   if (IndexExpr->isValueDependent())
14531     return;
14532 
14533   const Type *EffectiveType =
14534       BaseExpr->getType()->getPointeeOrArrayElementType();
14535   BaseExpr = BaseExpr->IgnoreParenCasts();
14536   const ConstantArrayType *ArrayTy =
14537       Context.getAsConstantArrayType(BaseExpr->getType());
14538 
14539   const Type *BaseType =
14540       ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
14541   bool IsUnboundedArray = (BaseType == nullptr);
14542   if (EffectiveType->isDependentType() ||
14543       (!IsUnboundedArray && BaseType->isDependentType()))
14544     return;
14545 
14546   Expr::EvalResult Result;
14547   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
14548     return;
14549 
14550   llvm::APSInt index = Result.Val.getInt();
14551   if (IndexNegated) {
14552     index.setIsUnsigned(false);
14553     index = -index;
14554   }
14555 
14556   const NamedDecl *ND = nullptr;
14557   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14558     ND = DRE->getDecl();
14559   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
14560     ND = ME->getMemberDecl();
14561 
14562   if (IsUnboundedArray) {
14563     if (index.isUnsigned() || !index.isNegative()) {
14564       const auto &ASTC = getASTContext();
14565       unsigned AddrBits =
14566           ASTC.getTargetInfo().getPointerWidth(ASTC.getTargetAddressSpace(
14567               EffectiveType->getCanonicalTypeInternal()));
14568       if (index.getBitWidth() < AddrBits)
14569         index = index.zext(AddrBits);
14570       CharUnits ElemCharUnits = ASTC.getTypeSizeInChars(EffectiveType);
14571       llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits.getQuantity());
14572       // If index has more active bits than address space, we already know
14573       // we have a bounds violation to warn about.  Otherwise, compute
14574       // address of (index + 1)th element, and warn about bounds violation
14575       // only if that address exceeds address space.
14576       if (index.getActiveBits() <= AddrBits) {
14577         bool Overflow;
14578         llvm::APInt Product(index);
14579         Product += 1;
14580         Product = Product.umul_ov(ElemBytes, Overflow);
14581         if (!Overflow && Product.getActiveBits() <= AddrBits)
14582           return;
14583       }
14584 
14585       // Need to compute max possible elements in address space, since that
14586       // is included in diag message.
14587       llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
14588       MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
14589       MaxElems += 1;
14590       ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
14591       MaxElems = MaxElems.udiv(ElemBytes);
14592 
14593       unsigned DiagID =
14594           ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
14595               : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
14596 
14597       // Diag message shows element size in bits and in "bytes" (platform-
14598       // dependent CharUnits)
14599       DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
14600                           PDiag(DiagID)
14601                               << toString(index, 10, true) << AddrBits
14602                               << (unsigned)ASTC.toBits(ElemCharUnits)
14603                               << toString(ElemBytes, 10, false)
14604                               << toString(MaxElems, 10, false)
14605                               << (unsigned)MaxElems.getLimitedValue(~0U)
14606                               << IndexExpr->getSourceRange());
14607 
14608       if (!ND) {
14609         // Try harder to find a NamedDecl to point at in the note.
14610         while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
14611           BaseExpr = ASE->getBase()->IgnoreParenCasts();
14612         if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14613           ND = DRE->getDecl();
14614         if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
14615           ND = ME->getMemberDecl();
14616       }
14617 
14618       if (ND)
14619         DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
14620                             PDiag(diag::note_array_declared_here) << ND);
14621     }
14622     return;
14623   }
14624 
14625   if (index.isUnsigned() || !index.isNegative()) {
14626     // It is possible that the type of the base expression after
14627     // IgnoreParenCasts is incomplete, even though the type of the base
14628     // expression before IgnoreParenCasts is complete (see PR39746 for an
14629     // example). In this case we have no information about whether the array
14630     // access exceeds the array bounds. However we can still diagnose an array
14631     // access which precedes the array bounds.
14632     if (BaseType->isIncompleteType())
14633       return;
14634 
14635     llvm::APInt size = ArrayTy->getSize();
14636     if (!size.isStrictlyPositive())
14637       return;
14638 
14639     if (BaseType != EffectiveType) {
14640       // Make sure we're comparing apples to apples when comparing index to size
14641       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
14642       uint64_t array_typesize = Context.getTypeSize(BaseType);
14643       // Handle ptrarith_typesize being zero, such as when casting to void*
14644       if (!ptrarith_typesize) ptrarith_typesize = 1;
14645       if (ptrarith_typesize != array_typesize) {
14646         // There's a cast to a different size type involved
14647         uint64_t ratio = array_typesize / ptrarith_typesize;
14648         // TODO: Be smarter about handling cases where array_typesize is not a
14649         // multiple of ptrarith_typesize
14650         if (ptrarith_typesize * ratio == array_typesize)
14651           size *= llvm::APInt(size.getBitWidth(), ratio);
14652       }
14653     }
14654 
14655     if (size.getBitWidth() > index.getBitWidth())
14656       index = index.zext(size.getBitWidth());
14657     else if (size.getBitWidth() < index.getBitWidth())
14658       size = size.zext(index.getBitWidth());
14659 
14660     // For array subscripting the index must be less than size, but for pointer
14661     // arithmetic also allow the index (offset) to be equal to size since
14662     // computing the next address after the end of the array is legal and
14663     // commonly done e.g. in C++ iterators and range-based for loops.
14664     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
14665       return;
14666 
14667     // Also don't warn for arrays of size 1 which are members of some
14668     // structure. These are often used to approximate flexible arrays in C89
14669     // code.
14670     if (IsTailPaddedMemberArray(*this, size, ND))
14671       return;
14672 
14673     // Suppress the warning if the subscript expression (as identified by the
14674     // ']' location) and the index expression are both from macro expansions
14675     // within a system header.
14676     if (ASE) {
14677       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
14678           ASE->getRBracketLoc());
14679       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
14680         SourceLocation IndexLoc =
14681             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
14682         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
14683           return;
14684       }
14685     }
14686 
14687     unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
14688                           : diag::warn_ptr_arith_exceeds_bounds;
14689 
14690     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
14691                         PDiag(DiagID) << toString(index, 10, true)
14692                                       << toString(size, 10, true)
14693                                       << (unsigned)size.getLimitedValue(~0U)
14694                                       << IndexExpr->getSourceRange());
14695   } else {
14696     unsigned DiagID = diag::warn_array_index_precedes_bounds;
14697     if (!ASE) {
14698       DiagID = diag::warn_ptr_arith_precedes_bounds;
14699       if (index.isNegative()) index = -index;
14700     }
14701 
14702     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
14703                         PDiag(DiagID) << toString(index, 10, true)
14704                                       << IndexExpr->getSourceRange());
14705   }
14706 
14707   if (!ND) {
14708     // Try harder to find a NamedDecl to point at in the note.
14709     while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
14710       BaseExpr = ASE->getBase()->IgnoreParenCasts();
14711     if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14712       ND = DRE->getDecl();
14713     if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
14714       ND = ME->getMemberDecl();
14715   }
14716 
14717   if (ND)
14718     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
14719                         PDiag(diag::note_array_declared_here) << ND);
14720 }
14721 
14722 void Sema::CheckArrayAccess(const Expr *expr) {
14723   int AllowOnePastEnd = 0;
14724   while (expr) {
14725     expr = expr->IgnoreParenImpCasts();
14726     switch (expr->getStmtClass()) {
14727       case Stmt::ArraySubscriptExprClass: {
14728         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
14729         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
14730                          AllowOnePastEnd > 0);
14731         expr = ASE->getBase();
14732         break;
14733       }
14734       case Stmt::MemberExprClass: {
14735         expr = cast<MemberExpr>(expr)->getBase();
14736         break;
14737       }
14738       case Stmt::OMPArraySectionExprClass: {
14739         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
14740         if (ASE->getLowerBound())
14741           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
14742                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
14743         return;
14744       }
14745       case Stmt::UnaryOperatorClass: {
14746         // Only unwrap the * and & unary operators
14747         const UnaryOperator *UO = cast<UnaryOperator>(expr);
14748         expr = UO->getSubExpr();
14749         switch (UO->getOpcode()) {
14750           case UO_AddrOf:
14751             AllowOnePastEnd++;
14752             break;
14753           case UO_Deref:
14754             AllowOnePastEnd--;
14755             break;
14756           default:
14757             return;
14758         }
14759         break;
14760       }
14761       case Stmt::ConditionalOperatorClass: {
14762         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
14763         if (const Expr *lhs = cond->getLHS())
14764           CheckArrayAccess(lhs);
14765         if (const Expr *rhs = cond->getRHS())
14766           CheckArrayAccess(rhs);
14767         return;
14768       }
14769       case Stmt::CXXOperatorCallExprClass: {
14770         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
14771         for (const auto *Arg : OCE->arguments())
14772           CheckArrayAccess(Arg);
14773         return;
14774       }
14775       default:
14776         return;
14777     }
14778   }
14779 }
14780 
14781 //===--- CHECK: Objective-C retain cycles ----------------------------------//
14782 
14783 namespace {
14784 
14785 struct RetainCycleOwner {
14786   VarDecl *Variable = nullptr;
14787   SourceRange Range;
14788   SourceLocation Loc;
14789   bool Indirect = false;
14790 
14791   RetainCycleOwner() = default;
14792 
14793   void setLocsFrom(Expr *e) {
14794     Loc = e->getExprLoc();
14795     Range = e->getSourceRange();
14796   }
14797 };
14798 
14799 } // namespace
14800 
14801 /// Consider whether capturing the given variable can possibly lead to
14802 /// a retain cycle.
14803 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
14804   // In ARC, it's captured strongly iff the variable has __strong
14805   // lifetime.  In MRR, it's captured strongly if the variable is
14806   // __block and has an appropriate type.
14807   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
14808     return false;
14809 
14810   owner.Variable = var;
14811   if (ref)
14812     owner.setLocsFrom(ref);
14813   return true;
14814 }
14815 
14816 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
14817   while (true) {
14818     e = e->IgnoreParens();
14819     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
14820       switch (cast->getCastKind()) {
14821       case CK_BitCast:
14822       case CK_LValueBitCast:
14823       case CK_LValueToRValue:
14824       case CK_ARCReclaimReturnedObject:
14825         e = cast->getSubExpr();
14826         continue;
14827 
14828       default:
14829         return false;
14830       }
14831     }
14832 
14833     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
14834       ObjCIvarDecl *ivar = ref->getDecl();
14835       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
14836         return false;
14837 
14838       // Try to find a retain cycle in the base.
14839       if (!findRetainCycleOwner(S, ref->getBase(), owner))
14840         return false;
14841 
14842       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
14843       owner.Indirect = true;
14844       return true;
14845     }
14846 
14847     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
14848       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
14849       if (!var) return false;
14850       return considerVariable(var, ref, owner);
14851     }
14852 
14853     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
14854       if (member->isArrow()) return false;
14855 
14856       // Don't count this as an indirect ownership.
14857       e = member->getBase();
14858       continue;
14859     }
14860 
14861     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
14862       // Only pay attention to pseudo-objects on property references.
14863       ObjCPropertyRefExpr *pre
14864         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
14865                                               ->IgnoreParens());
14866       if (!pre) return false;
14867       if (pre->isImplicitProperty()) return false;
14868       ObjCPropertyDecl *property = pre->getExplicitProperty();
14869       if (!property->isRetaining() &&
14870           !(property->getPropertyIvarDecl() &&
14871             property->getPropertyIvarDecl()->getType()
14872               .getObjCLifetime() == Qualifiers::OCL_Strong))
14873           return false;
14874 
14875       owner.Indirect = true;
14876       if (pre->isSuperReceiver()) {
14877         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
14878         if (!owner.Variable)
14879           return false;
14880         owner.Loc = pre->getLocation();
14881         owner.Range = pre->getSourceRange();
14882         return true;
14883       }
14884       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
14885                               ->getSourceExpr());
14886       continue;
14887     }
14888 
14889     // Array ivars?
14890 
14891     return false;
14892   }
14893 }
14894 
14895 namespace {
14896 
14897   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
14898     ASTContext &Context;
14899     VarDecl *Variable;
14900     Expr *Capturer = nullptr;
14901     bool VarWillBeReased = false;
14902 
14903     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
14904         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
14905           Context(Context), Variable(variable) {}
14906 
14907     void VisitDeclRefExpr(DeclRefExpr *ref) {
14908       if (ref->getDecl() == Variable && !Capturer)
14909         Capturer = ref;
14910     }
14911 
14912     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
14913       if (Capturer) return;
14914       Visit(ref->getBase());
14915       if (Capturer && ref->isFreeIvar())
14916         Capturer = ref;
14917     }
14918 
14919     void VisitBlockExpr(BlockExpr *block) {
14920       // Look inside nested blocks
14921       if (block->getBlockDecl()->capturesVariable(Variable))
14922         Visit(block->getBlockDecl()->getBody());
14923     }
14924 
14925     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
14926       if (Capturer) return;
14927       if (OVE->getSourceExpr())
14928         Visit(OVE->getSourceExpr());
14929     }
14930 
14931     void VisitBinaryOperator(BinaryOperator *BinOp) {
14932       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
14933         return;
14934       Expr *LHS = BinOp->getLHS();
14935       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
14936         if (DRE->getDecl() != Variable)
14937           return;
14938         if (Expr *RHS = BinOp->getRHS()) {
14939           RHS = RHS->IgnoreParenCasts();
14940           Optional<llvm::APSInt> Value;
14941           VarWillBeReased =
14942               (RHS && (Value = RHS->getIntegerConstantExpr(Context)) &&
14943                *Value == 0);
14944         }
14945       }
14946     }
14947   };
14948 
14949 } // namespace
14950 
14951 /// Check whether the given argument is a block which captures a
14952 /// variable.
14953 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
14954   assert(owner.Variable && owner.Loc.isValid());
14955 
14956   e = e->IgnoreParenCasts();
14957 
14958   // Look through [^{...} copy] and Block_copy(^{...}).
14959   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
14960     Selector Cmd = ME->getSelector();
14961     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
14962       e = ME->getInstanceReceiver();
14963       if (!e)
14964         return nullptr;
14965       e = e->IgnoreParenCasts();
14966     }
14967   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
14968     if (CE->getNumArgs() == 1) {
14969       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
14970       if (Fn) {
14971         const IdentifierInfo *FnI = Fn->getIdentifier();
14972         if (FnI && FnI->isStr("_Block_copy")) {
14973           e = CE->getArg(0)->IgnoreParenCasts();
14974         }
14975       }
14976     }
14977   }
14978 
14979   BlockExpr *block = dyn_cast<BlockExpr>(e);
14980   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
14981     return nullptr;
14982 
14983   FindCaptureVisitor visitor(S.Context, owner.Variable);
14984   visitor.Visit(block->getBlockDecl()->getBody());
14985   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
14986 }
14987 
14988 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
14989                                 RetainCycleOwner &owner) {
14990   assert(capturer);
14991   assert(owner.Variable && owner.Loc.isValid());
14992 
14993   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
14994     << owner.Variable << capturer->getSourceRange();
14995   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
14996     << owner.Indirect << owner.Range;
14997 }
14998 
14999 /// Check for a keyword selector that starts with the word 'add' or
15000 /// 'set'.
15001 static bool isSetterLikeSelector(Selector sel) {
15002   if (sel.isUnarySelector()) return false;
15003 
15004   StringRef str = sel.getNameForSlot(0);
15005   while (!str.empty() && str.front() == '_') str = str.substr(1);
15006   if (str.startswith("set"))
15007     str = str.substr(3);
15008   else if (str.startswith("add")) {
15009     // Specially allow 'addOperationWithBlock:'.
15010     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
15011       return false;
15012     str = str.substr(3);
15013   }
15014   else
15015     return false;
15016 
15017   if (str.empty()) return true;
15018   return !isLowercase(str.front());
15019 }
15020 
15021 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
15022                                                     ObjCMessageExpr *Message) {
15023   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
15024                                                 Message->getReceiverInterface(),
15025                                                 NSAPI::ClassId_NSMutableArray);
15026   if (!IsMutableArray) {
15027     return None;
15028   }
15029 
15030   Selector Sel = Message->getSelector();
15031 
15032   Optional<NSAPI::NSArrayMethodKind> MKOpt =
15033     S.NSAPIObj->getNSArrayMethodKind(Sel);
15034   if (!MKOpt) {
15035     return None;
15036   }
15037 
15038   NSAPI::NSArrayMethodKind MK = *MKOpt;
15039 
15040   switch (MK) {
15041     case NSAPI::NSMutableArr_addObject:
15042     case NSAPI::NSMutableArr_insertObjectAtIndex:
15043     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
15044       return 0;
15045     case NSAPI::NSMutableArr_replaceObjectAtIndex:
15046       return 1;
15047 
15048     default:
15049       return None;
15050   }
15051 
15052   return None;
15053 }
15054 
15055 static
15056 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
15057                                                   ObjCMessageExpr *Message) {
15058   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
15059                                             Message->getReceiverInterface(),
15060                                             NSAPI::ClassId_NSMutableDictionary);
15061   if (!IsMutableDictionary) {
15062     return None;
15063   }
15064 
15065   Selector Sel = Message->getSelector();
15066 
15067   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
15068     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
15069   if (!MKOpt) {
15070     return None;
15071   }
15072 
15073   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
15074 
15075   switch (MK) {
15076     case NSAPI::NSMutableDict_setObjectForKey:
15077     case NSAPI::NSMutableDict_setValueForKey:
15078     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
15079       return 0;
15080 
15081     default:
15082       return None;
15083   }
15084 
15085   return None;
15086 }
15087 
15088 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
15089   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
15090                                                 Message->getReceiverInterface(),
15091                                                 NSAPI::ClassId_NSMutableSet);
15092 
15093   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
15094                                             Message->getReceiverInterface(),
15095                                             NSAPI::ClassId_NSMutableOrderedSet);
15096   if (!IsMutableSet && !IsMutableOrderedSet) {
15097     return None;
15098   }
15099 
15100   Selector Sel = Message->getSelector();
15101 
15102   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
15103   if (!MKOpt) {
15104     return None;
15105   }
15106 
15107   NSAPI::NSSetMethodKind MK = *MKOpt;
15108 
15109   switch (MK) {
15110     case NSAPI::NSMutableSet_addObject:
15111     case NSAPI::NSOrderedSet_setObjectAtIndex:
15112     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
15113     case NSAPI::NSOrderedSet_insertObjectAtIndex:
15114       return 0;
15115     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
15116       return 1;
15117   }
15118 
15119   return None;
15120 }
15121 
15122 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
15123   if (!Message->isInstanceMessage()) {
15124     return;
15125   }
15126 
15127   Optional<int> ArgOpt;
15128 
15129   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
15130       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
15131       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
15132     return;
15133   }
15134 
15135   int ArgIndex = *ArgOpt;
15136 
15137   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
15138   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
15139     Arg = OE->getSourceExpr()->IgnoreImpCasts();
15140   }
15141 
15142   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
15143     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
15144       if (ArgRE->isObjCSelfExpr()) {
15145         Diag(Message->getSourceRange().getBegin(),
15146              diag::warn_objc_circular_container)
15147           << ArgRE->getDecl() << StringRef("'super'");
15148       }
15149     }
15150   } else {
15151     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
15152 
15153     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
15154       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
15155     }
15156 
15157     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
15158       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
15159         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
15160           ValueDecl *Decl = ReceiverRE->getDecl();
15161           Diag(Message->getSourceRange().getBegin(),
15162                diag::warn_objc_circular_container)
15163             << Decl << Decl;
15164           if (!ArgRE->isObjCSelfExpr()) {
15165             Diag(Decl->getLocation(),
15166                  diag::note_objc_circular_container_declared_here)
15167               << Decl;
15168           }
15169         }
15170       }
15171     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
15172       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
15173         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
15174           ObjCIvarDecl *Decl = IvarRE->getDecl();
15175           Diag(Message->getSourceRange().getBegin(),
15176                diag::warn_objc_circular_container)
15177             << Decl << Decl;
15178           Diag(Decl->getLocation(),
15179                diag::note_objc_circular_container_declared_here)
15180             << Decl;
15181         }
15182       }
15183     }
15184   }
15185 }
15186 
15187 /// Check a message send to see if it's likely to cause a retain cycle.
15188 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
15189   // Only check instance methods whose selector looks like a setter.
15190   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
15191     return;
15192 
15193   // Try to find a variable that the receiver is strongly owned by.
15194   RetainCycleOwner owner;
15195   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
15196     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
15197       return;
15198   } else {
15199     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
15200     owner.Variable = getCurMethodDecl()->getSelfDecl();
15201     owner.Loc = msg->getSuperLoc();
15202     owner.Range = msg->getSuperLoc();
15203   }
15204 
15205   // Check whether the receiver is captured by any of the arguments.
15206   const ObjCMethodDecl *MD = msg->getMethodDecl();
15207   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
15208     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
15209       // noescape blocks should not be retained by the method.
15210       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
15211         continue;
15212       return diagnoseRetainCycle(*this, capturer, owner);
15213     }
15214   }
15215 }
15216 
15217 /// Check a property assign to see if it's likely to cause a retain cycle.
15218 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
15219   RetainCycleOwner owner;
15220   if (!findRetainCycleOwner(*this, receiver, owner))
15221     return;
15222 
15223   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
15224     diagnoseRetainCycle(*this, capturer, owner);
15225 }
15226 
15227 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
15228   RetainCycleOwner Owner;
15229   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
15230     return;
15231 
15232   // Because we don't have an expression for the variable, we have to set the
15233   // location explicitly here.
15234   Owner.Loc = Var->getLocation();
15235   Owner.Range = Var->getSourceRange();
15236 
15237   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
15238     diagnoseRetainCycle(*this, Capturer, Owner);
15239 }
15240 
15241 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
15242                                      Expr *RHS, bool isProperty) {
15243   // Check if RHS is an Objective-C object literal, which also can get
15244   // immediately zapped in a weak reference.  Note that we explicitly
15245   // allow ObjCStringLiterals, since those are designed to never really die.
15246   RHS = RHS->IgnoreParenImpCasts();
15247 
15248   // This enum needs to match with the 'select' in
15249   // warn_objc_arc_literal_assign (off-by-1).
15250   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
15251   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
15252     return false;
15253 
15254   S.Diag(Loc, diag::warn_arc_literal_assign)
15255     << (unsigned) Kind
15256     << (isProperty ? 0 : 1)
15257     << RHS->getSourceRange();
15258 
15259   return true;
15260 }
15261 
15262 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
15263                                     Qualifiers::ObjCLifetime LT,
15264                                     Expr *RHS, bool isProperty) {
15265   // Strip off any implicit cast added to get to the one ARC-specific.
15266   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15267     if (cast->getCastKind() == CK_ARCConsumeObject) {
15268       S.Diag(Loc, diag::warn_arc_retained_assign)
15269         << (LT == Qualifiers::OCL_ExplicitNone)
15270         << (isProperty ? 0 : 1)
15271         << RHS->getSourceRange();
15272       return true;
15273     }
15274     RHS = cast->getSubExpr();
15275   }
15276 
15277   if (LT == Qualifiers::OCL_Weak &&
15278       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
15279     return true;
15280 
15281   return false;
15282 }
15283 
15284 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
15285                               QualType LHS, Expr *RHS) {
15286   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
15287 
15288   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
15289     return false;
15290 
15291   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
15292     return true;
15293 
15294   return false;
15295 }
15296 
15297 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
15298                               Expr *LHS, Expr *RHS) {
15299   QualType LHSType;
15300   // PropertyRef on LHS type need be directly obtained from
15301   // its declaration as it has a PseudoType.
15302   ObjCPropertyRefExpr *PRE
15303     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
15304   if (PRE && !PRE->isImplicitProperty()) {
15305     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15306     if (PD)
15307       LHSType = PD->getType();
15308   }
15309 
15310   if (LHSType.isNull())
15311     LHSType = LHS->getType();
15312 
15313   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
15314 
15315   if (LT == Qualifiers::OCL_Weak) {
15316     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
15317       getCurFunction()->markSafeWeakUse(LHS);
15318   }
15319 
15320   if (checkUnsafeAssigns(Loc, LHSType, RHS))
15321     return;
15322 
15323   // FIXME. Check for other life times.
15324   if (LT != Qualifiers::OCL_None)
15325     return;
15326 
15327   if (PRE) {
15328     if (PRE->isImplicitProperty())
15329       return;
15330     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15331     if (!PD)
15332       return;
15333 
15334     unsigned Attributes = PD->getPropertyAttributes();
15335     if (Attributes & ObjCPropertyAttribute::kind_assign) {
15336       // when 'assign' attribute was not explicitly specified
15337       // by user, ignore it and rely on property type itself
15338       // for lifetime info.
15339       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
15340       if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
15341           LHSType->isObjCRetainableType())
15342         return;
15343 
15344       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15345         if (cast->getCastKind() == CK_ARCConsumeObject) {
15346           Diag(Loc, diag::warn_arc_retained_property_assign)
15347           << RHS->getSourceRange();
15348           return;
15349         }
15350         RHS = cast->getSubExpr();
15351       }
15352     } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
15353       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
15354         return;
15355     }
15356   }
15357 }
15358 
15359 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
15360 
15361 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
15362                                         SourceLocation StmtLoc,
15363                                         const NullStmt *Body) {
15364   // Do not warn if the body is a macro that expands to nothing, e.g:
15365   //
15366   // #define CALL(x)
15367   // if (condition)
15368   //   CALL(0);
15369   if (Body->hasLeadingEmptyMacro())
15370     return false;
15371 
15372   // Get line numbers of statement and body.
15373   bool StmtLineInvalid;
15374   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
15375                                                       &StmtLineInvalid);
15376   if (StmtLineInvalid)
15377     return false;
15378 
15379   bool BodyLineInvalid;
15380   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
15381                                                       &BodyLineInvalid);
15382   if (BodyLineInvalid)
15383     return false;
15384 
15385   // Warn if null statement and body are on the same line.
15386   if (StmtLine != BodyLine)
15387     return false;
15388 
15389   return true;
15390 }
15391 
15392 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
15393                                  const Stmt *Body,
15394                                  unsigned DiagID) {
15395   // Since this is a syntactic check, don't emit diagnostic for template
15396   // instantiations, this just adds noise.
15397   if (CurrentInstantiationScope)
15398     return;
15399 
15400   // The body should be a null statement.
15401   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15402   if (!NBody)
15403     return;
15404 
15405   // Do the usual checks.
15406   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15407     return;
15408 
15409   Diag(NBody->getSemiLoc(), DiagID);
15410   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15411 }
15412 
15413 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
15414                                  const Stmt *PossibleBody) {
15415   assert(!CurrentInstantiationScope); // Ensured by caller
15416 
15417   SourceLocation StmtLoc;
15418   const Stmt *Body;
15419   unsigned DiagID;
15420   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
15421     StmtLoc = FS->getRParenLoc();
15422     Body = FS->getBody();
15423     DiagID = diag::warn_empty_for_body;
15424   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
15425     StmtLoc = WS->getCond()->getSourceRange().getEnd();
15426     Body = WS->getBody();
15427     DiagID = diag::warn_empty_while_body;
15428   } else
15429     return; // Neither `for' nor `while'.
15430 
15431   // The body should be a null statement.
15432   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15433   if (!NBody)
15434     return;
15435 
15436   // Skip expensive checks if diagnostic is disabled.
15437   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
15438     return;
15439 
15440   // Do the usual checks.
15441   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15442     return;
15443 
15444   // `for(...);' and `while(...);' are popular idioms, so in order to keep
15445   // noise level low, emit diagnostics only if for/while is followed by a
15446   // CompoundStmt, e.g.:
15447   //    for (int i = 0; i < n; i++);
15448   //    {
15449   //      a(i);
15450   //    }
15451   // or if for/while is followed by a statement with more indentation
15452   // than for/while itself:
15453   //    for (int i = 0; i < n; i++);
15454   //      a(i);
15455   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
15456   if (!ProbableTypo) {
15457     bool BodyColInvalid;
15458     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
15459         PossibleBody->getBeginLoc(), &BodyColInvalid);
15460     if (BodyColInvalid)
15461       return;
15462 
15463     bool StmtColInvalid;
15464     unsigned StmtCol =
15465         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
15466     if (StmtColInvalid)
15467       return;
15468 
15469     if (BodyCol > StmtCol)
15470       ProbableTypo = true;
15471   }
15472 
15473   if (ProbableTypo) {
15474     Diag(NBody->getSemiLoc(), DiagID);
15475     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15476   }
15477 }
15478 
15479 //===--- CHECK: Warn on self move with std::move. -------------------------===//
15480 
15481 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
15482 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
15483                              SourceLocation OpLoc) {
15484   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
15485     return;
15486 
15487   if (inTemplateInstantiation())
15488     return;
15489 
15490   // Strip parens and casts away.
15491   LHSExpr = LHSExpr->IgnoreParenImpCasts();
15492   RHSExpr = RHSExpr->IgnoreParenImpCasts();
15493 
15494   // Check for a call expression
15495   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
15496   if (!CE || CE->getNumArgs() != 1)
15497     return;
15498 
15499   // Check for a call to std::move
15500   if (!CE->isCallToStdMove())
15501     return;
15502 
15503   // Get argument from std::move
15504   RHSExpr = CE->getArg(0);
15505 
15506   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
15507   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
15508 
15509   // Two DeclRefExpr's, check that the decls are the same.
15510   if (LHSDeclRef && RHSDeclRef) {
15511     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15512       return;
15513     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15514         RHSDeclRef->getDecl()->getCanonicalDecl())
15515       return;
15516 
15517     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15518                                         << LHSExpr->getSourceRange()
15519                                         << RHSExpr->getSourceRange();
15520     return;
15521   }
15522 
15523   // Member variables require a different approach to check for self moves.
15524   // MemberExpr's are the same if every nested MemberExpr refers to the same
15525   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
15526   // the base Expr's are CXXThisExpr's.
15527   const Expr *LHSBase = LHSExpr;
15528   const Expr *RHSBase = RHSExpr;
15529   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
15530   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
15531   if (!LHSME || !RHSME)
15532     return;
15533 
15534   while (LHSME && RHSME) {
15535     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
15536         RHSME->getMemberDecl()->getCanonicalDecl())
15537       return;
15538 
15539     LHSBase = LHSME->getBase();
15540     RHSBase = RHSME->getBase();
15541     LHSME = dyn_cast<MemberExpr>(LHSBase);
15542     RHSME = dyn_cast<MemberExpr>(RHSBase);
15543   }
15544 
15545   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
15546   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
15547   if (LHSDeclRef && RHSDeclRef) {
15548     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15549       return;
15550     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15551         RHSDeclRef->getDecl()->getCanonicalDecl())
15552       return;
15553 
15554     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15555                                         << LHSExpr->getSourceRange()
15556                                         << RHSExpr->getSourceRange();
15557     return;
15558   }
15559 
15560   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
15561     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15562                                         << LHSExpr->getSourceRange()
15563                                         << RHSExpr->getSourceRange();
15564 }
15565 
15566 //===--- Layout compatibility ----------------------------------------------//
15567 
15568 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
15569 
15570 /// Check if two enumeration types are layout-compatible.
15571 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
15572   // C++11 [dcl.enum] p8:
15573   // Two enumeration types are layout-compatible if they have the same
15574   // underlying type.
15575   return ED1->isComplete() && ED2->isComplete() &&
15576          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
15577 }
15578 
15579 /// Check if two fields are layout-compatible.
15580 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
15581                                FieldDecl *Field2) {
15582   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
15583     return false;
15584 
15585   if (Field1->isBitField() != Field2->isBitField())
15586     return false;
15587 
15588   if (Field1->isBitField()) {
15589     // Make sure that the bit-fields are the same length.
15590     unsigned Bits1 = Field1->getBitWidthValue(C);
15591     unsigned Bits2 = Field2->getBitWidthValue(C);
15592 
15593     if (Bits1 != Bits2)
15594       return false;
15595   }
15596 
15597   return true;
15598 }
15599 
15600 /// Check if two standard-layout structs are layout-compatible.
15601 /// (C++11 [class.mem] p17)
15602 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
15603                                      RecordDecl *RD2) {
15604   // If both records are C++ classes, check that base classes match.
15605   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
15606     // If one of records is a CXXRecordDecl we are in C++ mode,
15607     // thus the other one is a CXXRecordDecl, too.
15608     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
15609     // Check number of base classes.
15610     if (D1CXX->getNumBases() != D2CXX->getNumBases())
15611       return false;
15612 
15613     // Check the base classes.
15614     for (CXXRecordDecl::base_class_const_iterator
15615                Base1 = D1CXX->bases_begin(),
15616            BaseEnd1 = D1CXX->bases_end(),
15617               Base2 = D2CXX->bases_begin();
15618          Base1 != BaseEnd1;
15619          ++Base1, ++Base2) {
15620       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
15621         return false;
15622     }
15623   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
15624     // If only RD2 is a C++ class, it should have zero base classes.
15625     if (D2CXX->getNumBases() > 0)
15626       return false;
15627   }
15628 
15629   // Check the fields.
15630   RecordDecl::field_iterator Field2 = RD2->field_begin(),
15631                              Field2End = RD2->field_end(),
15632                              Field1 = RD1->field_begin(),
15633                              Field1End = RD1->field_end();
15634   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
15635     if (!isLayoutCompatible(C, *Field1, *Field2))
15636       return false;
15637   }
15638   if (Field1 != Field1End || Field2 != Field2End)
15639     return false;
15640 
15641   return true;
15642 }
15643 
15644 /// Check if two standard-layout unions are layout-compatible.
15645 /// (C++11 [class.mem] p18)
15646 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
15647                                     RecordDecl *RD2) {
15648   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
15649   for (auto *Field2 : RD2->fields())
15650     UnmatchedFields.insert(Field2);
15651 
15652   for (auto *Field1 : RD1->fields()) {
15653     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
15654         I = UnmatchedFields.begin(),
15655         E = UnmatchedFields.end();
15656 
15657     for ( ; I != E; ++I) {
15658       if (isLayoutCompatible(C, Field1, *I)) {
15659         bool Result = UnmatchedFields.erase(*I);
15660         (void) Result;
15661         assert(Result);
15662         break;
15663       }
15664     }
15665     if (I == E)
15666       return false;
15667   }
15668 
15669   return UnmatchedFields.empty();
15670 }
15671 
15672 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
15673                                RecordDecl *RD2) {
15674   if (RD1->isUnion() != RD2->isUnion())
15675     return false;
15676 
15677   if (RD1->isUnion())
15678     return isLayoutCompatibleUnion(C, RD1, RD2);
15679   else
15680     return isLayoutCompatibleStruct(C, RD1, RD2);
15681 }
15682 
15683 /// Check if two types are layout-compatible in C++11 sense.
15684 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
15685   if (T1.isNull() || T2.isNull())
15686     return false;
15687 
15688   // C++11 [basic.types] p11:
15689   // If two types T1 and T2 are the same type, then T1 and T2 are
15690   // layout-compatible types.
15691   if (C.hasSameType(T1, T2))
15692     return true;
15693 
15694   T1 = T1.getCanonicalType().getUnqualifiedType();
15695   T2 = T2.getCanonicalType().getUnqualifiedType();
15696 
15697   const Type::TypeClass TC1 = T1->getTypeClass();
15698   const Type::TypeClass TC2 = T2->getTypeClass();
15699 
15700   if (TC1 != TC2)
15701     return false;
15702 
15703   if (TC1 == Type::Enum) {
15704     return isLayoutCompatible(C,
15705                               cast<EnumType>(T1)->getDecl(),
15706                               cast<EnumType>(T2)->getDecl());
15707   } else if (TC1 == Type::Record) {
15708     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
15709       return false;
15710 
15711     return isLayoutCompatible(C,
15712                               cast<RecordType>(T1)->getDecl(),
15713                               cast<RecordType>(T2)->getDecl());
15714   }
15715 
15716   return false;
15717 }
15718 
15719 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
15720 
15721 /// Given a type tag expression find the type tag itself.
15722 ///
15723 /// \param TypeExpr Type tag expression, as it appears in user's code.
15724 ///
15725 /// \param VD Declaration of an identifier that appears in a type tag.
15726 ///
15727 /// \param MagicValue Type tag magic value.
15728 ///
15729 /// \param isConstantEvaluated wether the evalaution should be performed in
15730 
15731 /// constant context.
15732 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
15733                             const ValueDecl **VD, uint64_t *MagicValue,
15734                             bool isConstantEvaluated) {
15735   while(true) {
15736     if (!TypeExpr)
15737       return false;
15738 
15739     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
15740 
15741     switch (TypeExpr->getStmtClass()) {
15742     case Stmt::UnaryOperatorClass: {
15743       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
15744       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
15745         TypeExpr = UO->getSubExpr();
15746         continue;
15747       }
15748       return false;
15749     }
15750 
15751     case Stmt::DeclRefExprClass: {
15752       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
15753       *VD = DRE->getDecl();
15754       return true;
15755     }
15756 
15757     case Stmt::IntegerLiteralClass: {
15758       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
15759       llvm::APInt MagicValueAPInt = IL->getValue();
15760       if (MagicValueAPInt.getActiveBits() <= 64) {
15761         *MagicValue = MagicValueAPInt.getZExtValue();
15762         return true;
15763       } else
15764         return false;
15765     }
15766 
15767     case Stmt::BinaryConditionalOperatorClass:
15768     case Stmt::ConditionalOperatorClass: {
15769       const AbstractConditionalOperator *ACO =
15770           cast<AbstractConditionalOperator>(TypeExpr);
15771       bool Result;
15772       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
15773                                                      isConstantEvaluated)) {
15774         if (Result)
15775           TypeExpr = ACO->getTrueExpr();
15776         else
15777           TypeExpr = ACO->getFalseExpr();
15778         continue;
15779       }
15780       return false;
15781     }
15782 
15783     case Stmt::BinaryOperatorClass: {
15784       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
15785       if (BO->getOpcode() == BO_Comma) {
15786         TypeExpr = BO->getRHS();
15787         continue;
15788       }
15789       return false;
15790     }
15791 
15792     default:
15793       return false;
15794     }
15795   }
15796 }
15797 
15798 /// Retrieve the C type corresponding to type tag TypeExpr.
15799 ///
15800 /// \param TypeExpr Expression that specifies a type tag.
15801 ///
15802 /// \param MagicValues Registered magic values.
15803 ///
15804 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
15805 ///        kind.
15806 ///
15807 /// \param TypeInfo Information about the corresponding C type.
15808 ///
15809 /// \param isConstantEvaluated wether the evalaution should be performed in
15810 /// constant context.
15811 ///
15812 /// \returns true if the corresponding C type was found.
15813 static bool GetMatchingCType(
15814     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
15815     const ASTContext &Ctx,
15816     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
15817         *MagicValues,
15818     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
15819     bool isConstantEvaluated) {
15820   FoundWrongKind = false;
15821 
15822   // Variable declaration that has type_tag_for_datatype attribute.
15823   const ValueDecl *VD = nullptr;
15824 
15825   uint64_t MagicValue;
15826 
15827   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
15828     return false;
15829 
15830   if (VD) {
15831     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
15832       if (I->getArgumentKind() != ArgumentKind) {
15833         FoundWrongKind = true;
15834         return false;
15835       }
15836       TypeInfo.Type = I->getMatchingCType();
15837       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
15838       TypeInfo.MustBeNull = I->getMustBeNull();
15839       return true;
15840     }
15841     return false;
15842   }
15843 
15844   if (!MagicValues)
15845     return false;
15846 
15847   llvm::DenseMap<Sema::TypeTagMagicValue,
15848                  Sema::TypeTagData>::const_iterator I =
15849       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
15850   if (I == MagicValues->end())
15851     return false;
15852 
15853   TypeInfo = I->second;
15854   return true;
15855 }
15856 
15857 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
15858                                       uint64_t MagicValue, QualType Type,
15859                                       bool LayoutCompatible,
15860                                       bool MustBeNull) {
15861   if (!TypeTagForDatatypeMagicValues)
15862     TypeTagForDatatypeMagicValues.reset(
15863         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
15864 
15865   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
15866   (*TypeTagForDatatypeMagicValues)[Magic] =
15867       TypeTagData(Type, LayoutCompatible, MustBeNull);
15868 }
15869 
15870 static bool IsSameCharType(QualType T1, QualType T2) {
15871   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
15872   if (!BT1)
15873     return false;
15874 
15875   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
15876   if (!BT2)
15877     return false;
15878 
15879   BuiltinType::Kind T1Kind = BT1->getKind();
15880   BuiltinType::Kind T2Kind = BT2->getKind();
15881 
15882   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
15883          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
15884          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
15885          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
15886 }
15887 
15888 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
15889                                     const ArrayRef<const Expr *> ExprArgs,
15890                                     SourceLocation CallSiteLoc) {
15891   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
15892   bool IsPointerAttr = Attr->getIsPointer();
15893 
15894   // Retrieve the argument representing the 'type_tag'.
15895   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
15896   if (TypeTagIdxAST >= ExprArgs.size()) {
15897     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
15898         << 0 << Attr->getTypeTagIdx().getSourceIndex();
15899     return;
15900   }
15901   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
15902   bool FoundWrongKind;
15903   TypeTagData TypeInfo;
15904   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
15905                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
15906                         TypeInfo, isConstantEvaluated())) {
15907     if (FoundWrongKind)
15908       Diag(TypeTagExpr->getExprLoc(),
15909            diag::warn_type_tag_for_datatype_wrong_kind)
15910         << TypeTagExpr->getSourceRange();
15911     return;
15912   }
15913 
15914   // Retrieve the argument representing the 'arg_idx'.
15915   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
15916   if (ArgumentIdxAST >= ExprArgs.size()) {
15917     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
15918         << 1 << Attr->getArgumentIdx().getSourceIndex();
15919     return;
15920   }
15921   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
15922   if (IsPointerAttr) {
15923     // Skip implicit cast of pointer to `void *' (as a function argument).
15924     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
15925       if (ICE->getType()->isVoidPointerType() &&
15926           ICE->getCastKind() == CK_BitCast)
15927         ArgumentExpr = ICE->getSubExpr();
15928   }
15929   QualType ArgumentType = ArgumentExpr->getType();
15930 
15931   // Passing a `void*' pointer shouldn't trigger a warning.
15932   if (IsPointerAttr && ArgumentType->isVoidPointerType())
15933     return;
15934 
15935   if (TypeInfo.MustBeNull) {
15936     // Type tag with matching void type requires a null pointer.
15937     if (!ArgumentExpr->isNullPointerConstant(Context,
15938                                              Expr::NPC_ValueDependentIsNotNull)) {
15939       Diag(ArgumentExpr->getExprLoc(),
15940            diag::warn_type_safety_null_pointer_required)
15941           << ArgumentKind->getName()
15942           << ArgumentExpr->getSourceRange()
15943           << TypeTagExpr->getSourceRange();
15944     }
15945     return;
15946   }
15947 
15948   QualType RequiredType = TypeInfo.Type;
15949   if (IsPointerAttr)
15950     RequiredType = Context.getPointerType(RequiredType);
15951 
15952   bool mismatch = false;
15953   if (!TypeInfo.LayoutCompatible) {
15954     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
15955 
15956     // C++11 [basic.fundamental] p1:
15957     // Plain char, signed char, and unsigned char are three distinct types.
15958     //
15959     // But we treat plain `char' as equivalent to `signed char' or `unsigned
15960     // char' depending on the current char signedness mode.
15961     if (mismatch)
15962       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
15963                                            RequiredType->getPointeeType())) ||
15964           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
15965         mismatch = false;
15966   } else
15967     if (IsPointerAttr)
15968       mismatch = !isLayoutCompatible(Context,
15969                                      ArgumentType->getPointeeType(),
15970                                      RequiredType->getPointeeType());
15971     else
15972       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
15973 
15974   if (mismatch)
15975     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
15976         << ArgumentType << ArgumentKind
15977         << TypeInfo.LayoutCompatible << RequiredType
15978         << ArgumentExpr->getSourceRange()
15979         << TypeTagExpr->getSourceRange();
15980 }
15981 
15982 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
15983                                          CharUnits Alignment) {
15984   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
15985 }
15986 
15987 void Sema::DiagnoseMisalignedMembers() {
15988   for (MisalignedMember &m : MisalignedMembers) {
15989     const NamedDecl *ND = m.RD;
15990     if (ND->getName().empty()) {
15991       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
15992         ND = TD;
15993     }
15994     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
15995         << m.MD << ND << m.E->getSourceRange();
15996   }
15997   MisalignedMembers.clear();
15998 }
15999 
16000 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
16001   E = E->IgnoreParens();
16002   if (!T->isPointerType() && !T->isIntegerType())
16003     return;
16004   if (isa<UnaryOperator>(E) &&
16005       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
16006     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
16007     if (isa<MemberExpr>(Op)) {
16008       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
16009       if (MA != MisalignedMembers.end() &&
16010           (T->isIntegerType() ||
16011            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
16012                                    Context.getTypeAlignInChars(
16013                                        T->getPointeeType()) <= MA->Alignment))))
16014         MisalignedMembers.erase(MA);
16015     }
16016   }
16017 }
16018 
16019 void Sema::RefersToMemberWithReducedAlignment(
16020     Expr *E,
16021     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
16022         Action) {
16023   const auto *ME = dyn_cast<MemberExpr>(E);
16024   if (!ME)
16025     return;
16026 
16027   // No need to check expressions with an __unaligned-qualified type.
16028   if (E->getType().getQualifiers().hasUnaligned())
16029     return;
16030 
16031   // For a chain of MemberExpr like "a.b.c.d" this list
16032   // will keep FieldDecl's like [d, c, b].
16033   SmallVector<FieldDecl *, 4> ReverseMemberChain;
16034   const MemberExpr *TopME = nullptr;
16035   bool AnyIsPacked = false;
16036   do {
16037     QualType BaseType = ME->getBase()->getType();
16038     if (BaseType->isDependentType())
16039       return;
16040     if (ME->isArrow())
16041       BaseType = BaseType->getPointeeType();
16042     RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
16043     if (RD->isInvalidDecl())
16044       return;
16045 
16046     ValueDecl *MD = ME->getMemberDecl();
16047     auto *FD = dyn_cast<FieldDecl>(MD);
16048     // We do not care about non-data members.
16049     if (!FD || FD->isInvalidDecl())
16050       return;
16051 
16052     AnyIsPacked =
16053         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
16054     ReverseMemberChain.push_back(FD);
16055 
16056     TopME = ME;
16057     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
16058   } while (ME);
16059   assert(TopME && "We did not compute a topmost MemberExpr!");
16060 
16061   // Not the scope of this diagnostic.
16062   if (!AnyIsPacked)
16063     return;
16064 
16065   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
16066   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
16067   // TODO: The innermost base of the member expression may be too complicated.
16068   // For now, just disregard these cases. This is left for future
16069   // improvement.
16070   if (!DRE && !isa<CXXThisExpr>(TopBase))
16071       return;
16072 
16073   // Alignment expected by the whole expression.
16074   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
16075 
16076   // No need to do anything else with this case.
16077   if (ExpectedAlignment.isOne())
16078     return;
16079 
16080   // Synthesize offset of the whole access.
16081   CharUnits Offset;
16082   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
16083        I++) {
16084     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
16085   }
16086 
16087   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
16088   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
16089       ReverseMemberChain.back()->getParent()->getTypeForDecl());
16090 
16091   // The base expression of the innermost MemberExpr may give
16092   // stronger guarantees than the class containing the member.
16093   if (DRE && !TopME->isArrow()) {
16094     const ValueDecl *VD = DRE->getDecl();
16095     if (!VD->getType()->isReferenceType())
16096       CompleteObjectAlignment =
16097           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
16098   }
16099 
16100   // Check if the synthesized offset fulfills the alignment.
16101   if (Offset % ExpectedAlignment != 0 ||
16102       // It may fulfill the offset it but the effective alignment may still be
16103       // lower than the expected expression alignment.
16104       CompleteObjectAlignment < ExpectedAlignment) {
16105     // If this happens, we want to determine a sensible culprit of this.
16106     // Intuitively, watching the chain of member expressions from right to
16107     // left, we start with the required alignment (as required by the field
16108     // type) but some packed attribute in that chain has reduced the alignment.
16109     // It may happen that another packed structure increases it again. But if
16110     // we are here such increase has not been enough. So pointing the first
16111     // FieldDecl that either is packed or else its RecordDecl is,
16112     // seems reasonable.
16113     FieldDecl *FD = nullptr;
16114     CharUnits Alignment;
16115     for (FieldDecl *FDI : ReverseMemberChain) {
16116       if (FDI->hasAttr<PackedAttr>() ||
16117           FDI->getParent()->hasAttr<PackedAttr>()) {
16118         FD = FDI;
16119         Alignment = std::min(
16120             Context.getTypeAlignInChars(FD->getType()),
16121             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
16122         break;
16123       }
16124     }
16125     assert(FD && "We did not find a packed FieldDecl!");
16126     Action(E, FD->getParent(), FD, Alignment);
16127   }
16128 }
16129 
16130 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
16131   using namespace std::placeholders;
16132 
16133   RefersToMemberWithReducedAlignment(
16134       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
16135                      _2, _3, _4));
16136 }
16137 
16138 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall,
16139                                             ExprResult CallResult) {
16140   if (checkArgCount(*this, TheCall, 1))
16141     return ExprError();
16142 
16143   ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
16144   if (MatrixArg.isInvalid())
16145     return MatrixArg;
16146   Expr *Matrix = MatrixArg.get();
16147 
16148   auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
16149   if (!MType) {
16150     Diag(Matrix->getBeginLoc(), diag::err_builtin_matrix_arg);
16151     return ExprError();
16152   }
16153 
16154   // Create returned matrix type by swapping rows and columns of the argument
16155   // matrix type.
16156   QualType ResultType = Context.getConstantMatrixType(
16157       MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
16158 
16159   // Change the return type to the type of the returned matrix.
16160   TheCall->setType(ResultType);
16161 
16162   // Update call argument to use the possibly converted matrix argument.
16163   TheCall->setArg(0, Matrix);
16164   return CallResult;
16165 }
16166 
16167 // Get and verify the matrix dimensions.
16168 static llvm::Optional<unsigned>
16169 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {
16170   SourceLocation ErrorPos;
16171   Optional<llvm::APSInt> Value =
16172       Expr->getIntegerConstantExpr(S.Context, &ErrorPos);
16173   if (!Value) {
16174     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
16175         << Name;
16176     return {};
16177   }
16178   uint64_t Dim = Value->getZExtValue();
16179   if (!ConstantMatrixType::isDimensionValid(Dim)) {
16180     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
16181         << Name << ConstantMatrixType::getMaxElementsPerDimension();
16182     return {};
16183   }
16184   return Dim;
16185 }
16186 
16187 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
16188                                                   ExprResult CallResult) {
16189   if (!getLangOpts().MatrixTypes) {
16190     Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
16191     return ExprError();
16192   }
16193 
16194   if (checkArgCount(*this, TheCall, 4))
16195     return ExprError();
16196 
16197   unsigned PtrArgIdx = 0;
16198   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16199   Expr *RowsExpr = TheCall->getArg(1);
16200   Expr *ColumnsExpr = TheCall->getArg(2);
16201   Expr *StrideExpr = TheCall->getArg(3);
16202 
16203   bool ArgError = false;
16204 
16205   // Check pointer argument.
16206   {
16207     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
16208     if (PtrConv.isInvalid())
16209       return PtrConv;
16210     PtrExpr = PtrConv.get();
16211     TheCall->setArg(0, PtrExpr);
16212     if (PtrExpr->isTypeDependent()) {
16213       TheCall->setType(Context.DependentTy);
16214       return TheCall;
16215     }
16216   }
16217 
16218   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16219   QualType ElementTy;
16220   if (!PtrTy) {
16221     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
16222         << PtrArgIdx + 1;
16223     ArgError = true;
16224   } else {
16225     ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
16226 
16227     if (!ConstantMatrixType::isValidElementType(ElementTy)) {
16228       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
16229           << PtrArgIdx + 1;
16230       ArgError = true;
16231     }
16232   }
16233 
16234   // Apply default Lvalue conversions and convert the expression to size_t.
16235   auto ApplyArgumentConversions = [this](Expr *E) {
16236     ExprResult Conv = DefaultLvalueConversion(E);
16237     if (Conv.isInvalid())
16238       return Conv;
16239 
16240     return tryConvertExprToType(Conv.get(), Context.getSizeType());
16241   };
16242 
16243   // Apply conversion to row and column expressions.
16244   ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
16245   if (!RowsConv.isInvalid()) {
16246     RowsExpr = RowsConv.get();
16247     TheCall->setArg(1, RowsExpr);
16248   } else
16249     RowsExpr = nullptr;
16250 
16251   ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
16252   if (!ColumnsConv.isInvalid()) {
16253     ColumnsExpr = ColumnsConv.get();
16254     TheCall->setArg(2, ColumnsExpr);
16255   } else
16256     ColumnsExpr = nullptr;
16257 
16258   // If any any part of the result matrix type is still pending, just use
16259   // Context.DependentTy, until all parts are resolved.
16260   if ((RowsExpr && RowsExpr->isTypeDependent()) ||
16261       (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
16262     TheCall->setType(Context.DependentTy);
16263     return CallResult;
16264   }
16265 
16266   // Check row and column dimenions.
16267   llvm::Optional<unsigned> MaybeRows;
16268   if (RowsExpr)
16269     MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
16270 
16271   llvm::Optional<unsigned> MaybeColumns;
16272   if (ColumnsExpr)
16273     MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
16274 
16275   // Check stride argument.
16276   ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
16277   if (StrideConv.isInvalid())
16278     return ExprError();
16279   StrideExpr = StrideConv.get();
16280   TheCall->setArg(3, StrideExpr);
16281 
16282   if (MaybeRows) {
16283     if (Optional<llvm::APSInt> Value =
16284             StrideExpr->getIntegerConstantExpr(Context)) {
16285       uint64_t Stride = Value->getZExtValue();
16286       if (Stride < *MaybeRows) {
16287         Diag(StrideExpr->getBeginLoc(),
16288              diag::err_builtin_matrix_stride_too_small);
16289         ArgError = true;
16290       }
16291     }
16292   }
16293 
16294   if (ArgError || !MaybeRows || !MaybeColumns)
16295     return ExprError();
16296 
16297   TheCall->setType(
16298       Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
16299   return CallResult;
16300 }
16301 
16302 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
16303                                                    ExprResult CallResult) {
16304   if (checkArgCount(*this, TheCall, 3))
16305     return ExprError();
16306 
16307   unsigned PtrArgIdx = 1;
16308   Expr *MatrixExpr = TheCall->getArg(0);
16309   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16310   Expr *StrideExpr = TheCall->getArg(2);
16311 
16312   bool ArgError = false;
16313 
16314   {
16315     ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
16316     if (MatrixConv.isInvalid())
16317       return MatrixConv;
16318     MatrixExpr = MatrixConv.get();
16319     TheCall->setArg(0, MatrixExpr);
16320   }
16321   if (MatrixExpr->isTypeDependent()) {
16322     TheCall->setType(Context.DependentTy);
16323     return TheCall;
16324   }
16325 
16326   auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
16327   if (!MatrixTy) {
16328     Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_matrix_arg) << 0;
16329     ArgError = true;
16330   }
16331 
16332   {
16333     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
16334     if (PtrConv.isInvalid())
16335       return PtrConv;
16336     PtrExpr = PtrConv.get();
16337     TheCall->setArg(1, PtrExpr);
16338     if (PtrExpr->isTypeDependent()) {
16339       TheCall->setType(Context.DependentTy);
16340       return TheCall;
16341     }
16342   }
16343 
16344   // Check pointer argument.
16345   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16346   if (!PtrTy) {
16347     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
16348         << PtrArgIdx + 1;
16349     ArgError = true;
16350   } else {
16351     QualType ElementTy = PtrTy->getPointeeType();
16352     if (ElementTy.isConstQualified()) {
16353       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
16354       ArgError = true;
16355     }
16356     ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
16357     if (MatrixTy &&
16358         !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
16359       Diag(PtrExpr->getBeginLoc(),
16360            diag::err_builtin_matrix_pointer_arg_mismatch)
16361           << ElementTy << MatrixTy->getElementType();
16362       ArgError = true;
16363     }
16364   }
16365 
16366   // Apply default Lvalue conversions and convert the stride expression to
16367   // size_t.
16368   {
16369     ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
16370     if (StrideConv.isInvalid())
16371       return StrideConv;
16372 
16373     StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
16374     if (StrideConv.isInvalid())
16375       return StrideConv;
16376     StrideExpr = StrideConv.get();
16377     TheCall->setArg(2, StrideExpr);
16378   }
16379 
16380   // Check stride argument.
16381   if (MatrixTy) {
16382     if (Optional<llvm::APSInt> Value =
16383             StrideExpr->getIntegerConstantExpr(Context)) {
16384       uint64_t Stride = Value->getZExtValue();
16385       if (Stride < MatrixTy->getNumRows()) {
16386         Diag(StrideExpr->getBeginLoc(),
16387              diag::err_builtin_matrix_stride_too_small);
16388         ArgError = true;
16389       }
16390     }
16391   }
16392 
16393   if (ArgError)
16394     return ExprError();
16395 
16396   return CallResult;
16397 }
16398 
16399 /// \brief Enforce the bounds of a TCB
16400 /// CheckTCBEnforcement - Enforces that every function in a named TCB only
16401 /// directly calls other functions in the same TCB as marked by the enforce_tcb
16402 /// and enforce_tcb_leaf attributes.
16403 void Sema::CheckTCBEnforcement(const CallExpr *TheCall,
16404                                const FunctionDecl *Callee) {
16405   const FunctionDecl *Caller = getCurFunctionDecl();
16406 
16407   // Calls to builtins are not enforced.
16408   if (!Caller || !Caller->hasAttr<EnforceTCBAttr>() ||
16409       Callee->getBuiltinID() != 0)
16410     return;
16411 
16412   // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
16413   // all TCBs the callee is a part of.
16414   llvm::StringSet<> CalleeTCBs;
16415   for_each(Callee->specific_attrs<EnforceTCBAttr>(),
16416            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
16417   for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(),
16418            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
16419 
16420   // Go through the TCBs the caller is a part of and emit warnings if Caller
16421   // is in a TCB that the Callee is not.
16422   for_each(
16423       Caller->specific_attrs<EnforceTCBAttr>(),
16424       [&](const auto *A) {
16425         StringRef CallerTCB = A->getTCBName();
16426         if (CalleeTCBs.count(CallerTCB) == 0) {
16427           this->Diag(TheCall->getExprLoc(),
16428                      diag::warn_tcb_enforcement_violation) << Callee
16429                                                            << CallerTCB;
16430         }
16431       });
16432 }
16433