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/StringSwitch.h"
79 #include "llvm/ADT/Triple.h"
80 #include "llvm/Support/AtomicOrdering.h"
81 #include "llvm/Support/Casting.h"
82 #include "llvm/Support/Compiler.h"
83 #include "llvm/Support/ConvertUTF.h"
84 #include "llvm/Support/ErrorHandling.h"
85 #include "llvm/Support/Format.h"
86 #include "llvm/Support/Locale.h"
87 #include "llvm/Support/MathExtras.h"
88 #include "llvm/Support/SaveAndRestore.h"
89 #include "llvm/Support/raw_ostream.h"
90 #include <algorithm>
91 #include <cassert>
92 #include <cstddef>
93 #include <cstdint>
94 #include <functional>
95 #include <limits>
96 #include <string>
97 #include <tuple>
98 #include <utility>
99 
100 using namespace clang;
101 using namespace sema;
102 
103 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
104                                                     unsigned ByteNo) const {
105   return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
106                                Context.getTargetInfo());
107 }
108 
109 /// Checks that a call expression's argument count is the desired number.
110 /// This is useful when doing custom type-checking.  Returns true on error.
111 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
112   unsigned argCount = call->getNumArgs();
113   if (argCount == desiredArgCount) return false;
114 
115   if (argCount < desiredArgCount)
116     return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args)
117            << 0 /*function call*/ << desiredArgCount << argCount
118            << call->getSourceRange();
119 
120   // Highlight all the excess arguments.
121   SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(),
122                     call->getArg(argCount - 1)->getEndLoc());
123 
124   return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
125     << 0 /*function call*/ << desiredArgCount << argCount
126     << call->getArg(1)->getSourceRange();
127 }
128 
129 /// Check that the first argument to __builtin_annotation is an integer
130 /// and the second argument is a non-wide string literal.
131 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
132   if (checkArgCount(S, TheCall, 2))
133     return true;
134 
135   // First argument should be an integer.
136   Expr *ValArg = TheCall->getArg(0);
137   QualType Ty = ValArg->getType();
138   if (!Ty->isIntegerType()) {
139     S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
140         << ValArg->getSourceRange();
141     return true;
142   }
143 
144   // Second argument should be a constant string.
145   Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
146   StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
147   if (!Literal || !Literal->isAscii()) {
148     S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
149         << StrArg->getSourceRange();
150     return true;
151   }
152 
153   TheCall->setType(Ty);
154   return false;
155 }
156 
157 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
158   // We need at least one argument.
159   if (TheCall->getNumArgs() < 1) {
160     S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
161         << 0 << 1 << TheCall->getNumArgs()
162         << TheCall->getCallee()->getSourceRange();
163     return true;
164   }
165 
166   // All arguments should be wide string literals.
167   for (Expr *Arg : TheCall->arguments()) {
168     auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
169     if (!Literal || !Literal->isWide()) {
170       S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
171           << Arg->getSourceRange();
172       return true;
173     }
174   }
175 
176   return false;
177 }
178 
179 /// Check that the argument to __builtin_addressof is a glvalue, and set the
180 /// result type to the corresponding pointer type.
181 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
182   if (checkArgCount(S, TheCall, 1))
183     return true;
184 
185   ExprResult Arg(TheCall->getArg(0));
186   QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
187   if (ResultType.isNull())
188     return true;
189 
190   TheCall->setArg(0, Arg.get());
191   TheCall->setType(ResultType);
192   return false;
193 }
194 
195 /// Check the number of arguments and set the result type to
196 /// the argument type.
197 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
198   if (checkArgCount(S, TheCall, 1))
199     return true;
200 
201   TheCall->setType(TheCall->getArg(0)->getType());
202   return false;
203 }
204 
205 /// Check that the value argument for __builtin_is_aligned(value, alignment) and
206 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
207 /// type (but not a function pointer) and that the alignment is a power-of-two.
208 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
209   if (checkArgCount(S, TheCall, 2))
210     return true;
211 
212   clang::Expr *Source = TheCall->getArg(0);
213   bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
214 
215   auto IsValidIntegerType = [](QualType Ty) {
216     return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
217   };
218   QualType SrcTy = Source->getType();
219   // We should also be able to use it with arrays (but not functions!).
220   if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
221     SrcTy = S.Context.getDecayedType(SrcTy);
222   }
223   if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
224       SrcTy->isFunctionPointerType()) {
225     // FIXME: this is not quite the right error message since we don't allow
226     // floating point types, or member pointers.
227     S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand)
228         << SrcTy;
229     return true;
230   }
231 
232   clang::Expr *AlignOp = TheCall->getArg(1);
233   if (!IsValidIntegerType(AlignOp->getType())) {
234     S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int)
235         << AlignOp->getType();
236     return true;
237   }
238   Expr::EvalResult AlignResult;
239   unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1;
240   // We can't check validity of alignment if it is type dependent.
241   if (!AlignOp->isInstantiationDependent() &&
242       AlignOp->EvaluateAsInt(AlignResult, S.Context,
243                              Expr::SE_AllowSideEffects)) {
244     llvm::APSInt AlignValue = AlignResult.Val.getInt();
245     llvm::APSInt MaxValue(
246         llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits));
247     if (AlignValue < 1) {
248       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1;
249       return true;
250     }
251     if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) {
252       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big)
253           << MaxValue.toString(10);
254       return true;
255     }
256     if (!AlignValue.isPowerOf2()) {
257       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two);
258       return true;
259     }
260     if (AlignValue == 1) {
261       S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless)
262           << IsBooleanAlignBuiltin;
263     }
264   }
265 
266   ExprResult SrcArg = S.PerformCopyInitialization(
267       InitializedEntity::InitializeParameter(S.Context, SrcTy, false),
268       SourceLocation(), Source);
269   if (SrcArg.isInvalid())
270     return true;
271   TheCall->setArg(0, SrcArg.get());
272   ExprResult AlignArg =
273       S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
274                                       S.Context, AlignOp->getType(), false),
275                                   SourceLocation(), AlignOp);
276   if (AlignArg.isInvalid())
277     return true;
278   TheCall->setArg(1, AlignArg.get());
279   // For align_up/align_down, the return type is the same as the (potentially
280   // decayed) argument type including qualifiers. For is_aligned(), the result
281   // is always bool.
282   TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
283   return false;
284 }
285 
286 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
287   if (checkArgCount(S, TheCall, 3))
288     return true;
289 
290   // First two arguments should be integers.
291   for (unsigned I = 0; I < 2; ++I) {
292     ExprResult Arg = TheCall->getArg(I);
293     QualType Ty = Arg.get()->getType();
294     if (!Ty->isIntegerType()) {
295       S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
296           << Ty << Arg.get()->getSourceRange();
297       return true;
298     }
299     InitializedEntity Entity = InitializedEntity::InitializeParameter(
300         S.getASTContext(), Ty, /*consume*/ false);
301     Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
302     if (Arg.isInvalid())
303       return true;
304     TheCall->setArg(I, Arg.get());
305   }
306 
307   // Third argument should be a pointer to a non-const integer.
308   // IRGen correctly handles volatile, restrict, and address spaces, and
309   // the other qualifiers aren't possible.
310   {
311     ExprResult Arg = TheCall->getArg(2);
312     QualType Ty = Arg.get()->getType();
313     const auto *PtrTy = Ty->getAs<PointerType>();
314     if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
315           !PtrTy->getPointeeType().isConstQualified())) {
316       S.Diag(Arg.get()->getBeginLoc(),
317              diag::err_overflow_builtin_must_be_ptr_int)
318           << Ty << Arg.get()->getSourceRange();
319       return true;
320     }
321     InitializedEntity Entity = InitializedEntity::InitializeParameter(
322         S.getASTContext(), Ty, /*consume*/ false);
323     Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
324     if (Arg.isInvalid())
325       return true;
326     TheCall->setArg(2, Arg.get());
327   }
328   return false;
329 }
330 
331 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
332   if (checkArgCount(S, BuiltinCall, 2))
333     return true;
334 
335   SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
336   Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
337   Expr *Call = BuiltinCall->getArg(0);
338   Expr *Chain = BuiltinCall->getArg(1);
339 
340   if (Call->getStmtClass() != Stmt::CallExprClass) {
341     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
342         << Call->getSourceRange();
343     return true;
344   }
345 
346   auto CE = cast<CallExpr>(Call);
347   if (CE->getCallee()->getType()->isBlockPointerType()) {
348     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
349         << Call->getSourceRange();
350     return true;
351   }
352 
353   const Decl *TargetDecl = CE->getCalleeDecl();
354   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
355     if (FD->getBuiltinID()) {
356       S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
357           << Call->getSourceRange();
358       return true;
359     }
360 
361   if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
362     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
363         << Call->getSourceRange();
364     return true;
365   }
366 
367   ExprResult ChainResult = S.UsualUnaryConversions(Chain);
368   if (ChainResult.isInvalid())
369     return true;
370   if (!ChainResult.get()->getType()->isPointerType()) {
371     S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
372         << Chain->getSourceRange();
373     return true;
374   }
375 
376   QualType ReturnTy = CE->getCallReturnType(S.Context);
377   QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
378   QualType BuiltinTy = S.Context.getFunctionType(
379       ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
380   QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
381 
382   Builtin =
383       S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
384 
385   BuiltinCall->setType(CE->getType());
386   BuiltinCall->setValueKind(CE->getValueKind());
387   BuiltinCall->setObjectKind(CE->getObjectKind());
388   BuiltinCall->setCallee(Builtin);
389   BuiltinCall->setArg(1, ChainResult.get());
390 
391   return false;
392 }
393 
394 namespace {
395 
396 class EstimateSizeFormatHandler
397     : public analyze_format_string::FormatStringHandler {
398   size_t Size;
399 
400 public:
401   EstimateSizeFormatHandler(StringRef Format)
402       : Size(std::min(Format.find(0), Format.size()) +
403              1 /* null byte always written by sprintf */) {}
404 
405   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
406                              const char *, unsigned SpecifierLen) override {
407 
408     const size_t FieldWidth = computeFieldWidth(FS);
409     const size_t Precision = computePrecision(FS);
410 
411     // The actual format.
412     switch (FS.getConversionSpecifier().getKind()) {
413     // Just a char.
414     case analyze_format_string::ConversionSpecifier::cArg:
415     case analyze_format_string::ConversionSpecifier::CArg:
416       Size += std::max(FieldWidth, (size_t)1);
417       break;
418     // Just an integer.
419     case analyze_format_string::ConversionSpecifier::dArg:
420     case analyze_format_string::ConversionSpecifier::DArg:
421     case analyze_format_string::ConversionSpecifier::iArg:
422     case analyze_format_string::ConversionSpecifier::oArg:
423     case analyze_format_string::ConversionSpecifier::OArg:
424     case analyze_format_string::ConversionSpecifier::uArg:
425     case analyze_format_string::ConversionSpecifier::UArg:
426     case analyze_format_string::ConversionSpecifier::xArg:
427     case analyze_format_string::ConversionSpecifier::XArg:
428       Size += std::max(FieldWidth, Precision);
429       break;
430 
431     // %g style conversion switches between %f or %e style dynamically.
432     // %f always takes less space, so default to it.
433     case analyze_format_string::ConversionSpecifier::gArg:
434     case analyze_format_string::ConversionSpecifier::GArg:
435 
436     // Floating point number in the form '[+]ddd.ddd'.
437     case analyze_format_string::ConversionSpecifier::fArg:
438     case analyze_format_string::ConversionSpecifier::FArg:
439       Size += std::max(FieldWidth, 1 /* integer part */ +
440                                        (Precision ? 1 + Precision
441                                                   : 0) /* period + decimal */);
442       break;
443 
444     // Floating point number in the form '[-]d.ddde[+-]dd'.
445     case analyze_format_string::ConversionSpecifier::eArg:
446     case analyze_format_string::ConversionSpecifier::EArg:
447       Size +=
448           std::max(FieldWidth,
449                    1 /* integer part */ +
450                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
451                        1 /* e or E letter */ + 2 /* exponent */);
452       break;
453 
454     // Floating point number in the form '[-]0xh.hhhhp±dd'.
455     case analyze_format_string::ConversionSpecifier::aArg:
456     case analyze_format_string::ConversionSpecifier::AArg:
457       Size +=
458           std::max(FieldWidth,
459                    2 /* 0x */ + 1 /* integer part */ +
460                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
461                        1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
462       break;
463 
464     // Just a string.
465     case analyze_format_string::ConversionSpecifier::sArg:
466     case analyze_format_string::ConversionSpecifier::SArg:
467       Size += FieldWidth;
468       break;
469 
470     // Just a pointer in the form '0xddd'.
471     case analyze_format_string::ConversionSpecifier::pArg:
472       Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
473       break;
474 
475     // A plain percent.
476     case analyze_format_string::ConversionSpecifier::PercentArg:
477       Size += 1;
478       break;
479 
480     default:
481       break;
482     }
483 
484     Size += FS.hasPlusPrefix() || FS.hasSpacePrefix();
485 
486     if (FS.hasAlternativeForm()) {
487       switch (FS.getConversionSpecifier().getKind()) {
488       default:
489         break;
490       // Force a leading '0'.
491       case analyze_format_string::ConversionSpecifier::oArg:
492         Size += 1;
493         break;
494       // Force a leading '0x'.
495       case analyze_format_string::ConversionSpecifier::xArg:
496       case analyze_format_string::ConversionSpecifier::XArg:
497         Size += 2;
498         break;
499       // Force a period '.' before decimal, even if precision is 0.
500       case analyze_format_string::ConversionSpecifier::aArg:
501       case analyze_format_string::ConversionSpecifier::AArg:
502       case analyze_format_string::ConversionSpecifier::eArg:
503       case analyze_format_string::ConversionSpecifier::EArg:
504       case analyze_format_string::ConversionSpecifier::fArg:
505       case analyze_format_string::ConversionSpecifier::FArg:
506       case analyze_format_string::ConversionSpecifier::gArg:
507       case analyze_format_string::ConversionSpecifier::GArg:
508         Size += (Precision ? 0 : 1);
509         break;
510       }
511     }
512     assert(SpecifierLen <= Size && "no underflow");
513     Size -= SpecifierLen;
514     return true;
515   }
516 
517   size_t getSizeLowerBound() const { return Size; }
518 
519 private:
520   static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
521     const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
522     size_t FieldWidth = 0;
523     if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant)
524       FieldWidth = FW.getConstantAmount();
525     return FieldWidth;
526   }
527 
528   static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
529     const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
530     size_t Precision = 0;
531 
532     // See man 3 printf for default precision value based on the specifier.
533     switch (FW.getHowSpecified()) {
534     case analyze_format_string::OptionalAmount::NotSpecified:
535       switch (FS.getConversionSpecifier().getKind()) {
536       default:
537         break;
538       case analyze_format_string::ConversionSpecifier::dArg: // %d
539       case analyze_format_string::ConversionSpecifier::DArg: // %D
540       case analyze_format_string::ConversionSpecifier::iArg: // %i
541         Precision = 1;
542         break;
543       case analyze_format_string::ConversionSpecifier::oArg: // %d
544       case analyze_format_string::ConversionSpecifier::OArg: // %D
545       case analyze_format_string::ConversionSpecifier::uArg: // %d
546       case analyze_format_string::ConversionSpecifier::UArg: // %D
547       case analyze_format_string::ConversionSpecifier::xArg: // %d
548       case analyze_format_string::ConversionSpecifier::XArg: // %D
549         Precision = 1;
550         break;
551       case analyze_format_string::ConversionSpecifier::fArg: // %f
552       case analyze_format_string::ConversionSpecifier::FArg: // %F
553       case analyze_format_string::ConversionSpecifier::eArg: // %e
554       case analyze_format_string::ConversionSpecifier::EArg: // %E
555       case analyze_format_string::ConversionSpecifier::gArg: // %g
556       case analyze_format_string::ConversionSpecifier::GArg: // %G
557         Precision = 6;
558         break;
559       case analyze_format_string::ConversionSpecifier::pArg: // %d
560         Precision = 1;
561         break;
562       }
563       break;
564     case analyze_format_string::OptionalAmount::Constant:
565       Precision = FW.getConstantAmount();
566       break;
567     default:
568       break;
569     }
570     return Precision;
571   }
572 };
573 
574 } // namespace
575 
576 /// Check a call to BuiltinID for buffer overflows. If BuiltinID is a
577 /// __builtin_*_chk function, then use the object size argument specified in the
578 /// source. Otherwise, infer the object size using __builtin_object_size.
579 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
580                                                CallExpr *TheCall) {
581   // FIXME: There are some more useful checks we could be doing here:
582   //  - Evaluate strlen of strcpy arguments, use as object size.
583 
584   if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
585       isConstantEvaluated())
586     return;
587 
588   unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true);
589   if (!BuiltinID)
590     return;
591 
592   const TargetInfo &TI = getASTContext().getTargetInfo();
593   unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
594 
595   unsigned DiagID = 0;
596   bool IsChkVariant = false;
597   Optional<llvm::APSInt> UsedSize;
598   unsigned SizeIndex, ObjectIndex;
599   switch (BuiltinID) {
600   default:
601     return;
602   case Builtin::BIsprintf:
603   case Builtin::BI__builtin___sprintf_chk: {
604     size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
605     auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
606 
607     if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) {
608 
609       if (!Format->isAscii() && !Format->isUTF8())
610         return;
611 
612       StringRef FormatStrRef = Format->getString();
613       EstimateSizeFormatHandler H(FormatStrRef);
614       const char *FormatBytes = FormatStrRef.data();
615       const ConstantArrayType *T =
616           Context.getAsConstantArrayType(Format->getType());
617       assert(T && "String literal not of constant array type!");
618       size_t TypeSize = T->getSize().getZExtValue();
619 
620       // In case there's a null byte somewhere.
621       size_t StrLen =
622           std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
623       if (!analyze_format_string::ParsePrintfString(
624               H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
625               Context.getTargetInfo(), false)) {
626         DiagID = diag::warn_fortify_source_format_overflow;
627         UsedSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
628                        .extOrTrunc(SizeTypeWidth);
629         if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
630           IsChkVariant = true;
631           ObjectIndex = 2;
632         } else {
633           IsChkVariant = false;
634           ObjectIndex = 0;
635         }
636         break;
637       }
638     }
639     return;
640   }
641   case Builtin::BI__builtin___memcpy_chk:
642   case Builtin::BI__builtin___memmove_chk:
643   case Builtin::BI__builtin___memset_chk:
644   case Builtin::BI__builtin___strlcat_chk:
645   case Builtin::BI__builtin___strlcpy_chk:
646   case Builtin::BI__builtin___strncat_chk:
647   case Builtin::BI__builtin___strncpy_chk:
648   case Builtin::BI__builtin___stpncpy_chk:
649   case Builtin::BI__builtin___memccpy_chk:
650   case Builtin::BI__builtin___mempcpy_chk: {
651     DiagID = diag::warn_builtin_chk_overflow;
652     IsChkVariant = true;
653     SizeIndex = TheCall->getNumArgs() - 2;
654     ObjectIndex = TheCall->getNumArgs() - 1;
655     break;
656   }
657 
658   case Builtin::BI__builtin___snprintf_chk:
659   case Builtin::BI__builtin___vsnprintf_chk: {
660     DiagID = diag::warn_builtin_chk_overflow;
661     IsChkVariant = true;
662     SizeIndex = 1;
663     ObjectIndex = 3;
664     break;
665   }
666 
667   case Builtin::BIstrncat:
668   case Builtin::BI__builtin_strncat:
669   case Builtin::BIstrncpy:
670   case Builtin::BI__builtin_strncpy:
671   case Builtin::BIstpncpy:
672   case Builtin::BI__builtin_stpncpy: {
673     // Whether these functions overflow depends on the runtime strlen of the
674     // string, not just the buffer size, so emitting the "always overflow"
675     // diagnostic isn't quite right. We should still diagnose passing a buffer
676     // size larger than the destination buffer though; this is a runtime abort
677     // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
678     DiagID = diag::warn_fortify_source_size_mismatch;
679     SizeIndex = TheCall->getNumArgs() - 1;
680     ObjectIndex = 0;
681     break;
682   }
683 
684   case Builtin::BImemcpy:
685   case Builtin::BI__builtin_memcpy:
686   case Builtin::BImemmove:
687   case Builtin::BI__builtin_memmove:
688   case Builtin::BImemset:
689   case Builtin::BI__builtin_memset:
690   case Builtin::BImempcpy:
691   case Builtin::BI__builtin_mempcpy: {
692     DiagID = diag::warn_fortify_source_overflow;
693     SizeIndex = TheCall->getNumArgs() - 1;
694     ObjectIndex = 0;
695     break;
696   }
697   case Builtin::BIsnprintf:
698   case Builtin::BI__builtin_snprintf:
699   case Builtin::BIvsnprintf:
700   case Builtin::BI__builtin_vsnprintf: {
701     DiagID = diag::warn_fortify_source_size_mismatch;
702     SizeIndex = 1;
703     ObjectIndex = 0;
704     break;
705   }
706   }
707 
708   llvm::APSInt ObjectSize;
709   // For __builtin___*_chk, the object size is explicitly provided by the caller
710   // (usually using __builtin_object_size). Use that value to check this call.
711   if (IsChkVariant) {
712     Expr::EvalResult Result;
713     Expr *SizeArg = TheCall->getArg(ObjectIndex);
714     if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
715       return;
716     ObjectSize = Result.Val.getInt();
717 
718   // Otherwise, try to evaluate an imaginary call to __builtin_object_size.
719   } else {
720     // If the parameter has a pass_object_size attribute, then we should use its
721     // (potentially) more strict checking mode. Otherwise, conservatively assume
722     // type 0.
723     int BOSType = 0;
724     if (const auto *POS =
725             FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>())
726       BOSType = POS->getType();
727 
728     Expr *ObjArg = TheCall->getArg(ObjectIndex);
729     uint64_t Result;
730     if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
731       return;
732     // Get the object size in the target's size_t width.
733     ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
734   }
735 
736   // Evaluate the number of bytes of the object that this call will use.
737   if (!UsedSize) {
738     Expr::EvalResult Result;
739     Expr *UsedSizeArg = TheCall->getArg(SizeIndex);
740     if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext()))
741       return;
742     UsedSize = Result.Val.getInt().extOrTrunc(SizeTypeWidth);
743   }
744 
745   if (UsedSize.getValue().ule(ObjectSize))
746     return;
747 
748   StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
749   // Skim off the details of whichever builtin was called to produce a better
750   // diagnostic, as it's unlikley that the user wrote the __builtin explicitly.
751   if (IsChkVariant) {
752     FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
753     FunctionName = FunctionName.drop_back(std::strlen("_chk"));
754   } else if (FunctionName.startswith("__builtin_")) {
755     FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
756   }
757 
758   DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
759                       PDiag(DiagID)
760                           << FunctionName << ObjectSize.toString(/*Radix=*/10)
761                           << UsedSize.getValue().toString(/*Radix=*/10));
762 }
763 
764 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
765                                      Scope::ScopeFlags NeededScopeFlags,
766                                      unsigned DiagID) {
767   // Scopes aren't available during instantiation. Fortunately, builtin
768   // functions cannot be template args so they cannot be formed through template
769   // instantiation. Therefore checking once during the parse is sufficient.
770   if (SemaRef.inTemplateInstantiation())
771     return false;
772 
773   Scope *S = SemaRef.getCurScope();
774   while (S && !S->isSEHExceptScope())
775     S = S->getParent();
776   if (!S || !(S->getFlags() & NeededScopeFlags)) {
777     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
778     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
779         << DRE->getDecl()->getIdentifier();
780     return true;
781   }
782 
783   return false;
784 }
785 
786 static inline bool isBlockPointer(Expr *Arg) {
787   return Arg->getType()->isBlockPointerType();
788 }
789 
790 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
791 /// void*, which is a requirement of device side enqueue.
792 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
793   const BlockPointerType *BPT =
794       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
795   ArrayRef<QualType> Params =
796       BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes();
797   unsigned ArgCounter = 0;
798   bool IllegalParams = false;
799   // Iterate through the block parameters until either one is found that is not
800   // a local void*, or the block is valid.
801   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
802        I != E; ++I, ++ArgCounter) {
803     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
804         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
805             LangAS::opencl_local) {
806       // Get the location of the error. If a block literal has been passed
807       // (BlockExpr) then we can point straight to the offending argument,
808       // else we just point to the variable reference.
809       SourceLocation ErrorLoc;
810       if (isa<BlockExpr>(BlockArg)) {
811         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
812         ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
813       } else if (isa<DeclRefExpr>(BlockArg)) {
814         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
815       }
816       S.Diag(ErrorLoc,
817              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
818       IllegalParams = true;
819     }
820   }
821 
822   return IllegalParams;
823 }
824 
825 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
826   if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
827     S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
828         << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
829     return true;
830   }
831   return false;
832 }
833 
834 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
835   if (checkArgCount(S, TheCall, 2))
836     return true;
837 
838   if (checkOpenCLSubgroupExt(S, TheCall))
839     return true;
840 
841   // First argument is an ndrange_t type.
842   Expr *NDRangeArg = TheCall->getArg(0);
843   if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
844     S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
845         << TheCall->getDirectCallee() << "'ndrange_t'";
846     return true;
847   }
848 
849   Expr *BlockArg = TheCall->getArg(1);
850   if (!isBlockPointer(BlockArg)) {
851     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
852         << TheCall->getDirectCallee() << "block";
853     return true;
854   }
855   return checkOpenCLBlockArgs(S, BlockArg);
856 }
857 
858 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
859 /// get_kernel_work_group_size
860 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
861 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
862   if (checkArgCount(S, TheCall, 1))
863     return true;
864 
865   Expr *BlockArg = TheCall->getArg(0);
866   if (!isBlockPointer(BlockArg)) {
867     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
868         << TheCall->getDirectCallee() << "block";
869     return true;
870   }
871   return checkOpenCLBlockArgs(S, BlockArg);
872 }
873 
874 /// Diagnose integer type and any valid implicit conversion to it.
875 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
876                                       const QualType &IntType);
877 
878 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
879                                             unsigned Start, unsigned End) {
880   bool IllegalParams = false;
881   for (unsigned I = Start; I <= End; ++I)
882     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
883                                               S.Context.getSizeType());
884   return IllegalParams;
885 }
886 
887 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
888 /// 'local void*' parameter of passed block.
889 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
890                                            Expr *BlockArg,
891                                            unsigned NumNonVarArgs) {
892   const BlockPointerType *BPT =
893       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
894   unsigned NumBlockParams =
895       BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams();
896   unsigned TotalNumArgs = TheCall->getNumArgs();
897 
898   // For each argument passed to the block, a corresponding uint needs to
899   // be passed to describe the size of the local memory.
900   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
901     S.Diag(TheCall->getBeginLoc(),
902            diag::err_opencl_enqueue_kernel_local_size_args);
903     return true;
904   }
905 
906   // Check that the sizes of the local memory are specified by integers.
907   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
908                                          TotalNumArgs - 1);
909 }
910 
911 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
912 /// overload formats specified in Table 6.13.17.1.
913 /// int enqueue_kernel(queue_t queue,
914 ///                    kernel_enqueue_flags_t flags,
915 ///                    const ndrange_t ndrange,
916 ///                    void (^block)(void))
917 /// int enqueue_kernel(queue_t queue,
918 ///                    kernel_enqueue_flags_t flags,
919 ///                    const ndrange_t ndrange,
920 ///                    uint num_events_in_wait_list,
921 ///                    clk_event_t *event_wait_list,
922 ///                    clk_event_t *event_ret,
923 ///                    void (^block)(void))
924 /// int enqueue_kernel(queue_t queue,
925 ///                    kernel_enqueue_flags_t flags,
926 ///                    const ndrange_t ndrange,
927 ///                    void (^block)(local void*, ...),
928 ///                    uint size0, ...)
929 /// int enqueue_kernel(queue_t queue,
930 ///                    kernel_enqueue_flags_t flags,
931 ///                    const ndrange_t ndrange,
932 ///                    uint num_events_in_wait_list,
933 ///                    clk_event_t *event_wait_list,
934 ///                    clk_event_t *event_ret,
935 ///                    void (^block)(local void*, ...),
936 ///                    uint size0, ...)
937 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
938   unsigned NumArgs = TheCall->getNumArgs();
939 
940   if (NumArgs < 4) {
941     S.Diag(TheCall->getBeginLoc(),
942            diag::err_typecheck_call_too_few_args_at_least)
943         << 0 << 4 << NumArgs;
944     return true;
945   }
946 
947   Expr *Arg0 = TheCall->getArg(0);
948   Expr *Arg1 = TheCall->getArg(1);
949   Expr *Arg2 = TheCall->getArg(2);
950   Expr *Arg3 = TheCall->getArg(3);
951 
952   // First argument always needs to be a queue_t type.
953   if (!Arg0->getType()->isQueueT()) {
954     S.Diag(TheCall->getArg(0)->getBeginLoc(),
955            diag::err_opencl_builtin_expected_type)
956         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
957     return true;
958   }
959 
960   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
961   if (!Arg1->getType()->isIntegerType()) {
962     S.Diag(TheCall->getArg(1)->getBeginLoc(),
963            diag::err_opencl_builtin_expected_type)
964         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
965     return true;
966   }
967 
968   // Third argument is always an ndrange_t type.
969   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
970     S.Diag(TheCall->getArg(2)->getBeginLoc(),
971            diag::err_opencl_builtin_expected_type)
972         << TheCall->getDirectCallee() << "'ndrange_t'";
973     return true;
974   }
975 
976   // With four arguments, there is only one form that the function could be
977   // called in: no events and no variable arguments.
978   if (NumArgs == 4) {
979     // check that the last argument is the right block type.
980     if (!isBlockPointer(Arg3)) {
981       S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
982           << TheCall->getDirectCallee() << "block";
983       return true;
984     }
985     // we have a block type, check the prototype
986     const BlockPointerType *BPT =
987         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
988     if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) {
989       S.Diag(Arg3->getBeginLoc(),
990              diag::err_opencl_enqueue_kernel_blocks_no_args);
991       return true;
992     }
993     return false;
994   }
995   // we can have block + varargs.
996   if (isBlockPointer(Arg3))
997     return (checkOpenCLBlockArgs(S, Arg3) ||
998             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
999   // last two cases with either exactly 7 args or 7 args and varargs.
1000   if (NumArgs >= 7) {
1001     // check common block argument.
1002     Expr *Arg6 = TheCall->getArg(6);
1003     if (!isBlockPointer(Arg6)) {
1004       S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1005           << TheCall->getDirectCallee() << "block";
1006       return true;
1007     }
1008     if (checkOpenCLBlockArgs(S, Arg6))
1009       return true;
1010 
1011     // Forth argument has to be any integer type.
1012     if (!Arg3->getType()->isIntegerType()) {
1013       S.Diag(TheCall->getArg(3)->getBeginLoc(),
1014              diag::err_opencl_builtin_expected_type)
1015           << TheCall->getDirectCallee() << "integer";
1016       return true;
1017     }
1018     // check remaining common arguments.
1019     Expr *Arg4 = TheCall->getArg(4);
1020     Expr *Arg5 = TheCall->getArg(5);
1021 
1022     // Fifth argument is always passed as a pointer to clk_event_t.
1023     if (!Arg4->isNullPointerConstant(S.Context,
1024                                      Expr::NPC_ValueDependentIsNotNull) &&
1025         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
1026       S.Diag(TheCall->getArg(4)->getBeginLoc(),
1027              diag::err_opencl_builtin_expected_type)
1028           << TheCall->getDirectCallee()
1029           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1030       return true;
1031     }
1032 
1033     // Sixth argument is always passed as a pointer to clk_event_t.
1034     if (!Arg5->isNullPointerConstant(S.Context,
1035                                      Expr::NPC_ValueDependentIsNotNull) &&
1036         !(Arg5->getType()->isPointerType() &&
1037           Arg5->getType()->getPointeeType()->isClkEventT())) {
1038       S.Diag(TheCall->getArg(5)->getBeginLoc(),
1039              diag::err_opencl_builtin_expected_type)
1040           << TheCall->getDirectCallee()
1041           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1042       return true;
1043     }
1044 
1045     if (NumArgs == 7)
1046       return false;
1047 
1048     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
1049   }
1050 
1051   // None of the specific case has been detected, give generic error
1052   S.Diag(TheCall->getBeginLoc(),
1053          diag::err_opencl_enqueue_kernel_incorrect_args);
1054   return true;
1055 }
1056 
1057 /// Returns OpenCL access qual.
1058 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
1059     return D->getAttr<OpenCLAccessAttr>();
1060 }
1061 
1062 /// Returns true if pipe element type is different from the pointer.
1063 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
1064   const Expr *Arg0 = Call->getArg(0);
1065   // First argument type should always be pipe.
1066   if (!Arg0->getType()->isPipeType()) {
1067     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1068         << Call->getDirectCallee() << Arg0->getSourceRange();
1069     return true;
1070   }
1071   OpenCLAccessAttr *AccessQual =
1072       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
1073   // Validates the access qualifier is compatible with the call.
1074   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
1075   // read_only and write_only, and assumed to be read_only if no qualifier is
1076   // specified.
1077   switch (Call->getDirectCallee()->getBuiltinID()) {
1078   case Builtin::BIread_pipe:
1079   case Builtin::BIreserve_read_pipe:
1080   case Builtin::BIcommit_read_pipe:
1081   case Builtin::BIwork_group_reserve_read_pipe:
1082   case Builtin::BIsub_group_reserve_read_pipe:
1083   case Builtin::BIwork_group_commit_read_pipe:
1084   case Builtin::BIsub_group_commit_read_pipe:
1085     if (!(!AccessQual || AccessQual->isReadOnly())) {
1086       S.Diag(Arg0->getBeginLoc(),
1087              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1088           << "read_only" << Arg0->getSourceRange();
1089       return true;
1090     }
1091     break;
1092   case Builtin::BIwrite_pipe:
1093   case Builtin::BIreserve_write_pipe:
1094   case Builtin::BIcommit_write_pipe:
1095   case Builtin::BIwork_group_reserve_write_pipe:
1096   case Builtin::BIsub_group_reserve_write_pipe:
1097   case Builtin::BIwork_group_commit_write_pipe:
1098   case Builtin::BIsub_group_commit_write_pipe:
1099     if (!(AccessQual && AccessQual->isWriteOnly())) {
1100       S.Diag(Arg0->getBeginLoc(),
1101              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1102           << "write_only" << Arg0->getSourceRange();
1103       return true;
1104     }
1105     break;
1106   default:
1107     break;
1108   }
1109   return false;
1110 }
1111 
1112 /// Returns true if pipe element type is different from the pointer.
1113 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
1114   const Expr *Arg0 = Call->getArg(0);
1115   const Expr *ArgIdx = Call->getArg(Idx);
1116   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
1117   const QualType EltTy = PipeTy->getElementType();
1118   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
1119   // The Idx argument should be a pointer and the type of the pointer and
1120   // the type of pipe element should also be the same.
1121   if (!ArgTy ||
1122       !S.Context.hasSameType(
1123           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
1124     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1125         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
1126         << ArgIdx->getType() << ArgIdx->getSourceRange();
1127     return true;
1128   }
1129   return false;
1130 }
1131 
1132 // Performs semantic analysis for the read/write_pipe call.
1133 // \param S Reference to the semantic analyzer.
1134 // \param Call A pointer to the builtin call.
1135 // \return True if a semantic error has been found, false otherwise.
1136 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
1137   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
1138   // functions have two forms.
1139   switch (Call->getNumArgs()) {
1140   case 2:
1141     if (checkOpenCLPipeArg(S, Call))
1142       return true;
1143     // The call with 2 arguments should be
1144     // read/write_pipe(pipe T, T*).
1145     // Check packet type T.
1146     if (checkOpenCLPipePacketType(S, Call, 1))
1147       return true;
1148     break;
1149 
1150   case 4: {
1151     if (checkOpenCLPipeArg(S, Call))
1152       return true;
1153     // The call with 4 arguments should be
1154     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
1155     // Check reserve_id_t.
1156     if (!Call->getArg(1)->getType()->isReserveIDT()) {
1157       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1158           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1159           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1160       return true;
1161     }
1162 
1163     // Check the index.
1164     const Expr *Arg2 = Call->getArg(2);
1165     if (!Arg2->getType()->isIntegerType() &&
1166         !Arg2->getType()->isUnsignedIntegerType()) {
1167       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1168           << Call->getDirectCallee() << S.Context.UnsignedIntTy
1169           << Arg2->getType() << Arg2->getSourceRange();
1170       return true;
1171     }
1172 
1173     // Check packet type T.
1174     if (checkOpenCLPipePacketType(S, Call, 3))
1175       return true;
1176   } break;
1177   default:
1178     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
1179         << Call->getDirectCallee() << Call->getSourceRange();
1180     return true;
1181   }
1182 
1183   return false;
1184 }
1185 
1186 // Performs a semantic analysis on the {work_group_/sub_group_
1187 //        /_}reserve_{read/write}_pipe
1188 // \param S Reference to the semantic analyzer.
1189 // \param Call The call to the builtin function to be analyzed.
1190 // \return True if a semantic error was found, false otherwise.
1191 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
1192   if (checkArgCount(S, Call, 2))
1193     return true;
1194 
1195   if (checkOpenCLPipeArg(S, Call))
1196     return true;
1197 
1198   // Check the reserve size.
1199   if (!Call->getArg(1)->getType()->isIntegerType() &&
1200       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
1201     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1202         << Call->getDirectCallee() << S.Context.UnsignedIntTy
1203         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1204     return true;
1205   }
1206 
1207   // Since return type of reserve_read/write_pipe built-in function is
1208   // reserve_id_t, which is not defined in the builtin def file , we used int
1209   // as return type and need to override the return type of these functions.
1210   Call->setType(S.Context.OCLReserveIDTy);
1211 
1212   return false;
1213 }
1214 
1215 // Performs a semantic analysis on {work_group_/sub_group_
1216 //        /_}commit_{read/write}_pipe
1217 // \param S Reference to the semantic analyzer.
1218 // \param Call The call to the builtin function to be analyzed.
1219 // \return True if a semantic error was found, false otherwise.
1220 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
1221   if (checkArgCount(S, Call, 2))
1222     return true;
1223 
1224   if (checkOpenCLPipeArg(S, Call))
1225     return true;
1226 
1227   // Check reserve_id_t.
1228   if (!Call->getArg(1)->getType()->isReserveIDT()) {
1229     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1230         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1231         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1232     return true;
1233   }
1234 
1235   return false;
1236 }
1237 
1238 // Performs a semantic analysis on the call to built-in Pipe
1239 //        Query Functions.
1240 // \param S Reference to the semantic analyzer.
1241 // \param Call The call to the builtin function to be analyzed.
1242 // \return True if a semantic error was found, false otherwise.
1243 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
1244   if (checkArgCount(S, Call, 1))
1245     return true;
1246 
1247   if (!Call->getArg(0)->getType()->isPipeType()) {
1248     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1249         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
1250     return true;
1251   }
1252 
1253   return false;
1254 }
1255 
1256 // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
1257 // Performs semantic analysis for the to_global/local/private call.
1258 // \param S Reference to the semantic analyzer.
1259 // \param BuiltinID ID of the builtin function.
1260 // \param Call A pointer to the builtin call.
1261 // \return True if a semantic error has been found, false otherwise.
1262 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
1263                                     CallExpr *Call) {
1264   if (Call->getNumArgs() != 1) {
1265     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_arg_num)
1266         << Call->getDirectCallee() << Call->getSourceRange();
1267     return true;
1268   }
1269 
1270   auto RT = Call->getArg(0)->getType();
1271   if (!RT->isPointerType() || RT->getPointeeType()
1272       .getAddressSpace() == LangAS::opencl_constant) {
1273     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
1274         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
1275     return true;
1276   }
1277 
1278   if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
1279     S.Diag(Call->getArg(0)->getBeginLoc(),
1280            diag::warn_opencl_generic_address_space_arg)
1281         << Call->getDirectCallee()->getNameInfo().getAsString()
1282         << Call->getArg(0)->getSourceRange();
1283   }
1284 
1285   RT = RT->getPointeeType();
1286   auto Qual = RT.getQualifiers();
1287   switch (BuiltinID) {
1288   case Builtin::BIto_global:
1289     Qual.setAddressSpace(LangAS::opencl_global);
1290     break;
1291   case Builtin::BIto_local:
1292     Qual.setAddressSpace(LangAS::opencl_local);
1293     break;
1294   case Builtin::BIto_private:
1295     Qual.setAddressSpace(LangAS::opencl_private);
1296     break;
1297   default:
1298     llvm_unreachable("Invalid builtin function");
1299   }
1300   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
1301       RT.getUnqualifiedType(), Qual)));
1302 
1303   return false;
1304 }
1305 
1306 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
1307   if (checkArgCount(S, TheCall, 1))
1308     return ExprError();
1309 
1310   // Compute __builtin_launder's parameter type from the argument.
1311   // The parameter type is:
1312   //  * The type of the argument if it's not an array or function type,
1313   //  Otherwise,
1314   //  * The decayed argument type.
1315   QualType ParamTy = [&]() {
1316     QualType ArgTy = TheCall->getArg(0)->getType();
1317     if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1318       return S.Context.getPointerType(Ty->getElementType());
1319     if (ArgTy->isFunctionType()) {
1320       return S.Context.getPointerType(ArgTy);
1321     }
1322     return ArgTy;
1323   }();
1324 
1325   TheCall->setType(ParamTy);
1326 
1327   auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
1328     if (!ParamTy->isPointerType())
1329       return 0;
1330     if (ParamTy->isFunctionPointerType())
1331       return 1;
1332     if (ParamTy->isVoidPointerType())
1333       return 2;
1334     return llvm::Optional<unsigned>{};
1335   }();
1336   if (DiagSelect.hasValue()) {
1337     S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1338         << DiagSelect.getValue() << TheCall->getSourceRange();
1339     return ExprError();
1340   }
1341 
1342   // We either have an incomplete class type, or we have a class template
1343   // whose instantiation has not been forced. Example:
1344   //
1345   //   template <class T> struct Foo { T value; };
1346   //   Foo<int> *p = nullptr;
1347   //   auto *d = __builtin_launder(p);
1348   if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1349                             diag::err_incomplete_type))
1350     return ExprError();
1351 
1352   assert(ParamTy->getPointeeType()->isObjectType() &&
1353          "Unhandled non-object pointer case");
1354 
1355   InitializedEntity Entity =
1356       InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
1357   ExprResult Arg =
1358       S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1359   if (Arg.isInvalid())
1360     return ExprError();
1361   TheCall->setArg(0, Arg.get());
1362 
1363   return TheCall;
1364 }
1365 
1366 // Emit an error and return true if the current architecture is not in the list
1367 // of supported architectures.
1368 static bool
1369 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1370                           ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
1371   llvm::Triple::ArchType CurArch =
1372       S.getASTContext().getTargetInfo().getTriple().getArch();
1373   if (llvm::is_contained(SupportedArchs, CurArch))
1374     return false;
1375   S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1376       << TheCall->getSourceRange();
1377   return true;
1378 }
1379 
1380 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
1381                                  SourceLocation CallSiteLoc);
1382 
1383 bool Sema::CheckTSBuiltinFunctionCall(llvm::Triple::ArchType Arch,
1384                                       unsigned BuiltinID, CallExpr *TheCall) {
1385   switch (Arch) {
1386   default:
1387     // Some builtins don't require additional checking, so just consider these
1388     // acceptable.
1389     return false;
1390   case llvm::Triple::arm:
1391   case llvm::Triple::armeb:
1392   case llvm::Triple::thumb:
1393   case llvm::Triple::thumbeb:
1394     return CheckARMBuiltinFunctionCall(BuiltinID, TheCall);
1395   case llvm::Triple::aarch64:
1396   case llvm::Triple::aarch64_32:
1397   case llvm::Triple::aarch64_be:
1398     return CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall);
1399   case llvm::Triple::bpfeb:
1400   case llvm::Triple::bpfel:
1401     return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
1402   case llvm::Triple::hexagon:
1403     return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
1404   case llvm::Triple::mips:
1405   case llvm::Triple::mipsel:
1406   case llvm::Triple::mips64:
1407   case llvm::Triple::mips64el:
1408     return CheckMipsBuiltinFunctionCall(BuiltinID, TheCall);
1409   case llvm::Triple::systemz:
1410     return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
1411   case llvm::Triple::x86:
1412   case llvm::Triple::x86_64:
1413     return CheckX86BuiltinFunctionCall(BuiltinID, TheCall);
1414   case llvm::Triple::ppc:
1415   case llvm::Triple::ppc64:
1416   case llvm::Triple::ppc64le:
1417     return CheckPPCBuiltinFunctionCall(BuiltinID, TheCall);
1418   case llvm::Triple::amdgcn:
1419     return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
1420   }
1421 }
1422 
1423 ExprResult
1424 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
1425                                CallExpr *TheCall) {
1426   ExprResult TheCallResult(TheCall);
1427 
1428   // Find out if any arguments are required to be integer constant expressions.
1429   unsigned ICEArguments = 0;
1430   ASTContext::GetBuiltinTypeError Error;
1431   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
1432   if (Error != ASTContext::GE_None)
1433     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
1434 
1435   // If any arguments are required to be ICE's, check and diagnose.
1436   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
1437     // Skip arguments not required to be ICE's.
1438     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
1439 
1440     llvm::APSInt Result;
1441     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
1442       return true;
1443     ICEArguments &= ~(1 << ArgNo);
1444   }
1445 
1446   switch (BuiltinID) {
1447   case Builtin::BI__builtin___CFStringMakeConstantString:
1448     assert(TheCall->getNumArgs() == 1 &&
1449            "Wrong # arguments to builtin CFStringMakeConstantString");
1450     if (CheckObjCString(TheCall->getArg(0)))
1451       return ExprError();
1452     break;
1453   case Builtin::BI__builtin_ms_va_start:
1454   case Builtin::BI__builtin_stdarg_start:
1455   case Builtin::BI__builtin_va_start:
1456     if (SemaBuiltinVAStart(BuiltinID, TheCall))
1457       return ExprError();
1458     break;
1459   case Builtin::BI__va_start: {
1460     switch (Context.getTargetInfo().getTriple().getArch()) {
1461     case llvm::Triple::aarch64:
1462     case llvm::Triple::arm:
1463     case llvm::Triple::thumb:
1464       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
1465         return ExprError();
1466       break;
1467     default:
1468       if (SemaBuiltinVAStart(BuiltinID, TheCall))
1469         return ExprError();
1470       break;
1471     }
1472     break;
1473   }
1474 
1475   // The acquire, release, and no fence variants are ARM and AArch64 only.
1476   case Builtin::BI_interlockedbittestandset_acq:
1477   case Builtin::BI_interlockedbittestandset_rel:
1478   case Builtin::BI_interlockedbittestandset_nf:
1479   case Builtin::BI_interlockedbittestandreset_acq:
1480   case Builtin::BI_interlockedbittestandreset_rel:
1481   case Builtin::BI_interlockedbittestandreset_nf:
1482     if (CheckBuiltinTargetSupport(
1483             *this, BuiltinID, TheCall,
1484             {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
1485       return ExprError();
1486     break;
1487 
1488   // The 64-bit bittest variants are x64, ARM, and AArch64 only.
1489   case Builtin::BI_bittest64:
1490   case Builtin::BI_bittestandcomplement64:
1491   case Builtin::BI_bittestandreset64:
1492   case Builtin::BI_bittestandset64:
1493   case Builtin::BI_interlockedbittestandreset64:
1494   case Builtin::BI_interlockedbittestandset64:
1495     if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
1496                                   {llvm::Triple::x86_64, llvm::Triple::arm,
1497                                    llvm::Triple::thumb, llvm::Triple::aarch64}))
1498       return ExprError();
1499     break;
1500 
1501   case Builtin::BI__builtin_isgreater:
1502   case Builtin::BI__builtin_isgreaterequal:
1503   case Builtin::BI__builtin_isless:
1504   case Builtin::BI__builtin_islessequal:
1505   case Builtin::BI__builtin_islessgreater:
1506   case Builtin::BI__builtin_isunordered:
1507     if (SemaBuiltinUnorderedCompare(TheCall))
1508       return ExprError();
1509     break;
1510   case Builtin::BI__builtin_fpclassify:
1511     if (SemaBuiltinFPClassification(TheCall, 6))
1512       return ExprError();
1513     break;
1514   case Builtin::BI__builtin_isfinite:
1515   case Builtin::BI__builtin_isinf:
1516   case Builtin::BI__builtin_isinf_sign:
1517   case Builtin::BI__builtin_isnan:
1518   case Builtin::BI__builtin_isnormal:
1519   case Builtin::BI__builtin_signbit:
1520   case Builtin::BI__builtin_signbitf:
1521   case Builtin::BI__builtin_signbitl:
1522     if (SemaBuiltinFPClassification(TheCall, 1))
1523       return ExprError();
1524     break;
1525   case Builtin::BI__builtin_shufflevector:
1526     return SemaBuiltinShuffleVector(TheCall);
1527     // TheCall will be freed by the smart pointer here, but that's fine, since
1528     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1529   case Builtin::BI__builtin_prefetch:
1530     if (SemaBuiltinPrefetch(TheCall))
1531       return ExprError();
1532     break;
1533   case Builtin::BI__builtin_alloca_with_align:
1534     if (SemaBuiltinAllocaWithAlign(TheCall))
1535       return ExprError();
1536     LLVM_FALLTHROUGH;
1537   case Builtin::BI__builtin_alloca:
1538     Diag(TheCall->getBeginLoc(), diag::warn_alloca)
1539         << TheCall->getDirectCallee();
1540     break;
1541   case Builtin::BI__assume:
1542   case Builtin::BI__builtin_assume:
1543     if (SemaBuiltinAssume(TheCall))
1544       return ExprError();
1545     break;
1546   case Builtin::BI__builtin_assume_aligned:
1547     if (SemaBuiltinAssumeAligned(TheCall))
1548       return ExprError();
1549     break;
1550   case Builtin::BI__builtin_dynamic_object_size:
1551   case Builtin::BI__builtin_object_size:
1552     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1553       return ExprError();
1554     break;
1555   case Builtin::BI__builtin_longjmp:
1556     if (SemaBuiltinLongjmp(TheCall))
1557       return ExprError();
1558     break;
1559   case Builtin::BI__builtin_setjmp:
1560     if (SemaBuiltinSetjmp(TheCall))
1561       return ExprError();
1562     break;
1563   case Builtin::BI_setjmp:
1564   case Builtin::BI_setjmpex:
1565     if (checkArgCount(*this, TheCall, 1))
1566       return true;
1567     break;
1568   case Builtin::BI__builtin_classify_type:
1569     if (checkArgCount(*this, TheCall, 1)) return true;
1570     TheCall->setType(Context.IntTy);
1571     break;
1572   case Builtin::BI__builtin_constant_p: {
1573     if (checkArgCount(*this, TheCall, 1)) return true;
1574     ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
1575     if (Arg.isInvalid()) return true;
1576     TheCall->setArg(0, Arg.get());
1577     TheCall->setType(Context.IntTy);
1578     break;
1579   }
1580   case Builtin::BI__builtin_launder:
1581     return SemaBuiltinLaunder(*this, TheCall);
1582   case Builtin::BI__sync_fetch_and_add:
1583   case Builtin::BI__sync_fetch_and_add_1:
1584   case Builtin::BI__sync_fetch_and_add_2:
1585   case Builtin::BI__sync_fetch_and_add_4:
1586   case Builtin::BI__sync_fetch_and_add_8:
1587   case Builtin::BI__sync_fetch_and_add_16:
1588   case Builtin::BI__sync_fetch_and_sub:
1589   case Builtin::BI__sync_fetch_and_sub_1:
1590   case Builtin::BI__sync_fetch_and_sub_2:
1591   case Builtin::BI__sync_fetch_and_sub_4:
1592   case Builtin::BI__sync_fetch_and_sub_8:
1593   case Builtin::BI__sync_fetch_and_sub_16:
1594   case Builtin::BI__sync_fetch_and_or:
1595   case Builtin::BI__sync_fetch_and_or_1:
1596   case Builtin::BI__sync_fetch_and_or_2:
1597   case Builtin::BI__sync_fetch_and_or_4:
1598   case Builtin::BI__sync_fetch_and_or_8:
1599   case Builtin::BI__sync_fetch_and_or_16:
1600   case Builtin::BI__sync_fetch_and_and:
1601   case Builtin::BI__sync_fetch_and_and_1:
1602   case Builtin::BI__sync_fetch_and_and_2:
1603   case Builtin::BI__sync_fetch_and_and_4:
1604   case Builtin::BI__sync_fetch_and_and_8:
1605   case Builtin::BI__sync_fetch_and_and_16:
1606   case Builtin::BI__sync_fetch_and_xor:
1607   case Builtin::BI__sync_fetch_and_xor_1:
1608   case Builtin::BI__sync_fetch_and_xor_2:
1609   case Builtin::BI__sync_fetch_and_xor_4:
1610   case Builtin::BI__sync_fetch_and_xor_8:
1611   case Builtin::BI__sync_fetch_and_xor_16:
1612   case Builtin::BI__sync_fetch_and_nand:
1613   case Builtin::BI__sync_fetch_and_nand_1:
1614   case Builtin::BI__sync_fetch_and_nand_2:
1615   case Builtin::BI__sync_fetch_and_nand_4:
1616   case Builtin::BI__sync_fetch_and_nand_8:
1617   case Builtin::BI__sync_fetch_and_nand_16:
1618   case Builtin::BI__sync_add_and_fetch:
1619   case Builtin::BI__sync_add_and_fetch_1:
1620   case Builtin::BI__sync_add_and_fetch_2:
1621   case Builtin::BI__sync_add_and_fetch_4:
1622   case Builtin::BI__sync_add_and_fetch_8:
1623   case Builtin::BI__sync_add_and_fetch_16:
1624   case Builtin::BI__sync_sub_and_fetch:
1625   case Builtin::BI__sync_sub_and_fetch_1:
1626   case Builtin::BI__sync_sub_and_fetch_2:
1627   case Builtin::BI__sync_sub_and_fetch_4:
1628   case Builtin::BI__sync_sub_and_fetch_8:
1629   case Builtin::BI__sync_sub_and_fetch_16:
1630   case Builtin::BI__sync_and_and_fetch:
1631   case Builtin::BI__sync_and_and_fetch_1:
1632   case Builtin::BI__sync_and_and_fetch_2:
1633   case Builtin::BI__sync_and_and_fetch_4:
1634   case Builtin::BI__sync_and_and_fetch_8:
1635   case Builtin::BI__sync_and_and_fetch_16:
1636   case Builtin::BI__sync_or_and_fetch:
1637   case Builtin::BI__sync_or_and_fetch_1:
1638   case Builtin::BI__sync_or_and_fetch_2:
1639   case Builtin::BI__sync_or_and_fetch_4:
1640   case Builtin::BI__sync_or_and_fetch_8:
1641   case Builtin::BI__sync_or_and_fetch_16:
1642   case Builtin::BI__sync_xor_and_fetch:
1643   case Builtin::BI__sync_xor_and_fetch_1:
1644   case Builtin::BI__sync_xor_and_fetch_2:
1645   case Builtin::BI__sync_xor_and_fetch_4:
1646   case Builtin::BI__sync_xor_and_fetch_8:
1647   case Builtin::BI__sync_xor_and_fetch_16:
1648   case Builtin::BI__sync_nand_and_fetch:
1649   case Builtin::BI__sync_nand_and_fetch_1:
1650   case Builtin::BI__sync_nand_and_fetch_2:
1651   case Builtin::BI__sync_nand_and_fetch_4:
1652   case Builtin::BI__sync_nand_and_fetch_8:
1653   case Builtin::BI__sync_nand_and_fetch_16:
1654   case Builtin::BI__sync_val_compare_and_swap:
1655   case Builtin::BI__sync_val_compare_and_swap_1:
1656   case Builtin::BI__sync_val_compare_and_swap_2:
1657   case Builtin::BI__sync_val_compare_and_swap_4:
1658   case Builtin::BI__sync_val_compare_and_swap_8:
1659   case Builtin::BI__sync_val_compare_and_swap_16:
1660   case Builtin::BI__sync_bool_compare_and_swap:
1661   case Builtin::BI__sync_bool_compare_and_swap_1:
1662   case Builtin::BI__sync_bool_compare_and_swap_2:
1663   case Builtin::BI__sync_bool_compare_and_swap_4:
1664   case Builtin::BI__sync_bool_compare_and_swap_8:
1665   case Builtin::BI__sync_bool_compare_and_swap_16:
1666   case Builtin::BI__sync_lock_test_and_set:
1667   case Builtin::BI__sync_lock_test_and_set_1:
1668   case Builtin::BI__sync_lock_test_and_set_2:
1669   case Builtin::BI__sync_lock_test_and_set_4:
1670   case Builtin::BI__sync_lock_test_and_set_8:
1671   case Builtin::BI__sync_lock_test_and_set_16:
1672   case Builtin::BI__sync_lock_release:
1673   case Builtin::BI__sync_lock_release_1:
1674   case Builtin::BI__sync_lock_release_2:
1675   case Builtin::BI__sync_lock_release_4:
1676   case Builtin::BI__sync_lock_release_8:
1677   case Builtin::BI__sync_lock_release_16:
1678   case Builtin::BI__sync_swap:
1679   case Builtin::BI__sync_swap_1:
1680   case Builtin::BI__sync_swap_2:
1681   case Builtin::BI__sync_swap_4:
1682   case Builtin::BI__sync_swap_8:
1683   case Builtin::BI__sync_swap_16:
1684     return SemaBuiltinAtomicOverloaded(TheCallResult);
1685   case Builtin::BI__sync_synchronize:
1686     Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1687         << TheCall->getCallee()->getSourceRange();
1688     break;
1689   case Builtin::BI__builtin_nontemporal_load:
1690   case Builtin::BI__builtin_nontemporal_store:
1691     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1692   case Builtin::BI__builtin_memcpy_inline: {
1693     clang::Expr *SizeOp = TheCall->getArg(2);
1694     // We warn about copying to or from `nullptr` pointers when `size` is
1695     // greater than 0. When `size` is value dependent we cannot evaluate its
1696     // value so we bail out.
1697     if (SizeOp->isValueDependent())
1698       break;
1699     if (!SizeOp->EvaluateKnownConstInt(Context).isNullValue()) {
1700       CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
1701       CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
1702     }
1703     break;
1704   }
1705 #define BUILTIN(ID, TYPE, ATTRS)
1706 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1707   case Builtin::BI##ID: \
1708     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1709 #include "clang/Basic/Builtins.def"
1710   case Builtin::BI__annotation:
1711     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1712       return ExprError();
1713     break;
1714   case Builtin::BI__builtin_annotation:
1715     if (SemaBuiltinAnnotation(*this, TheCall))
1716       return ExprError();
1717     break;
1718   case Builtin::BI__builtin_addressof:
1719     if (SemaBuiltinAddressof(*this, TheCall))
1720       return ExprError();
1721     break;
1722   case Builtin::BI__builtin_is_aligned:
1723   case Builtin::BI__builtin_align_up:
1724   case Builtin::BI__builtin_align_down:
1725     if (SemaBuiltinAlignment(*this, TheCall, BuiltinID))
1726       return ExprError();
1727     break;
1728   case Builtin::BI__builtin_add_overflow:
1729   case Builtin::BI__builtin_sub_overflow:
1730   case Builtin::BI__builtin_mul_overflow:
1731     if (SemaBuiltinOverflow(*this, TheCall))
1732       return ExprError();
1733     break;
1734   case Builtin::BI__builtin_operator_new:
1735   case Builtin::BI__builtin_operator_delete: {
1736     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1737     ExprResult Res =
1738         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1739     if (Res.isInvalid())
1740       CorrectDelayedTyposInExpr(TheCallResult.get());
1741     return Res;
1742   }
1743   case Builtin::BI__builtin_dump_struct: {
1744     // We first want to ensure we are called with 2 arguments
1745     if (checkArgCount(*this, TheCall, 2))
1746       return ExprError();
1747     // Ensure that the first argument is of type 'struct XX *'
1748     const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1749     const QualType PtrArgType = PtrArg->getType();
1750     if (!PtrArgType->isPointerType() ||
1751         !PtrArgType->getPointeeType()->isRecordType()) {
1752       Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1753           << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1754           << "structure pointer";
1755       return ExprError();
1756     }
1757 
1758     // Ensure that the second argument is of type 'FunctionType'
1759     const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1760     const QualType FnPtrArgType = FnPtrArg->getType();
1761     if (!FnPtrArgType->isPointerType()) {
1762       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1763           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1764           << FnPtrArgType << "'int (*)(const char *, ...)'";
1765       return ExprError();
1766     }
1767 
1768     const auto *FuncType =
1769         FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1770 
1771     if (!FuncType) {
1772       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1773           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1774           << FnPtrArgType << "'int (*)(const char *, ...)'";
1775       return ExprError();
1776     }
1777 
1778     if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1779       if (!FT->getNumParams()) {
1780         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1781             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1782             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1783         return ExprError();
1784       }
1785       QualType PT = FT->getParamType(0);
1786       if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1787           !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1788           !PT->getPointeeType().isConstQualified()) {
1789         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1790             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1791             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1792         return ExprError();
1793       }
1794     }
1795 
1796     TheCall->setType(Context.IntTy);
1797     break;
1798   }
1799   case Builtin::BI__builtin_preserve_access_index:
1800     if (SemaBuiltinPreserveAI(*this, TheCall))
1801       return ExprError();
1802     break;
1803   case Builtin::BI__builtin_call_with_static_chain:
1804     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1805       return ExprError();
1806     break;
1807   case Builtin::BI__exception_code:
1808   case Builtin::BI_exception_code:
1809     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1810                                  diag::err_seh___except_block))
1811       return ExprError();
1812     break;
1813   case Builtin::BI__exception_info:
1814   case Builtin::BI_exception_info:
1815     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1816                                  diag::err_seh___except_filter))
1817       return ExprError();
1818     break;
1819   case Builtin::BI__GetExceptionInfo:
1820     if (checkArgCount(*this, TheCall, 1))
1821       return ExprError();
1822 
1823     if (CheckCXXThrowOperand(
1824             TheCall->getBeginLoc(),
1825             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1826             TheCall))
1827       return ExprError();
1828 
1829     TheCall->setType(Context.VoidPtrTy);
1830     break;
1831   // OpenCL v2.0, s6.13.16 - Pipe functions
1832   case Builtin::BIread_pipe:
1833   case Builtin::BIwrite_pipe:
1834     // Since those two functions are declared with var args, we need a semantic
1835     // check for the argument.
1836     if (SemaBuiltinRWPipe(*this, TheCall))
1837       return ExprError();
1838     break;
1839   case Builtin::BIreserve_read_pipe:
1840   case Builtin::BIreserve_write_pipe:
1841   case Builtin::BIwork_group_reserve_read_pipe:
1842   case Builtin::BIwork_group_reserve_write_pipe:
1843     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1844       return ExprError();
1845     break;
1846   case Builtin::BIsub_group_reserve_read_pipe:
1847   case Builtin::BIsub_group_reserve_write_pipe:
1848     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1849         SemaBuiltinReserveRWPipe(*this, TheCall))
1850       return ExprError();
1851     break;
1852   case Builtin::BIcommit_read_pipe:
1853   case Builtin::BIcommit_write_pipe:
1854   case Builtin::BIwork_group_commit_read_pipe:
1855   case Builtin::BIwork_group_commit_write_pipe:
1856     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1857       return ExprError();
1858     break;
1859   case Builtin::BIsub_group_commit_read_pipe:
1860   case Builtin::BIsub_group_commit_write_pipe:
1861     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1862         SemaBuiltinCommitRWPipe(*this, TheCall))
1863       return ExprError();
1864     break;
1865   case Builtin::BIget_pipe_num_packets:
1866   case Builtin::BIget_pipe_max_packets:
1867     if (SemaBuiltinPipePackets(*this, TheCall))
1868       return ExprError();
1869     break;
1870   case Builtin::BIto_global:
1871   case Builtin::BIto_local:
1872   case Builtin::BIto_private:
1873     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1874       return ExprError();
1875     break;
1876   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1877   case Builtin::BIenqueue_kernel:
1878     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1879       return ExprError();
1880     break;
1881   case Builtin::BIget_kernel_work_group_size:
1882   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1883     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1884       return ExprError();
1885     break;
1886   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1887   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1888     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1889       return ExprError();
1890     break;
1891   case Builtin::BI__builtin_os_log_format:
1892     Cleanup.setExprNeedsCleanups(true);
1893     LLVM_FALLTHROUGH;
1894   case Builtin::BI__builtin_os_log_format_buffer_size:
1895     if (SemaBuiltinOSLogFormat(TheCall))
1896       return ExprError();
1897     break;
1898   case Builtin::BI__builtin_frame_address:
1899   case Builtin::BI__builtin_return_address:
1900     if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
1901       return ExprError();
1902 
1903     // -Wframe-address warning if non-zero passed to builtin
1904     // return/frame address.
1905     Expr::EvalResult Result;
1906     if (TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
1907         Result.Val.getInt() != 0)
1908       Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
1909           << ((BuiltinID == Builtin::BI__builtin_return_address)
1910                   ? "__builtin_return_address"
1911                   : "__builtin_frame_address")
1912           << TheCall->getSourceRange();
1913     break;
1914   }
1915 
1916   // Since the target specific builtins for each arch overlap, only check those
1917   // of the arch we are compiling for.
1918   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1919     if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
1920       assert(Context.getAuxTargetInfo() &&
1921              "Aux Target Builtin, but not an aux target?");
1922 
1923       if (CheckTSBuiltinFunctionCall(
1924               Context.getAuxTargetInfo()->getTriple().getArch(),
1925               Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
1926         return ExprError();
1927     } else {
1928       if (CheckTSBuiltinFunctionCall(
1929               Context.getTargetInfo().getTriple().getArch(), BuiltinID,
1930               TheCall))
1931         return ExprError();
1932     }
1933   }
1934 
1935   return TheCallResult;
1936 }
1937 
1938 // Get the valid immediate range for the specified NEON type code.
1939 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1940   NeonTypeFlags Type(t);
1941   int IsQuad = ForceQuad ? true : Type.isQuad();
1942   switch (Type.getEltType()) {
1943   case NeonTypeFlags::Int8:
1944   case NeonTypeFlags::Poly8:
1945     return shift ? 7 : (8 << IsQuad) - 1;
1946   case NeonTypeFlags::Int16:
1947   case NeonTypeFlags::Poly16:
1948     return shift ? 15 : (4 << IsQuad) - 1;
1949   case NeonTypeFlags::Int32:
1950     return shift ? 31 : (2 << IsQuad) - 1;
1951   case NeonTypeFlags::Int64:
1952   case NeonTypeFlags::Poly64:
1953     return shift ? 63 : (1 << IsQuad) - 1;
1954   case NeonTypeFlags::Poly128:
1955     return shift ? 127 : (1 << IsQuad) - 1;
1956   case NeonTypeFlags::Float16:
1957     assert(!shift && "cannot shift float types!");
1958     return (4 << IsQuad) - 1;
1959   case NeonTypeFlags::Float32:
1960     assert(!shift && "cannot shift float types!");
1961     return (2 << IsQuad) - 1;
1962   case NeonTypeFlags::Float64:
1963     assert(!shift && "cannot shift float types!");
1964     return (1 << IsQuad) - 1;
1965   }
1966   llvm_unreachable("Invalid NeonTypeFlag!");
1967 }
1968 
1969 /// getNeonEltType - Return the QualType corresponding to the elements of
1970 /// the vector type specified by the NeonTypeFlags.  This is used to check
1971 /// the pointer arguments for Neon load/store intrinsics.
1972 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
1973                                bool IsPolyUnsigned, bool IsInt64Long) {
1974   switch (Flags.getEltType()) {
1975   case NeonTypeFlags::Int8:
1976     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1977   case NeonTypeFlags::Int16:
1978     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1979   case NeonTypeFlags::Int32:
1980     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1981   case NeonTypeFlags::Int64:
1982     if (IsInt64Long)
1983       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1984     else
1985       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1986                                 : Context.LongLongTy;
1987   case NeonTypeFlags::Poly8:
1988     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
1989   case NeonTypeFlags::Poly16:
1990     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
1991   case NeonTypeFlags::Poly64:
1992     if (IsInt64Long)
1993       return Context.UnsignedLongTy;
1994     else
1995       return Context.UnsignedLongLongTy;
1996   case NeonTypeFlags::Poly128:
1997     break;
1998   case NeonTypeFlags::Float16:
1999     return Context.HalfTy;
2000   case NeonTypeFlags::Float32:
2001     return Context.FloatTy;
2002   case NeonTypeFlags::Float64:
2003     return Context.DoubleTy;
2004   }
2005   llvm_unreachable("Invalid NeonTypeFlag!");
2006 }
2007 
2008 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2009   // Range check SVE intrinsics that take immediate values.
2010   SmallVector<std::tuple<int,int,int>, 3> ImmChecks;
2011 
2012   switch (BuiltinID) {
2013   default:
2014     return false;
2015 #define GET_SVE_IMMEDIATE_CHECK
2016 #include "clang/Basic/arm_sve_sema_rangechecks.inc"
2017 #undef GET_SVE_IMMEDIATE_CHECK
2018   }
2019 
2020   // Perform all the immediate checks for this builtin call.
2021   bool HasError = false;
2022   for (auto &I : ImmChecks) {
2023     int ArgNum, CheckTy, ElementSizeInBits;
2024     std::tie(ArgNum, CheckTy, ElementSizeInBits) = I;
2025 
2026     typedef bool(*OptionSetCheckFnTy)(int64_t Value);
2027 
2028     // Function that checks whether the operand (ArgNum) is an immediate
2029     // that is one of the predefined values.
2030     auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm,
2031                                    int ErrDiag) -> bool {
2032       // We can't check the value of a dependent argument.
2033       Expr *Arg = TheCall->getArg(ArgNum);
2034       if (Arg->isTypeDependent() || Arg->isValueDependent())
2035         return false;
2036 
2037       // Check constant-ness first.
2038       llvm::APSInt Imm;
2039       if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm))
2040         return true;
2041 
2042       if (!CheckImm(Imm.getSExtValue()))
2043         return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange();
2044       return false;
2045     };
2046 
2047     switch ((SVETypeFlags::ImmCheckType)CheckTy) {
2048     case SVETypeFlags::ImmCheck0_31:
2049       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31))
2050         HasError = true;
2051       break;
2052     case SVETypeFlags::ImmCheck0_13:
2053       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13))
2054         HasError = true;
2055       break;
2056     case SVETypeFlags::ImmCheck1_16:
2057       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16))
2058         HasError = true;
2059       break;
2060     case SVETypeFlags::ImmCheck0_7:
2061       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7))
2062         HasError = true;
2063       break;
2064     case SVETypeFlags::ImmCheckExtract:
2065       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2066                                       (2048 / ElementSizeInBits) - 1))
2067         HasError = true;
2068       break;
2069     case SVETypeFlags::ImmCheckShiftRight:
2070       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits))
2071         HasError = true;
2072       break;
2073     case SVETypeFlags::ImmCheckShiftRightNarrow:
2074       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1,
2075                                       ElementSizeInBits / 2))
2076         HasError = true;
2077       break;
2078     case SVETypeFlags::ImmCheckShiftLeft:
2079       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2080                                       ElementSizeInBits - 1))
2081         HasError = true;
2082       break;
2083     case SVETypeFlags::ImmCheckLaneIndex:
2084       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2085                                       (128 / (1 * ElementSizeInBits)) - 1))
2086         HasError = true;
2087       break;
2088     case SVETypeFlags::ImmCheckLaneIndexCompRotate:
2089       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2090                                       (128 / (2 * ElementSizeInBits)) - 1))
2091         HasError = true;
2092       break;
2093     case SVETypeFlags::ImmCheckLaneIndexDot:
2094       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2095                                       (128 / (4 * ElementSizeInBits)) - 1))
2096         HasError = true;
2097       break;
2098     case SVETypeFlags::ImmCheckComplexRot90_270:
2099       if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; },
2100                               diag::err_rotation_argument_to_cadd))
2101         HasError = true;
2102       break;
2103     case SVETypeFlags::ImmCheckComplexRotAll90:
2104       if (CheckImmediateInSet(
2105               [](int64_t V) {
2106                 return V == 0 || V == 90 || V == 180 || V == 270;
2107               },
2108               diag::err_rotation_argument_to_cmla))
2109         HasError = true;
2110       break;
2111     }
2112   }
2113 
2114   return HasError;
2115 }
2116 
2117 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2118   llvm::APSInt Result;
2119   uint64_t mask = 0;
2120   unsigned TV = 0;
2121   int PtrArgNum = -1;
2122   bool HasConstPtr = false;
2123   switch (BuiltinID) {
2124 #define GET_NEON_OVERLOAD_CHECK
2125 #include "clang/Basic/arm_neon.inc"
2126 #include "clang/Basic/arm_fp16.inc"
2127 #undef GET_NEON_OVERLOAD_CHECK
2128   }
2129 
2130   // For NEON intrinsics which are overloaded on vector element type, validate
2131   // the immediate which specifies which variant to emit.
2132   unsigned ImmArg = TheCall->getNumArgs()-1;
2133   if (mask) {
2134     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
2135       return true;
2136 
2137     TV = Result.getLimitedValue(64);
2138     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
2139       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
2140              << TheCall->getArg(ImmArg)->getSourceRange();
2141   }
2142 
2143   if (PtrArgNum >= 0) {
2144     // Check that pointer arguments have the specified type.
2145     Expr *Arg = TheCall->getArg(PtrArgNum);
2146     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
2147       Arg = ICE->getSubExpr();
2148     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
2149     QualType RHSTy = RHS.get()->getType();
2150 
2151     llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
2152     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
2153                           Arch == llvm::Triple::aarch64_32 ||
2154                           Arch == llvm::Triple::aarch64_be;
2155     bool IsInt64Long =
2156         Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
2157     QualType EltTy =
2158         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
2159     if (HasConstPtr)
2160       EltTy = EltTy.withConst();
2161     QualType LHSTy = Context.getPointerType(EltTy);
2162     AssignConvertType ConvTy;
2163     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
2164     if (RHS.isInvalid())
2165       return true;
2166     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
2167                                  RHS.get(), AA_Assigning))
2168       return true;
2169   }
2170 
2171   // For NEON intrinsics which take an immediate value as part of the
2172   // instruction, range check them here.
2173   unsigned i = 0, l = 0, u = 0;
2174   switch (BuiltinID) {
2175   default:
2176     return false;
2177   #define GET_NEON_IMMEDIATE_CHECK
2178   #include "clang/Basic/arm_neon.inc"
2179   #include "clang/Basic/arm_fp16.inc"
2180   #undef GET_NEON_IMMEDIATE_CHECK
2181   }
2182 
2183   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2184 }
2185 
2186 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2187   switch (BuiltinID) {
2188   default:
2189     return false;
2190   #include "clang/Basic/arm_mve_builtin_sema.inc"
2191   }
2192 }
2193 
2194 bool Sema::CheckCDEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2195   bool Err = false;
2196   switch (BuiltinID) {
2197   default:
2198     return false;
2199 #include "clang/Basic/arm_cde_builtin_sema.inc"
2200   }
2201 
2202   if (Err)
2203     return true;
2204 
2205   return CheckARMCoprocessorImmediate(TheCall->getArg(0), /*WantCDE*/ true);
2206 }
2207 
2208 bool Sema::CheckARMCoprocessorImmediate(const Expr *CoprocArg, bool WantCDE) {
2209   if (isConstantEvaluated())
2210     return false;
2211 
2212   // We can't check the value of a dependent argument.
2213   if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent())
2214     return false;
2215 
2216   llvm::APSInt CoprocNoAP;
2217   bool IsICE = CoprocArg->isIntegerConstantExpr(CoprocNoAP, Context);
2218   (void)IsICE;
2219   assert(IsICE && "Coprocossor immediate is not a constant expression");
2220   int64_t CoprocNo = CoprocNoAP.getExtValue();
2221   assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative");
2222 
2223   uint32_t CDECoprocMask = Context.getTargetInfo().getARMCDECoprocMask();
2224   bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo));
2225 
2226   if (IsCDECoproc != WantCDE)
2227     return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc)
2228            << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange();
2229 
2230   return false;
2231 }
2232 
2233 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
2234                                         unsigned MaxWidth) {
2235   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
2236           BuiltinID == ARM::BI__builtin_arm_ldaex ||
2237           BuiltinID == ARM::BI__builtin_arm_strex ||
2238           BuiltinID == ARM::BI__builtin_arm_stlex ||
2239           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2240           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2241           BuiltinID == AArch64::BI__builtin_arm_strex ||
2242           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
2243          "unexpected ARM builtin");
2244   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
2245                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
2246                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2247                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
2248 
2249   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2250 
2251   // Ensure that we have the proper number of arguments.
2252   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
2253     return true;
2254 
2255   // Inspect the pointer argument of the atomic builtin.  This should always be
2256   // a pointer type, whose element is an integral scalar or pointer type.
2257   // Because it is a pointer type, we don't have to worry about any implicit
2258   // casts here.
2259   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
2260   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
2261   if (PointerArgRes.isInvalid())
2262     return true;
2263   PointerArg = PointerArgRes.get();
2264 
2265   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2266   if (!pointerType) {
2267     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
2268         << PointerArg->getType() << PointerArg->getSourceRange();
2269     return true;
2270   }
2271 
2272   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
2273   // task is to insert the appropriate casts into the AST. First work out just
2274   // what the appropriate type is.
2275   QualType ValType = pointerType->getPointeeType();
2276   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
2277   if (IsLdrex)
2278     AddrType.addConst();
2279 
2280   // Issue a warning if the cast is dodgy.
2281   CastKind CastNeeded = CK_NoOp;
2282   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
2283     CastNeeded = CK_BitCast;
2284     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
2285         << PointerArg->getType() << Context.getPointerType(AddrType)
2286         << AA_Passing << PointerArg->getSourceRange();
2287   }
2288 
2289   // Finally, do the cast and replace the argument with the corrected version.
2290   AddrType = Context.getPointerType(AddrType);
2291   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
2292   if (PointerArgRes.isInvalid())
2293     return true;
2294   PointerArg = PointerArgRes.get();
2295 
2296   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
2297 
2298   // In general, we allow ints, floats and pointers to be loaded and stored.
2299   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2300       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
2301     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
2302         << PointerArg->getType() << PointerArg->getSourceRange();
2303     return true;
2304   }
2305 
2306   // But ARM doesn't have instructions to deal with 128-bit versions.
2307   if (Context.getTypeSize(ValType) > MaxWidth) {
2308     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
2309     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
2310         << PointerArg->getType() << PointerArg->getSourceRange();
2311     return true;
2312   }
2313 
2314   switch (ValType.getObjCLifetime()) {
2315   case Qualifiers::OCL_None:
2316   case Qualifiers::OCL_ExplicitNone:
2317     // okay
2318     break;
2319 
2320   case Qualifiers::OCL_Weak:
2321   case Qualifiers::OCL_Strong:
2322   case Qualifiers::OCL_Autoreleasing:
2323     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
2324         << ValType << PointerArg->getSourceRange();
2325     return true;
2326   }
2327 
2328   if (IsLdrex) {
2329     TheCall->setType(ValType);
2330     return false;
2331   }
2332 
2333   // Initialize the argument to be stored.
2334   ExprResult ValArg = TheCall->getArg(0);
2335   InitializedEntity Entity = InitializedEntity::InitializeParameter(
2336       Context, ValType, /*consume*/ false);
2337   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2338   if (ValArg.isInvalid())
2339     return true;
2340   TheCall->setArg(0, ValArg.get());
2341 
2342   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
2343   // but the custom checker bypasses all default analysis.
2344   TheCall->setType(Context.IntTy);
2345   return false;
2346 }
2347 
2348 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2349   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
2350       BuiltinID == ARM::BI__builtin_arm_ldaex ||
2351       BuiltinID == ARM::BI__builtin_arm_strex ||
2352       BuiltinID == ARM::BI__builtin_arm_stlex) {
2353     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
2354   }
2355 
2356   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
2357     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2358       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
2359   }
2360 
2361   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2362       BuiltinID == ARM::BI__builtin_arm_wsr64)
2363     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
2364 
2365   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
2366       BuiltinID == ARM::BI__builtin_arm_rsrp ||
2367       BuiltinID == ARM::BI__builtin_arm_wsr ||
2368       BuiltinID == ARM::BI__builtin_arm_wsrp)
2369     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2370 
2371   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
2372     return true;
2373   if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
2374     return true;
2375   if (CheckCDEBuiltinFunctionCall(BuiltinID, TheCall))
2376     return true;
2377 
2378   // For intrinsics which take an immediate value as part of the instruction,
2379   // range check them here.
2380   // FIXME: VFP Intrinsics should error if VFP not present.
2381   switch (BuiltinID) {
2382   default: return false;
2383   case ARM::BI__builtin_arm_ssat:
2384     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
2385   case ARM::BI__builtin_arm_usat:
2386     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
2387   case ARM::BI__builtin_arm_ssat16:
2388     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
2389   case ARM::BI__builtin_arm_usat16:
2390     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2391   case ARM::BI__builtin_arm_vcvtr_f:
2392   case ARM::BI__builtin_arm_vcvtr_d:
2393     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
2394   case ARM::BI__builtin_arm_dmb:
2395   case ARM::BI__builtin_arm_dsb:
2396   case ARM::BI__builtin_arm_isb:
2397   case ARM::BI__builtin_arm_dbg:
2398     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
2399   case ARM::BI__builtin_arm_cdp:
2400   case ARM::BI__builtin_arm_cdp2:
2401   case ARM::BI__builtin_arm_mcr:
2402   case ARM::BI__builtin_arm_mcr2:
2403   case ARM::BI__builtin_arm_mrc:
2404   case ARM::BI__builtin_arm_mrc2:
2405   case ARM::BI__builtin_arm_mcrr:
2406   case ARM::BI__builtin_arm_mcrr2:
2407   case ARM::BI__builtin_arm_mrrc:
2408   case ARM::BI__builtin_arm_mrrc2:
2409   case ARM::BI__builtin_arm_ldc:
2410   case ARM::BI__builtin_arm_ldcl:
2411   case ARM::BI__builtin_arm_ldc2:
2412   case ARM::BI__builtin_arm_ldc2l:
2413   case ARM::BI__builtin_arm_stc:
2414   case ARM::BI__builtin_arm_stcl:
2415   case ARM::BI__builtin_arm_stc2:
2416   case ARM::BI__builtin_arm_stc2l:
2417     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) ||
2418            CheckARMCoprocessorImmediate(TheCall->getArg(0), /*WantCDE*/ false);
2419   }
2420 }
2421 
2422 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
2423                                          CallExpr *TheCall) {
2424   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2425       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2426       BuiltinID == AArch64::BI__builtin_arm_strex ||
2427       BuiltinID == AArch64::BI__builtin_arm_stlex) {
2428     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
2429   }
2430 
2431   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
2432     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2433       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
2434       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
2435       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
2436   }
2437 
2438   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2439       BuiltinID == AArch64::BI__builtin_arm_wsr64)
2440     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2441 
2442   // Memory Tagging Extensions (MTE) Intrinsics
2443   if (BuiltinID == AArch64::BI__builtin_arm_irg ||
2444       BuiltinID == AArch64::BI__builtin_arm_addg ||
2445       BuiltinID == AArch64::BI__builtin_arm_gmi ||
2446       BuiltinID == AArch64::BI__builtin_arm_ldg ||
2447       BuiltinID == AArch64::BI__builtin_arm_stg ||
2448       BuiltinID == AArch64::BI__builtin_arm_subp) {
2449     return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
2450   }
2451 
2452   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
2453       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2454       BuiltinID == AArch64::BI__builtin_arm_wsr ||
2455       BuiltinID == AArch64::BI__builtin_arm_wsrp)
2456     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2457 
2458   // Only check the valid encoding range. Any constant in this range would be
2459   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
2460   // an exception for incorrect registers. This matches MSVC behavior.
2461   if (BuiltinID == AArch64::BI_ReadStatusReg ||
2462       BuiltinID == AArch64::BI_WriteStatusReg)
2463     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
2464 
2465   if (BuiltinID == AArch64::BI__getReg)
2466     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
2467 
2468   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
2469     return true;
2470 
2471   if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall))
2472     return true;
2473 
2474   // For intrinsics which take an immediate value as part of the instruction,
2475   // range check them here.
2476   unsigned i = 0, l = 0, u = 0;
2477   switch (BuiltinID) {
2478   default: return false;
2479   case AArch64::BI__builtin_arm_dmb:
2480   case AArch64::BI__builtin_arm_dsb:
2481   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
2482   case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
2483   }
2484 
2485   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2486 }
2487 
2488 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
2489                                        CallExpr *TheCall) {
2490   assert((BuiltinID == BPF::BI__builtin_preserve_field_info ||
2491           BuiltinID == BPF::BI__builtin_btf_type_id) &&
2492          "unexpected ARM builtin");
2493 
2494   if (checkArgCount(*this, TheCall, 2))
2495     return true;
2496 
2497   Expr *Arg;
2498   if (BuiltinID == BPF::BI__builtin_btf_type_id) {
2499     // The second argument needs to be a constant int
2500     llvm::APSInt Value;
2501     Arg = TheCall->getArg(1);
2502     if (!Arg->isIntegerConstantExpr(Value, Context)) {
2503       Diag(Arg->getBeginLoc(), diag::err_btf_type_id_not_const)
2504           << 2 << Arg->getSourceRange();
2505       return true;
2506     }
2507 
2508     TheCall->setType(Context.UnsignedIntTy);
2509     return false;
2510   }
2511 
2512   // The first argument needs to be a record field access.
2513   // If it is an array element access, we delay decision
2514   // to BPF backend to check whether the access is a
2515   // field access or not.
2516   Arg = TheCall->getArg(0);
2517   if (Arg->getType()->getAsPlaceholderType() ||
2518       (Arg->IgnoreParens()->getObjectKind() != OK_BitField &&
2519        !dyn_cast<MemberExpr>(Arg->IgnoreParens()) &&
2520        !dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens()))) {
2521     Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_field)
2522         << 1 << Arg->getSourceRange();
2523     return true;
2524   }
2525 
2526   // The second argument needs to be a constant int
2527   Arg = TheCall->getArg(1);
2528   llvm::APSInt Value;
2529   if (!Arg->isIntegerConstantExpr(Value, Context)) {
2530     Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_const)
2531         << 2 << Arg->getSourceRange();
2532     return true;
2533   }
2534 
2535   TheCall->setType(Context.UnsignedIntTy);
2536   return false;
2537 }
2538 
2539 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2540   struct ArgInfo {
2541     uint8_t OpNum;
2542     bool IsSigned;
2543     uint8_t BitWidth;
2544     uint8_t Align;
2545   };
2546   struct BuiltinInfo {
2547     unsigned BuiltinID;
2548     ArgInfo Infos[2];
2549   };
2550 
2551   static BuiltinInfo Infos[] = {
2552     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
2553     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
2554     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
2555     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  1 }} },
2556     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
2557     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
2558     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
2559     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
2560     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
2561     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
2562     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
2563 
2564     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
2565     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
2566     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
2567     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
2568     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
2569     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
2570     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
2571     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
2572     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
2573     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
2574     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
2575 
2576     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
2577     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
2578     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
2579     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
2580     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
2581     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
2582     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
2583     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
2584     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
2585     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
2586     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
2587     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
2588     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
2589     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
2590     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
2591     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
2592     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
2593     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
2594     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
2595     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
2596     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
2597     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
2598     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
2599     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
2600     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
2601     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
2602     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
2603     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
2604     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
2605     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
2606     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
2607     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
2608     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
2609     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
2610     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
2611     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
2612     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
2613     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
2614     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
2615     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
2616     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
2617     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
2618     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
2619     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
2620     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
2621     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
2622     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
2623     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
2624     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
2625     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
2626     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
2627     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
2628                                                       {{ 1, false, 6,  0 }} },
2629     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
2630     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
2631     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
2632     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
2633     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
2634     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
2635     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
2636                                                       {{ 1, false, 5,  0 }} },
2637     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
2638     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
2639     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
2640     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
2641     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
2642     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
2643                                                        { 2, false, 5,  0 }} },
2644     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
2645                                                        { 2, false, 6,  0 }} },
2646     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
2647                                                        { 3, false, 5,  0 }} },
2648     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
2649                                                        { 3, false, 6,  0 }} },
2650     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
2651     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
2652     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
2653     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
2654     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
2655     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
2656     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
2657     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
2658     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
2659     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
2660     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
2661     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
2662     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
2663     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
2664     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
2665     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
2666                                                       {{ 2, false, 4,  0 },
2667                                                        { 3, false, 5,  0 }} },
2668     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
2669                                                       {{ 2, false, 4,  0 },
2670                                                        { 3, false, 5,  0 }} },
2671     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
2672                                                       {{ 2, false, 4,  0 },
2673                                                        { 3, false, 5,  0 }} },
2674     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
2675                                                       {{ 2, false, 4,  0 },
2676                                                        { 3, false, 5,  0 }} },
2677     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
2678     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
2679     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
2680     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
2681     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
2682     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
2683     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
2684     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
2685     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
2686     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
2687     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
2688                                                        { 2, false, 5,  0 }} },
2689     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
2690                                                        { 2, false, 6,  0 }} },
2691     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
2692     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
2693     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
2694     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
2695     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
2696     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
2697     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
2698     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
2699     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
2700                                                       {{ 1, false, 4,  0 }} },
2701     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
2702     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
2703                                                       {{ 1, false, 4,  0 }} },
2704     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
2705     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
2706     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
2707     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
2708     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
2709     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
2710     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
2711     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
2712     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
2713     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
2714     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
2715     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
2716     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
2717     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
2718     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
2719     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
2720     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
2721     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
2722     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
2723     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
2724                                                       {{ 3, false, 1,  0 }} },
2725     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
2726     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
2727     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
2728     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
2729                                                       {{ 3, false, 1,  0 }} },
2730     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
2731     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
2732     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
2733     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
2734                                                       {{ 3, false, 1,  0 }} },
2735   };
2736 
2737   // Use a dynamically initialized static to sort the table exactly once on
2738   // first run.
2739   static const bool SortOnce =
2740       (llvm::sort(Infos,
2741                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
2742                    return LHS.BuiltinID < RHS.BuiltinID;
2743                  }),
2744        true);
2745   (void)SortOnce;
2746 
2747   const BuiltinInfo *F = llvm::partition_point(
2748       Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
2749   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
2750     return false;
2751 
2752   bool Error = false;
2753 
2754   for (const ArgInfo &A : F->Infos) {
2755     // Ignore empty ArgInfo elements.
2756     if (A.BitWidth == 0)
2757       continue;
2758 
2759     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
2760     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
2761     if (!A.Align) {
2762       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
2763     } else {
2764       unsigned M = 1 << A.Align;
2765       Min *= M;
2766       Max *= M;
2767       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
2768                SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
2769     }
2770   }
2771   return Error;
2772 }
2773 
2774 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
2775                                            CallExpr *TheCall) {
2776   return CheckHexagonBuiltinArgument(BuiltinID, TheCall);
2777 }
2778 
2779 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2780   return CheckMipsBuiltinCpu(BuiltinID, TheCall) ||
2781          CheckMipsBuiltinArgument(BuiltinID, TheCall);
2782 }
2783 
2784 bool Sema::CheckMipsBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) {
2785   const TargetInfo &TI = Context.getTargetInfo();
2786 
2787   if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
2788       BuiltinID <= Mips::BI__builtin_mips_lwx) {
2789     if (!TI.hasFeature("dsp"))
2790       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
2791   }
2792 
2793   if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
2794       BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
2795     if (!TI.hasFeature("dspr2"))
2796       return Diag(TheCall->getBeginLoc(),
2797                   diag::err_mips_builtin_requires_dspr2);
2798   }
2799 
2800   if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
2801       BuiltinID <= Mips::BI__builtin_msa_xori_b) {
2802     if (!TI.hasFeature("msa"))
2803       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
2804   }
2805 
2806   return false;
2807 }
2808 
2809 // CheckMipsBuiltinArgument - Checks the constant value passed to the
2810 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
2811 // ordering for DSP is unspecified. MSA is ordered by the data format used
2812 // by the underlying instruction i.e., df/m, df/n and then by size.
2813 //
2814 // FIXME: The size tests here should instead be tablegen'd along with the
2815 //        definitions from include/clang/Basic/BuiltinsMips.def.
2816 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
2817 //        be too.
2818 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2819   unsigned i = 0, l = 0, u = 0, m = 0;
2820   switch (BuiltinID) {
2821   default: return false;
2822   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
2823   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
2824   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
2825   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
2826   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
2827   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
2828   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
2829   // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
2830   // df/m field.
2831   // These intrinsics take an unsigned 3 bit immediate.
2832   case Mips::BI__builtin_msa_bclri_b:
2833   case Mips::BI__builtin_msa_bnegi_b:
2834   case Mips::BI__builtin_msa_bseti_b:
2835   case Mips::BI__builtin_msa_sat_s_b:
2836   case Mips::BI__builtin_msa_sat_u_b:
2837   case Mips::BI__builtin_msa_slli_b:
2838   case Mips::BI__builtin_msa_srai_b:
2839   case Mips::BI__builtin_msa_srari_b:
2840   case Mips::BI__builtin_msa_srli_b:
2841   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
2842   case Mips::BI__builtin_msa_binsli_b:
2843   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
2844   // These intrinsics take an unsigned 4 bit immediate.
2845   case Mips::BI__builtin_msa_bclri_h:
2846   case Mips::BI__builtin_msa_bnegi_h:
2847   case Mips::BI__builtin_msa_bseti_h:
2848   case Mips::BI__builtin_msa_sat_s_h:
2849   case Mips::BI__builtin_msa_sat_u_h:
2850   case Mips::BI__builtin_msa_slli_h:
2851   case Mips::BI__builtin_msa_srai_h:
2852   case Mips::BI__builtin_msa_srari_h:
2853   case Mips::BI__builtin_msa_srli_h:
2854   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
2855   case Mips::BI__builtin_msa_binsli_h:
2856   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
2857   // These intrinsics take an unsigned 5 bit immediate.
2858   // The first block of intrinsics actually have an unsigned 5 bit field,
2859   // not a df/n field.
2860   case Mips::BI__builtin_msa_cfcmsa:
2861   case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
2862   case Mips::BI__builtin_msa_clei_u_b:
2863   case Mips::BI__builtin_msa_clei_u_h:
2864   case Mips::BI__builtin_msa_clei_u_w:
2865   case Mips::BI__builtin_msa_clei_u_d:
2866   case Mips::BI__builtin_msa_clti_u_b:
2867   case Mips::BI__builtin_msa_clti_u_h:
2868   case Mips::BI__builtin_msa_clti_u_w:
2869   case Mips::BI__builtin_msa_clti_u_d:
2870   case Mips::BI__builtin_msa_maxi_u_b:
2871   case Mips::BI__builtin_msa_maxi_u_h:
2872   case Mips::BI__builtin_msa_maxi_u_w:
2873   case Mips::BI__builtin_msa_maxi_u_d:
2874   case Mips::BI__builtin_msa_mini_u_b:
2875   case Mips::BI__builtin_msa_mini_u_h:
2876   case Mips::BI__builtin_msa_mini_u_w:
2877   case Mips::BI__builtin_msa_mini_u_d:
2878   case Mips::BI__builtin_msa_addvi_b:
2879   case Mips::BI__builtin_msa_addvi_h:
2880   case Mips::BI__builtin_msa_addvi_w:
2881   case Mips::BI__builtin_msa_addvi_d:
2882   case Mips::BI__builtin_msa_bclri_w:
2883   case Mips::BI__builtin_msa_bnegi_w:
2884   case Mips::BI__builtin_msa_bseti_w:
2885   case Mips::BI__builtin_msa_sat_s_w:
2886   case Mips::BI__builtin_msa_sat_u_w:
2887   case Mips::BI__builtin_msa_slli_w:
2888   case Mips::BI__builtin_msa_srai_w:
2889   case Mips::BI__builtin_msa_srari_w:
2890   case Mips::BI__builtin_msa_srli_w:
2891   case Mips::BI__builtin_msa_srlri_w:
2892   case Mips::BI__builtin_msa_subvi_b:
2893   case Mips::BI__builtin_msa_subvi_h:
2894   case Mips::BI__builtin_msa_subvi_w:
2895   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
2896   case Mips::BI__builtin_msa_binsli_w:
2897   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
2898   // These intrinsics take an unsigned 6 bit immediate.
2899   case Mips::BI__builtin_msa_bclri_d:
2900   case Mips::BI__builtin_msa_bnegi_d:
2901   case Mips::BI__builtin_msa_bseti_d:
2902   case Mips::BI__builtin_msa_sat_s_d:
2903   case Mips::BI__builtin_msa_sat_u_d:
2904   case Mips::BI__builtin_msa_slli_d:
2905   case Mips::BI__builtin_msa_srai_d:
2906   case Mips::BI__builtin_msa_srari_d:
2907   case Mips::BI__builtin_msa_srli_d:
2908   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
2909   case Mips::BI__builtin_msa_binsli_d:
2910   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
2911   // These intrinsics take a signed 5 bit immediate.
2912   case Mips::BI__builtin_msa_ceqi_b:
2913   case Mips::BI__builtin_msa_ceqi_h:
2914   case Mips::BI__builtin_msa_ceqi_w:
2915   case Mips::BI__builtin_msa_ceqi_d:
2916   case Mips::BI__builtin_msa_clti_s_b:
2917   case Mips::BI__builtin_msa_clti_s_h:
2918   case Mips::BI__builtin_msa_clti_s_w:
2919   case Mips::BI__builtin_msa_clti_s_d:
2920   case Mips::BI__builtin_msa_clei_s_b:
2921   case Mips::BI__builtin_msa_clei_s_h:
2922   case Mips::BI__builtin_msa_clei_s_w:
2923   case Mips::BI__builtin_msa_clei_s_d:
2924   case Mips::BI__builtin_msa_maxi_s_b:
2925   case Mips::BI__builtin_msa_maxi_s_h:
2926   case Mips::BI__builtin_msa_maxi_s_w:
2927   case Mips::BI__builtin_msa_maxi_s_d:
2928   case Mips::BI__builtin_msa_mini_s_b:
2929   case Mips::BI__builtin_msa_mini_s_h:
2930   case Mips::BI__builtin_msa_mini_s_w:
2931   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
2932   // These intrinsics take an unsigned 8 bit immediate.
2933   case Mips::BI__builtin_msa_andi_b:
2934   case Mips::BI__builtin_msa_nori_b:
2935   case Mips::BI__builtin_msa_ori_b:
2936   case Mips::BI__builtin_msa_shf_b:
2937   case Mips::BI__builtin_msa_shf_h:
2938   case Mips::BI__builtin_msa_shf_w:
2939   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
2940   case Mips::BI__builtin_msa_bseli_b:
2941   case Mips::BI__builtin_msa_bmnzi_b:
2942   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
2943   // df/n format
2944   // These intrinsics take an unsigned 4 bit immediate.
2945   case Mips::BI__builtin_msa_copy_s_b:
2946   case Mips::BI__builtin_msa_copy_u_b:
2947   case Mips::BI__builtin_msa_insve_b:
2948   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
2949   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
2950   // These intrinsics take an unsigned 3 bit immediate.
2951   case Mips::BI__builtin_msa_copy_s_h:
2952   case Mips::BI__builtin_msa_copy_u_h:
2953   case Mips::BI__builtin_msa_insve_h:
2954   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
2955   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
2956   // These intrinsics take an unsigned 2 bit immediate.
2957   case Mips::BI__builtin_msa_copy_s_w:
2958   case Mips::BI__builtin_msa_copy_u_w:
2959   case Mips::BI__builtin_msa_insve_w:
2960   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
2961   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
2962   // These intrinsics take an unsigned 1 bit immediate.
2963   case Mips::BI__builtin_msa_copy_s_d:
2964   case Mips::BI__builtin_msa_copy_u_d:
2965   case Mips::BI__builtin_msa_insve_d:
2966   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
2967   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
2968   // Memory offsets and immediate loads.
2969   // These intrinsics take a signed 10 bit immediate.
2970   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
2971   case Mips::BI__builtin_msa_ldi_h:
2972   case Mips::BI__builtin_msa_ldi_w:
2973   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
2974   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
2975   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
2976   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
2977   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
2978   case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break;
2979   case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break;
2980   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
2981   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
2982   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
2983   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
2984   case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break;
2985   case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break;
2986   }
2987 
2988   if (!m)
2989     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2990 
2991   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
2992          SemaBuiltinConstantArgMultiple(TheCall, i, m);
2993 }
2994 
2995 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2996   unsigned i = 0, l = 0, u = 0;
2997   bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
2998                       BuiltinID == PPC::BI__builtin_divdeu ||
2999                       BuiltinID == PPC::BI__builtin_bpermd;
3000   bool IsTarget64Bit = Context.getTargetInfo()
3001                               .getTypeWidth(Context
3002                                             .getTargetInfo()
3003                                             .getIntPtrType()) == 64;
3004   bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
3005                        BuiltinID == PPC::BI__builtin_divweu ||
3006                        BuiltinID == PPC::BI__builtin_divde ||
3007                        BuiltinID == PPC::BI__builtin_divdeu;
3008 
3009   if (Is64BitBltin && !IsTarget64Bit)
3010     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3011            << TheCall->getSourceRange();
3012 
3013   if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
3014       (BuiltinID == PPC::BI__builtin_bpermd &&
3015        !Context.getTargetInfo().hasFeature("bpermd")))
3016     return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3017            << TheCall->getSourceRange();
3018 
3019   auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool {
3020     if (!Context.getTargetInfo().hasFeature("vsx"))
3021       return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3022              << TheCall->getSourceRange();
3023     return false;
3024   };
3025 
3026   switch (BuiltinID) {
3027   default: return false;
3028   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3029   case PPC::BI__builtin_altivec_crypto_vshasigmad:
3030     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3031            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3032   case PPC::BI__builtin_altivec_dss:
3033     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
3034   case PPC::BI__builtin_tbegin:
3035   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
3036   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
3037   case PPC::BI__builtin_tabortwc:
3038   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
3039   case PPC::BI__builtin_tabortwci:
3040   case PPC::BI__builtin_tabortdci:
3041     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3042            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
3043   case PPC::BI__builtin_altivec_dst:
3044   case PPC::BI__builtin_altivec_dstt:
3045   case PPC::BI__builtin_altivec_dstst:
3046   case PPC::BI__builtin_altivec_dststt:
3047     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
3048   case PPC::BI__builtin_vsx_xxpermdi:
3049   case PPC::BI__builtin_vsx_xxsldwi:
3050     return SemaBuiltinVSX(TheCall);
3051   case PPC::BI__builtin_unpack_vector_int128:
3052     return SemaVSXCheck(TheCall) ||
3053            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3054   case PPC::BI__builtin_pack_vector_int128:
3055     return SemaVSXCheck(TheCall);
3056   }
3057   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3058 }
3059 
3060 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID,
3061                                           CallExpr *TheCall) {
3062   switch (BuiltinID) {
3063   case AMDGPU::BI__builtin_amdgcn_fence: {
3064     ExprResult Arg = TheCall->getArg(0);
3065     auto ArgExpr = Arg.get();
3066     Expr::EvalResult ArgResult;
3067 
3068     if (!ArgExpr->EvaluateAsInt(ArgResult, Context))
3069       return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int)
3070              << ArgExpr->getType();
3071     int ord = ArgResult.Val.getInt().getZExtValue();
3072 
3073     // Check valididty of memory ordering as per C11 / C++11's memody model.
3074     switch (static_cast<llvm::AtomicOrderingCABI>(ord)) {
3075     case llvm::AtomicOrderingCABI::acquire:
3076     case llvm::AtomicOrderingCABI::release:
3077     case llvm::AtomicOrderingCABI::acq_rel:
3078     case llvm::AtomicOrderingCABI::seq_cst:
3079       break;
3080     default: {
3081       return Diag(ArgExpr->getBeginLoc(),
3082                   diag::warn_atomic_op_has_invalid_memory_order)
3083              << ArgExpr->getSourceRange();
3084     }
3085     }
3086 
3087     Arg = TheCall->getArg(1);
3088     ArgExpr = Arg.get();
3089     Expr::EvalResult ArgResult1;
3090     // Check that sync scope is a constant literal
3091     if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Expr::EvaluateForCodeGen,
3092                                          Context))
3093       return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal)
3094              << ArgExpr->getType();
3095   } break;
3096   }
3097   return false;
3098 }
3099 
3100 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3101                                            CallExpr *TheCall) {
3102   if (BuiltinID == SystemZ::BI__builtin_tabort) {
3103     Expr *Arg = TheCall->getArg(0);
3104     llvm::APSInt AbortCode(32);
3105     if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
3106         AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
3107       return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
3108              << Arg->getSourceRange();
3109   }
3110 
3111   // For intrinsics which take an immediate value as part of the instruction,
3112   // range check them here.
3113   unsigned i = 0, l = 0, u = 0;
3114   switch (BuiltinID) {
3115   default: return false;
3116   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3117   case SystemZ::BI__builtin_s390_verimb:
3118   case SystemZ::BI__builtin_s390_verimh:
3119   case SystemZ::BI__builtin_s390_verimf:
3120   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
3121   case SystemZ::BI__builtin_s390_vfaeb:
3122   case SystemZ::BI__builtin_s390_vfaeh:
3123   case SystemZ::BI__builtin_s390_vfaef:
3124   case SystemZ::BI__builtin_s390_vfaebs:
3125   case SystemZ::BI__builtin_s390_vfaehs:
3126   case SystemZ::BI__builtin_s390_vfaefs:
3127   case SystemZ::BI__builtin_s390_vfaezb:
3128   case SystemZ::BI__builtin_s390_vfaezh:
3129   case SystemZ::BI__builtin_s390_vfaezf:
3130   case SystemZ::BI__builtin_s390_vfaezbs:
3131   case SystemZ::BI__builtin_s390_vfaezhs:
3132   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
3133   case SystemZ::BI__builtin_s390_vfisb:
3134   case SystemZ::BI__builtin_s390_vfidb:
3135     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3136            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3137   case SystemZ::BI__builtin_s390_vftcisb:
3138   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3139   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3140   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3141   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3142   case SystemZ::BI__builtin_s390_vstrcb:
3143   case SystemZ::BI__builtin_s390_vstrch:
3144   case SystemZ::BI__builtin_s390_vstrcf:
3145   case SystemZ::BI__builtin_s390_vstrczb:
3146   case SystemZ::BI__builtin_s390_vstrczh:
3147   case SystemZ::BI__builtin_s390_vstrczf:
3148   case SystemZ::BI__builtin_s390_vstrcbs:
3149   case SystemZ::BI__builtin_s390_vstrchs:
3150   case SystemZ::BI__builtin_s390_vstrcfs:
3151   case SystemZ::BI__builtin_s390_vstrczbs:
3152   case SystemZ::BI__builtin_s390_vstrczhs:
3153   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
3154   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3155   case SystemZ::BI__builtin_s390_vfminsb:
3156   case SystemZ::BI__builtin_s390_vfmaxsb:
3157   case SystemZ::BI__builtin_s390_vfmindb:
3158   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
3159   case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
3160   case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
3161   }
3162   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3163 }
3164 
3165 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3166 /// This checks that the target supports __builtin_cpu_supports and
3167 /// that the string argument is constant and valid.
3168 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
3169   Expr *Arg = TheCall->getArg(0);
3170 
3171   // Check if the argument is a string literal.
3172   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3173     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3174            << Arg->getSourceRange();
3175 
3176   // Check the contents of the string.
3177   StringRef Feature =
3178       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3179   if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
3180     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
3181            << Arg->getSourceRange();
3182   return false;
3183 }
3184 
3185 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3186 /// This checks that the target supports __builtin_cpu_is and
3187 /// that the string argument is constant and valid.
3188 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
3189   Expr *Arg = TheCall->getArg(0);
3190 
3191   // Check if the argument is a string literal.
3192   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3193     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3194            << Arg->getSourceRange();
3195 
3196   // Check the contents of the string.
3197   StringRef Feature =
3198       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3199   if (!S.Context.getTargetInfo().validateCpuIs(Feature))
3200     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
3201            << Arg->getSourceRange();
3202   return false;
3203 }
3204 
3205 // Check if the rounding mode is legal.
3206 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3207   // Indicates if this instruction has rounding control or just SAE.
3208   bool HasRC = false;
3209 
3210   unsigned ArgNum = 0;
3211   switch (BuiltinID) {
3212   default:
3213     return false;
3214   case X86::BI__builtin_ia32_vcvttsd2si32:
3215   case X86::BI__builtin_ia32_vcvttsd2si64:
3216   case X86::BI__builtin_ia32_vcvttsd2usi32:
3217   case X86::BI__builtin_ia32_vcvttsd2usi64:
3218   case X86::BI__builtin_ia32_vcvttss2si32:
3219   case X86::BI__builtin_ia32_vcvttss2si64:
3220   case X86::BI__builtin_ia32_vcvttss2usi32:
3221   case X86::BI__builtin_ia32_vcvttss2usi64:
3222     ArgNum = 1;
3223     break;
3224   case X86::BI__builtin_ia32_maxpd512:
3225   case X86::BI__builtin_ia32_maxps512:
3226   case X86::BI__builtin_ia32_minpd512:
3227   case X86::BI__builtin_ia32_minps512:
3228     ArgNum = 2;
3229     break;
3230   case X86::BI__builtin_ia32_cvtps2pd512_mask:
3231   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
3232   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
3233   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
3234   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
3235   case X86::BI__builtin_ia32_cvttps2dq512_mask:
3236   case X86::BI__builtin_ia32_cvttps2qq512_mask:
3237   case X86::BI__builtin_ia32_cvttps2udq512_mask:
3238   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
3239   case X86::BI__builtin_ia32_exp2pd_mask:
3240   case X86::BI__builtin_ia32_exp2ps_mask:
3241   case X86::BI__builtin_ia32_getexppd512_mask:
3242   case X86::BI__builtin_ia32_getexpps512_mask:
3243   case X86::BI__builtin_ia32_rcp28pd_mask:
3244   case X86::BI__builtin_ia32_rcp28ps_mask:
3245   case X86::BI__builtin_ia32_rsqrt28pd_mask:
3246   case X86::BI__builtin_ia32_rsqrt28ps_mask:
3247   case X86::BI__builtin_ia32_vcomisd:
3248   case X86::BI__builtin_ia32_vcomiss:
3249   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
3250     ArgNum = 3;
3251     break;
3252   case X86::BI__builtin_ia32_cmppd512_mask:
3253   case X86::BI__builtin_ia32_cmpps512_mask:
3254   case X86::BI__builtin_ia32_cmpsd_mask:
3255   case X86::BI__builtin_ia32_cmpss_mask:
3256   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
3257   case X86::BI__builtin_ia32_getexpsd128_round_mask:
3258   case X86::BI__builtin_ia32_getexpss128_round_mask:
3259   case X86::BI__builtin_ia32_getmantpd512_mask:
3260   case X86::BI__builtin_ia32_getmantps512_mask:
3261   case X86::BI__builtin_ia32_maxsd_round_mask:
3262   case X86::BI__builtin_ia32_maxss_round_mask:
3263   case X86::BI__builtin_ia32_minsd_round_mask:
3264   case X86::BI__builtin_ia32_minss_round_mask:
3265   case X86::BI__builtin_ia32_rcp28sd_round_mask:
3266   case X86::BI__builtin_ia32_rcp28ss_round_mask:
3267   case X86::BI__builtin_ia32_reducepd512_mask:
3268   case X86::BI__builtin_ia32_reduceps512_mask:
3269   case X86::BI__builtin_ia32_rndscalepd_mask:
3270   case X86::BI__builtin_ia32_rndscaleps_mask:
3271   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
3272   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
3273     ArgNum = 4;
3274     break;
3275   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3276   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3277   case X86::BI__builtin_ia32_fixupimmps512_mask:
3278   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3279   case X86::BI__builtin_ia32_fixupimmsd_mask:
3280   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3281   case X86::BI__builtin_ia32_fixupimmss_mask:
3282   case X86::BI__builtin_ia32_fixupimmss_maskz:
3283   case X86::BI__builtin_ia32_getmantsd_round_mask:
3284   case X86::BI__builtin_ia32_getmantss_round_mask:
3285   case X86::BI__builtin_ia32_rangepd512_mask:
3286   case X86::BI__builtin_ia32_rangeps512_mask:
3287   case X86::BI__builtin_ia32_rangesd128_round_mask:
3288   case X86::BI__builtin_ia32_rangess128_round_mask:
3289   case X86::BI__builtin_ia32_reducesd_mask:
3290   case X86::BI__builtin_ia32_reducess_mask:
3291   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3292   case X86::BI__builtin_ia32_rndscaless_round_mask:
3293     ArgNum = 5;
3294     break;
3295   case X86::BI__builtin_ia32_vcvtsd2si64:
3296   case X86::BI__builtin_ia32_vcvtsd2si32:
3297   case X86::BI__builtin_ia32_vcvtsd2usi32:
3298   case X86::BI__builtin_ia32_vcvtsd2usi64:
3299   case X86::BI__builtin_ia32_vcvtss2si32:
3300   case X86::BI__builtin_ia32_vcvtss2si64:
3301   case X86::BI__builtin_ia32_vcvtss2usi32:
3302   case X86::BI__builtin_ia32_vcvtss2usi64:
3303   case X86::BI__builtin_ia32_sqrtpd512:
3304   case X86::BI__builtin_ia32_sqrtps512:
3305     ArgNum = 1;
3306     HasRC = true;
3307     break;
3308   case X86::BI__builtin_ia32_addpd512:
3309   case X86::BI__builtin_ia32_addps512:
3310   case X86::BI__builtin_ia32_divpd512:
3311   case X86::BI__builtin_ia32_divps512:
3312   case X86::BI__builtin_ia32_mulpd512:
3313   case X86::BI__builtin_ia32_mulps512:
3314   case X86::BI__builtin_ia32_subpd512:
3315   case X86::BI__builtin_ia32_subps512:
3316   case X86::BI__builtin_ia32_cvtsi2sd64:
3317   case X86::BI__builtin_ia32_cvtsi2ss32:
3318   case X86::BI__builtin_ia32_cvtsi2ss64:
3319   case X86::BI__builtin_ia32_cvtusi2sd64:
3320   case X86::BI__builtin_ia32_cvtusi2ss32:
3321   case X86::BI__builtin_ia32_cvtusi2ss64:
3322     ArgNum = 2;
3323     HasRC = true;
3324     break;
3325   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
3326   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
3327   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
3328   case X86::BI__builtin_ia32_cvtpd2dq512_mask:
3329   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
3330   case X86::BI__builtin_ia32_cvtpd2udq512_mask:
3331   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
3332   case X86::BI__builtin_ia32_cvtps2dq512_mask:
3333   case X86::BI__builtin_ia32_cvtps2qq512_mask:
3334   case X86::BI__builtin_ia32_cvtps2udq512_mask:
3335   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
3336   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
3337   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
3338   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
3339   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
3340     ArgNum = 3;
3341     HasRC = true;
3342     break;
3343   case X86::BI__builtin_ia32_addss_round_mask:
3344   case X86::BI__builtin_ia32_addsd_round_mask:
3345   case X86::BI__builtin_ia32_divss_round_mask:
3346   case X86::BI__builtin_ia32_divsd_round_mask:
3347   case X86::BI__builtin_ia32_mulss_round_mask:
3348   case X86::BI__builtin_ia32_mulsd_round_mask:
3349   case X86::BI__builtin_ia32_subss_round_mask:
3350   case X86::BI__builtin_ia32_subsd_round_mask:
3351   case X86::BI__builtin_ia32_scalefpd512_mask:
3352   case X86::BI__builtin_ia32_scalefps512_mask:
3353   case X86::BI__builtin_ia32_scalefsd_round_mask:
3354   case X86::BI__builtin_ia32_scalefss_round_mask:
3355   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
3356   case X86::BI__builtin_ia32_sqrtsd_round_mask:
3357   case X86::BI__builtin_ia32_sqrtss_round_mask:
3358   case X86::BI__builtin_ia32_vfmaddsd3_mask:
3359   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
3360   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
3361   case X86::BI__builtin_ia32_vfmaddss3_mask:
3362   case X86::BI__builtin_ia32_vfmaddss3_maskz:
3363   case X86::BI__builtin_ia32_vfmaddss3_mask3:
3364   case X86::BI__builtin_ia32_vfmaddpd512_mask:
3365   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
3366   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
3367   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
3368   case X86::BI__builtin_ia32_vfmaddps512_mask:
3369   case X86::BI__builtin_ia32_vfmaddps512_maskz:
3370   case X86::BI__builtin_ia32_vfmaddps512_mask3:
3371   case X86::BI__builtin_ia32_vfmsubps512_mask3:
3372   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
3373   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
3374   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
3375   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
3376   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
3377   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
3378   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
3379   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
3380     ArgNum = 4;
3381     HasRC = true;
3382     break;
3383   }
3384 
3385   llvm::APSInt Result;
3386 
3387   // We can't check the value of a dependent argument.
3388   Expr *Arg = TheCall->getArg(ArgNum);
3389   if (Arg->isTypeDependent() || Arg->isValueDependent())
3390     return false;
3391 
3392   // Check constant-ness first.
3393   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3394     return true;
3395 
3396   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
3397   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
3398   // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
3399   // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
3400   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
3401       Result == 8/*ROUND_NO_EXC*/ ||
3402       (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
3403       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
3404     return false;
3405 
3406   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
3407          << Arg->getSourceRange();
3408 }
3409 
3410 // Check if the gather/scatter scale is legal.
3411 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
3412                                              CallExpr *TheCall) {
3413   unsigned ArgNum = 0;
3414   switch (BuiltinID) {
3415   default:
3416     return false;
3417   case X86::BI__builtin_ia32_gatherpfdpd:
3418   case X86::BI__builtin_ia32_gatherpfdps:
3419   case X86::BI__builtin_ia32_gatherpfqpd:
3420   case X86::BI__builtin_ia32_gatherpfqps:
3421   case X86::BI__builtin_ia32_scatterpfdpd:
3422   case X86::BI__builtin_ia32_scatterpfdps:
3423   case X86::BI__builtin_ia32_scatterpfqpd:
3424   case X86::BI__builtin_ia32_scatterpfqps:
3425     ArgNum = 3;
3426     break;
3427   case X86::BI__builtin_ia32_gatherd_pd:
3428   case X86::BI__builtin_ia32_gatherd_pd256:
3429   case X86::BI__builtin_ia32_gatherq_pd:
3430   case X86::BI__builtin_ia32_gatherq_pd256:
3431   case X86::BI__builtin_ia32_gatherd_ps:
3432   case X86::BI__builtin_ia32_gatherd_ps256:
3433   case X86::BI__builtin_ia32_gatherq_ps:
3434   case X86::BI__builtin_ia32_gatherq_ps256:
3435   case X86::BI__builtin_ia32_gatherd_q:
3436   case X86::BI__builtin_ia32_gatherd_q256:
3437   case X86::BI__builtin_ia32_gatherq_q:
3438   case X86::BI__builtin_ia32_gatherq_q256:
3439   case X86::BI__builtin_ia32_gatherd_d:
3440   case X86::BI__builtin_ia32_gatherd_d256:
3441   case X86::BI__builtin_ia32_gatherq_d:
3442   case X86::BI__builtin_ia32_gatherq_d256:
3443   case X86::BI__builtin_ia32_gather3div2df:
3444   case X86::BI__builtin_ia32_gather3div2di:
3445   case X86::BI__builtin_ia32_gather3div4df:
3446   case X86::BI__builtin_ia32_gather3div4di:
3447   case X86::BI__builtin_ia32_gather3div4sf:
3448   case X86::BI__builtin_ia32_gather3div4si:
3449   case X86::BI__builtin_ia32_gather3div8sf:
3450   case X86::BI__builtin_ia32_gather3div8si:
3451   case X86::BI__builtin_ia32_gather3siv2df:
3452   case X86::BI__builtin_ia32_gather3siv2di:
3453   case X86::BI__builtin_ia32_gather3siv4df:
3454   case X86::BI__builtin_ia32_gather3siv4di:
3455   case X86::BI__builtin_ia32_gather3siv4sf:
3456   case X86::BI__builtin_ia32_gather3siv4si:
3457   case X86::BI__builtin_ia32_gather3siv8sf:
3458   case X86::BI__builtin_ia32_gather3siv8si:
3459   case X86::BI__builtin_ia32_gathersiv8df:
3460   case X86::BI__builtin_ia32_gathersiv16sf:
3461   case X86::BI__builtin_ia32_gatherdiv8df:
3462   case X86::BI__builtin_ia32_gatherdiv16sf:
3463   case X86::BI__builtin_ia32_gathersiv8di:
3464   case X86::BI__builtin_ia32_gathersiv16si:
3465   case X86::BI__builtin_ia32_gatherdiv8di:
3466   case X86::BI__builtin_ia32_gatherdiv16si:
3467   case X86::BI__builtin_ia32_scatterdiv2df:
3468   case X86::BI__builtin_ia32_scatterdiv2di:
3469   case X86::BI__builtin_ia32_scatterdiv4df:
3470   case X86::BI__builtin_ia32_scatterdiv4di:
3471   case X86::BI__builtin_ia32_scatterdiv4sf:
3472   case X86::BI__builtin_ia32_scatterdiv4si:
3473   case X86::BI__builtin_ia32_scatterdiv8sf:
3474   case X86::BI__builtin_ia32_scatterdiv8si:
3475   case X86::BI__builtin_ia32_scattersiv2df:
3476   case X86::BI__builtin_ia32_scattersiv2di:
3477   case X86::BI__builtin_ia32_scattersiv4df:
3478   case X86::BI__builtin_ia32_scattersiv4di:
3479   case X86::BI__builtin_ia32_scattersiv4sf:
3480   case X86::BI__builtin_ia32_scattersiv4si:
3481   case X86::BI__builtin_ia32_scattersiv8sf:
3482   case X86::BI__builtin_ia32_scattersiv8si:
3483   case X86::BI__builtin_ia32_scattersiv8df:
3484   case X86::BI__builtin_ia32_scattersiv16sf:
3485   case X86::BI__builtin_ia32_scatterdiv8df:
3486   case X86::BI__builtin_ia32_scatterdiv16sf:
3487   case X86::BI__builtin_ia32_scattersiv8di:
3488   case X86::BI__builtin_ia32_scattersiv16si:
3489   case X86::BI__builtin_ia32_scatterdiv8di:
3490   case X86::BI__builtin_ia32_scatterdiv16si:
3491     ArgNum = 4;
3492     break;
3493   }
3494 
3495   llvm::APSInt Result;
3496 
3497   // We can't check the value of a dependent argument.
3498   Expr *Arg = TheCall->getArg(ArgNum);
3499   if (Arg->isTypeDependent() || Arg->isValueDependent())
3500     return false;
3501 
3502   // Check constant-ness first.
3503   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3504     return true;
3505 
3506   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
3507     return false;
3508 
3509   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
3510          << Arg->getSourceRange();
3511 }
3512 
3513 static bool isX86_32Builtin(unsigned BuiltinID) {
3514   // These builtins only work on x86-32 targets.
3515   switch (BuiltinID) {
3516   case X86::BI__builtin_ia32_readeflags_u32:
3517   case X86::BI__builtin_ia32_writeeflags_u32:
3518     return true;
3519   }
3520 
3521   return false;
3522 }
3523 
3524 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3525   if (BuiltinID == X86::BI__builtin_cpu_supports)
3526     return SemaBuiltinCpuSupports(*this, TheCall);
3527 
3528   if (BuiltinID == X86::BI__builtin_cpu_is)
3529     return SemaBuiltinCpuIs(*this, TheCall);
3530 
3531   // Check for 32-bit only builtins on a 64-bit target.
3532   const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3533   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
3534     return Diag(TheCall->getCallee()->getBeginLoc(),
3535                 diag::err_32_bit_builtin_64_bit_tgt);
3536 
3537   // If the intrinsic has rounding or SAE make sure its valid.
3538   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
3539     return true;
3540 
3541   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
3542   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
3543     return true;
3544 
3545   // For intrinsics which take an immediate value as part of the instruction,
3546   // range check them here.
3547   int i = 0, l = 0, u = 0;
3548   switch (BuiltinID) {
3549   default:
3550     return false;
3551   case X86::BI__builtin_ia32_vec_ext_v2si:
3552   case X86::BI__builtin_ia32_vec_ext_v2di:
3553   case X86::BI__builtin_ia32_vextractf128_pd256:
3554   case X86::BI__builtin_ia32_vextractf128_ps256:
3555   case X86::BI__builtin_ia32_vextractf128_si256:
3556   case X86::BI__builtin_ia32_extract128i256:
3557   case X86::BI__builtin_ia32_extractf64x4_mask:
3558   case X86::BI__builtin_ia32_extracti64x4_mask:
3559   case X86::BI__builtin_ia32_extractf32x8_mask:
3560   case X86::BI__builtin_ia32_extracti32x8_mask:
3561   case X86::BI__builtin_ia32_extractf64x2_256_mask:
3562   case X86::BI__builtin_ia32_extracti64x2_256_mask:
3563   case X86::BI__builtin_ia32_extractf32x4_256_mask:
3564   case X86::BI__builtin_ia32_extracti32x4_256_mask:
3565     i = 1; l = 0; u = 1;
3566     break;
3567   case X86::BI__builtin_ia32_vec_set_v2di:
3568   case X86::BI__builtin_ia32_vinsertf128_pd256:
3569   case X86::BI__builtin_ia32_vinsertf128_ps256:
3570   case X86::BI__builtin_ia32_vinsertf128_si256:
3571   case X86::BI__builtin_ia32_insert128i256:
3572   case X86::BI__builtin_ia32_insertf32x8:
3573   case X86::BI__builtin_ia32_inserti32x8:
3574   case X86::BI__builtin_ia32_insertf64x4:
3575   case X86::BI__builtin_ia32_inserti64x4:
3576   case X86::BI__builtin_ia32_insertf64x2_256:
3577   case X86::BI__builtin_ia32_inserti64x2_256:
3578   case X86::BI__builtin_ia32_insertf32x4_256:
3579   case X86::BI__builtin_ia32_inserti32x4_256:
3580     i = 2; l = 0; u = 1;
3581     break;
3582   case X86::BI__builtin_ia32_vpermilpd:
3583   case X86::BI__builtin_ia32_vec_ext_v4hi:
3584   case X86::BI__builtin_ia32_vec_ext_v4si:
3585   case X86::BI__builtin_ia32_vec_ext_v4sf:
3586   case X86::BI__builtin_ia32_vec_ext_v4di:
3587   case X86::BI__builtin_ia32_extractf32x4_mask:
3588   case X86::BI__builtin_ia32_extracti32x4_mask:
3589   case X86::BI__builtin_ia32_extractf64x2_512_mask:
3590   case X86::BI__builtin_ia32_extracti64x2_512_mask:
3591     i = 1; l = 0; u = 3;
3592     break;
3593   case X86::BI_mm_prefetch:
3594   case X86::BI__builtin_ia32_vec_ext_v8hi:
3595   case X86::BI__builtin_ia32_vec_ext_v8si:
3596     i = 1; l = 0; u = 7;
3597     break;
3598   case X86::BI__builtin_ia32_sha1rnds4:
3599   case X86::BI__builtin_ia32_blendpd:
3600   case X86::BI__builtin_ia32_shufpd:
3601   case X86::BI__builtin_ia32_vec_set_v4hi:
3602   case X86::BI__builtin_ia32_vec_set_v4si:
3603   case X86::BI__builtin_ia32_vec_set_v4di:
3604   case X86::BI__builtin_ia32_shuf_f32x4_256:
3605   case X86::BI__builtin_ia32_shuf_f64x2_256:
3606   case X86::BI__builtin_ia32_shuf_i32x4_256:
3607   case X86::BI__builtin_ia32_shuf_i64x2_256:
3608   case X86::BI__builtin_ia32_insertf64x2_512:
3609   case X86::BI__builtin_ia32_inserti64x2_512:
3610   case X86::BI__builtin_ia32_insertf32x4:
3611   case X86::BI__builtin_ia32_inserti32x4:
3612     i = 2; l = 0; u = 3;
3613     break;
3614   case X86::BI__builtin_ia32_vpermil2pd:
3615   case X86::BI__builtin_ia32_vpermil2pd256:
3616   case X86::BI__builtin_ia32_vpermil2ps:
3617   case X86::BI__builtin_ia32_vpermil2ps256:
3618     i = 3; l = 0; u = 3;
3619     break;
3620   case X86::BI__builtin_ia32_cmpb128_mask:
3621   case X86::BI__builtin_ia32_cmpw128_mask:
3622   case X86::BI__builtin_ia32_cmpd128_mask:
3623   case X86::BI__builtin_ia32_cmpq128_mask:
3624   case X86::BI__builtin_ia32_cmpb256_mask:
3625   case X86::BI__builtin_ia32_cmpw256_mask:
3626   case X86::BI__builtin_ia32_cmpd256_mask:
3627   case X86::BI__builtin_ia32_cmpq256_mask:
3628   case X86::BI__builtin_ia32_cmpb512_mask:
3629   case X86::BI__builtin_ia32_cmpw512_mask:
3630   case X86::BI__builtin_ia32_cmpd512_mask:
3631   case X86::BI__builtin_ia32_cmpq512_mask:
3632   case X86::BI__builtin_ia32_ucmpb128_mask:
3633   case X86::BI__builtin_ia32_ucmpw128_mask:
3634   case X86::BI__builtin_ia32_ucmpd128_mask:
3635   case X86::BI__builtin_ia32_ucmpq128_mask:
3636   case X86::BI__builtin_ia32_ucmpb256_mask:
3637   case X86::BI__builtin_ia32_ucmpw256_mask:
3638   case X86::BI__builtin_ia32_ucmpd256_mask:
3639   case X86::BI__builtin_ia32_ucmpq256_mask:
3640   case X86::BI__builtin_ia32_ucmpb512_mask:
3641   case X86::BI__builtin_ia32_ucmpw512_mask:
3642   case X86::BI__builtin_ia32_ucmpd512_mask:
3643   case X86::BI__builtin_ia32_ucmpq512_mask:
3644   case X86::BI__builtin_ia32_vpcomub:
3645   case X86::BI__builtin_ia32_vpcomuw:
3646   case X86::BI__builtin_ia32_vpcomud:
3647   case X86::BI__builtin_ia32_vpcomuq:
3648   case X86::BI__builtin_ia32_vpcomb:
3649   case X86::BI__builtin_ia32_vpcomw:
3650   case X86::BI__builtin_ia32_vpcomd:
3651   case X86::BI__builtin_ia32_vpcomq:
3652   case X86::BI__builtin_ia32_vec_set_v8hi:
3653   case X86::BI__builtin_ia32_vec_set_v8si:
3654     i = 2; l = 0; u = 7;
3655     break;
3656   case X86::BI__builtin_ia32_vpermilpd256:
3657   case X86::BI__builtin_ia32_roundps:
3658   case X86::BI__builtin_ia32_roundpd:
3659   case X86::BI__builtin_ia32_roundps256:
3660   case X86::BI__builtin_ia32_roundpd256:
3661   case X86::BI__builtin_ia32_getmantpd128_mask:
3662   case X86::BI__builtin_ia32_getmantpd256_mask:
3663   case X86::BI__builtin_ia32_getmantps128_mask:
3664   case X86::BI__builtin_ia32_getmantps256_mask:
3665   case X86::BI__builtin_ia32_getmantpd512_mask:
3666   case X86::BI__builtin_ia32_getmantps512_mask:
3667   case X86::BI__builtin_ia32_vec_ext_v16qi:
3668   case X86::BI__builtin_ia32_vec_ext_v16hi:
3669     i = 1; l = 0; u = 15;
3670     break;
3671   case X86::BI__builtin_ia32_pblendd128:
3672   case X86::BI__builtin_ia32_blendps:
3673   case X86::BI__builtin_ia32_blendpd256:
3674   case X86::BI__builtin_ia32_shufpd256:
3675   case X86::BI__builtin_ia32_roundss:
3676   case X86::BI__builtin_ia32_roundsd:
3677   case X86::BI__builtin_ia32_rangepd128_mask:
3678   case X86::BI__builtin_ia32_rangepd256_mask:
3679   case X86::BI__builtin_ia32_rangepd512_mask:
3680   case X86::BI__builtin_ia32_rangeps128_mask:
3681   case X86::BI__builtin_ia32_rangeps256_mask:
3682   case X86::BI__builtin_ia32_rangeps512_mask:
3683   case X86::BI__builtin_ia32_getmantsd_round_mask:
3684   case X86::BI__builtin_ia32_getmantss_round_mask:
3685   case X86::BI__builtin_ia32_vec_set_v16qi:
3686   case X86::BI__builtin_ia32_vec_set_v16hi:
3687     i = 2; l = 0; u = 15;
3688     break;
3689   case X86::BI__builtin_ia32_vec_ext_v32qi:
3690     i = 1; l = 0; u = 31;
3691     break;
3692   case X86::BI__builtin_ia32_cmpps:
3693   case X86::BI__builtin_ia32_cmpss:
3694   case X86::BI__builtin_ia32_cmppd:
3695   case X86::BI__builtin_ia32_cmpsd:
3696   case X86::BI__builtin_ia32_cmpps256:
3697   case X86::BI__builtin_ia32_cmppd256:
3698   case X86::BI__builtin_ia32_cmpps128_mask:
3699   case X86::BI__builtin_ia32_cmppd128_mask:
3700   case X86::BI__builtin_ia32_cmpps256_mask:
3701   case X86::BI__builtin_ia32_cmppd256_mask:
3702   case X86::BI__builtin_ia32_cmpps512_mask:
3703   case X86::BI__builtin_ia32_cmppd512_mask:
3704   case X86::BI__builtin_ia32_cmpsd_mask:
3705   case X86::BI__builtin_ia32_cmpss_mask:
3706   case X86::BI__builtin_ia32_vec_set_v32qi:
3707     i = 2; l = 0; u = 31;
3708     break;
3709   case X86::BI__builtin_ia32_permdf256:
3710   case X86::BI__builtin_ia32_permdi256:
3711   case X86::BI__builtin_ia32_permdf512:
3712   case X86::BI__builtin_ia32_permdi512:
3713   case X86::BI__builtin_ia32_vpermilps:
3714   case X86::BI__builtin_ia32_vpermilps256:
3715   case X86::BI__builtin_ia32_vpermilpd512:
3716   case X86::BI__builtin_ia32_vpermilps512:
3717   case X86::BI__builtin_ia32_pshufd:
3718   case X86::BI__builtin_ia32_pshufd256:
3719   case X86::BI__builtin_ia32_pshufd512:
3720   case X86::BI__builtin_ia32_pshufhw:
3721   case X86::BI__builtin_ia32_pshufhw256:
3722   case X86::BI__builtin_ia32_pshufhw512:
3723   case X86::BI__builtin_ia32_pshuflw:
3724   case X86::BI__builtin_ia32_pshuflw256:
3725   case X86::BI__builtin_ia32_pshuflw512:
3726   case X86::BI__builtin_ia32_vcvtps2ph:
3727   case X86::BI__builtin_ia32_vcvtps2ph_mask:
3728   case X86::BI__builtin_ia32_vcvtps2ph256:
3729   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
3730   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
3731   case X86::BI__builtin_ia32_rndscaleps_128_mask:
3732   case X86::BI__builtin_ia32_rndscalepd_128_mask:
3733   case X86::BI__builtin_ia32_rndscaleps_256_mask:
3734   case X86::BI__builtin_ia32_rndscalepd_256_mask:
3735   case X86::BI__builtin_ia32_rndscaleps_mask:
3736   case X86::BI__builtin_ia32_rndscalepd_mask:
3737   case X86::BI__builtin_ia32_reducepd128_mask:
3738   case X86::BI__builtin_ia32_reducepd256_mask:
3739   case X86::BI__builtin_ia32_reducepd512_mask:
3740   case X86::BI__builtin_ia32_reduceps128_mask:
3741   case X86::BI__builtin_ia32_reduceps256_mask:
3742   case X86::BI__builtin_ia32_reduceps512_mask:
3743   case X86::BI__builtin_ia32_prold512:
3744   case X86::BI__builtin_ia32_prolq512:
3745   case X86::BI__builtin_ia32_prold128:
3746   case X86::BI__builtin_ia32_prold256:
3747   case X86::BI__builtin_ia32_prolq128:
3748   case X86::BI__builtin_ia32_prolq256:
3749   case X86::BI__builtin_ia32_prord512:
3750   case X86::BI__builtin_ia32_prorq512:
3751   case X86::BI__builtin_ia32_prord128:
3752   case X86::BI__builtin_ia32_prord256:
3753   case X86::BI__builtin_ia32_prorq128:
3754   case X86::BI__builtin_ia32_prorq256:
3755   case X86::BI__builtin_ia32_fpclasspd128_mask:
3756   case X86::BI__builtin_ia32_fpclasspd256_mask:
3757   case X86::BI__builtin_ia32_fpclassps128_mask:
3758   case X86::BI__builtin_ia32_fpclassps256_mask:
3759   case X86::BI__builtin_ia32_fpclassps512_mask:
3760   case X86::BI__builtin_ia32_fpclasspd512_mask:
3761   case X86::BI__builtin_ia32_fpclasssd_mask:
3762   case X86::BI__builtin_ia32_fpclassss_mask:
3763   case X86::BI__builtin_ia32_pslldqi128_byteshift:
3764   case X86::BI__builtin_ia32_pslldqi256_byteshift:
3765   case X86::BI__builtin_ia32_pslldqi512_byteshift:
3766   case X86::BI__builtin_ia32_psrldqi128_byteshift:
3767   case X86::BI__builtin_ia32_psrldqi256_byteshift:
3768   case X86::BI__builtin_ia32_psrldqi512_byteshift:
3769   case X86::BI__builtin_ia32_kshiftliqi:
3770   case X86::BI__builtin_ia32_kshiftlihi:
3771   case X86::BI__builtin_ia32_kshiftlisi:
3772   case X86::BI__builtin_ia32_kshiftlidi:
3773   case X86::BI__builtin_ia32_kshiftriqi:
3774   case X86::BI__builtin_ia32_kshiftrihi:
3775   case X86::BI__builtin_ia32_kshiftrisi:
3776   case X86::BI__builtin_ia32_kshiftridi:
3777     i = 1; l = 0; u = 255;
3778     break;
3779   case X86::BI__builtin_ia32_vperm2f128_pd256:
3780   case X86::BI__builtin_ia32_vperm2f128_ps256:
3781   case X86::BI__builtin_ia32_vperm2f128_si256:
3782   case X86::BI__builtin_ia32_permti256:
3783   case X86::BI__builtin_ia32_pblendw128:
3784   case X86::BI__builtin_ia32_pblendw256:
3785   case X86::BI__builtin_ia32_blendps256:
3786   case X86::BI__builtin_ia32_pblendd256:
3787   case X86::BI__builtin_ia32_palignr128:
3788   case X86::BI__builtin_ia32_palignr256:
3789   case X86::BI__builtin_ia32_palignr512:
3790   case X86::BI__builtin_ia32_alignq512:
3791   case X86::BI__builtin_ia32_alignd512:
3792   case X86::BI__builtin_ia32_alignd128:
3793   case X86::BI__builtin_ia32_alignd256:
3794   case X86::BI__builtin_ia32_alignq128:
3795   case X86::BI__builtin_ia32_alignq256:
3796   case X86::BI__builtin_ia32_vcomisd:
3797   case X86::BI__builtin_ia32_vcomiss:
3798   case X86::BI__builtin_ia32_shuf_f32x4:
3799   case X86::BI__builtin_ia32_shuf_f64x2:
3800   case X86::BI__builtin_ia32_shuf_i32x4:
3801   case X86::BI__builtin_ia32_shuf_i64x2:
3802   case X86::BI__builtin_ia32_shufpd512:
3803   case X86::BI__builtin_ia32_shufps:
3804   case X86::BI__builtin_ia32_shufps256:
3805   case X86::BI__builtin_ia32_shufps512:
3806   case X86::BI__builtin_ia32_dbpsadbw128:
3807   case X86::BI__builtin_ia32_dbpsadbw256:
3808   case X86::BI__builtin_ia32_dbpsadbw512:
3809   case X86::BI__builtin_ia32_vpshldd128:
3810   case X86::BI__builtin_ia32_vpshldd256:
3811   case X86::BI__builtin_ia32_vpshldd512:
3812   case X86::BI__builtin_ia32_vpshldq128:
3813   case X86::BI__builtin_ia32_vpshldq256:
3814   case X86::BI__builtin_ia32_vpshldq512:
3815   case X86::BI__builtin_ia32_vpshldw128:
3816   case X86::BI__builtin_ia32_vpshldw256:
3817   case X86::BI__builtin_ia32_vpshldw512:
3818   case X86::BI__builtin_ia32_vpshrdd128:
3819   case X86::BI__builtin_ia32_vpshrdd256:
3820   case X86::BI__builtin_ia32_vpshrdd512:
3821   case X86::BI__builtin_ia32_vpshrdq128:
3822   case X86::BI__builtin_ia32_vpshrdq256:
3823   case X86::BI__builtin_ia32_vpshrdq512:
3824   case X86::BI__builtin_ia32_vpshrdw128:
3825   case X86::BI__builtin_ia32_vpshrdw256:
3826   case X86::BI__builtin_ia32_vpshrdw512:
3827     i = 2; l = 0; u = 255;
3828     break;
3829   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3830   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3831   case X86::BI__builtin_ia32_fixupimmps512_mask:
3832   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3833   case X86::BI__builtin_ia32_fixupimmsd_mask:
3834   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3835   case X86::BI__builtin_ia32_fixupimmss_mask:
3836   case X86::BI__builtin_ia32_fixupimmss_maskz:
3837   case X86::BI__builtin_ia32_fixupimmpd128_mask:
3838   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
3839   case X86::BI__builtin_ia32_fixupimmpd256_mask:
3840   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
3841   case X86::BI__builtin_ia32_fixupimmps128_mask:
3842   case X86::BI__builtin_ia32_fixupimmps128_maskz:
3843   case X86::BI__builtin_ia32_fixupimmps256_mask:
3844   case X86::BI__builtin_ia32_fixupimmps256_maskz:
3845   case X86::BI__builtin_ia32_pternlogd512_mask:
3846   case X86::BI__builtin_ia32_pternlogd512_maskz:
3847   case X86::BI__builtin_ia32_pternlogq512_mask:
3848   case X86::BI__builtin_ia32_pternlogq512_maskz:
3849   case X86::BI__builtin_ia32_pternlogd128_mask:
3850   case X86::BI__builtin_ia32_pternlogd128_maskz:
3851   case X86::BI__builtin_ia32_pternlogd256_mask:
3852   case X86::BI__builtin_ia32_pternlogd256_maskz:
3853   case X86::BI__builtin_ia32_pternlogq128_mask:
3854   case X86::BI__builtin_ia32_pternlogq128_maskz:
3855   case X86::BI__builtin_ia32_pternlogq256_mask:
3856   case X86::BI__builtin_ia32_pternlogq256_maskz:
3857     i = 3; l = 0; u = 255;
3858     break;
3859   case X86::BI__builtin_ia32_gatherpfdpd:
3860   case X86::BI__builtin_ia32_gatherpfdps:
3861   case X86::BI__builtin_ia32_gatherpfqpd:
3862   case X86::BI__builtin_ia32_gatherpfqps:
3863   case X86::BI__builtin_ia32_scatterpfdpd:
3864   case X86::BI__builtin_ia32_scatterpfdps:
3865   case X86::BI__builtin_ia32_scatterpfqpd:
3866   case X86::BI__builtin_ia32_scatterpfqps:
3867     i = 4; l = 2; u = 3;
3868     break;
3869   case X86::BI__builtin_ia32_reducesd_mask:
3870   case X86::BI__builtin_ia32_reducess_mask:
3871   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3872   case X86::BI__builtin_ia32_rndscaless_round_mask:
3873     i = 4; l = 0; u = 255;
3874     break;
3875   }
3876 
3877   // Note that we don't force a hard error on the range check here, allowing
3878   // template-generated or macro-generated dead code to potentially have out-of-
3879   // range values. These need to code generate, but don't need to necessarily
3880   // make any sense. We use a warning that defaults to an error.
3881   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
3882 }
3883 
3884 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
3885 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
3886 /// Returns true when the format fits the function and the FormatStringInfo has
3887 /// been populated.
3888 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
3889                                FormatStringInfo *FSI) {
3890   FSI->HasVAListArg = Format->getFirstArg() == 0;
3891   FSI->FormatIdx = Format->getFormatIdx() - 1;
3892   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
3893 
3894   // The way the format attribute works in GCC, the implicit this argument
3895   // of member functions is counted. However, it doesn't appear in our own
3896   // lists, so decrement format_idx in that case.
3897   if (IsCXXMember) {
3898     if(FSI->FormatIdx == 0)
3899       return false;
3900     --FSI->FormatIdx;
3901     if (FSI->FirstDataArg != 0)
3902       --FSI->FirstDataArg;
3903   }
3904   return true;
3905 }
3906 
3907 /// Checks if a the given expression evaluates to null.
3908 ///
3909 /// Returns true if the value evaluates to null.
3910 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
3911   // If the expression has non-null type, it doesn't evaluate to null.
3912   if (auto nullability
3913         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
3914     if (*nullability == NullabilityKind::NonNull)
3915       return false;
3916   }
3917 
3918   // As a special case, transparent unions initialized with zero are
3919   // considered null for the purposes of the nonnull attribute.
3920   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
3921     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
3922       if (const CompoundLiteralExpr *CLE =
3923           dyn_cast<CompoundLiteralExpr>(Expr))
3924         if (const InitListExpr *ILE =
3925             dyn_cast<InitListExpr>(CLE->getInitializer()))
3926           Expr = ILE->getInit(0);
3927   }
3928 
3929   bool Result;
3930   return (!Expr->isValueDependent() &&
3931           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
3932           !Result);
3933 }
3934 
3935 static void CheckNonNullArgument(Sema &S,
3936                                  const Expr *ArgExpr,
3937                                  SourceLocation CallSiteLoc) {
3938   if (CheckNonNullExpr(S, ArgExpr))
3939     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
3940                           S.PDiag(diag::warn_null_arg)
3941                               << ArgExpr->getSourceRange());
3942 }
3943 
3944 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
3945   FormatStringInfo FSI;
3946   if ((GetFormatStringType(Format) == FST_NSString) &&
3947       getFormatStringInfo(Format, false, &FSI)) {
3948     Idx = FSI.FormatIdx;
3949     return true;
3950   }
3951   return false;
3952 }
3953 
3954 /// Diagnose use of %s directive in an NSString which is being passed
3955 /// as formatting string to formatting method.
3956 static void
3957 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
3958                                         const NamedDecl *FDecl,
3959                                         Expr **Args,
3960                                         unsigned NumArgs) {
3961   unsigned Idx = 0;
3962   bool Format = false;
3963   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
3964   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
3965     Idx = 2;
3966     Format = true;
3967   }
3968   else
3969     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
3970       if (S.GetFormatNSStringIdx(I, Idx)) {
3971         Format = true;
3972         break;
3973       }
3974     }
3975   if (!Format || NumArgs <= Idx)
3976     return;
3977   const Expr *FormatExpr = Args[Idx];
3978   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
3979     FormatExpr = CSCE->getSubExpr();
3980   const StringLiteral *FormatString;
3981   if (const ObjCStringLiteral *OSL =
3982       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
3983     FormatString = OSL->getString();
3984   else
3985     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
3986   if (!FormatString)
3987     return;
3988   if (S.FormatStringHasSArg(FormatString)) {
3989     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
3990       << "%s" << 1 << 1;
3991     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
3992       << FDecl->getDeclName();
3993   }
3994 }
3995 
3996 /// Determine whether the given type has a non-null nullability annotation.
3997 static bool isNonNullType(ASTContext &ctx, QualType type) {
3998   if (auto nullability = type->getNullability(ctx))
3999     return *nullability == NullabilityKind::NonNull;
4000 
4001   return false;
4002 }
4003 
4004 static void CheckNonNullArguments(Sema &S,
4005                                   const NamedDecl *FDecl,
4006                                   const FunctionProtoType *Proto,
4007                                   ArrayRef<const Expr *> Args,
4008                                   SourceLocation CallSiteLoc) {
4009   assert((FDecl || Proto) && "Need a function declaration or prototype");
4010 
4011   // Already checked by by constant evaluator.
4012   if (S.isConstantEvaluated())
4013     return;
4014   // Check the attributes attached to the method/function itself.
4015   llvm::SmallBitVector NonNullArgs;
4016   if (FDecl) {
4017     // Handle the nonnull attribute on the function/method declaration itself.
4018     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4019       if (!NonNull->args_size()) {
4020         // Easy case: all pointer arguments are nonnull.
4021         for (const auto *Arg : Args)
4022           if (S.isValidPointerAttrType(Arg->getType()))
4023             CheckNonNullArgument(S, Arg, CallSiteLoc);
4024         return;
4025       }
4026 
4027       for (const ParamIdx &Idx : NonNull->args()) {
4028         unsigned IdxAST = Idx.getASTIndex();
4029         if (IdxAST >= Args.size())
4030           continue;
4031         if (NonNullArgs.empty())
4032           NonNullArgs.resize(Args.size());
4033         NonNullArgs.set(IdxAST);
4034       }
4035     }
4036   }
4037 
4038   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4039     // Handle the nonnull attribute on the parameters of the
4040     // function/method.
4041     ArrayRef<ParmVarDecl*> parms;
4042     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4043       parms = FD->parameters();
4044     else
4045       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4046 
4047     unsigned ParamIndex = 0;
4048     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4049          I != E; ++I, ++ParamIndex) {
4050       const ParmVarDecl *PVD = *I;
4051       if (PVD->hasAttr<NonNullAttr>() ||
4052           isNonNullType(S.Context, PVD->getType())) {
4053         if (NonNullArgs.empty())
4054           NonNullArgs.resize(Args.size());
4055 
4056         NonNullArgs.set(ParamIndex);
4057       }
4058     }
4059   } else {
4060     // If we have a non-function, non-method declaration but no
4061     // function prototype, try to dig out the function prototype.
4062     if (!Proto) {
4063       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4064         QualType type = VD->getType().getNonReferenceType();
4065         if (auto pointerType = type->getAs<PointerType>())
4066           type = pointerType->getPointeeType();
4067         else if (auto blockType = type->getAs<BlockPointerType>())
4068           type = blockType->getPointeeType();
4069         // FIXME: data member pointers?
4070 
4071         // Dig out the function prototype, if there is one.
4072         Proto = type->getAs<FunctionProtoType>();
4073       }
4074     }
4075 
4076     // Fill in non-null argument information from the nullability
4077     // information on the parameter types (if we have them).
4078     if (Proto) {
4079       unsigned Index = 0;
4080       for (auto paramType : Proto->getParamTypes()) {
4081         if (isNonNullType(S.Context, paramType)) {
4082           if (NonNullArgs.empty())
4083             NonNullArgs.resize(Args.size());
4084 
4085           NonNullArgs.set(Index);
4086         }
4087 
4088         ++Index;
4089       }
4090     }
4091   }
4092 
4093   // Check for non-null arguments.
4094   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4095        ArgIndex != ArgIndexEnd; ++ArgIndex) {
4096     if (NonNullArgs[ArgIndex])
4097       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
4098   }
4099 }
4100 
4101 /// Handles the checks for format strings, non-POD arguments to vararg
4102 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
4103 /// attributes.
4104 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
4105                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
4106                      bool IsMemberFunction, SourceLocation Loc,
4107                      SourceRange Range, VariadicCallType CallType) {
4108   // FIXME: We should check as much as we can in the template definition.
4109   if (CurContext->isDependentContext())
4110     return;
4111 
4112   // Printf and scanf checking.
4113   llvm::SmallBitVector CheckedVarArgs;
4114   if (FDecl) {
4115     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4116       // Only create vector if there are format attributes.
4117       CheckedVarArgs.resize(Args.size());
4118 
4119       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4120                            CheckedVarArgs);
4121     }
4122   }
4123 
4124   // Refuse POD arguments that weren't caught by the format string
4125   // checks above.
4126   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4127   if (CallType != VariadicDoesNotApply &&
4128       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4129     unsigned NumParams = Proto ? Proto->getNumParams()
4130                        : FDecl && isa<FunctionDecl>(FDecl)
4131                            ? cast<FunctionDecl>(FDecl)->getNumParams()
4132                        : FDecl && isa<ObjCMethodDecl>(FDecl)
4133                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
4134                        : 0;
4135 
4136     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4137       // Args[ArgIdx] can be null in malformed code.
4138       if (const Expr *Arg = Args[ArgIdx]) {
4139         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4140           checkVariadicArgument(Arg, CallType);
4141       }
4142     }
4143   }
4144 
4145   if (FDecl || Proto) {
4146     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4147 
4148     // Type safety checking.
4149     if (FDecl) {
4150       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4151         CheckArgumentWithTypeTag(I, Args, Loc);
4152     }
4153   }
4154 
4155   if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
4156     auto *AA = FDecl->getAttr<AllocAlignAttr>();
4157     const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
4158     if (!Arg->isValueDependent()) {
4159       Expr::EvalResult Align;
4160       if (Arg->EvaluateAsInt(Align, Context)) {
4161         const llvm::APSInt &I = Align.Val.getInt();
4162         if (!I.isPowerOf2())
4163           Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
4164               << Arg->getSourceRange();
4165 
4166         if (I > Sema::MaximumAlignment)
4167           Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
4168               << Arg->getSourceRange() << Sema::MaximumAlignment;
4169       }
4170     }
4171   }
4172 
4173   if (FD)
4174     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4175 }
4176 
4177 /// CheckConstructorCall - Check a constructor call for correctness and safety
4178 /// properties not enforced by the C type system.
4179 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
4180                                 ArrayRef<const Expr *> Args,
4181                                 const FunctionProtoType *Proto,
4182                                 SourceLocation Loc) {
4183   VariadicCallType CallType =
4184     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4185   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4186             Loc, SourceRange(), CallType);
4187 }
4188 
4189 /// CheckFunctionCall - Check a direct function call for various correctness
4190 /// and safety properties not strictly enforced by the C type system.
4191 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
4192                              const FunctionProtoType *Proto) {
4193   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4194                               isa<CXXMethodDecl>(FDecl);
4195   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4196                           IsMemberOperatorCall;
4197   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4198                                                   TheCall->getCallee());
4199   Expr** Args = TheCall->getArgs();
4200   unsigned NumArgs = TheCall->getNumArgs();
4201 
4202   Expr *ImplicitThis = nullptr;
4203   if (IsMemberOperatorCall) {
4204     // If this is a call to a member operator, hide the first argument
4205     // from checkCall.
4206     // FIXME: Our choice of AST representation here is less than ideal.
4207     ImplicitThis = Args[0];
4208     ++Args;
4209     --NumArgs;
4210   } else if (IsMemberFunction)
4211     ImplicitThis =
4212         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4213 
4214   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
4215             IsMemberFunction, TheCall->getRParenLoc(),
4216             TheCall->getCallee()->getSourceRange(), CallType);
4217 
4218   IdentifierInfo *FnInfo = FDecl->getIdentifier();
4219   // None of the checks below are needed for functions that don't have
4220   // simple names (e.g., C++ conversion functions).
4221   if (!FnInfo)
4222     return false;
4223 
4224   CheckAbsoluteValueFunction(TheCall, FDecl);
4225   CheckMaxUnsignedZero(TheCall, FDecl);
4226 
4227   if (getLangOpts().ObjC)
4228     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
4229 
4230   unsigned CMId = FDecl->getMemoryFunctionKind();
4231   if (CMId == 0)
4232     return false;
4233 
4234   // Handle memory setting and copying functions.
4235   if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
4236     CheckStrlcpycatArguments(TheCall, FnInfo);
4237   else if (CMId == Builtin::BIstrncat)
4238     CheckStrncatArguments(TheCall, FnInfo);
4239   else
4240     CheckMemaccessArguments(TheCall, CMId, FnInfo);
4241 
4242   return false;
4243 }
4244 
4245 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
4246                                ArrayRef<const Expr *> Args) {
4247   VariadicCallType CallType =
4248       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
4249 
4250   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
4251             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
4252             CallType);
4253 
4254   return false;
4255 }
4256 
4257 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4258                             const FunctionProtoType *Proto) {
4259   QualType Ty;
4260   if (const auto *V = dyn_cast<VarDecl>(NDecl))
4261     Ty = V->getType().getNonReferenceType();
4262   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4263     Ty = F->getType().getNonReferenceType();
4264   else
4265     return false;
4266 
4267   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4268       !Ty->isFunctionProtoType())
4269     return false;
4270 
4271   VariadicCallType CallType;
4272   if (!Proto || !Proto->isVariadic()) {
4273     CallType = VariadicDoesNotApply;
4274   } else if (Ty->isBlockPointerType()) {
4275     CallType = VariadicBlock;
4276   } else { // Ty->isFunctionPointerType()
4277     CallType = VariadicFunction;
4278   }
4279 
4280   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4281             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4282             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4283             TheCall->getCallee()->getSourceRange(), CallType);
4284 
4285   return false;
4286 }
4287 
4288 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
4289 /// such as function pointers returned from functions.
4290 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4291   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4292                                                   TheCall->getCallee());
4293   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4294             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4295             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4296             TheCall->getCallee()->getSourceRange(), CallType);
4297 
4298   return false;
4299 }
4300 
4301 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4302   if (!llvm::isValidAtomicOrderingCABI(Ordering))
4303     return false;
4304 
4305   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4306   switch (Op) {
4307   case AtomicExpr::AO__c11_atomic_init:
4308   case AtomicExpr::AO__opencl_atomic_init:
4309     llvm_unreachable("There is no ordering argument for an init");
4310 
4311   case AtomicExpr::AO__c11_atomic_load:
4312   case AtomicExpr::AO__opencl_atomic_load:
4313   case AtomicExpr::AO__atomic_load_n:
4314   case AtomicExpr::AO__atomic_load:
4315     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4316            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4317 
4318   case AtomicExpr::AO__c11_atomic_store:
4319   case AtomicExpr::AO__opencl_atomic_store:
4320   case AtomicExpr::AO__atomic_store:
4321   case AtomicExpr::AO__atomic_store_n:
4322     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4323            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4324            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4325 
4326   default:
4327     return true;
4328   }
4329 }
4330 
4331 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
4332                                          AtomicExpr::AtomicOp Op) {
4333   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4334   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4335   MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
4336   return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
4337                          DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
4338                          Op);
4339 }
4340 
4341 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
4342                                  SourceLocation RParenLoc, MultiExprArg Args,
4343                                  AtomicExpr::AtomicOp Op,
4344                                  AtomicArgumentOrder ArgOrder) {
4345   // All the non-OpenCL operations take one of the following forms.
4346   // The OpenCL operations take the __c11 forms with one extra argument for
4347   // synchronization scope.
4348   enum {
4349     // C    __c11_atomic_init(A *, C)
4350     Init,
4351 
4352     // C    __c11_atomic_load(A *, int)
4353     Load,
4354 
4355     // void __atomic_load(A *, CP, int)
4356     LoadCopy,
4357 
4358     // void __atomic_store(A *, CP, int)
4359     Copy,
4360 
4361     // C    __c11_atomic_add(A *, M, int)
4362     Arithmetic,
4363 
4364     // C    __atomic_exchange_n(A *, CP, int)
4365     Xchg,
4366 
4367     // void __atomic_exchange(A *, C *, CP, int)
4368     GNUXchg,
4369 
4370     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4371     C11CmpXchg,
4372 
4373     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4374     GNUCmpXchg
4375   } Form = Init;
4376 
4377   const unsigned NumForm = GNUCmpXchg + 1;
4378   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
4379   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
4380   // where:
4381   //   C is an appropriate type,
4382   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4383   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4384   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4385   //   the int parameters are for orderings.
4386 
4387   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4388       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4389       "need to update code for modified forms");
4390   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
4391                     AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
4392                         AtomicExpr::AO__atomic_load,
4393                 "need to update code for modified C11 atomics");
4394   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
4395                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
4396   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
4397                Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
4398                IsOpenCL;
4399   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4400              Op == AtomicExpr::AO__atomic_store_n ||
4401              Op == AtomicExpr::AO__atomic_exchange_n ||
4402              Op == AtomicExpr::AO__atomic_compare_exchange_n;
4403   bool IsAddSub = false;
4404 
4405   switch (Op) {
4406   case AtomicExpr::AO__c11_atomic_init:
4407   case AtomicExpr::AO__opencl_atomic_init:
4408     Form = Init;
4409     break;
4410 
4411   case AtomicExpr::AO__c11_atomic_load:
4412   case AtomicExpr::AO__opencl_atomic_load:
4413   case AtomicExpr::AO__atomic_load_n:
4414     Form = Load;
4415     break;
4416 
4417   case AtomicExpr::AO__atomic_load:
4418     Form = LoadCopy;
4419     break;
4420 
4421   case AtomicExpr::AO__c11_atomic_store:
4422   case AtomicExpr::AO__opencl_atomic_store:
4423   case AtomicExpr::AO__atomic_store:
4424   case AtomicExpr::AO__atomic_store_n:
4425     Form = Copy;
4426     break;
4427 
4428   case AtomicExpr::AO__c11_atomic_fetch_add:
4429   case AtomicExpr::AO__c11_atomic_fetch_sub:
4430   case AtomicExpr::AO__opencl_atomic_fetch_add:
4431   case AtomicExpr::AO__opencl_atomic_fetch_sub:
4432   case AtomicExpr::AO__atomic_fetch_add:
4433   case AtomicExpr::AO__atomic_fetch_sub:
4434   case AtomicExpr::AO__atomic_add_fetch:
4435   case AtomicExpr::AO__atomic_sub_fetch:
4436     IsAddSub = true;
4437     LLVM_FALLTHROUGH;
4438   case AtomicExpr::AO__c11_atomic_fetch_and:
4439   case AtomicExpr::AO__c11_atomic_fetch_or:
4440   case AtomicExpr::AO__c11_atomic_fetch_xor:
4441   case AtomicExpr::AO__opencl_atomic_fetch_and:
4442   case AtomicExpr::AO__opencl_atomic_fetch_or:
4443   case AtomicExpr::AO__opencl_atomic_fetch_xor:
4444   case AtomicExpr::AO__atomic_fetch_and:
4445   case AtomicExpr::AO__atomic_fetch_or:
4446   case AtomicExpr::AO__atomic_fetch_xor:
4447   case AtomicExpr::AO__atomic_fetch_nand:
4448   case AtomicExpr::AO__atomic_and_fetch:
4449   case AtomicExpr::AO__atomic_or_fetch:
4450   case AtomicExpr::AO__atomic_xor_fetch:
4451   case AtomicExpr::AO__atomic_nand_fetch:
4452   case AtomicExpr::AO__c11_atomic_fetch_min:
4453   case AtomicExpr::AO__c11_atomic_fetch_max:
4454   case AtomicExpr::AO__opencl_atomic_fetch_min:
4455   case AtomicExpr::AO__opencl_atomic_fetch_max:
4456   case AtomicExpr::AO__atomic_min_fetch:
4457   case AtomicExpr::AO__atomic_max_fetch:
4458   case AtomicExpr::AO__atomic_fetch_min:
4459   case AtomicExpr::AO__atomic_fetch_max:
4460     Form = Arithmetic;
4461     break;
4462 
4463   case AtomicExpr::AO__c11_atomic_exchange:
4464   case AtomicExpr::AO__opencl_atomic_exchange:
4465   case AtomicExpr::AO__atomic_exchange_n:
4466     Form = Xchg;
4467     break;
4468 
4469   case AtomicExpr::AO__atomic_exchange:
4470     Form = GNUXchg;
4471     break;
4472 
4473   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
4474   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
4475   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
4476   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
4477     Form = C11CmpXchg;
4478     break;
4479 
4480   case AtomicExpr::AO__atomic_compare_exchange:
4481   case AtomicExpr::AO__atomic_compare_exchange_n:
4482     Form = GNUCmpXchg;
4483     break;
4484   }
4485 
4486   unsigned AdjustedNumArgs = NumArgs[Form];
4487   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
4488     ++AdjustedNumArgs;
4489   // Check we have the right number of arguments.
4490   if (Args.size() < AdjustedNumArgs) {
4491     Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
4492         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4493         << ExprRange;
4494     return ExprError();
4495   } else if (Args.size() > AdjustedNumArgs) {
4496     Diag(Args[AdjustedNumArgs]->getBeginLoc(),
4497          diag::err_typecheck_call_too_many_args)
4498         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4499         << ExprRange;
4500     return ExprError();
4501   }
4502 
4503   // Inspect the first argument of the atomic operation.
4504   Expr *Ptr = Args[0];
4505   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
4506   if (ConvertedPtr.isInvalid())
4507     return ExprError();
4508 
4509   Ptr = ConvertedPtr.get();
4510   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
4511   if (!pointerType) {
4512     Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
4513         << Ptr->getType() << Ptr->getSourceRange();
4514     return ExprError();
4515   }
4516 
4517   // For a __c11 builtin, this should be a pointer to an _Atomic type.
4518   QualType AtomTy = pointerType->getPointeeType(); // 'A'
4519   QualType ValType = AtomTy; // 'C'
4520   if (IsC11) {
4521     if (!AtomTy->isAtomicType()) {
4522       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
4523           << Ptr->getType() << Ptr->getSourceRange();
4524       return ExprError();
4525     }
4526     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
4527         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
4528       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
4529           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
4530           << Ptr->getSourceRange();
4531       return ExprError();
4532     }
4533     ValType = AtomTy->castAs<AtomicType>()->getValueType();
4534   } else if (Form != Load && Form != LoadCopy) {
4535     if (ValType.isConstQualified()) {
4536       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
4537           << Ptr->getType() << Ptr->getSourceRange();
4538       return ExprError();
4539     }
4540   }
4541 
4542   // For an arithmetic operation, the implied arithmetic must be well-formed.
4543   if (Form == Arithmetic) {
4544     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
4545     if (IsAddSub && !ValType->isIntegerType()
4546         && !ValType->isPointerType()) {
4547       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4548           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4549       return ExprError();
4550     }
4551     if (!IsAddSub && !ValType->isIntegerType()) {
4552       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
4553           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4554       return ExprError();
4555     }
4556     if (IsC11 && ValType->isPointerType() &&
4557         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
4558                             diag::err_incomplete_type)) {
4559       return ExprError();
4560     }
4561   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
4562     // For __atomic_*_n operations, the value type must be a scalar integral or
4563     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
4564     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4565         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4566     return ExprError();
4567   }
4568 
4569   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
4570       !AtomTy->isScalarType()) {
4571     // For GNU atomics, require a trivially-copyable type. This is not part of
4572     // the GNU atomics specification, but we enforce it for sanity.
4573     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
4574         << Ptr->getType() << Ptr->getSourceRange();
4575     return ExprError();
4576   }
4577 
4578   switch (ValType.getObjCLifetime()) {
4579   case Qualifiers::OCL_None:
4580   case Qualifiers::OCL_ExplicitNone:
4581     // okay
4582     break;
4583 
4584   case Qualifiers::OCL_Weak:
4585   case Qualifiers::OCL_Strong:
4586   case Qualifiers::OCL_Autoreleasing:
4587     // FIXME: Can this happen? By this point, ValType should be known
4588     // to be trivially copyable.
4589     Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
4590         << ValType << Ptr->getSourceRange();
4591     return ExprError();
4592   }
4593 
4594   // All atomic operations have an overload which takes a pointer to a volatile
4595   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
4596   // into the result or the other operands. Similarly atomic_load takes a
4597   // pointer to a const 'A'.
4598   ValType.removeLocalVolatile();
4599   ValType.removeLocalConst();
4600   QualType ResultType = ValType;
4601   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
4602       Form == Init)
4603     ResultType = Context.VoidTy;
4604   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
4605     ResultType = Context.BoolTy;
4606 
4607   // The type of a parameter passed 'by value'. In the GNU atomics, such
4608   // arguments are actually passed as pointers.
4609   QualType ByValType = ValType; // 'CP'
4610   bool IsPassedByAddress = false;
4611   if (!IsC11 && !IsN) {
4612     ByValType = Ptr->getType();
4613     IsPassedByAddress = true;
4614   }
4615 
4616   SmallVector<Expr *, 5> APIOrderedArgs;
4617   if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
4618     APIOrderedArgs.push_back(Args[0]);
4619     switch (Form) {
4620     case Init:
4621     case Load:
4622       APIOrderedArgs.push_back(Args[1]); // Val1/Order
4623       break;
4624     case LoadCopy:
4625     case Copy:
4626     case Arithmetic:
4627     case Xchg:
4628       APIOrderedArgs.push_back(Args[2]); // Val1
4629       APIOrderedArgs.push_back(Args[1]); // Order
4630       break;
4631     case GNUXchg:
4632       APIOrderedArgs.push_back(Args[2]); // Val1
4633       APIOrderedArgs.push_back(Args[3]); // Val2
4634       APIOrderedArgs.push_back(Args[1]); // Order
4635       break;
4636     case C11CmpXchg:
4637       APIOrderedArgs.push_back(Args[2]); // Val1
4638       APIOrderedArgs.push_back(Args[4]); // Val2
4639       APIOrderedArgs.push_back(Args[1]); // Order
4640       APIOrderedArgs.push_back(Args[3]); // OrderFail
4641       break;
4642     case GNUCmpXchg:
4643       APIOrderedArgs.push_back(Args[2]); // Val1
4644       APIOrderedArgs.push_back(Args[4]); // Val2
4645       APIOrderedArgs.push_back(Args[5]); // Weak
4646       APIOrderedArgs.push_back(Args[1]); // Order
4647       APIOrderedArgs.push_back(Args[3]); // OrderFail
4648       break;
4649     }
4650   } else
4651     APIOrderedArgs.append(Args.begin(), Args.end());
4652 
4653   // The first argument's non-CV pointer type is used to deduce the type of
4654   // subsequent arguments, except for:
4655   //  - weak flag (always converted to bool)
4656   //  - memory order (always converted to int)
4657   //  - scope  (always converted to int)
4658   for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
4659     QualType Ty;
4660     if (i < NumVals[Form] + 1) {
4661       switch (i) {
4662       case 0:
4663         // The first argument is always a pointer. It has a fixed type.
4664         // It is always dereferenced, a nullptr is undefined.
4665         CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4666         // Nothing else to do: we already know all we want about this pointer.
4667         continue;
4668       case 1:
4669         // The second argument is the non-atomic operand. For arithmetic, this
4670         // is always passed by value, and for a compare_exchange it is always
4671         // passed by address. For the rest, GNU uses by-address and C11 uses
4672         // by-value.
4673         assert(Form != Load);
4674         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
4675           Ty = ValType;
4676         else if (Form == Copy || Form == Xchg) {
4677           if (IsPassedByAddress) {
4678             // The value pointer is always dereferenced, a nullptr is undefined.
4679             CheckNonNullArgument(*this, APIOrderedArgs[i],
4680                                  ExprRange.getBegin());
4681           }
4682           Ty = ByValType;
4683         } else if (Form == Arithmetic)
4684           Ty = Context.getPointerDiffType();
4685         else {
4686           Expr *ValArg = APIOrderedArgs[i];
4687           // The value pointer is always dereferenced, a nullptr is undefined.
4688           CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
4689           LangAS AS = LangAS::Default;
4690           // Keep address space of non-atomic pointer type.
4691           if (const PointerType *PtrTy =
4692                   ValArg->getType()->getAs<PointerType>()) {
4693             AS = PtrTy->getPointeeType().getAddressSpace();
4694           }
4695           Ty = Context.getPointerType(
4696               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
4697         }
4698         break;
4699       case 2:
4700         // The third argument to compare_exchange / GNU exchange is the desired
4701         // value, either by-value (for the C11 and *_n variant) or as a pointer.
4702         if (IsPassedByAddress)
4703           CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4704         Ty = ByValType;
4705         break;
4706       case 3:
4707         // The fourth argument to GNU compare_exchange is a 'weak' flag.
4708         Ty = Context.BoolTy;
4709         break;
4710       }
4711     } else {
4712       // The order(s) and scope are always converted to int.
4713       Ty = Context.IntTy;
4714     }
4715 
4716     InitializedEntity Entity =
4717         InitializedEntity::InitializeParameter(Context, Ty, false);
4718     ExprResult Arg = APIOrderedArgs[i];
4719     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4720     if (Arg.isInvalid())
4721       return true;
4722     APIOrderedArgs[i] = Arg.get();
4723   }
4724 
4725   // Permute the arguments into a 'consistent' order.
4726   SmallVector<Expr*, 5> SubExprs;
4727   SubExprs.push_back(Ptr);
4728   switch (Form) {
4729   case Init:
4730     // Note, AtomicExpr::getVal1() has a special case for this atomic.
4731     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4732     break;
4733   case Load:
4734     SubExprs.push_back(APIOrderedArgs[1]); // Order
4735     break;
4736   case LoadCopy:
4737   case Copy:
4738   case Arithmetic:
4739   case Xchg:
4740     SubExprs.push_back(APIOrderedArgs[2]); // Order
4741     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4742     break;
4743   case GNUXchg:
4744     // Note, AtomicExpr::getVal2() has a special case for this atomic.
4745     SubExprs.push_back(APIOrderedArgs[3]); // Order
4746     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4747     SubExprs.push_back(APIOrderedArgs[2]); // Val2
4748     break;
4749   case C11CmpXchg:
4750     SubExprs.push_back(APIOrderedArgs[3]); // Order
4751     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4752     SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
4753     SubExprs.push_back(APIOrderedArgs[2]); // Val2
4754     break;
4755   case GNUCmpXchg:
4756     SubExprs.push_back(APIOrderedArgs[4]); // Order
4757     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4758     SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
4759     SubExprs.push_back(APIOrderedArgs[2]); // Val2
4760     SubExprs.push_back(APIOrderedArgs[3]); // Weak
4761     break;
4762   }
4763 
4764   if (SubExprs.size() >= 2 && Form != Init) {
4765     llvm::APSInt Result(32);
4766     if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
4767         !isValidOrderingForOp(Result.getSExtValue(), Op))
4768       Diag(SubExprs[1]->getBeginLoc(),
4769            diag::warn_atomic_op_has_invalid_memory_order)
4770           << SubExprs[1]->getSourceRange();
4771   }
4772 
4773   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
4774     auto *Scope = Args[Args.size() - 1];
4775     llvm::APSInt Result(32);
4776     if (Scope->isIntegerConstantExpr(Result, Context) &&
4777         !ScopeModel->isValid(Result.getZExtValue())) {
4778       Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
4779           << Scope->getSourceRange();
4780     }
4781     SubExprs.push_back(Scope);
4782   }
4783 
4784   AtomicExpr *AE = new (Context)
4785       AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
4786 
4787   if ((Op == AtomicExpr::AO__c11_atomic_load ||
4788        Op == AtomicExpr::AO__c11_atomic_store ||
4789        Op == AtomicExpr::AO__opencl_atomic_load ||
4790        Op == AtomicExpr::AO__opencl_atomic_store ) &&
4791       Context.AtomicUsesUnsupportedLibcall(AE))
4792     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
4793         << ((Op == AtomicExpr::AO__c11_atomic_load ||
4794              Op == AtomicExpr::AO__opencl_atomic_load)
4795                 ? 0
4796                 : 1);
4797 
4798   return AE;
4799 }
4800 
4801 /// checkBuiltinArgument - Given a call to a builtin function, perform
4802 /// normal type-checking on the given argument, updating the call in
4803 /// place.  This is useful when a builtin function requires custom
4804 /// type-checking for some of its arguments but not necessarily all of
4805 /// them.
4806 ///
4807 /// Returns true on error.
4808 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
4809   FunctionDecl *Fn = E->getDirectCallee();
4810   assert(Fn && "builtin call without direct callee!");
4811 
4812   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
4813   InitializedEntity Entity =
4814     InitializedEntity::InitializeParameter(S.Context, Param);
4815 
4816   ExprResult Arg = E->getArg(0);
4817   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
4818   if (Arg.isInvalid())
4819     return true;
4820 
4821   E->setArg(ArgIndex, Arg.get());
4822   return false;
4823 }
4824 
4825 /// We have a call to a function like __sync_fetch_and_add, which is an
4826 /// overloaded function based on the pointer type of its first argument.
4827 /// The main BuildCallExpr routines have already promoted the types of
4828 /// arguments because all of these calls are prototyped as void(...).
4829 ///
4830 /// This function goes through and does final semantic checking for these
4831 /// builtins, as well as generating any warnings.
4832 ExprResult
4833 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
4834   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
4835   Expr *Callee = TheCall->getCallee();
4836   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
4837   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4838 
4839   // Ensure that we have at least one argument to do type inference from.
4840   if (TheCall->getNumArgs() < 1) {
4841     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
4842         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
4843     return ExprError();
4844   }
4845 
4846   // Inspect the first argument of the atomic builtin.  This should always be
4847   // a pointer type, whose element is an integral scalar or pointer type.
4848   // Because it is a pointer type, we don't have to worry about any implicit
4849   // casts here.
4850   // FIXME: We don't allow floating point scalars as input.
4851   Expr *FirstArg = TheCall->getArg(0);
4852   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
4853   if (FirstArgResult.isInvalid())
4854     return ExprError();
4855   FirstArg = FirstArgResult.get();
4856   TheCall->setArg(0, FirstArg);
4857 
4858   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
4859   if (!pointerType) {
4860     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
4861         << FirstArg->getType() << FirstArg->getSourceRange();
4862     return ExprError();
4863   }
4864 
4865   QualType ValType = pointerType->getPointeeType();
4866   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
4867       !ValType->isBlockPointerType()) {
4868     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
4869         << FirstArg->getType() << FirstArg->getSourceRange();
4870     return ExprError();
4871   }
4872 
4873   if (ValType.isConstQualified()) {
4874     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
4875         << FirstArg->getType() << FirstArg->getSourceRange();
4876     return ExprError();
4877   }
4878 
4879   switch (ValType.getObjCLifetime()) {
4880   case Qualifiers::OCL_None:
4881   case Qualifiers::OCL_ExplicitNone:
4882     // okay
4883     break;
4884 
4885   case Qualifiers::OCL_Weak:
4886   case Qualifiers::OCL_Strong:
4887   case Qualifiers::OCL_Autoreleasing:
4888     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
4889         << ValType << FirstArg->getSourceRange();
4890     return ExprError();
4891   }
4892 
4893   // Strip any qualifiers off ValType.
4894   ValType = ValType.getUnqualifiedType();
4895 
4896   // The majority of builtins return a value, but a few have special return
4897   // types, so allow them to override appropriately below.
4898   QualType ResultType = ValType;
4899 
4900   // We need to figure out which concrete builtin this maps onto.  For example,
4901   // __sync_fetch_and_add with a 2 byte object turns into
4902   // __sync_fetch_and_add_2.
4903 #define BUILTIN_ROW(x) \
4904   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
4905     Builtin::BI##x##_8, Builtin::BI##x##_16 }
4906 
4907   static const unsigned BuiltinIndices[][5] = {
4908     BUILTIN_ROW(__sync_fetch_and_add),
4909     BUILTIN_ROW(__sync_fetch_and_sub),
4910     BUILTIN_ROW(__sync_fetch_and_or),
4911     BUILTIN_ROW(__sync_fetch_and_and),
4912     BUILTIN_ROW(__sync_fetch_and_xor),
4913     BUILTIN_ROW(__sync_fetch_and_nand),
4914 
4915     BUILTIN_ROW(__sync_add_and_fetch),
4916     BUILTIN_ROW(__sync_sub_and_fetch),
4917     BUILTIN_ROW(__sync_and_and_fetch),
4918     BUILTIN_ROW(__sync_or_and_fetch),
4919     BUILTIN_ROW(__sync_xor_and_fetch),
4920     BUILTIN_ROW(__sync_nand_and_fetch),
4921 
4922     BUILTIN_ROW(__sync_val_compare_and_swap),
4923     BUILTIN_ROW(__sync_bool_compare_and_swap),
4924     BUILTIN_ROW(__sync_lock_test_and_set),
4925     BUILTIN_ROW(__sync_lock_release),
4926     BUILTIN_ROW(__sync_swap)
4927   };
4928 #undef BUILTIN_ROW
4929 
4930   // Determine the index of the size.
4931   unsigned SizeIndex;
4932   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
4933   case 1: SizeIndex = 0; break;
4934   case 2: SizeIndex = 1; break;
4935   case 4: SizeIndex = 2; break;
4936   case 8: SizeIndex = 3; break;
4937   case 16: SizeIndex = 4; break;
4938   default:
4939     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
4940         << FirstArg->getType() << FirstArg->getSourceRange();
4941     return ExprError();
4942   }
4943 
4944   // Each of these builtins has one pointer argument, followed by some number of
4945   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
4946   // that we ignore.  Find out which row of BuiltinIndices to read from as well
4947   // as the number of fixed args.
4948   unsigned BuiltinID = FDecl->getBuiltinID();
4949   unsigned BuiltinIndex, NumFixed = 1;
4950   bool WarnAboutSemanticsChange = false;
4951   switch (BuiltinID) {
4952   default: llvm_unreachable("Unknown overloaded atomic builtin!");
4953   case Builtin::BI__sync_fetch_and_add:
4954   case Builtin::BI__sync_fetch_and_add_1:
4955   case Builtin::BI__sync_fetch_and_add_2:
4956   case Builtin::BI__sync_fetch_and_add_4:
4957   case Builtin::BI__sync_fetch_and_add_8:
4958   case Builtin::BI__sync_fetch_and_add_16:
4959     BuiltinIndex = 0;
4960     break;
4961 
4962   case Builtin::BI__sync_fetch_and_sub:
4963   case Builtin::BI__sync_fetch_and_sub_1:
4964   case Builtin::BI__sync_fetch_and_sub_2:
4965   case Builtin::BI__sync_fetch_and_sub_4:
4966   case Builtin::BI__sync_fetch_and_sub_8:
4967   case Builtin::BI__sync_fetch_and_sub_16:
4968     BuiltinIndex = 1;
4969     break;
4970 
4971   case Builtin::BI__sync_fetch_and_or:
4972   case Builtin::BI__sync_fetch_and_or_1:
4973   case Builtin::BI__sync_fetch_and_or_2:
4974   case Builtin::BI__sync_fetch_and_or_4:
4975   case Builtin::BI__sync_fetch_and_or_8:
4976   case Builtin::BI__sync_fetch_and_or_16:
4977     BuiltinIndex = 2;
4978     break;
4979 
4980   case Builtin::BI__sync_fetch_and_and:
4981   case Builtin::BI__sync_fetch_and_and_1:
4982   case Builtin::BI__sync_fetch_and_and_2:
4983   case Builtin::BI__sync_fetch_and_and_4:
4984   case Builtin::BI__sync_fetch_and_and_8:
4985   case Builtin::BI__sync_fetch_and_and_16:
4986     BuiltinIndex = 3;
4987     break;
4988 
4989   case Builtin::BI__sync_fetch_and_xor:
4990   case Builtin::BI__sync_fetch_and_xor_1:
4991   case Builtin::BI__sync_fetch_and_xor_2:
4992   case Builtin::BI__sync_fetch_and_xor_4:
4993   case Builtin::BI__sync_fetch_and_xor_8:
4994   case Builtin::BI__sync_fetch_and_xor_16:
4995     BuiltinIndex = 4;
4996     break;
4997 
4998   case Builtin::BI__sync_fetch_and_nand:
4999   case Builtin::BI__sync_fetch_and_nand_1:
5000   case Builtin::BI__sync_fetch_and_nand_2:
5001   case Builtin::BI__sync_fetch_and_nand_4:
5002   case Builtin::BI__sync_fetch_and_nand_8:
5003   case Builtin::BI__sync_fetch_and_nand_16:
5004     BuiltinIndex = 5;
5005     WarnAboutSemanticsChange = true;
5006     break;
5007 
5008   case Builtin::BI__sync_add_and_fetch:
5009   case Builtin::BI__sync_add_and_fetch_1:
5010   case Builtin::BI__sync_add_and_fetch_2:
5011   case Builtin::BI__sync_add_and_fetch_4:
5012   case Builtin::BI__sync_add_and_fetch_8:
5013   case Builtin::BI__sync_add_and_fetch_16:
5014     BuiltinIndex = 6;
5015     break;
5016 
5017   case Builtin::BI__sync_sub_and_fetch:
5018   case Builtin::BI__sync_sub_and_fetch_1:
5019   case Builtin::BI__sync_sub_and_fetch_2:
5020   case Builtin::BI__sync_sub_and_fetch_4:
5021   case Builtin::BI__sync_sub_and_fetch_8:
5022   case Builtin::BI__sync_sub_and_fetch_16:
5023     BuiltinIndex = 7;
5024     break;
5025 
5026   case Builtin::BI__sync_and_and_fetch:
5027   case Builtin::BI__sync_and_and_fetch_1:
5028   case Builtin::BI__sync_and_and_fetch_2:
5029   case Builtin::BI__sync_and_and_fetch_4:
5030   case Builtin::BI__sync_and_and_fetch_8:
5031   case Builtin::BI__sync_and_and_fetch_16:
5032     BuiltinIndex = 8;
5033     break;
5034 
5035   case Builtin::BI__sync_or_and_fetch:
5036   case Builtin::BI__sync_or_and_fetch_1:
5037   case Builtin::BI__sync_or_and_fetch_2:
5038   case Builtin::BI__sync_or_and_fetch_4:
5039   case Builtin::BI__sync_or_and_fetch_8:
5040   case Builtin::BI__sync_or_and_fetch_16:
5041     BuiltinIndex = 9;
5042     break;
5043 
5044   case Builtin::BI__sync_xor_and_fetch:
5045   case Builtin::BI__sync_xor_and_fetch_1:
5046   case Builtin::BI__sync_xor_and_fetch_2:
5047   case Builtin::BI__sync_xor_and_fetch_4:
5048   case Builtin::BI__sync_xor_and_fetch_8:
5049   case Builtin::BI__sync_xor_and_fetch_16:
5050     BuiltinIndex = 10;
5051     break;
5052 
5053   case Builtin::BI__sync_nand_and_fetch:
5054   case Builtin::BI__sync_nand_and_fetch_1:
5055   case Builtin::BI__sync_nand_and_fetch_2:
5056   case Builtin::BI__sync_nand_and_fetch_4:
5057   case Builtin::BI__sync_nand_and_fetch_8:
5058   case Builtin::BI__sync_nand_and_fetch_16:
5059     BuiltinIndex = 11;
5060     WarnAboutSemanticsChange = true;
5061     break;
5062 
5063   case Builtin::BI__sync_val_compare_and_swap:
5064   case Builtin::BI__sync_val_compare_and_swap_1:
5065   case Builtin::BI__sync_val_compare_and_swap_2:
5066   case Builtin::BI__sync_val_compare_and_swap_4:
5067   case Builtin::BI__sync_val_compare_and_swap_8:
5068   case Builtin::BI__sync_val_compare_and_swap_16:
5069     BuiltinIndex = 12;
5070     NumFixed = 2;
5071     break;
5072 
5073   case Builtin::BI__sync_bool_compare_and_swap:
5074   case Builtin::BI__sync_bool_compare_and_swap_1:
5075   case Builtin::BI__sync_bool_compare_and_swap_2:
5076   case Builtin::BI__sync_bool_compare_and_swap_4:
5077   case Builtin::BI__sync_bool_compare_and_swap_8:
5078   case Builtin::BI__sync_bool_compare_and_swap_16:
5079     BuiltinIndex = 13;
5080     NumFixed = 2;
5081     ResultType = Context.BoolTy;
5082     break;
5083 
5084   case Builtin::BI__sync_lock_test_and_set:
5085   case Builtin::BI__sync_lock_test_and_set_1:
5086   case Builtin::BI__sync_lock_test_and_set_2:
5087   case Builtin::BI__sync_lock_test_and_set_4:
5088   case Builtin::BI__sync_lock_test_and_set_8:
5089   case Builtin::BI__sync_lock_test_and_set_16:
5090     BuiltinIndex = 14;
5091     break;
5092 
5093   case Builtin::BI__sync_lock_release:
5094   case Builtin::BI__sync_lock_release_1:
5095   case Builtin::BI__sync_lock_release_2:
5096   case Builtin::BI__sync_lock_release_4:
5097   case Builtin::BI__sync_lock_release_8:
5098   case Builtin::BI__sync_lock_release_16:
5099     BuiltinIndex = 15;
5100     NumFixed = 0;
5101     ResultType = Context.VoidTy;
5102     break;
5103 
5104   case Builtin::BI__sync_swap:
5105   case Builtin::BI__sync_swap_1:
5106   case Builtin::BI__sync_swap_2:
5107   case Builtin::BI__sync_swap_4:
5108   case Builtin::BI__sync_swap_8:
5109   case Builtin::BI__sync_swap_16:
5110     BuiltinIndex = 16;
5111     break;
5112   }
5113 
5114   // Now that we know how many fixed arguments we expect, first check that we
5115   // have at least that many.
5116   if (TheCall->getNumArgs() < 1+NumFixed) {
5117     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5118         << 0 << 1 + NumFixed << TheCall->getNumArgs()
5119         << Callee->getSourceRange();
5120     return ExprError();
5121   }
5122 
5123   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5124       << Callee->getSourceRange();
5125 
5126   if (WarnAboutSemanticsChange) {
5127     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
5128         << Callee->getSourceRange();
5129   }
5130 
5131   // Get the decl for the concrete builtin from this, we can tell what the
5132   // concrete integer type we should convert to is.
5133   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5134   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
5135   FunctionDecl *NewBuiltinDecl;
5136   if (NewBuiltinID == BuiltinID)
5137     NewBuiltinDecl = FDecl;
5138   else {
5139     // Perform builtin lookup to avoid redeclaring it.
5140     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
5141     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5142     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5143     assert(Res.getFoundDecl());
5144     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
5145     if (!NewBuiltinDecl)
5146       return ExprError();
5147   }
5148 
5149   // The first argument --- the pointer --- has a fixed type; we
5150   // deduce the types of the rest of the arguments accordingly.  Walk
5151   // the remaining arguments, converting them to the deduced value type.
5152   for (unsigned i = 0; i != NumFixed; ++i) {
5153     ExprResult Arg = TheCall->getArg(i+1);
5154 
5155     // GCC does an implicit conversion to the pointer or integer ValType.  This
5156     // can fail in some cases (1i -> int**), check for this error case now.
5157     // Initialize the argument.
5158     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5159                                                    ValType, /*consume*/ false);
5160     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5161     if (Arg.isInvalid())
5162       return ExprError();
5163 
5164     // Okay, we have something that *can* be converted to the right type.  Check
5165     // to see if there is a potentially weird extension going on here.  This can
5166     // happen when you do an atomic operation on something like an char* and
5167     // pass in 42.  The 42 gets converted to char.  This is even more strange
5168     // for things like 45.123 -> char, etc.
5169     // FIXME: Do this check.
5170     TheCall->setArg(i+1, Arg.get());
5171   }
5172 
5173   // Create a new DeclRefExpr to refer to the new decl.
5174   DeclRefExpr *NewDRE = DeclRefExpr::Create(
5175       Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
5176       /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
5177       DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
5178 
5179   // Set the callee in the CallExpr.
5180   // FIXME: This loses syntactic information.
5181   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5182   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5183                                               CK_BuiltinFnToFnPtr);
5184   TheCall->setCallee(PromotedCall.get());
5185 
5186   // Change the result type of the call to match the original value type. This
5187   // is arbitrary, but the codegen for these builtins ins design to handle it
5188   // gracefully.
5189   TheCall->setType(ResultType);
5190 
5191   return TheCallResult;
5192 }
5193 
5194 /// SemaBuiltinNontemporalOverloaded - We have a call to
5195 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
5196 /// overloaded function based on the pointer type of its last argument.
5197 ///
5198 /// This function goes through and does final semantic checking for these
5199 /// builtins.
5200 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5201   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5202   DeclRefExpr *DRE =
5203       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5204   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5205   unsigned BuiltinID = FDecl->getBuiltinID();
5206   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5207           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5208          "Unexpected nontemporal load/store builtin!");
5209   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5210   unsigned numArgs = isStore ? 2 : 1;
5211 
5212   // Ensure that we have the proper number of arguments.
5213   if (checkArgCount(*this, TheCall, numArgs))
5214     return ExprError();
5215 
5216   // Inspect the last argument of the nontemporal builtin.  This should always
5217   // be a pointer type, from which we imply the type of the memory access.
5218   // Because it is a pointer type, we don't have to worry about any implicit
5219   // casts here.
5220   Expr *PointerArg = TheCall->getArg(numArgs - 1);
5221   ExprResult PointerArgResult =
5222       DefaultFunctionArrayLvalueConversion(PointerArg);
5223 
5224   if (PointerArgResult.isInvalid())
5225     return ExprError();
5226   PointerArg = PointerArgResult.get();
5227   TheCall->setArg(numArgs - 1, PointerArg);
5228 
5229   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5230   if (!pointerType) {
5231     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
5232         << PointerArg->getType() << PointerArg->getSourceRange();
5233     return ExprError();
5234   }
5235 
5236   QualType ValType = pointerType->getPointeeType();
5237 
5238   // Strip any qualifiers off ValType.
5239   ValType = ValType.getUnqualifiedType();
5240   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5241       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5242       !ValType->isVectorType()) {
5243     Diag(DRE->getBeginLoc(),
5244          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5245         << PointerArg->getType() << PointerArg->getSourceRange();
5246     return ExprError();
5247   }
5248 
5249   if (!isStore) {
5250     TheCall->setType(ValType);
5251     return TheCallResult;
5252   }
5253 
5254   ExprResult ValArg = TheCall->getArg(0);
5255   InitializedEntity Entity = InitializedEntity::InitializeParameter(
5256       Context, ValType, /*consume*/ false);
5257   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
5258   if (ValArg.isInvalid())
5259     return ExprError();
5260 
5261   TheCall->setArg(0, ValArg.get());
5262   TheCall->setType(Context.VoidTy);
5263   return TheCallResult;
5264 }
5265 
5266 /// CheckObjCString - Checks that the argument to the builtin
5267 /// CFString constructor is correct
5268 /// Note: It might also make sense to do the UTF-16 conversion here (would
5269 /// simplify the backend).
5270 bool Sema::CheckObjCString(Expr *Arg) {
5271   Arg = Arg->IgnoreParenCasts();
5272   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
5273 
5274   if (!Literal || !Literal->isAscii()) {
5275     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
5276         << Arg->getSourceRange();
5277     return true;
5278   }
5279 
5280   if (Literal->containsNonAsciiOrNull()) {
5281     StringRef String = Literal->getString();
5282     unsigned NumBytes = String.size();
5283     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
5284     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
5285     llvm::UTF16 *ToPtr = &ToBuf[0];
5286 
5287     llvm::ConversionResult Result =
5288         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
5289                                  ToPtr + NumBytes, llvm::strictConversion);
5290     // Check for conversion failure.
5291     if (Result != llvm::conversionOK)
5292       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
5293           << Arg->getSourceRange();
5294   }
5295   return false;
5296 }
5297 
5298 /// CheckObjCString - Checks that the format string argument to the os_log()
5299 /// and os_trace() functions is correct, and converts it to const char *.
5300 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5301   Arg = Arg->IgnoreParenCasts();
5302   auto *Literal = dyn_cast<StringLiteral>(Arg);
5303   if (!Literal) {
5304     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
5305       Literal = ObjcLiteral->getString();
5306     }
5307   }
5308 
5309   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
5310     return ExprError(
5311         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
5312         << Arg->getSourceRange());
5313   }
5314 
5315   ExprResult Result(Literal);
5316   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
5317   InitializedEntity Entity =
5318       InitializedEntity::InitializeParameter(Context, ResultTy, false);
5319   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
5320   return Result;
5321 }
5322 
5323 /// Check that the user is calling the appropriate va_start builtin for the
5324 /// target and calling convention.
5325 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5326   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5327   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
5328   bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
5329                     TT.getArch() == llvm::Triple::aarch64_32);
5330   bool IsWindows = TT.isOSWindows();
5331   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5332   if (IsX64 || IsAArch64) {
5333     CallingConv CC = CC_C;
5334     if (const FunctionDecl *FD = S.getCurFunctionDecl())
5335       CC = FD->getType()->castAs<FunctionType>()->getCallConv();
5336     if (IsMSVAStart) {
5337       // Don't allow this in System V ABI functions.
5338       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
5339         return S.Diag(Fn->getBeginLoc(),
5340                       diag::err_ms_va_start_used_in_sysv_function);
5341     } else {
5342       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
5343       // On x64 Windows, don't allow this in System V ABI functions.
5344       // (Yes, that means there's no corresponding way to support variadic
5345       // System V ABI functions on Windows.)
5346       if ((IsWindows && CC == CC_X86_64SysV) ||
5347           (!IsWindows && CC == CC_Win64))
5348         return S.Diag(Fn->getBeginLoc(),
5349                       diag::err_va_start_used_in_wrong_abi_function)
5350                << !IsWindows;
5351     }
5352     return false;
5353   }
5354 
5355   if (IsMSVAStart)
5356     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
5357   return false;
5358 }
5359 
5360 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
5361                                              ParmVarDecl **LastParam = nullptr) {
5362   // Determine whether the current function, block, or obj-c method is variadic
5363   // and get its parameter list.
5364   bool IsVariadic = false;
5365   ArrayRef<ParmVarDecl *> Params;
5366   DeclContext *Caller = S.CurContext;
5367   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
5368     IsVariadic = Block->isVariadic();
5369     Params = Block->parameters();
5370   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
5371     IsVariadic = FD->isVariadic();
5372     Params = FD->parameters();
5373   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
5374     IsVariadic = MD->isVariadic();
5375     // FIXME: This isn't correct for methods (results in bogus warning).
5376     Params = MD->parameters();
5377   } else if (isa<CapturedDecl>(Caller)) {
5378     // We don't support va_start in a CapturedDecl.
5379     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
5380     return true;
5381   } else {
5382     // This must be some other declcontext that parses exprs.
5383     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
5384     return true;
5385   }
5386 
5387   if (!IsVariadic) {
5388     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
5389     return true;
5390   }
5391 
5392   if (LastParam)
5393     *LastParam = Params.empty() ? nullptr : Params.back();
5394 
5395   return false;
5396 }
5397 
5398 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
5399 /// for validity.  Emit an error and return true on failure; return false
5400 /// on success.
5401 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5402   Expr *Fn = TheCall->getCallee();
5403 
5404   if (checkVAStartABI(*this, BuiltinID, Fn))
5405     return true;
5406 
5407   if (TheCall->getNumArgs() > 2) {
5408     Diag(TheCall->getArg(2)->getBeginLoc(),
5409          diag::err_typecheck_call_too_many_args)
5410         << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5411         << Fn->getSourceRange()
5412         << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5413                        (*(TheCall->arg_end() - 1))->getEndLoc());
5414     return true;
5415   }
5416 
5417   if (TheCall->getNumArgs() < 2) {
5418     return Diag(TheCall->getEndLoc(),
5419                 diag::err_typecheck_call_too_few_args_at_least)
5420            << 0 /*function call*/ << 2 << TheCall->getNumArgs();
5421   }
5422 
5423   // Type-check the first argument normally.
5424   if (checkBuiltinArgument(*this, TheCall, 0))
5425     return true;
5426 
5427   // Check that the current function is variadic, and get its last parameter.
5428   ParmVarDecl *LastParam;
5429   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
5430     return true;
5431 
5432   // Verify that the second argument to the builtin is the last argument of the
5433   // current function or method.
5434   bool SecondArgIsLastNamedArgument = false;
5435   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
5436 
5437   // These are valid if SecondArgIsLastNamedArgument is false after the next
5438   // block.
5439   QualType Type;
5440   SourceLocation ParamLoc;
5441   bool IsCRegister = false;
5442 
5443   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
5444     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
5445       SecondArgIsLastNamedArgument = PV == LastParam;
5446 
5447       Type = PV->getType();
5448       ParamLoc = PV->getLocation();
5449       IsCRegister =
5450           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
5451     }
5452   }
5453 
5454   if (!SecondArgIsLastNamedArgument)
5455     Diag(TheCall->getArg(1)->getBeginLoc(),
5456          diag::warn_second_arg_of_va_start_not_last_named_param);
5457   else if (IsCRegister || Type->isReferenceType() ||
5458            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
5459              // Promotable integers are UB, but enumerations need a bit of
5460              // extra checking to see what their promotable type actually is.
5461              if (!Type->isPromotableIntegerType())
5462                return false;
5463              if (!Type->isEnumeralType())
5464                return true;
5465              const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
5466              return !(ED &&
5467                       Context.typesAreCompatible(ED->getPromotionType(), Type));
5468            }()) {
5469     unsigned Reason = 0;
5470     if (Type->isReferenceType())  Reason = 1;
5471     else if (IsCRegister)         Reason = 2;
5472     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
5473     Diag(ParamLoc, diag::note_parameter_type) << Type;
5474   }
5475 
5476   TheCall->setType(Context.VoidTy);
5477   return false;
5478 }
5479 
5480 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
5481   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
5482   //                 const char *named_addr);
5483 
5484   Expr *Func = Call->getCallee();
5485 
5486   if (Call->getNumArgs() < 3)
5487     return Diag(Call->getEndLoc(),
5488                 diag::err_typecheck_call_too_few_args_at_least)
5489            << 0 /*function call*/ << 3 << Call->getNumArgs();
5490 
5491   // Type-check the first argument normally.
5492   if (checkBuiltinArgument(*this, Call, 0))
5493     return true;
5494 
5495   // Check that the current function is variadic.
5496   if (checkVAStartIsInVariadicFunction(*this, Func))
5497     return true;
5498 
5499   // __va_start on Windows does not validate the parameter qualifiers
5500 
5501   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
5502   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
5503 
5504   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
5505   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
5506 
5507   const QualType &ConstCharPtrTy =
5508       Context.getPointerType(Context.CharTy.withConst());
5509   if (!Arg1Ty->isPointerType() ||
5510       Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
5511     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5512         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
5513         << 0                                      /* qualifier difference */
5514         << 3                                      /* parameter mismatch */
5515         << 2 << Arg1->getType() << ConstCharPtrTy;
5516 
5517   const QualType SizeTy = Context.getSizeType();
5518   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
5519     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5520         << Arg2->getType() << SizeTy << 1 /* different class */
5521         << 0                              /* qualifier difference */
5522         << 3                              /* parameter mismatch */
5523         << 3 << Arg2->getType() << SizeTy;
5524 
5525   return false;
5526 }
5527 
5528 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
5529 /// friends.  This is declared to take (...), so we have to check everything.
5530 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
5531   if (TheCall->getNumArgs() < 2)
5532     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5533            << 0 << 2 << TheCall->getNumArgs() /*function call*/;
5534   if (TheCall->getNumArgs() > 2)
5535     return Diag(TheCall->getArg(2)->getBeginLoc(),
5536                 diag::err_typecheck_call_too_many_args)
5537            << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5538            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5539                           (*(TheCall->arg_end() - 1))->getEndLoc());
5540 
5541   ExprResult OrigArg0 = TheCall->getArg(0);
5542   ExprResult OrigArg1 = TheCall->getArg(1);
5543 
5544   // Do standard promotions between the two arguments, returning their common
5545   // type.
5546   QualType Res = UsualArithmeticConversions(
5547       OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
5548   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
5549     return true;
5550 
5551   // Make sure any conversions are pushed back into the call; this is
5552   // type safe since unordered compare builtins are declared as "_Bool
5553   // foo(...)".
5554   TheCall->setArg(0, OrigArg0.get());
5555   TheCall->setArg(1, OrigArg1.get());
5556 
5557   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
5558     return false;
5559 
5560   // If the common type isn't a real floating type, then the arguments were
5561   // invalid for this operation.
5562   if (Res.isNull() || !Res->isRealFloatingType())
5563     return Diag(OrigArg0.get()->getBeginLoc(),
5564                 diag::err_typecheck_call_invalid_ordered_compare)
5565            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
5566            << SourceRange(OrigArg0.get()->getBeginLoc(),
5567                           OrigArg1.get()->getEndLoc());
5568 
5569   return false;
5570 }
5571 
5572 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
5573 /// __builtin_isnan and friends.  This is declared to take (...), so we have
5574 /// to check everything. We expect the last argument to be a floating point
5575 /// value.
5576 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
5577   if (TheCall->getNumArgs() < NumArgs)
5578     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5579            << 0 << NumArgs << TheCall->getNumArgs() /*function call*/;
5580   if (TheCall->getNumArgs() > NumArgs)
5581     return Diag(TheCall->getArg(NumArgs)->getBeginLoc(),
5582                 diag::err_typecheck_call_too_many_args)
5583            << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
5584            << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(),
5585                           (*(TheCall->arg_end() - 1))->getEndLoc());
5586 
5587   // __builtin_fpclassify is the only case where NumArgs != 1, so we can count
5588   // on all preceding parameters just being int.  Try all of those.
5589   for (unsigned i = 0; i < NumArgs - 1; ++i) {
5590     Expr *Arg = TheCall->getArg(i);
5591 
5592     if (Arg->isTypeDependent())
5593       return false;
5594 
5595     ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);
5596 
5597     if (Res.isInvalid())
5598       return true;
5599     TheCall->setArg(i, Res.get());
5600   }
5601 
5602   Expr *OrigArg = TheCall->getArg(NumArgs-1);
5603 
5604   if (OrigArg->isTypeDependent())
5605     return false;
5606 
5607   // Usual Unary Conversions will convert half to float, which we want for
5608   // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
5609   // type how it is, but do normal L->Rvalue conversions.
5610   if (Context.getTargetInfo().useFP16ConversionIntrinsics())
5611     OrigArg = UsualUnaryConversions(OrigArg).get();
5612   else
5613     OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
5614   TheCall->setArg(NumArgs - 1, OrigArg);
5615 
5616   // This operation requires a non-_Complex floating-point number.
5617   if (!OrigArg->getType()->isRealFloatingType())
5618     return Diag(OrigArg->getBeginLoc(),
5619                 diag::err_typecheck_call_invalid_unary_fp)
5620            << OrigArg->getType() << OrigArg->getSourceRange();
5621 
5622   return false;
5623 }
5624 
5625 // Customized Sema Checking for VSX builtins that have the following signature:
5626 // vector [...] builtinName(vector [...], vector [...], const int);
5627 // Which takes the same type of vectors (any legal vector type) for the first
5628 // two arguments and takes compile time constant for the third argument.
5629 // Example builtins are :
5630 // vector double vec_xxpermdi(vector double, vector double, int);
5631 // vector short vec_xxsldwi(vector short, vector short, int);
5632 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
5633   unsigned ExpectedNumArgs = 3;
5634   if (TheCall->getNumArgs() < ExpectedNumArgs)
5635     return Diag(TheCall->getEndLoc(),
5636                 diag::err_typecheck_call_too_few_args_at_least)
5637            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5638            << TheCall->getSourceRange();
5639 
5640   if (TheCall->getNumArgs() > ExpectedNumArgs)
5641     return Diag(TheCall->getEndLoc(),
5642                 diag::err_typecheck_call_too_many_args_at_most)
5643            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5644            << TheCall->getSourceRange();
5645 
5646   // Check the third argument is a compile time constant
5647   llvm::APSInt Value;
5648   if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
5649     return Diag(TheCall->getBeginLoc(),
5650                 diag::err_vsx_builtin_nonconstant_argument)
5651            << 3 /* argument index */ << TheCall->getDirectCallee()
5652            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5653                           TheCall->getArg(2)->getEndLoc());
5654 
5655   QualType Arg1Ty = TheCall->getArg(0)->getType();
5656   QualType Arg2Ty = TheCall->getArg(1)->getType();
5657 
5658   // Check the type of argument 1 and argument 2 are vectors.
5659   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
5660   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
5661       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
5662     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
5663            << TheCall->getDirectCallee()
5664            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5665                           TheCall->getArg(1)->getEndLoc());
5666   }
5667 
5668   // Check the first two arguments are the same type.
5669   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
5670     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
5671            << TheCall->getDirectCallee()
5672            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5673                           TheCall->getArg(1)->getEndLoc());
5674   }
5675 
5676   // When default clang type checking is turned off and the customized type
5677   // checking is used, the returning type of the function must be explicitly
5678   // set. Otherwise it is _Bool by default.
5679   TheCall->setType(Arg1Ty);
5680 
5681   return false;
5682 }
5683 
5684 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
5685 // This is declared to take (...), so we have to check everything.
5686 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
5687   if (TheCall->getNumArgs() < 2)
5688     return ExprError(Diag(TheCall->getEndLoc(),
5689                           diag::err_typecheck_call_too_few_args_at_least)
5690                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5691                      << TheCall->getSourceRange());
5692 
5693   // Determine which of the following types of shufflevector we're checking:
5694   // 1) unary, vector mask: (lhs, mask)
5695   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
5696   QualType resType = TheCall->getArg(0)->getType();
5697   unsigned numElements = 0;
5698 
5699   if (!TheCall->getArg(0)->isTypeDependent() &&
5700       !TheCall->getArg(1)->isTypeDependent()) {
5701     QualType LHSType = TheCall->getArg(0)->getType();
5702     QualType RHSType = TheCall->getArg(1)->getType();
5703 
5704     if (!LHSType->isVectorType() || !RHSType->isVectorType())
5705       return ExprError(
5706           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
5707           << TheCall->getDirectCallee()
5708           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5709                          TheCall->getArg(1)->getEndLoc()));
5710 
5711     numElements = LHSType->castAs<VectorType>()->getNumElements();
5712     unsigned numResElements = TheCall->getNumArgs() - 2;
5713 
5714     // Check to see if we have a call with 2 vector arguments, the unary shuffle
5715     // with mask.  If so, verify that RHS is an integer vector type with the
5716     // same number of elts as lhs.
5717     if (TheCall->getNumArgs() == 2) {
5718       if (!RHSType->hasIntegerRepresentation() ||
5719           RHSType->castAs<VectorType>()->getNumElements() != numElements)
5720         return ExprError(Diag(TheCall->getBeginLoc(),
5721                               diag::err_vec_builtin_incompatible_vector)
5722                          << TheCall->getDirectCallee()
5723                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
5724                                         TheCall->getArg(1)->getEndLoc()));
5725     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
5726       return ExprError(Diag(TheCall->getBeginLoc(),
5727                             diag::err_vec_builtin_incompatible_vector)
5728                        << TheCall->getDirectCallee()
5729                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5730                                       TheCall->getArg(1)->getEndLoc()));
5731     } else if (numElements != numResElements) {
5732       QualType eltType = LHSType->castAs<VectorType>()->getElementType();
5733       resType = Context.getVectorType(eltType, numResElements,
5734                                       VectorType::GenericVector);
5735     }
5736   }
5737 
5738   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
5739     if (TheCall->getArg(i)->isTypeDependent() ||
5740         TheCall->getArg(i)->isValueDependent())
5741       continue;
5742 
5743     llvm::APSInt Result(32);
5744     if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
5745       return ExprError(Diag(TheCall->getBeginLoc(),
5746                             diag::err_shufflevector_nonconstant_argument)
5747                        << TheCall->getArg(i)->getSourceRange());
5748 
5749     // Allow -1 which will be translated to undef in the IR.
5750     if (Result.isSigned() && Result.isAllOnesValue())
5751       continue;
5752 
5753     if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
5754       return ExprError(Diag(TheCall->getBeginLoc(),
5755                             diag::err_shufflevector_argument_too_large)
5756                        << TheCall->getArg(i)->getSourceRange());
5757   }
5758 
5759   SmallVector<Expr*, 32> exprs;
5760 
5761   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
5762     exprs.push_back(TheCall->getArg(i));
5763     TheCall->setArg(i, nullptr);
5764   }
5765 
5766   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
5767                                          TheCall->getCallee()->getBeginLoc(),
5768                                          TheCall->getRParenLoc());
5769 }
5770 
5771 /// SemaConvertVectorExpr - Handle __builtin_convertvector
5772 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
5773                                        SourceLocation BuiltinLoc,
5774                                        SourceLocation RParenLoc) {
5775   ExprValueKind VK = VK_RValue;
5776   ExprObjectKind OK = OK_Ordinary;
5777   QualType DstTy = TInfo->getType();
5778   QualType SrcTy = E->getType();
5779 
5780   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
5781     return ExprError(Diag(BuiltinLoc,
5782                           diag::err_convertvector_non_vector)
5783                      << E->getSourceRange());
5784   if (!DstTy->isVectorType() && !DstTy->isDependentType())
5785     return ExprError(Diag(BuiltinLoc,
5786                           diag::err_convertvector_non_vector_type));
5787 
5788   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
5789     unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
5790     unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
5791     if (SrcElts != DstElts)
5792       return ExprError(Diag(BuiltinLoc,
5793                             diag::err_convertvector_incompatible_vector)
5794                        << E->getSourceRange());
5795   }
5796 
5797   return new (Context)
5798       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5799 }
5800 
5801 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
5802 // This is declared to take (const void*, ...) and can take two
5803 // optional constant int args.
5804 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
5805   unsigned NumArgs = TheCall->getNumArgs();
5806 
5807   if (NumArgs > 3)
5808     return Diag(TheCall->getEndLoc(),
5809                 diag::err_typecheck_call_too_many_args_at_most)
5810            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
5811 
5812   // Argument 0 is checked for us and the remaining arguments must be
5813   // constant integers.
5814   for (unsigned i = 1; i != NumArgs; ++i)
5815     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
5816       return true;
5817 
5818   return false;
5819 }
5820 
5821 /// SemaBuiltinAssume - Handle __assume (MS Extension).
5822 // __assume does not evaluate its arguments, and should warn if its argument
5823 // has side effects.
5824 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
5825   Expr *Arg = TheCall->getArg(0);
5826   if (Arg->isInstantiationDependent()) return false;
5827 
5828   if (Arg->HasSideEffects(Context))
5829     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
5830         << Arg->getSourceRange()
5831         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
5832 
5833   return false;
5834 }
5835 
5836 /// Handle __builtin_alloca_with_align. This is declared
5837 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
5838 /// than 8.
5839 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
5840   // The alignment must be a constant integer.
5841   Expr *Arg = TheCall->getArg(1);
5842 
5843   // We can't check the value of a dependent argument.
5844   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
5845     if (const auto *UE =
5846             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
5847       if (UE->getKind() == UETT_AlignOf ||
5848           UE->getKind() == UETT_PreferredAlignOf)
5849         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
5850             << Arg->getSourceRange();
5851 
5852     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
5853 
5854     if (!Result.isPowerOf2())
5855       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5856              << Arg->getSourceRange();
5857 
5858     if (Result < Context.getCharWidth())
5859       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
5860              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
5861 
5862     if (Result > std::numeric_limits<int32_t>::max())
5863       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
5864              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
5865   }
5866 
5867   return false;
5868 }
5869 
5870 /// Handle __builtin_assume_aligned. This is declared
5871 /// as (const void*, size_t, ...) and can take one optional constant int arg.
5872 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
5873   unsigned NumArgs = TheCall->getNumArgs();
5874 
5875   if (NumArgs > 3)
5876     return Diag(TheCall->getEndLoc(),
5877                 diag::err_typecheck_call_too_many_args_at_most)
5878            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
5879 
5880   // The alignment must be a constant integer.
5881   Expr *Arg = TheCall->getArg(1);
5882 
5883   // We can't check the value of a dependent argument.
5884   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
5885     llvm::APSInt Result;
5886     if (SemaBuiltinConstantArg(TheCall, 1, Result))
5887       return true;
5888 
5889     if (!Result.isPowerOf2())
5890       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5891              << Arg->getSourceRange();
5892 
5893     if (Result > Sema::MaximumAlignment)
5894       Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
5895           << Arg->getSourceRange() << Sema::MaximumAlignment;
5896   }
5897 
5898   if (NumArgs > 2) {
5899     ExprResult Arg(TheCall->getArg(2));
5900     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5901       Context.getSizeType(), false);
5902     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5903     if (Arg.isInvalid()) return true;
5904     TheCall->setArg(2, Arg.get());
5905   }
5906 
5907   return false;
5908 }
5909 
5910 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
5911   unsigned BuiltinID =
5912       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
5913   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
5914 
5915   unsigned NumArgs = TheCall->getNumArgs();
5916   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
5917   if (NumArgs < NumRequiredArgs) {
5918     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5919            << 0 /* function call */ << NumRequiredArgs << NumArgs
5920            << TheCall->getSourceRange();
5921   }
5922   if (NumArgs >= NumRequiredArgs + 0x100) {
5923     return Diag(TheCall->getEndLoc(),
5924                 diag::err_typecheck_call_too_many_args_at_most)
5925            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
5926            << TheCall->getSourceRange();
5927   }
5928   unsigned i = 0;
5929 
5930   // For formatting call, check buffer arg.
5931   if (!IsSizeCall) {
5932     ExprResult Arg(TheCall->getArg(i));
5933     InitializedEntity Entity = InitializedEntity::InitializeParameter(
5934         Context, Context.VoidPtrTy, false);
5935     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5936     if (Arg.isInvalid())
5937       return true;
5938     TheCall->setArg(i, Arg.get());
5939     i++;
5940   }
5941 
5942   // Check string literal arg.
5943   unsigned FormatIdx = i;
5944   {
5945     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
5946     if (Arg.isInvalid())
5947       return true;
5948     TheCall->setArg(i, Arg.get());
5949     i++;
5950   }
5951 
5952   // Make sure variadic args are scalar.
5953   unsigned FirstDataArg = i;
5954   while (i < NumArgs) {
5955     ExprResult Arg = DefaultVariadicArgumentPromotion(
5956         TheCall->getArg(i), VariadicFunction, nullptr);
5957     if (Arg.isInvalid())
5958       return true;
5959     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
5960     if (ArgSize.getQuantity() >= 0x100) {
5961       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
5962              << i << (int)ArgSize.getQuantity() << 0xff
5963              << TheCall->getSourceRange();
5964     }
5965     TheCall->setArg(i, Arg.get());
5966     i++;
5967   }
5968 
5969   // Check formatting specifiers. NOTE: We're only doing this for the non-size
5970   // call to avoid duplicate diagnostics.
5971   if (!IsSizeCall) {
5972     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
5973     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
5974     bool Success = CheckFormatArguments(
5975         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
5976         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
5977         CheckedVarArgs);
5978     if (!Success)
5979       return true;
5980   }
5981 
5982   if (IsSizeCall) {
5983     TheCall->setType(Context.getSizeType());
5984   } else {
5985     TheCall->setType(Context.VoidPtrTy);
5986   }
5987   return false;
5988 }
5989 
5990 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
5991 /// TheCall is a constant expression.
5992 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
5993                                   llvm::APSInt &Result) {
5994   Expr *Arg = TheCall->getArg(ArgNum);
5995   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5996   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5997 
5998   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
5999 
6000   if (!Arg->isIntegerConstantExpr(Result, Context))
6001     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6002            << FDecl->getDeclName() << Arg->getSourceRange();
6003 
6004   return false;
6005 }
6006 
6007 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
6008 /// TheCall is a constant expression in the range [Low, High].
6009 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
6010                                        int Low, int High, bool RangeIsError) {
6011   if (isConstantEvaluated())
6012     return false;
6013   llvm::APSInt Result;
6014 
6015   // We can't check the value of a dependent argument.
6016   Expr *Arg = TheCall->getArg(ArgNum);
6017   if (Arg->isTypeDependent() || Arg->isValueDependent())
6018     return false;
6019 
6020   // Check constant-ness first.
6021   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6022     return true;
6023 
6024   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6025     if (RangeIsError)
6026       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
6027              << Result.toString(10) << Low << High << Arg->getSourceRange();
6028     else
6029       // Defer the warning until we know if the code will be emitted so that
6030       // dead code can ignore this.
6031       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6032                           PDiag(diag::warn_argument_invalid_range)
6033                               << Result.toString(10) << Low << High
6034                               << Arg->getSourceRange());
6035   }
6036 
6037   return false;
6038 }
6039 
6040 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
6041 /// TheCall is a constant expression is a multiple of Num..
6042 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
6043                                           unsigned Num) {
6044   llvm::APSInt Result;
6045 
6046   // We can't check the value of a dependent argument.
6047   Expr *Arg = TheCall->getArg(ArgNum);
6048   if (Arg->isTypeDependent() || Arg->isValueDependent())
6049     return false;
6050 
6051   // Check constant-ness first.
6052   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6053     return true;
6054 
6055   if (Result.getSExtValue() % Num != 0)
6056     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6057            << Num << Arg->getSourceRange();
6058 
6059   return false;
6060 }
6061 
6062 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
6063 /// constant expression representing a power of 2.
6064 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
6065   llvm::APSInt Result;
6066 
6067   // We can't check the value of a dependent argument.
6068   Expr *Arg = TheCall->getArg(ArgNum);
6069   if (Arg->isTypeDependent() || Arg->isValueDependent())
6070     return false;
6071 
6072   // Check constant-ness first.
6073   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6074     return true;
6075 
6076   // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
6077   // and only if x is a power of 2.
6078   if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
6079     return false;
6080 
6081   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
6082          << Arg->getSourceRange();
6083 }
6084 
6085 static bool IsShiftedByte(llvm::APSInt Value) {
6086   if (Value.isNegative())
6087     return false;
6088 
6089   // Check if it's a shifted byte, by shifting it down
6090   while (true) {
6091     // If the value fits in the bottom byte, the check passes.
6092     if (Value < 0x100)
6093       return true;
6094 
6095     // Otherwise, if the value has _any_ bits in the bottom byte, the check
6096     // fails.
6097     if ((Value & 0xFF) != 0)
6098       return false;
6099 
6100     // If the bottom 8 bits are all 0, but something above that is nonzero,
6101     // then shifting the value right by 8 bits won't affect whether it's a
6102     // shifted byte or not. So do that, and go round again.
6103     Value >>= 8;
6104   }
6105 }
6106 
6107 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
6108 /// a constant expression representing an arbitrary byte value shifted left by
6109 /// a multiple of 8 bits.
6110 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
6111                                              unsigned ArgBits) {
6112   llvm::APSInt Result;
6113 
6114   // We can't check the value of a dependent argument.
6115   Expr *Arg = TheCall->getArg(ArgNum);
6116   if (Arg->isTypeDependent() || Arg->isValueDependent())
6117     return false;
6118 
6119   // Check constant-ness first.
6120   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6121     return true;
6122 
6123   // Truncate to the given size.
6124   Result = Result.getLoBits(ArgBits);
6125   Result.setIsUnsigned(true);
6126 
6127   if (IsShiftedByte(Result))
6128     return false;
6129 
6130   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
6131          << Arg->getSourceRange();
6132 }
6133 
6134 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
6135 /// TheCall is a constant expression representing either a shifted byte value,
6136 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
6137 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
6138 /// Arm MVE intrinsics.
6139 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
6140                                                    int ArgNum,
6141                                                    unsigned ArgBits) {
6142   llvm::APSInt Result;
6143 
6144   // We can't check the value of a dependent argument.
6145   Expr *Arg = TheCall->getArg(ArgNum);
6146   if (Arg->isTypeDependent() || Arg->isValueDependent())
6147     return false;
6148 
6149   // Check constant-ness first.
6150   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6151     return true;
6152 
6153   // Truncate to the given size.
6154   Result = Result.getLoBits(ArgBits);
6155   Result.setIsUnsigned(true);
6156 
6157   // Check to see if it's in either of the required forms.
6158   if (IsShiftedByte(Result) ||
6159       (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
6160     return false;
6161 
6162   return Diag(TheCall->getBeginLoc(),
6163               diag::err_argument_not_shifted_byte_or_xxff)
6164          << Arg->getSourceRange();
6165 }
6166 
6167 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
6168 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
6169   if (BuiltinID == AArch64::BI__builtin_arm_irg) {
6170     if (checkArgCount(*this, TheCall, 2))
6171       return true;
6172     Expr *Arg0 = TheCall->getArg(0);
6173     Expr *Arg1 = TheCall->getArg(1);
6174 
6175     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6176     if (FirstArg.isInvalid())
6177       return true;
6178     QualType FirstArgType = FirstArg.get()->getType();
6179     if (!FirstArgType->isAnyPointerType())
6180       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6181                << "first" << FirstArgType << Arg0->getSourceRange();
6182     TheCall->setArg(0, FirstArg.get());
6183 
6184     ExprResult SecArg = DefaultLvalueConversion(Arg1);
6185     if (SecArg.isInvalid())
6186       return true;
6187     QualType SecArgType = SecArg.get()->getType();
6188     if (!SecArgType->isIntegerType())
6189       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6190                << "second" << SecArgType << Arg1->getSourceRange();
6191 
6192     // Derive the return type from the pointer argument.
6193     TheCall->setType(FirstArgType);
6194     return false;
6195   }
6196 
6197   if (BuiltinID == AArch64::BI__builtin_arm_addg) {
6198     if (checkArgCount(*this, TheCall, 2))
6199       return true;
6200 
6201     Expr *Arg0 = TheCall->getArg(0);
6202     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6203     if (FirstArg.isInvalid())
6204       return true;
6205     QualType FirstArgType = FirstArg.get()->getType();
6206     if (!FirstArgType->isAnyPointerType())
6207       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6208                << "first" << FirstArgType << Arg0->getSourceRange();
6209     TheCall->setArg(0, FirstArg.get());
6210 
6211     // Derive the return type from the pointer argument.
6212     TheCall->setType(FirstArgType);
6213 
6214     // Second arg must be an constant in range [0,15]
6215     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6216   }
6217 
6218   if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
6219     if (checkArgCount(*this, TheCall, 2))
6220       return true;
6221     Expr *Arg0 = TheCall->getArg(0);
6222     Expr *Arg1 = TheCall->getArg(1);
6223 
6224     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6225     if (FirstArg.isInvalid())
6226       return true;
6227     QualType FirstArgType = FirstArg.get()->getType();
6228     if (!FirstArgType->isAnyPointerType())
6229       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6230                << "first" << FirstArgType << Arg0->getSourceRange();
6231 
6232     QualType SecArgType = Arg1->getType();
6233     if (!SecArgType->isIntegerType())
6234       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6235                << "second" << SecArgType << Arg1->getSourceRange();
6236     TheCall->setType(Context.IntTy);
6237     return false;
6238   }
6239 
6240   if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
6241       BuiltinID == AArch64::BI__builtin_arm_stg) {
6242     if (checkArgCount(*this, TheCall, 1))
6243       return true;
6244     Expr *Arg0 = TheCall->getArg(0);
6245     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6246     if (FirstArg.isInvalid())
6247       return true;
6248 
6249     QualType FirstArgType = FirstArg.get()->getType();
6250     if (!FirstArgType->isAnyPointerType())
6251       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6252                << "first" << FirstArgType << Arg0->getSourceRange();
6253     TheCall->setArg(0, FirstArg.get());
6254 
6255     // Derive the return type from the pointer argument.
6256     if (BuiltinID == AArch64::BI__builtin_arm_ldg)
6257       TheCall->setType(FirstArgType);
6258     return false;
6259   }
6260 
6261   if (BuiltinID == AArch64::BI__builtin_arm_subp) {
6262     Expr *ArgA = TheCall->getArg(0);
6263     Expr *ArgB = TheCall->getArg(1);
6264 
6265     ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
6266     ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
6267 
6268     if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
6269       return true;
6270 
6271     QualType ArgTypeA = ArgExprA.get()->getType();
6272     QualType ArgTypeB = ArgExprB.get()->getType();
6273 
6274     auto isNull = [&] (Expr *E) -> bool {
6275       return E->isNullPointerConstant(
6276                         Context, Expr::NPC_ValueDependentIsNotNull); };
6277 
6278     // argument should be either a pointer or null
6279     if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
6280       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6281         << "first" << ArgTypeA << ArgA->getSourceRange();
6282 
6283     if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
6284       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6285         << "second" << ArgTypeB << ArgB->getSourceRange();
6286 
6287     // Ensure Pointee types are compatible
6288     if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
6289         ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
6290       QualType pointeeA = ArgTypeA->getPointeeType();
6291       QualType pointeeB = ArgTypeB->getPointeeType();
6292       if (!Context.typesAreCompatible(
6293              Context.getCanonicalType(pointeeA).getUnqualifiedType(),
6294              Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
6295         return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
6296           << ArgTypeA <<  ArgTypeB << ArgA->getSourceRange()
6297           << ArgB->getSourceRange();
6298       }
6299     }
6300 
6301     // at least one argument should be pointer type
6302     if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
6303       return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
6304         <<  ArgTypeA << ArgTypeB << ArgA->getSourceRange();
6305 
6306     if (isNull(ArgA)) // adopt type of the other pointer
6307       ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
6308 
6309     if (isNull(ArgB))
6310       ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
6311 
6312     TheCall->setArg(0, ArgExprA.get());
6313     TheCall->setArg(1, ArgExprB.get());
6314     TheCall->setType(Context.LongLongTy);
6315     return false;
6316   }
6317   assert(false && "Unhandled ARM MTE intrinsic");
6318   return true;
6319 }
6320 
6321 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
6322 /// TheCall is an ARM/AArch64 special register string literal.
6323 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
6324                                     int ArgNum, unsigned ExpectedFieldNum,
6325                                     bool AllowName) {
6326   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
6327                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
6328                       BuiltinID == ARM::BI__builtin_arm_rsr ||
6329                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
6330                       BuiltinID == ARM::BI__builtin_arm_wsr ||
6331                       BuiltinID == ARM::BI__builtin_arm_wsrp;
6332   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
6333                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
6334                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
6335                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
6336                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
6337                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
6338   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
6339 
6340   // We can't check the value of a dependent argument.
6341   Expr *Arg = TheCall->getArg(ArgNum);
6342   if (Arg->isTypeDependent() || Arg->isValueDependent())
6343     return false;
6344 
6345   // Check if the argument is a string literal.
6346   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
6347     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
6348            << Arg->getSourceRange();
6349 
6350   // Check the type of special register given.
6351   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
6352   SmallVector<StringRef, 6> Fields;
6353   Reg.split(Fields, ":");
6354 
6355   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
6356     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6357            << Arg->getSourceRange();
6358 
6359   // If the string is the name of a register then we cannot check that it is
6360   // valid here but if the string is of one the forms described in ACLE then we
6361   // can check that the supplied fields are integers and within the valid
6362   // ranges.
6363   if (Fields.size() > 1) {
6364     bool FiveFields = Fields.size() == 5;
6365 
6366     bool ValidString = true;
6367     if (IsARMBuiltin) {
6368       ValidString &= Fields[0].startswith_lower("cp") ||
6369                      Fields[0].startswith_lower("p");
6370       if (ValidString)
6371         Fields[0] =
6372           Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
6373 
6374       ValidString &= Fields[2].startswith_lower("c");
6375       if (ValidString)
6376         Fields[2] = Fields[2].drop_front(1);
6377 
6378       if (FiveFields) {
6379         ValidString &= Fields[3].startswith_lower("c");
6380         if (ValidString)
6381           Fields[3] = Fields[3].drop_front(1);
6382       }
6383     }
6384 
6385     SmallVector<int, 5> Ranges;
6386     if (FiveFields)
6387       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
6388     else
6389       Ranges.append({15, 7, 15});
6390 
6391     for (unsigned i=0; i<Fields.size(); ++i) {
6392       int IntField;
6393       ValidString &= !Fields[i].getAsInteger(10, IntField);
6394       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
6395     }
6396 
6397     if (!ValidString)
6398       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6399              << Arg->getSourceRange();
6400   } else if (IsAArch64Builtin && Fields.size() == 1) {
6401     // If the register name is one of those that appear in the condition below
6402     // and the special register builtin being used is one of the write builtins,
6403     // then we require that the argument provided for writing to the register
6404     // is an integer constant expression. This is because it will be lowered to
6405     // an MSR (immediate) instruction, so we need to know the immediate at
6406     // compile time.
6407     if (TheCall->getNumArgs() != 2)
6408       return false;
6409 
6410     std::string RegLower = Reg.lower();
6411     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
6412         RegLower != "pan" && RegLower != "uao")
6413       return false;
6414 
6415     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6416   }
6417 
6418   return false;
6419 }
6420 
6421 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
6422 /// This checks that the target supports __builtin_longjmp and
6423 /// that val is a constant 1.
6424 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
6425   if (!Context.getTargetInfo().hasSjLjLowering())
6426     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
6427            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6428 
6429   Expr *Arg = TheCall->getArg(1);
6430   llvm::APSInt Result;
6431 
6432   // TODO: This is less than ideal. Overload this to take a value.
6433   if (SemaBuiltinConstantArg(TheCall, 1, Result))
6434     return true;
6435 
6436   if (Result != 1)
6437     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
6438            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
6439 
6440   return false;
6441 }
6442 
6443 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
6444 /// This checks that the target supports __builtin_setjmp.
6445 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
6446   if (!Context.getTargetInfo().hasSjLjLowering())
6447     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
6448            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6449   return false;
6450 }
6451 
6452 namespace {
6453 
6454 class UncoveredArgHandler {
6455   enum { Unknown = -1, AllCovered = -2 };
6456 
6457   signed FirstUncoveredArg = Unknown;
6458   SmallVector<const Expr *, 4> DiagnosticExprs;
6459 
6460 public:
6461   UncoveredArgHandler() = default;
6462 
6463   bool hasUncoveredArg() const {
6464     return (FirstUncoveredArg >= 0);
6465   }
6466 
6467   unsigned getUncoveredArg() const {
6468     assert(hasUncoveredArg() && "no uncovered argument");
6469     return FirstUncoveredArg;
6470   }
6471 
6472   void setAllCovered() {
6473     // A string has been found with all arguments covered, so clear out
6474     // the diagnostics.
6475     DiagnosticExprs.clear();
6476     FirstUncoveredArg = AllCovered;
6477   }
6478 
6479   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
6480     assert(NewFirstUncoveredArg >= 0 && "Outside range");
6481 
6482     // Don't update if a previous string covers all arguments.
6483     if (FirstUncoveredArg == AllCovered)
6484       return;
6485 
6486     // UncoveredArgHandler tracks the highest uncovered argument index
6487     // and with it all the strings that match this index.
6488     if (NewFirstUncoveredArg == FirstUncoveredArg)
6489       DiagnosticExprs.push_back(StrExpr);
6490     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
6491       DiagnosticExprs.clear();
6492       DiagnosticExprs.push_back(StrExpr);
6493       FirstUncoveredArg = NewFirstUncoveredArg;
6494     }
6495   }
6496 
6497   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
6498 };
6499 
6500 enum StringLiteralCheckType {
6501   SLCT_NotALiteral,
6502   SLCT_UncheckedLiteral,
6503   SLCT_CheckedLiteral
6504 };
6505 
6506 } // namespace
6507 
6508 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
6509                                      BinaryOperatorKind BinOpKind,
6510                                      bool AddendIsRight) {
6511   unsigned BitWidth = Offset.getBitWidth();
6512   unsigned AddendBitWidth = Addend.getBitWidth();
6513   // There might be negative interim results.
6514   if (Addend.isUnsigned()) {
6515     Addend = Addend.zext(++AddendBitWidth);
6516     Addend.setIsSigned(true);
6517   }
6518   // Adjust the bit width of the APSInts.
6519   if (AddendBitWidth > BitWidth) {
6520     Offset = Offset.sext(AddendBitWidth);
6521     BitWidth = AddendBitWidth;
6522   } else if (BitWidth > AddendBitWidth) {
6523     Addend = Addend.sext(BitWidth);
6524   }
6525 
6526   bool Ov = false;
6527   llvm::APSInt ResOffset = Offset;
6528   if (BinOpKind == BO_Add)
6529     ResOffset = Offset.sadd_ov(Addend, Ov);
6530   else {
6531     assert(AddendIsRight && BinOpKind == BO_Sub &&
6532            "operator must be add or sub with addend on the right");
6533     ResOffset = Offset.ssub_ov(Addend, Ov);
6534   }
6535 
6536   // We add an offset to a pointer here so we should support an offset as big as
6537   // possible.
6538   if (Ov) {
6539     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
6540            "index (intermediate) result too big");
6541     Offset = Offset.sext(2 * BitWidth);
6542     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
6543     return;
6544   }
6545 
6546   Offset = ResOffset;
6547 }
6548 
6549 namespace {
6550 
6551 // This is a wrapper class around StringLiteral to support offsetted string
6552 // literals as format strings. It takes the offset into account when returning
6553 // the string and its length or the source locations to display notes correctly.
6554 class FormatStringLiteral {
6555   const StringLiteral *FExpr;
6556   int64_t Offset;
6557 
6558  public:
6559   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
6560       : FExpr(fexpr), Offset(Offset) {}
6561 
6562   StringRef getString() const {
6563     return FExpr->getString().drop_front(Offset);
6564   }
6565 
6566   unsigned getByteLength() const {
6567     return FExpr->getByteLength() - getCharByteWidth() * Offset;
6568   }
6569 
6570   unsigned getLength() const { return FExpr->getLength() - Offset; }
6571   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
6572 
6573   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
6574 
6575   QualType getType() const { return FExpr->getType(); }
6576 
6577   bool isAscii() const { return FExpr->isAscii(); }
6578   bool isWide() const { return FExpr->isWide(); }
6579   bool isUTF8() const { return FExpr->isUTF8(); }
6580   bool isUTF16() const { return FExpr->isUTF16(); }
6581   bool isUTF32() const { return FExpr->isUTF32(); }
6582   bool isPascal() const { return FExpr->isPascal(); }
6583 
6584   SourceLocation getLocationOfByte(
6585       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
6586       const TargetInfo &Target, unsigned *StartToken = nullptr,
6587       unsigned *StartTokenByteOffset = nullptr) const {
6588     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
6589                                     StartToken, StartTokenByteOffset);
6590   }
6591 
6592   SourceLocation getBeginLoc() const LLVM_READONLY {
6593     return FExpr->getBeginLoc().getLocWithOffset(Offset);
6594   }
6595 
6596   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
6597 };
6598 
6599 }  // namespace
6600 
6601 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
6602                               const Expr *OrigFormatExpr,
6603                               ArrayRef<const Expr *> Args,
6604                               bool HasVAListArg, unsigned format_idx,
6605                               unsigned firstDataArg,
6606                               Sema::FormatStringType Type,
6607                               bool inFunctionCall,
6608                               Sema::VariadicCallType CallType,
6609                               llvm::SmallBitVector &CheckedVarArgs,
6610                               UncoveredArgHandler &UncoveredArg,
6611                               bool IgnoreStringsWithoutSpecifiers);
6612 
6613 // Determine if an expression is a string literal or constant string.
6614 // If this function returns false on the arguments to a function expecting a
6615 // format string, we will usually need to emit a warning.
6616 // True string literals are then checked by CheckFormatString.
6617 static StringLiteralCheckType
6618 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
6619                       bool HasVAListArg, unsigned format_idx,
6620                       unsigned firstDataArg, Sema::FormatStringType Type,
6621                       Sema::VariadicCallType CallType, bool InFunctionCall,
6622                       llvm::SmallBitVector &CheckedVarArgs,
6623                       UncoveredArgHandler &UncoveredArg,
6624                       llvm::APSInt Offset,
6625                       bool IgnoreStringsWithoutSpecifiers = false) {
6626   if (S.isConstantEvaluated())
6627     return SLCT_NotALiteral;
6628  tryAgain:
6629   assert(Offset.isSigned() && "invalid offset");
6630 
6631   if (E->isTypeDependent() || E->isValueDependent())
6632     return SLCT_NotALiteral;
6633 
6634   E = E->IgnoreParenCasts();
6635 
6636   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
6637     // Technically -Wformat-nonliteral does not warn about this case.
6638     // The behavior of printf and friends in this case is implementation
6639     // dependent.  Ideally if the format string cannot be null then
6640     // it should have a 'nonnull' attribute in the function prototype.
6641     return SLCT_UncheckedLiteral;
6642 
6643   switch (E->getStmtClass()) {
6644   case Stmt::BinaryConditionalOperatorClass:
6645   case Stmt::ConditionalOperatorClass: {
6646     // The expression is a literal if both sub-expressions were, and it was
6647     // completely checked only if both sub-expressions were checked.
6648     const AbstractConditionalOperator *C =
6649         cast<AbstractConditionalOperator>(E);
6650 
6651     // Determine whether it is necessary to check both sub-expressions, for
6652     // example, because the condition expression is a constant that can be
6653     // evaluated at compile time.
6654     bool CheckLeft = true, CheckRight = true;
6655 
6656     bool Cond;
6657     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
6658                                                  S.isConstantEvaluated())) {
6659       if (Cond)
6660         CheckRight = false;
6661       else
6662         CheckLeft = false;
6663     }
6664 
6665     // We need to maintain the offsets for the right and the left hand side
6666     // separately to check if every possible indexed expression is a valid
6667     // string literal. They might have different offsets for different string
6668     // literals in the end.
6669     StringLiteralCheckType Left;
6670     if (!CheckLeft)
6671       Left = SLCT_UncheckedLiteral;
6672     else {
6673       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
6674                                    HasVAListArg, format_idx, firstDataArg,
6675                                    Type, CallType, InFunctionCall,
6676                                    CheckedVarArgs, UncoveredArg, Offset,
6677                                    IgnoreStringsWithoutSpecifiers);
6678       if (Left == SLCT_NotALiteral || !CheckRight) {
6679         return Left;
6680       }
6681     }
6682 
6683     StringLiteralCheckType Right = checkFormatStringExpr(
6684         S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
6685         Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6686         IgnoreStringsWithoutSpecifiers);
6687 
6688     return (CheckLeft && Left < Right) ? Left : Right;
6689   }
6690 
6691   case Stmt::ImplicitCastExprClass:
6692     E = cast<ImplicitCastExpr>(E)->getSubExpr();
6693     goto tryAgain;
6694 
6695   case Stmt::OpaqueValueExprClass:
6696     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
6697       E = src;
6698       goto tryAgain;
6699     }
6700     return SLCT_NotALiteral;
6701 
6702   case Stmt::PredefinedExprClass:
6703     // While __func__, etc., are technically not string literals, they
6704     // cannot contain format specifiers and thus are not a security
6705     // liability.
6706     return SLCT_UncheckedLiteral;
6707 
6708   case Stmt::DeclRefExprClass: {
6709     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6710 
6711     // As an exception, do not flag errors for variables binding to
6712     // const string literals.
6713     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
6714       bool isConstant = false;
6715       QualType T = DR->getType();
6716 
6717       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
6718         isConstant = AT->getElementType().isConstant(S.Context);
6719       } else if (const PointerType *PT = T->getAs<PointerType>()) {
6720         isConstant = T.isConstant(S.Context) &&
6721                      PT->getPointeeType().isConstant(S.Context);
6722       } else if (T->isObjCObjectPointerType()) {
6723         // In ObjC, there is usually no "const ObjectPointer" type,
6724         // so don't check if the pointee type is constant.
6725         isConstant = T.isConstant(S.Context);
6726       }
6727 
6728       if (isConstant) {
6729         if (const Expr *Init = VD->getAnyInitializer()) {
6730           // Look through initializers like const char c[] = { "foo" }
6731           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
6732             if (InitList->isStringLiteralInit())
6733               Init = InitList->getInit(0)->IgnoreParenImpCasts();
6734           }
6735           return checkFormatStringExpr(S, Init, Args,
6736                                        HasVAListArg, format_idx,
6737                                        firstDataArg, Type, CallType,
6738                                        /*InFunctionCall*/ false, CheckedVarArgs,
6739                                        UncoveredArg, Offset);
6740         }
6741       }
6742 
6743       // For vprintf* functions (i.e., HasVAListArg==true), we add a
6744       // special check to see if the format string is a function parameter
6745       // of the function calling the printf function.  If the function
6746       // has an attribute indicating it is a printf-like function, then we
6747       // should suppress warnings concerning non-literals being used in a call
6748       // to a vprintf function.  For example:
6749       //
6750       // void
6751       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
6752       //      va_list ap;
6753       //      va_start(ap, fmt);
6754       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
6755       //      ...
6756       // }
6757       if (HasVAListArg) {
6758         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
6759           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
6760             int PVIndex = PV->getFunctionScopeIndex() + 1;
6761             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
6762               // adjust for implicit parameter
6763               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6764                 if (MD->isInstance())
6765                   ++PVIndex;
6766               // We also check if the formats are compatible.
6767               // We can't pass a 'scanf' string to a 'printf' function.
6768               if (PVIndex == PVFormat->getFormatIdx() &&
6769                   Type == S.GetFormatStringType(PVFormat))
6770                 return SLCT_UncheckedLiteral;
6771             }
6772           }
6773         }
6774       }
6775     }
6776 
6777     return SLCT_NotALiteral;
6778   }
6779 
6780   case Stmt::CallExprClass:
6781   case Stmt::CXXMemberCallExprClass: {
6782     const CallExpr *CE = cast<CallExpr>(E);
6783     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
6784       bool IsFirst = true;
6785       StringLiteralCheckType CommonResult;
6786       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
6787         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
6788         StringLiteralCheckType Result = checkFormatStringExpr(
6789             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
6790             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6791             IgnoreStringsWithoutSpecifiers);
6792         if (IsFirst) {
6793           CommonResult = Result;
6794           IsFirst = false;
6795         }
6796       }
6797       if (!IsFirst)
6798         return CommonResult;
6799 
6800       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
6801         unsigned BuiltinID = FD->getBuiltinID();
6802         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
6803             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
6804           const Expr *Arg = CE->getArg(0);
6805           return checkFormatStringExpr(S, Arg, Args,
6806                                        HasVAListArg, format_idx,
6807                                        firstDataArg, Type, CallType,
6808                                        InFunctionCall, CheckedVarArgs,
6809                                        UncoveredArg, Offset,
6810                                        IgnoreStringsWithoutSpecifiers);
6811         }
6812       }
6813     }
6814 
6815     return SLCT_NotALiteral;
6816   }
6817   case Stmt::ObjCMessageExprClass: {
6818     const auto *ME = cast<ObjCMessageExpr>(E);
6819     if (const auto *MD = ME->getMethodDecl()) {
6820       if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
6821         // As a special case heuristic, if we're using the method -[NSBundle
6822         // localizedStringForKey:value:table:], ignore any key strings that lack
6823         // format specifiers. The idea is that if the key doesn't have any
6824         // format specifiers then its probably just a key to map to the
6825         // localized strings. If it does have format specifiers though, then its
6826         // likely that the text of the key is the format string in the
6827         // programmer's language, and should be checked.
6828         const ObjCInterfaceDecl *IFace;
6829         if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
6830             IFace->getIdentifier()->isStr("NSBundle") &&
6831             MD->getSelector().isKeywordSelector(
6832                 {"localizedStringForKey", "value", "table"})) {
6833           IgnoreStringsWithoutSpecifiers = true;
6834         }
6835 
6836         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
6837         return checkFormatStringExpr(
6838             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
6839             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6840             IgnoreStringsWithoutSpecifiers);
6841       }
6842     }
6843 
6844     return SLCT_NotALiteral;
6845   }
6846   case Stmt::ObjCStringLiteralClass:
6847   case Stmt::StringLiteralClass: {
6848     const StringLiteral *StrE = nullptr;
6849 
6850     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
6851       StrE = ObjCFExpr->getString();
6852     else
6853       StrE = cast<StringLiteral>(E);
6854 
6855     if (StrE) {
6856       if (Offset.isNegative() || Offset > StrE->getLength()) {
6857         // TODO: It would be better to have an explicit warning for out of
6858         // bounds literals.
6859         return SLCT_NotALiteral;
6860       }
6861       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
6862       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
6863                         firstDataArg, Type, InFunctionCall, CallType,
6864                         CheckedVarArgs, UncoveredArg,
6865                         IgnoreStringsWithoutSpecifiers);
6866       return SLCT_CheckedLiteral;
6867     }
6868 
6869     return SLCT_NotALiteral;
6870   }
6871   case Stmt::BinaryOperatorClass: {
6872     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
6873 
6874     // A string literal + an int offset is still a string literal.
6875     if (BinOp->isAdditiveOp()) {
6876       Expr::EvalResult LResult, RResult;
6877 
6878       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
6879           LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
6880       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
6881           RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
6882 
6883       if (LIsInt != RIsInt) {
6884         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
6885 
6886         if (LIsInt) {
6887           if (BinOpKind == BO_Add) {
6888             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
6889             E = BinOp->getRHS();
6890             goto tryAgain;
6891           }
6892         } else {
6893           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
6894           E = BinOp->getLHS();
6895           goto tryAgain;
6896         }
6897       }
6898     }
6899 
6900     return SLCT_NotALiteral;
6901   }
6902   case Stmt::UnaryOperatorClass: {
6903     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
6904     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
6905     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
6906       Expr::EvalResult IndexResult;
6907       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
6908                                        Expr::SE_NoSideEffects,
6909                                        S.isConstantEvaluated())) {
6910         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
6911                    /*RHS is int*/ true);
6912         E = ASE->getBase();
6913         goto tryAgain;
6914       }
6915     }
6916 
6917     return SLCT_NotALiteral;
6918   }
6919 
6920   default:
6921     return SLCT_NotALiteral;
6922   }
6923 }
6924 
6925 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
6926   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
6927       .Case("scanf", FST_Scanf)
6928       .Cases("printf", "printf0", FST_Printf)
6929       .Cases("NSString", "CFString", FST_NSString)
6930       .Case("strftime", FST_Strftime)
6931       .Case("strfmon", FST_Strfmon)
6932       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
6933       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
6934       .Case("os_trace", FST_OSLog)
6935       .Case("os_log", FST_OSLog)
6936       .Default(FST_Unknown);
6937 }
6938 
6939 /// CheckFormatArguments - Check calls to printf and scanf (and similar
6940 /// functions) for correct use of format strings.
6941 /// Returns true if a format string has been fully checked.
6942 bool Sema::CheckFormatArguments(const FormatAttr *Format,
6943                                 ArrayRef<const Expr *> Args,
6944                                 bool IsCXXMember,
6945                                 VariadicCallType CallType,
6946                                 SourceLocation Loc, SourceRange Range,
6947                                 llvm::SmallBitVector &CheckedVarArgs) {
6948   FormatStringInfo FSI;
6949   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
6950     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
6951                                 FSI.FirstDataArg, GetFormatStringType(Format),
6952                                 CallType, Loc, Range, CheckedVarArgs);
6953   return false;
6954 }
6955 
6956 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
6957                                 bool HasVAListArg, unsigned format_idx,
6958                                 unsigned firstDataArg, FormatStringType Type,
6959                                 VariadicCallType CallType,
6960                                 SourceLocation Loc, SourceRange Range,
6961                                 llvm::SmallBitVector &CheckedVarArgs) {
6962   // CHECK: printf/scanf-like function is called with no format string.
6963   if (format_idx >= Args.size()) {
6964     Diag(Loc, diag::warn_missing_format_string) << Range;
6965     return false;
6966   }
6967 
6968   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
6969 
6970   // CHECK: format string is not a string literal.
6971   //
6972   // Dynamically generated format strings are difficult to
6973   // automatically vet at compile time.  Requiring that format strings
6974   // are string literals: (1) permits the checking of format strings by
6975   // the compiler and thereby (2) can practically remove the source of
6976   // many format string exploits.
6977 
6978   // Format string can be either ObjC string (e.g. @"%d") or
6979   // C string (e.g. "%d")
6980   // ObjC string uses the same format specifiers as C string, so we can use
6981   // the same format string checking logic for both ObjC and C strings.
6982   UncoveredArgHandler UncoveredArg;
6983   StringLiteralCheckType CT =
6984       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
6985                             format_idx, firstDataArg, Type, CallType,
6986                             /*IsFunctionCall*/ true, CheckedVarArgs,
6987                             UncoveredArg,
6988                             /*no string offset*/ llvm::APSInt(64, false) = 0);
6989 
6990   // Generate a diagnostic where an uncovered argument is detected.
6991   if (UncoveredArg.hasUncoveredArg()) {
6992     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
6993     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
6994     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
6995   }
6996 
6997   if (CT != SLCT_NotALiteral)
6998     // Literal format string found, check done!
6999     return CT == SLCT_CheckedLiteral;
7000 
7001   // Strftime is particular as it always uses a single 'time' argument,
7002   // so it is safe to pass a non-literal string.
7003   if (Type == FST_Strftime)
7004     return false;
7005 
7006   // Do not emit diag when the string param is a macro expansion and the
7007   // format is either NSString or CFString. This is a hack to prevent
7008   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
7009   // which are usually used in place of NS and CF string literals.
7010   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
7011   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
7012     return false;
7013 
7014   // If there are no arguments specified, warn with -Wformat-security, otherwise
7015   // warn only with -Wformat-nonliteral.
7016   if (Args.size() == firstDataArg) {
7017     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
7018       << OrigFormatExpr->getSourceRange();
7019     switch (Type) {
7020     default:
7021       break;
7022     case FST_Kprintf:
7023     case FST_FreeBSDKPrintf:
7024     case FST_Printf:
7025       Diag(FormatLoc, diag::note_format_security_fixit)
7026         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
7027       break;
7028     case FST_NSString:
7029       Diag(FormatLoc, diag::note_format_security_fixit)
7030         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
7031       break;
7032     }
7033   } else {
7034     Diag(FormatLoc, diag::warn_format_nonliteral)
7035       << OrigFormatExpr->getSourceRange();
7036   }
7037   return false;
7038 }
7039 
7040 namespace {
7041 
7042 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
7043 protected:
7044   Sema &S;
7045   const FormatStringLiteral *FExpr;
7046   const Expr *OrigFormatExpr;
7047   const Sema::FormatStringType FSType;
7048   const unsigned FirstDataArg;
7049   const unsigned NumDataArgs;
7050   const char *Beg; // Start of format string.
7051   const bool HasVAListArg;
7052   ArrayRef<const Expr *> Args;
7053   unsigned FormatIdx;
7054   llvm::SmallBitVector CoveredArgs;
7055   bool usesPositionalArgs = false;
7056   bool atFirstArg = true;
7057   bool inFunctionCall;
7058   Sema::VariadicCallType CallType;
7059   llvm::SmallBitVector &CheckedVarArgs;
7060   UncoveredArgHandler &UncoveredArg;
7061 
7062 public:
7063   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
7064                      const Expr *origFormatExpr,
7065                      const Sema::FormatStringType type, unsigned firstDataArg,
7066                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
7067                      ArrayRef<const Expr *> Args, unsigned formatIdx,
7068                      bool inFunctionCall, Sema::VariadicCallType callType,
7069                      llvm::SmallBitVector &CheckedVarArgs,
7070                      UncoveredArgHandler &UncoveredArg)
7071       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
7072         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
7073         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
7074         inFunctionCall(inFunctionCall), CallType(callType),
7075         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
7076     CoveredArgs.resize(numDataArgs);
7077     CoveredArgs.reset();
7078   }
7079 
7080   void DoneProcessing();
7081 
7082   void HandleIncompleteSpecifier(const char *startSpecifier,
7083                                  unsigned specifierLen) override;
7084 
7085   void HandleInvalidLengthModifier(
7086                            const analyze_format_string::FormatSpecifier &FS,
7087                            const analyze_format_string::ConversionSpecifier &CS,
7088                            const char *startSpecifier, unsigned specifierLen,
7089                            unsigned DiagID);
7090 
7091   void HandleNonStandardLengthModifier(
7092                     const analyze_format_string::FormatSpecifier &FS,
7093                     const char *startSpecifier, unsigned specifierLen);
7094 
7095   void HandleNonStandardConversionSpecifier(
7096                     const analyze_format_string::ConversionSpecifier &CS,
7097                     const char *startSpecifier, unsigned specifierLen);
7098 
7099   void HandlePosition(const char *startPos, unsigned posLen) override;
7100 
7101   void HandleInvalidPosition(const char *startSpecifier,
7102                              unsigned specifierLen,
7103                              analyze_format_string::PositionContext p) override;
7104 
7105   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
7106 
7107   void HandleNullChar(const char *nullCharacter) override;
7108 
7109   template <typename Range>
7110   static void
7111   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
7112                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
7113                        bool IsStringLocation, Range StringRange,
7114                        ArrayRef<FixItHint> Fixit = None);
7115 
7116 protected:
7117   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
7118                                         const char *startSpec,
7119                                         unsigned specifierLen,
7120                                         const char *csStart, unsigned csLen);
7121 
7122   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
7123                                          const char *startSpec,
7124                                          unsigned specifierLen);
7125 
7126   SourceRange getFormatStringRange();
7127   CharSourceRange getSpecifierRange(const char *startSpecifier,
7128                                     unsigned specifierLen);
7129   SourceLocation getLocationOfByte(const char *x);
7130 
7131   const Expr *getDataArg(unsigned i) const;
7132 
7133   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
7134                     const analyze_format_string::ConversionSpecifier &CS,
7135                     const char *startSpecifier, unsigned specifierLen,
7136                     unsigned argIndex);
7137 
7138   template <typename Range>
7139   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
7140                             bool IsStringLocation, Range StringRange,
7141                             ArrayRef<FixItHint> Fixit = None);
7142 };
7143 
7144 } // namespace
7145 
7146 SourceRange CheckFormatHandler::getFormatStringRange() {
7147   return OrigFormatExpr->getSourceRange();
7148 }
7149 
7150 CharSourceRange CheckFormatHandler::
7151 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
7152   SourceLocation Start = getLocationOfByte(startSpecifier);
7153   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
7154 
7155   // Advance the end SourceLocation by one due to half-open ranges.
7156   End = End.getLocWithOffset(1);
7157 
7158   return CharSourceRange::getCharRange(Start, End);
7159 }
7160 
7161 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
7162   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
7163                                   S.getLangOpts(), S.Context.getTargetInfo());
7164 }
7165 
7166 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
7167                                                    unsigned specifierLen){
7168   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
7169                        getLocationOfByte(startSpecifier),
7170                        /*IsStringLocation*/true,
7171                        getSpecifierRange(startSpecifier, specifierLen));
7172 }
7173 
7174 void CheckFormatHandler::HandleInvalidLengthModifier(
7175     const analyze_format_string::FormatSpecifier &FS,
7176     const analyze_format_string::ConversionSpecifier &CS,
7177     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
7178   using namespace analyze_format_string;
7179 
7180   const LengthModifier &LM = FS.getLengthModifier();
7181   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7182 
7183   // See if we know how to fix this length modifier.
7184   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7185   if (FixedLM) {
7186     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7187                          getLocationOfByte(LM.getStart()),
7188                          /*IsStringLocation*/true,
7189                          getSpecifierRange(startSpecifier, specifierLen));
7190 
7191     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7192       << FixedLM->toString()
7193       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7194 
7195   } else {
7196     FixItHint Hint;
7197     if (DiagID == diag::warn_format_nonsensical_length)
7198       Hint = FixItHint::CreateRemoval(LMRange);
7199 
7200     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7201                          getLocationOfByte(LM.getStart()),
7202                          /*IsStringLocation*/true,
7203                          getSpecifierRange(startSpecifier, specifierLen),
7204                          Hint);
7205   }
7206 }
7207 
7208 void CheckFormatHandler::HandleNonStandardLengthModifier(
7209     const analyze_format_string::FormatSpecifier &FS,
7210     const char *startSpecifier, unsigned specifierLen) {
7211   using namespace analyze_format_string;
7212 
7213   const LengthModifier &LM = FS.getLengthModifier();
7214   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7215 
7216   // See if we know how to fix this length modifier.
7217   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7218   if (FixedLM) {
7219     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7220                            << LM.toString() << 0,
7221                          getLocationOfByte(LM.getStart()),
7222                          /*IsStringLocation*/true,
7223                          getSpecifierRange(startSpecifier, specifierLen));
7224 
7225     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7226       << FixedLM->toString()
7227       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7228 
7229   } else {
7230     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7231                            << LM.toString() << 0,
7232                          getLocationOfByte(LM.getStart()),
7233                          /*IsStringLocation*/true,
7234                          getSpecifierRange(startSpecifier, specifierLen));
7235   }
7236 }
7237 
7238 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
7239     const analyze_format_string::ConversionSpecifier &CS,
7240     const char *startSpecifier, unsigned specifierLen) {
7241   using namespace analyze_format_string;
7242 
7243   // See if we know how to fix this conversion specifier.
7244   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
7245   if (FixedCS) {
7246     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7247                           << CS.toString() << /*conversion specifier*/1,
7248                          getLocationOfByte(CS.getStart()),
7249                          /*IsStringLocation*/true,
7250                          getSpecifierRange(startSpecifier, specifierLen));
7251 
7252     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
7253     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
7254       << FixedCS->toString()
7255       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
7256   } else {
7257     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7258                           << CS.toString() << /*conversion specifier*/1,
7259                          getLocationOfByte(CS.getStart()),
7260                          /*IsStringLocation*/true,
7261                          getSpecifierRange(startSpecifier, specifierLen));
7262   }
7263 }
7264 
7265 void CheckFormatHandler::HandlePosition(const char *startPos,
7266                                         unsigned posLen) {
7267   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
7268                                getLocationOfByte(startPos),
7269                                /*IsStringLocation*/true,
7270                                getSpecifierRange(startPos, posLen));
7271 }
7272 
7273 void
7274 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
7275                                      analyze_format_string::PositionContext p) {
7276   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
7277                          << (unsigned) p,
7278                        getLocationOfByte(startPos), /*IsStringLocation*/true,
7279                        getSpecifierRange(startPos, posLen));
7280 }
7281 
7282 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
7283                                             unsigned posLen) {
7284   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
7285                                getLocationOfByte(startPos),
7286                                /*IsStringLocation*/true,
7287                                getSpecifierRange(startPos, posLen));
7288 }
7289 
7290 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
7291   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
7292     // The presence of a null character is likely an error.
7293     EmitFormatDiagnostic(
7294       S.PDiag(diag::warn_printf_format_string_contains_null_char),
7295       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
7296       getFormatStringRange());
7297   }
7298 }
7299 
7300 // Note that this may return NULL if there was an error parsing or building
7301 // one of the argument expressions.
7302 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
7303   return Args[FirstDataArg + i];
7304 }
7305 
7306 void CheckFormatHandler::DoneProcessing() {
7307   // Does the number of data arguments exceed the number of
7308   // format conversions in the format string?
7309   if (!HasVAListArg) {
7310       // Find any arguments that weren't covered.
7311     CoveredArgs.flip();
7312     signed notCoveredArg = CoveredArgs.find_first();
7313     if (notCoveredArg >= 0) {
7314       assert((unsigned)notCoveredArg < NumDataArgs);
7315       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
7316     } else {
7317       UncoveredArg.setAllCovered();
7318     }
7319   }
7320 }
7321 
7322 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
7323                                    const Expr *ArgExpr) {
7324   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
7325          "Invalid state");
7326 
7327   if (!ArgExpr)
7328     return;
7329 
7330   SourceLocation Loc = ArgExpr->getBeginLoc();
7331 
7332   if (S.getSourceManager().isInSystemMacro(Loc))
7333     return;
7334 
7335   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
7336   for (auto E : DiagnosticExprs)
7337     PDiag << E->getSourceRange();
7338 
7339   CheckFormatHandler::EmitFormatDiagnostic(
7340                                   S, IsFunctionCall, DiagnosticExprs[0],
7341                                   PDiag, Loc, /*IsStringLocation*/false,
7342                                   DiagnosticExprs[0]->getSourceRange());
7343 }
7344 
7345 bool
7346 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
7347                                                      SourceLocation Loc,
7348                                                      const char *startSpec,
7349                                                      unsigned specifierLen,
7350                                                      const char *csStart,
7351                                                      unsigned csLen) {
7352   bool keepGoing = true;
7353   if (argIndex < NumDataArgs) {
7354     // Consider the argument coverered, even though the specifier doesn't
7355     // make sense.
7356     CoveredArgs.set(argIndex);
7357   }
7358   else {
7359     // If argIndex exceeds the number of data arguments we
7360     // don't issue a warning because that is just a cascade of warnings (and
7361     // they may have intended '%%' anyway). We don't want to continue processing
7362     // the format string after this point, however, as we will like just get
7363     // gibberish when trying to match arguments.
7364     keepGoing = false;
7365   }
7366 
7367   StringRef Specifier(csStart, csLen);
7368 
7369   // If the specifier in non-printable, it could be the first byte of a UTF-8
7370   // sequence. In that case, print the UTF-8 code point. If not, print the byte
7371   // hex value.
7372   std::string CodePointStr;
7373   if (!llvm::sys::locale::isPrint(*csStart)) {
7374     llvm::UTF32 CodePoint;
7375     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
7376     const llvm::UTF8 *E =
7377         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
7378     llvm::ConversionResult Result =
7379         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
7380 
7381     if (Result != llvm::conversionOK) {
7382       unsigned char FirstChar = *csStart;
7383       CodePoint = (llvm::UTF32)FirstChar;
7384     }
7385 
7386     llvm::raw_string_ostream OS(CodePointStr);
7387     if (CodePoint < 256)
7388       OS << "\\x" << llvm::format("%02x", CodePoint);
7389     else if (CodePoint <= 0xFFFF)
7390       OS << "\\u" << llvm::format("%04x", CodePoint);
7391     else
7392       OS << "\\U" << llvm::format("%08x", CodePoint);
7393     OS.flush();
7394     Specifier = CodePointStr;
7395   }
7396 
7397   EmitFormatDiagnostic(
7398       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
7399       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
7400 
7401   return keepGoing;
7402 }
7403 
7404 void
7405 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
7406                                                       const char *startSpec,
7407                                                       unsigned specifierLen) {
7408   EmitFormatDiagnostic(
7409     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
7410     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
7411 }
7412 
7413 bool
7414 CheckFormatHandler::CheckNumArgs(
7415   const analyze_format_string::FormatSpecifier &FS,
7416   const analyze_format_string::ConversionSpecifier &CS,
7417   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
7418 
7419   if (argIndex >= NumDataArgs) {
7420     PartialDiagnostic PDiag = FS.usesPositionalArg()
7421       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
7422            << (argIndex+1) << NumDataArgs)
7423       : S.PDiag(diag::warn_printf_insufficient_data_args);
7424     EmitFormatDiagnostic(
7425       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
7426       getSpecifierRange(startSpecifier, specifierLen));
7427 
7428     // Since more arguments than conversion tokens are given, by extension
7429     // all arguments are covered, so mark this as so.
7430     UncoveredArg.setAllCovered();
7431     return false;
7432   }
7433   return true;
7434 }
7435 
7436 template<typename Range>
7437 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
7438                                               SourceLocation Loc,
7439                                               bool IsStringLocation,
7440                                               Range StringRange,
7441                                               ArrayRef<FixItHint> FixIt) {
7442   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
7443                        Loc, IsStringLocation, StringRange, FixIt);
7444 }
7445 
7446 /// If the format string is not within the function call, emit a note
7447 /// so that the function call and string are in diagnostic messages.
7448 ///
7449 /// \param InFunctionCall if true, the format string is within the function
7450 /// call and only one diagnostic message will be produced.  Otherwise, an
7451 /// extra note will be emitted pointing to location of the format string.
7452 ///
7453 /// \param ArgumentExpr the expression that is passed as the format string
7454 /// argument in the function call.  Used for getting locations when two
7455 /// diagnostics are emitted.
7456 ///
7457 /// \param PDiag the callee should already have provided any strings for the
7458 /// diagnostic message.  This function only adds locations and fixits
7459 /// to diagnostics.
7460 ///
7461 /// \param Loc primary location for diagnostic.  If two diagnostics are
7462 /// required, one will be at Loc and a new SourceLocation will be created for
7463 /// the other one.
7464 ///
7465 /// \param IsStringLocation if true, Loc points to the format string should be
7466 /// used for the note.  Otherwise, Loc points to the argument list and will
7467 /// be used with PDiag.
7468 ///
7469 /// \param StringRange some or all of the string to highlight.  This is
7470 /// templated so it can accept either a CharSourceRange or a SourceRange.
7471 ///
7472 /// \param FixIt optional fix it hint for the format string.
7473 template <typename Range>
7474 void CheckFormatHandler::EmitFormatDiagnostic(
7475     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
7476     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
7477     Range StringRange, ArrayRef<FixItHint> FixIt) {
7478   if (InFunctionCall) {
7479     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
7480     D << StringRange;
7481     D << FixIt;
7482   } else {
7483     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
7484       << ArgumentExpr->getSourceRange();
7485 
7486     const Sema::SemaDiagnosticBuilder &Note =
7487       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
7488              diag::note_format_string_defined);
7489 
7490     Note << StringRange;
7491     Note << FixIt;
7492   }
7493 }
7494 
7495 //===--- CHECK: Printf format string checking ------------------------------===//
7496 
7497 namespace {
7498 
7499 class CheckPrintfHandler : public CheckFormatHandler {
7500 public:
7501   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
7502                      const Expr *origFormatExpr,
7503                      const Sema::FormatStringType type, unsigned firstDataArg,
7504                      unsigned numDataArgs, bool isObjC, const char *beg,
7505                      bool hasVAListArg, ArrayRef<const Expr *> Args,
7506                      unsigned formatIdx, bool inFunctionCall,
7507                      Sema::VariadicCallType CallType,
7508                      llvm::SmallBitVector &CheckedVarArgs,
7509                      UncoveredArgHandler &UncoveredArg)
7510       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7511                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
7512                            inFunctionCall, CallType, CheckedVarArgs,
7513                            UncoveredArg) {}
7514 
7515   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
7516 
7517   /// Returns true if '%@' specifiers are allowed in the format string.
7518   bool allowsObjCArg() const {
7519     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
7520            FSType == Sema::FST_OSTrace;
7521   }
7522 
7523   bool HandleInvalidPrintfConversionSpecifier(
7524                                       const analyze_printf::PrintfSpecifier &FS,
7525                                       const char *startSpecifier,
7526                                       unsigned specifierLen) override;
7527 
7528   void handleInvalidMaskType(StringRef MaskType) override;
7529 
7530   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
7531                              const char *startSpecifier,
7532                              unsigned specifierLen) override;
7533   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7534                        const char *StartSpecifier,
7535                        unsigned SpecifierLen,
7536                        const Expr *E);
7537 
7538   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
7539                     const char *startSpecifier, unsigned specifierLen);
7540   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
7541                            const analyze_printf::OptionalAmount &Amt,
7542                            unsigned type,
7543                            const char *startSpecifier, unsigned specifierLen);
7544   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7545                   const analyze_printf::OptionalFlag &flag,
7546                   const char *startSpecifier, unsigned specifierLen);
7547   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
7548                          const analyze_printf::OptionalFlag &ignoredFlag,
7549                          const analyze_printf::OptionalFlag &flag,
7550                          const char *startSpecifier, unsigned specifierLen);
7551   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
7552                            const Expr *E);
7553 
7554   void HandleEmptyObjCModifierFlag(const char *startFlag,
7555                                    unsigned flagLen) override;
7556 
7557   void HandleInvalidObjCModifierFlag(const char *startFlag,
7558                                             unsigned flagLen) override;
7559 
7560   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
7561                                            const char *flagsEnd,
7562                                            const char *conversionPosition)
7563                                              override;
7564 };
7565 
7566 } // namespace
7567 
7568 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
7569                                       const analyze_printf::PrintfSpecifier &FS,
7570                                       const char *startSpecifier,
7571                                       unsigned specifierLen) {
7572   const analyze_printf::PrintfConversionSpecifier &CS =
7573     FS.getConversionSpecifier();
7574 
7575   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
7576                                           getLocationOfByte(CS.getStart()),
7577                                           startSpecifier, specifierLen,
7578                                           CS.getStart(), CS.getLength());
7579 }
7580 
7581 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
7582   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
7583 }
7584 
7585 bool CheckPrintfHandler::HandleAmount(
7586                                const analyze_format_string::OptionalAmount &Amt,
7587                                unsigned k, const char *startSpecifier,
7588                                unsigned specifierLen) {
7589   if (Amt.hasDataArgument()) {
7590     if (!HasVAListArg) {
7591       unsigned argIndex = Amt.getArgIndex();
7592       if (argIndex >= NumDataArgs) {
7593         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
7594                                << k,
7595                              getLocationOfByte(Amt.getStart()),
7596                              /*IsStringLocation*/true,
7597                              getSpecifierRange(startSpecifier, specifierLen));
7598         // Don't do any more checking.  We will just emit
7599         // spurious errors.
7600         return false;
7601       }
7602 
7603       // Type check the data argument.  It should be an 'int'.
7604       // Although not in conformance with C99, we also allow the argument to be
7605       // an 'unsigned int' as that is a reasonably safe case.  GCC also
7606       // doesn't emit a warning for that case.
7607       CoveredArgs.set(argIndex);
7608       const Expr *Arg = getDataArg(argIndex);
7609       if (!Arg)
7610         return false;
7611 
7612       QualType T = Arg->getType();
7613 
7614       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
7615       assert(AT.isValid());
7616 
7617       if (!AT.matchesType(S.Context, T)) {
7618         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
7619                                << k << AT.getRepresentativeTypeName(S.Context)
7620                                << T << Arg->getSourceRange(),
7621                              getLocationOfByte(Amt.getStart()),
7622                              /*IsStringLocation*/true,
7623                              getSpecifierRange(startSpecifier, specifierLen));
7624         // Don't do any more checking.  We will just emit
7625         // spurious errors.
7626         return false;
7627       }
7628     }
7629   }
7630   return true;
7631 }
7632 
7633 void CheckPrintfHandler::HandleInvalidAmount(
7634                                       const analyze_printf::PrintfSpecifier &FS,
7635                                       const analyze_printf::OptionalAmount &Amt,
7636                                       unsigned type,
7637                                       const char *startSpecifier,
7638                                       unsigned specifierLen) {
7639   const analyze_printf::PrintfConversionSpecifier &CS =
7640     FS.getConversionSpecifier();
7641 
7642   FixItHint fixit =
7643     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
7644       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
7645                                  Amt.getConstantLength()))
7646       : FixItHint();
7647 
7648   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
7649                          << type << CS.toString(),
7650                        getLocationOfByte(Amt.getStart()),
7651                        /*IsStringLocation*/true,
7652                        getSpecifierRange(startSpecifier, specifierLen),
7653                        fixit);
7654 }
7655 
7656 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7657                                     const analyze_printf::OptionalFlag &flag,
7658                                     const char *startSpecifier,
7659                                     unsigned specifierLen) {
7660   // Warn about pointless flag with a fixit removal.
7661   const analyze_printf::PrintfConversionSpecifier &CS =
7662     FS.getConversionSpecifier();
7663   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
7664                          << flag.toString() << CS.toString(),
7665                        getLocationOfByte(flag.getPosition()),
7666                        /*IsStringLocation*/true,
7667                        getSpecifierRange(startSpecifier, specifierLen),
7668                        FixItHint::CreateRemoval(
7669                          getSpecifierRange(flag.getPosition(), 1)));
7670 }
7671 
7672 void CheckPrintfHandler::HandleIgnoredFlag(
7673                                 const analyze_printf::PrintfSpecifier &FS,
7674                                 const analyze_printf::OptionalFlag &ignoredFlag,
7675                                 const analyze_printf::OptionalFlag &flag,
7676                                 const char *startSpecifier,
7677                                 unsigned specifierLen) {
7678   // Warn about ignored flag with a fixit removal.
7679   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
7680                          << ignoredFlag.toString() << flag.toString(),
7681                        getLocationOfByte(ignoredFlag.getPosition()),
7682                        /*IsStringLocation*/true,
7683                        getSpecifierRange(startSpecifier, specifierLen),
7684                        FixItHint::CreateRemoval(
7685                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
7686 }
7687 
7688 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
7689                                                      unsigned flagLen) {
7690   // Warn about an empty flag.
7691   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
7692                        getLocationOfByte(startFlag),
7693                        /*IsStringLocation*/true,
7694                        getSpecifierRange(startFlag, flagLen));
7695 }
7696 
7697 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
7698                                                        unsigned flagLen) {
7699   // Warn about an invalid flag.
7700   auto Range = getSpecifierRange(startFlag, flagLen);
7701   StringRef flag(startFlag, flagLen);
7702   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
7703                       getLocationOfByte(startFlag),
7704                       /*IsStringLocation*/true,
7705                       Range, FixItHint::CreateRemoval(Range));
7706 }
7707 
7708 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
7709     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
7710     // Warn about using '[...]' without a '@' conversion.
7711     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
7712     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
7713     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
7714                          getLocationOfByte(conversionPosition),
7715                          /*IsStringLocation*/true,
7716                          Range, FixItHint::CreateRemoval(Range));
7717 }
7718 
7719 // Determines if the specified is a C++ class or struct containing
7720 // a member with the specified name and kind (e.g. a CXXMethodDecl named
7721 // "c_str()").
7722 template<typename MemberKind>
7723 static llvm::SmallPtrSet<MemberKind*, 1>
7724 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
7725   const RecordType *RT = Ty->getAs<RecordType>();
7726   llvm::SmallPtrSet<MemberKind*, 1> Results;
7727 
7728   if (!RT)
7729     return Results;
7730   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
7731   if (!RD || !RD->getDefinition())
7732     return Results;
7733 
7734   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
7735                  Sema::LookupMemberName);
7736   R.suppressDiagnostics();
7737 
7738   // We just need to include all members of the right kind turned up by the
7739   // filter, at this point.
7740   if (S.LookupQualifiedName(R, RT->getDecl()))
7741     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7742       NamedDecl *decl = (*I)->getUnderlyingDecl();
7743       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
7744         Results.insert(FK);
7745     }
7746   return Results;
7747 }
7748 
7749 /// Check if we could call '.c_str()' on an object.
7750 ///
7751 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
7752 /// allow the call, or if it would be ambiguous).
7753 bool Sema::hasCStrMethod(const Expr *E) {
7754   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7755 
7756   MethodSet Results =
7757       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
7758   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7759        MI != ME; ++MI)
7760     if ((*MI)->getMinRequiredArguments() == 0)
7761       return true;
7762   return false;
7763 }
7764 
7765 // Check if a (w)string was passed when a (w)char* was needed, and offer a
7766 // better diagnostic if so. AT is assumed to be valid.
7767 // Returns true when a c_str() conversion method is found.
7768 bool CheckPrintfHandler::checkForCStrMembers(
7769     const analyze_printf::ArgType &AT, const Expr *E) {
7770   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7771 
7772   MethodSet Results =
7773       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
7774 
7775   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7776        MI != ME; ++MI) {
7777     const CXXMethodDecl *Method = *MI;
7778     if (Method->getMinRequiredArguments() == 0 &&
7779         AT.matchesType(S.Context, Method->getReturnType())) {
7780       // FIXME: Suggest parens if the expression needs them.
7781       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
7782       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
7783           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
7784       return true;
7785     }
7786   }
7787 
7788   return false;
7789 }
7790 
7791 bool
7792 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
7793                                             &FS,
7794                                           const char *startSpecifier,
7795                                           unsigned specifierLen) {
7796   using namespace analyze_format_string;
7797   using namespace analyze_printf;
7798 
7799   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
7800 
7801   if (FS.consumesDataArgument()) {
7802     if (atFirstArg) {
7803         atFirstArg = false;
7804         usesPositionalArgs = FS.usesPositionalArg();
7805     }
7806     else if (usesPositionalArgs != FS.usesPositionalArg()) {
7807       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
7808                                         startSpecifier, specifierLen);
7809       return false;
7810     }
7811   }
7812 
7813   // First check if the field width, precision, and conversion specifier
7814   // have matching data arguments.
7815   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
7816                     startSpecifier, specifierLen)) {
7817     return false;
7818   }
7819 
7820   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
7821                     startSpecifier, specifierLen)) {
7822     return false;
7823   }
7824 
7825   if (!CS.consumesDataArgument()) {
7826     // FIXME: Technically specifying a precision or field width here
7827     // makes no sense.  Worth issuing a warning at some point.
7828     return true;
7829   }
7830 
7831   // Consume the argument.
7832   unsigned argIndex = FS.getArgIndex();
7833   if (argIndex < NumDataArgs) {
7834     // The check to see if the argIndex is valid will come later.
7835     // We set the bit here because we may exit early from this
7836     // function if we encounter some other error.
7837     CoveredArgs.set(argIndex);
7838   }
7839 
7840   // FreeBSD kernel extensions.
7841   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
7842       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
7843     // We need at least two arguments.
7844     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
7845       return false;
7846 
7847     // Claim the second argument.
7848     CoveredArgs.set(argIndex + 1);
7849 
7850     // Type check the first argument (int for %b, pointer for %D)
7851     const Expr *Ex = getDataArg(argIndex);
7852     const analyze_printf::ArgType &AT =
7853       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
7854         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
7855     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
7856       EmitFormatDiagnostic(
7857           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7858               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
7859               << false << Ex->getSourceRange(),
7860           Ex->getBeginLoc(), /*IsStringLocation*/ false,
7861           getSpecifierRange(startSpecifier, specifierLen));
7862 
7863     // Type check the second argument (char * for both %b and %D)
7864     Ex = getDataArg(argIndex + 1);
7865     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
7866     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
7867       EmitFormatDiagnostic(
7868           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7869               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
7870               << false << Ex->getSourceRange(),
7871           Ex->getBeginLoc(), /*IsStringLocation*/ false,
7872           getSpecifierRange(startSpecifier, specifierLen));
7873 
7874      return true;
7875   }
7876 
7877   // Check for using an Objective-C specific conversion specifier
7878   // in a non-ObjC literal.
7879   if (!allowsObjCArg() && CS.isObjCArg()) {
7880     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7881                                                   specifierLen);
7882   }
7883 
7884   // %P can only be used with os_log.
7885   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
7886     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7887                                                   specifierLen);
7888   }
7889 
7890   // %n is not allowed with os_log.
7891   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
7892     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
7893                          getLocationOfByte(CS.getStart()),
7894                          /*IsStringLocation*/ false,
7895                          getSpecifierRange(startSpecifier, specifierLen));
7896 
7897     return true;
7898   }
7899 
7900   // Only scalars are allowed for os_trace.
7901   if (FSType == Sema::FST_OSTrace &&
7902       (CS.getKind() == ConversionSpecifier::PArg ||
7903        CS.getKind() == ConversionSpecifier::sArg ||
7904        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
7905     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7906                                                   specifierLen);
7907   }
7908 
7909   // Check for use of public/private annotation outside of os_log().
7910   if (FSType != Sema::FST_OSLog) {
7911     if (FS.isPublic().isSet()) {
7912       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
7913                                << "public",
7914                            getLocationOfByte(FS.isPublic().getPosition()),
7915                            /*IsStringLocation*/ false,
7916                            getSpecifierRange(startSpecifier, specifierLen));
7917     }
7918     if (FS.isPrivate().isSet()) {
7919       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
7920                                << "private",
7921                            getLocationOfByte(FS.isPrivate().getPosition()),
7922                            /*IsStringLocation*/ false,
7923                            getSpecifierRange(startSpecifier, specifierLen));
7924     }
7925   }
7926 
7927   // Check for invalid use of field width
7928   if (!FS.hasValidFieldWidth()) {
7929     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
7930         startSpecifier, specifierLen);
7931   }
7932 
7933   // Check for invalid use of precision
7934   if (!FS.hasValidPrecision()) {
7935     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
7936         startSpecifier, specifierLen);
7937   }
7938 
7939   // Precision is mandatory for %P specifier.
7940   if (CS.getKind() == ConversionSpecifier::PArg &&
7941       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
7942     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
7943                          getLocationOfByte(startSpecifier),
7944                          /*IsStringLocation*/ false,
7945                          getSpecifierRange(startSpecifier, specifierLen));
7946   }
7947 
7948   // Check each flag does not conflict with any other component.
7949   if (!FS.hasValidThousandsGroupingPrefix())
7950     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
7951   if (!FS.hasValidLeadingZeros())
7952     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
7953   if (!FS.hasValidPlusPrefix())
7954     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
7955   if (!FS.hasValidSpacePrefix())
7956     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
7957   if (!FS.hasValidAlternativeForm())
7958     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
7959   if (!FS.hasValidLeftJustified())
7960     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
7961 
7962   // Check that flags are not ignored by another flag
7963   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
7964     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
7965         startSpecifier, specifierLen);
7966   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
7967     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
7968             startSpecifier, specifierLen);
7969 
7970   // Check the length modifier is valid with the given conversion specifier.
7971   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
7972                                  S.getLangOpts()))
7973     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7974                                 diag::warn_format_nonsensical_length);
7975   else if (!FS.hasStandardLengthModifier())
7976     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
7977   else if (!FS.hasStandardLengthConversionCombination())
7978     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7979                                 diag::warn_format_non_standard_conversion_spec);
7980 
7981   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
7982     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
7983 
7984   // The remaining checks depend on the data arguments.
7985   if (HasVAListArg)
7986     return true;
7987 
7988   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
7989     return false;
7990 
7991   const Expr *Arg = getDataArg(argIndex);
7992   if (!Arg)
7993     return true;
7994 
7995   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
7996 }
7997 
7998 static bool requiresParensToAddCast(const Expr *E) {
7999   // FIXME: We should have a general way to reason about operator
8000   // precedence and whether parens are actually needed here.
8001   // Take care of a few common cases where they aren't.
8002   const Expr *Inside = E->IgnoreImpCasts();
8003   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
8004     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
8005 
8006   switch (Inside->getStmtClass()) {
8007   case Stmt::ArraySubscriptExprClass:
8008   case Stmt::CallExprClass:
8009   case Stmt::CharacterLiteralClass:
8010   case Stmt::CXXBoolLiteralExprClass:
8011   case Stmt::DeclRefExprClass:
8012   case Stmt::FloatingLiteralClass:
8013   case Stmt::IntegerLiteralClass:
8014   case Stmt::MemberExprClass:
8015   case Stmt::ObjCArrayLiteralClass:
8016   case Stmt::ObjCBoolLiteralExprClass:
8017   case Stmt::ObjCBoxedExprClass:
8018   case Stmt::ObjCDictionaryLiteralClass:
8019   case Stmt::ObjCEncodeExprClass:
8020   case Stmt::ObjCIvarRefExprClass:
8021   case Stmt::ObjCMessageExprClass:
8022   case Stmt::ObjCPropertyRefExprClass:
8023   case Stmt::ObjCStringLiteralClass:
8024   case Stmt::ObjCSubscriptRefExprClass:
8025   case Stmt::ParenExprClass:
8026   case Stmt::StringLiteralClass:
8027   case Stmt::UnaryOperatorClass:
8028     return false;
8029   default:
8030     return true;
8031   }
8032 }
8033 
8034 static std::pair<QualType, StringRef>
8035 shouldNotPrintDirectly(const ASTContext &Context,
8036                        QualType IntendedTy,
8037                        const Expr *E) {
8038   // Use a 'while' to peel off layers of typedefs.
8039   QualType TyTy = IntendedTy;
8040   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
8041     StringRef Name = UserTy->getDecl()->getName();
8042     QualType CastTy = llvm::StringSwitch<QualType>(Name)
8043       .Case("CFIndex", Context.getNSIntegerType())
8044       .Case("NSInteger", Context.getNSIntegerType())
8045       .Case("NSUInteger", Context.getNSUIntegerType())
8046       .Case("SInt32", Context.IntTy)
8047       .Case("UInt32", Context.UnsignedIntTy)
8048       .Default(QualType());
8049 
8050     if (!CastTy.isNull())
8051       return std::make_pair(CastTy, Name);
8052 
8053     TyTy = UserTy->desugar();
8054   }
8055 
8056   // Strip parens if necessary.
8057   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
8058     return shouldNotPrintDirectly(Context,
8059                                   PE->getSubExpr()->getType(),
8060                                   PE->getSubExpr());
8061 
8062   // If this is a conditional expression, then its result type is constructed
8063   // via usual arithmetic conversions and thus there might be no necessary
8064   // typedef sugar there.  Recurse to operands to check for NSInteger &
8065   // Co. usage condition.
8066   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8067     QualType TrueTy, FalseTy;
8068     StringRef TrueName, FalseName;
8069 
8070     std::tie(TrueTy, TrueName) =
8071       shouldNotPrintDirectly(Context,
8072                              CO->getTrueExpr()->getType(),
8073                              CO->getTrueExpr());
8074     std::tie(FalseTy, FalseName) =
8075       shouldNotPrintDirectly(Context,
8076                              CO->getFalseExpr()->getType(),
8077                              CO->getFalseExpr());
8078 
8079     if (TrueTy == FalseTy)
8080       return std::make_pair(TrueTy, TrueName);
8081     else if (TrueTy.isNull())
8082       return std::make_pair(FalseTy, FalseName);
8083     else if (FalseTy.isNull())
8084       return std::make_pair(TrueTy, TrueName);
8085   }
8086 
8087   return std::make_pair(QualType(), StringRef());
8088 }
8089 
8090 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
8091 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
8092 /// type do not count.
8093 static bool
8094 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
8095   QualType From = ICE->getSubExpr()->getType();
8096   QualType To = ICE->getType();
8097   // It's an integer promotion if the destination type is the promoted
8098   // source type.
8099   if (ICE->getCastKind() == CK_IntegralCast &&
8100       From->isPromotableIntegerType() &&
8101       S.Context.getPromotedIntegerType(From) == To)
8102     return true;
8103   // Look through vector types, since we do default argument promotion for
8104   // those in OpenCL.
8105   if (const auto *VecTy = From->getAs<ExtVectorType>())
8106     From = VecTy->getElementType();
8107   if (const auto *VecTy = To->getAs<ExtVectorType>())
8108     To = VecTy->getElementType();
8109   // It's a floating promotion if the source type is a lower rank.
8110   return ICE->getCastKind() == CK_FloatingCast &&
8111          S.Context.getFloatingTypeOrder(From, To) < 0;
8112 }
8113 
8114 bool
8115 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8116                                     const char *StartSpecifier,
8117                                     unsigned SpecifierLen,
8118                                     const Expr *E) {
8119   using namespace analyze_format_string;
8120   using namespace analyze_printf;
8121 
8122   // Now type check the data expression that matches the
8123   // format specifier.
8124   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
8125   if (!AT.isValid())
8126     return true;
8127 
8128   QualType ExprTy = E->getType();
8129   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
8130     ExprTy = TET->getUnderlyingExpr()->getType();
8131   }
8132 
8133   // Diagnose attempts to print a boolean value as a character. Unlike other
8134   // -Wformat diagnostics, this is fine from a type perspective, but it still
8135   // doesn't make sense.
8136   if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
8137       E->isKnownToHaveBooleanValue()) {
8138     const CharSourceRange &CSR =
8139         getSpecifierRange(StartSpecifier, SpecifierLen);
8140     SmallString<4> FSString;
8141     llvm::raw_svector_ostream os(FSString);
8142     FS.toString(os);
8143     EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
8144                              << FSString,
8145                          E->getExprLoc(), false, CSR);
8146     return true;
8147   }
8148 
8149   analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
8150   if (Match == analyze_printf::ArgType::Match)
8151     return true;
8152 
8153   // Look through argument promotions for our error message's reported type.
8154   // This includes the integral and floating promotions, but excludes array
8155   // and function pointer decay (seeing that an argument intended to be a
8156   // string has type 'char [6]' is probably more confusing than 'char *') and
8157   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
8158   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8159     if (isArithmeticArgumentPromotion(S, ICE)) {
8160       E = ICE->getSubExpr();
8161       ExprTy = E->getType();
8162 
8163       // Check if we didn't match because of an implicit cast from a 'char'
8164       // or 'short' to an 'int'.  This is done because printf is a varargs
8165       // function.
8166       if (ICE->getType() == S.Context.IntTy ||
8167           ICE->getType() == S.Context.UnsignedIntTy) {
8168         // All further checking is done on the subexpression
8169         const analyze_printf::ArgType::MatchKind ImplicitMatch =
8170             AT.matchesType(S.Context, ExprTy);
8171         if (ImplicitMatch == analyze_printf::ArgType::Match)
8172           return true;
8173         if (ImplicitMatch == ArgType::NoMatchPedantic ||
8174             ImplicitMatch == ArgType::NoMatchTypeConfusion)
8175           Match = ImplicitMatch;
8176       }
8177     }
8178   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
8179     // Special case for 'a', which has type 'int' in C.
8180     // Note, however, that we do /not/ want to treat multibyte constants like
8181     // 'MooV' as characters! This form is deprecated but still exists.
8182     if (ExprTy == S.Context.IntTy)
8183       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
8184         ExprTy = S.Context.CharTy;
8185   }
8186 
8187   // Look through enums to their underlying type.
8188   bool IsEnum = false;
8189   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
8190     ExprTy = EnumTy->getDecl()->getIntegerType();
8191     IsEnum = true;
8192   }
8193 
8194   // %C in an Objective-C context prints a unichar, not a wchar_t.
8195   // If the argument is an integer of some kind, believe the %C and suggest
8196   // a cast instead of changing the conversion specifier.
8197   QualType IntendedTy = ExprTy;
8198   if (isObjCContext() &&
8199       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
8200     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
8201         !ExprTy->isCharType()) {
8202       // 'unichar' is defined as a typedef of unsigned short, but we should
8203       // prefer using the typedef if it is visible.
8204       IntendedTy = S.Context.UnsignedShortTy;
8205 
8206       // While we are here, check if the value is an IntegerLiteral that happens
8207       // to be within the valid range.
8208       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
8209         const llvm::APInt &V = IL->getValue();
8210         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
8211           return true;
8212       }
8213 
8214       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
8215                           Sema::LookupOrdinaryName);
8216       if (S.LookupName(Result, S.getCurScope())) {
8217         NamedDecl *ND = Result.getFoundDecl();
8218         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
8219           if (TD->getUnderlyingType() == IntendedTy)
8220             IntendedTy = S.Context.getTypedefType(TD);
8221       }
8222     }
8223   }
8224 
8225   // Special-case some of Darwin's platform-independence types by suggesting
8226   // casts to primitive types that are known to be large enough.
8227   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
8228   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
8229     QualType CastTy;
8230     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
8231     if (!CastTy.isNull()) {
8232       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
8233       // (long in ASTContext). Only complain to pedants.
8234       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
8235           (AT.isSizeT() || AT.isPtrdiffT()) &&
8236           AT.matchesType(S.Context, CastTy))
8237         Match = ArgType::NoMatchPedantic;
8238       IntendedTy = CastTy;
8239       ShouldNotPrintDirectly = true;
8240     }
8241   }
8242 
8243   // We may be able to offer a FixItHint if it is a supported type.
8244   PrintfSpecifier fixedFS = FS;
8245   bool Success =
8246       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
8247 
8248   if (Success) {
8249     // Get the fix string from the fixed format specifier
8250     SmallString<16> buf;
8251     llvm::raw_svector_ostream os(buf);
8252     fixedFS.toString(os);
8253 
8254     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
8255 
8256     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
8257       unsigned Diag;
8258       switch (Match) {
8259       case ArgType::Match: llvm_unreachable("expected non-matching");
8260       case ArgType::NoMatchPedantic:
8261         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8262         break;
8263       case ArgType::NoMatchTypeConfusion:
8264         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8265         break;
8266       case ArgType::NoMatch:
8267         Diag = diag::warn_format_conversion_argument_type_mismatch;
8268         break;
8269       }
8270 
8271       // In this case, the specifier is wrong and should be changed to match
8272       // the argument.
8273       EmitFormatDiagnostic(S.PDiag(Diag)
8274                                << AT.getRepresentativeTypeName(S.Context)
8275                                << IntendedTy << IsEnum << E->getSourceRange(),
8276                            E->getBeginLoc(),
8277                            /*IsStringLocation*/ false, SpecRange,
8278                            FixItHint::CreateReplacement(SpecRange, os.str()));
8279     } else {
8280       // The canonical type for formatting this value is different from the
8281       // actual type of the expression. (This occurs, for example, with Darwin's
8282       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
8283       // should be printed as 'long' for 64-bit compatibility.)
8284       // Rather than emitting a normal format/argument mismatch, we want to
8285       // add a cast to the recommended type (and correct the format string
8286       // if necessary).
8287       SmallString<16> CastBuf;
8288       llvm::raw_svector_ostream CastFix(CastBuf);
8289       CastFix << "(";
8290       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
8291       CastFix << ")";
8292 
8293       SmallVector<FixItHint,4> Hints;
8294       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
8295         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
8296 
8297       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
8298         // If there's already a cast present, just replace it.
8299         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
8300         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
8301 
8302       } else if (!requiresParensToAddCast(E)) {
8303         // If the expression has high enough precedence,
8304         // just write the C-style cast.
8305         Hints.push_back(
8306             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8307       } else {
8308         // Otherwise, add parens around the expression as well as the cast.
8309         CastFix << "(";
8310         Hints.push_back(
8311             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8312 
8313         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
8314         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
8315       }
8316 
8317       if (ShouldNotPrintDirectly) {
8318         // The expression has a type that should not be printed directly.
8319         // We extract the name from the typedef because we don't want to show
8320         // the underlying type in the diagnostic.
8321         StringRef Name;
8322         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
8323           Name = TypedefTy->getDecl()->getName();
8324         else
8325           Name = CastTyName;
8326         unsigned Diag = Match == ArgType::NoMatchPedantic
8327                             ? diag::warn_format_argument_needs_cast_pedantic
8328                             : diag::warn_format_argument_needs_cast;
8329         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
8330                                            << E->getSourceRange(),
8331                              E->getBeginLoc(), /*IsStringLocation=*/false,
8332                              SpecRange, Hints);
8333       } else {
8334         // In this case, the expression could be printed using a different
8335         // specifier, but we've decided that the specifier is probably correct
8336         // and we should cast instead. Just use the normal warning message.
8337         EmitFormatDiagnostic(
8338             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8339                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
8340                 << E->getSourceRange(),
8341             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
8342       }
8343     }
8344   } else {
8345     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
8346                                                    SpecifierLen);
8347     // Since the warning for passing non-POD types to variadic functions
8348     // was deferred until now, we emit a warning for non-POD
8349     // arguments here.
8350     switch (S.isValidVarArgType(ExprTy)) {
8351     case Sema::VAK_Valid:
8352     case Sema::VAK_ValidInCXX11: {
8353       unsigned Diag;
8354       switch (Match) {
8355       case ArgType::Match: llvm_unreachable("expected non-matching");
8356       case ArgType::NoMatchPedantic:
8357         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8358         break;
8359       case ArgType::NoMatchTypeConfusion:
8360         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8361         break;
8362       case ArgType::NoMatch:
8363         Diag = diag::warn_format_conversion_argument_type_mismatch;
8364         break;
8365       }
8366 
8367       EmitFormatDiagnostic(
8368           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
8369                         << IsEnum << CSR << E->getSourceRange(),
8370           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8371       break;
8372     }
8373     case Sema::VAK_Undefined:
8374     case Sema::VAK_MSVCUndefined:
8375       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
8376                                << S.getLangOpts().CPlusPlus11 << ExprTy
8377                                << CallType
8378                                << AT.getRepresentativeTypeName(S.Context) << CSR
8379                                << E->getSourceRange(),
8380                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8381       checkForCStrMembers(AT, E);
8382       break;
8383 
8384     case Sema::VAK_Invalid:
8385       if (ExprTy->isObjCObjectType())
8386         EmitFormatDiagnostic(
8387             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
8388                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
8389                 << AT.getRepresentativeTypeName(S.Context) << CSR
8390                 << E->getSourceRange(),
8391             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8392       else
8393         // FIXME: If this is an initializer list, suggest removing the braces
8394         // or inserting a cast to the target type.
8395         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
8396             << isa<InitListExpr>(E) << ExprTy << CallType
8397             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
8398       break;
8399     }
8400 
8401     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
8402            "format string specifier index out of range");
8403     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
8404   }
8405 
8406   return true;
8407 }
8408 
8409 //===--- CHECK: Scanf format string checking ------------------------------===//
8410 
8411 namespace {
8412 
8413 class CheckScanfHandler : public CheckFormatHandler {
8414 public:
8415   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
8416                     const Expr *origFormatExpr, Sema::FormatStringType type,
8417                     unsigned firstDataArg, unsigned numDataArgs,
8418                     const char *beg, bool hasVAListArg,
8419                     ArrayRef<const Expr *> Args, unsigned formatIdx,
8420                     bool inFunctionCall, Sema::VariadicCallType CallType,
8421                     llvm::SmallBitVector &CheckedVarArgs,
8422                     UncoveredArgHandler &UncoveredArg)
8423       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8424                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
8425                            inFunctionCall, CallType, CheckedVarArgs,
8426                            UncoveredArg) {}
8427 
8428   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
8429                             const char *startSpecifier,
8430                             unsigned specifierLen) override;
8431 
8432   bool HandleInvalidScanfConversionSpecifier(
8433           const analyze_scanf::ScanfSpecifier &FS,
8434           const char *startSpecifier,
8435           unsigned specifierLen) override;
8436 
8437   void HandleIncompleteScanList(const char *start, const char *end) override;
8438 };
8439 
8440 } // namespace
8441 
8442 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
8443                                                  const char *end) {
8444   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
8445                        getLocationOfByte(end), /*IsStringLocation*/true,
8446                        getSpecifierRange(start, end - start));
8447 }
8448 
8449 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
8450                                         const analyze_scanf::ScanfSpecifier &FS,
8451                                         const char *startSpecifier,
8452                                         unsigned specifierLen) {
8453   const analyze_scanf::ScanfConversionSpecifier &CS =
8454     FS.getConversionSpecifier();
8455 
8456   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8457                                           getLocationOfByte(CS.getStart()),
8458                                           startSpecifier, specifierLen,
8459                                           CS.getStart(), CS.getLength());
8460 }
8461 
8462 bool CheckScanfHandler::HandleScanfSpecifier(
8463                                        const analyze_scanf::ScanfSpecifier &FS,
8464                                        const char *startSpecifier,
8465                                        unsigned specifierLen) {
8466   using namespace analyze_scanf;
8467   using namespace analyze_format_string;
8468 
8469   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
8470 
8471   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
8472   // be used to decide if we are using positional arguments consistently.
8473   if (FS.consumesDataArgument()) {
8474     if (atFirstArg) {
8475       atFirstArg = false;
8476       usesPositionalArgs = FS.usesPositionalArg();
8477     }
8478     else if (usesPositionalArgs != FS.usesPositionalArg()) {
8479       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8480                                         startSpecifier, specifierLen);
8481       return false;
8482     }
8483   }
8484 
8485   // Check if the field with is non-zero.
8486   const OptionalAmount &Amt = FS.getFieldWidth();
8487   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
8488     if (Amt.getConstantAmount() == 0) {
8489       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
8490                                                    Amt.getConstantLength());
8491       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
8492                            getLocationOfByte(Amt.getStart()),
8493                            /*IsStringLocation*/true, R,
8494                            FixItHint::CreateRemoval(R));
8495     }
8496   }
8497 
8498   if (!FS.consumesDataArgument()) {
8499     // FIXME: Technically specifying a precision or field width here
8500     // makes no sense.  Worth issuing a warning at some point.
8501     return true;
8502   }
8503 
8504   // Consume the argument.
8505   unsigned argIndex = FS.getArgIndex();
8506   if (argIndex < NumDataArgs) {
8507       // The check to see if the argIndex is valid will come later.
8508       // We set the bit here because we may exit early from this
8509       // function if we encounter some other error.
8510     CoveredArgs.set(argIndex);
8511   }
8512 
8513   // Check the length modifier is valid with the given conversion specifier.
8514   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8515                                  S.getLangOpts()))
8516     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8517                                 diag::warn_format_nonsensical_length);
8518   else if (!FS.hasStandardLengthModifier())
8519     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8520   else if (!FS.hasStandardLengthConversionCombination())
8521     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8522                                 diag::warn_format_non_standard_conversion_spec);
8523 
8524   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8525     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8526 
8527   // The remaining checks depend on the data arguments.
8528   if (HasVAListArg)
8529     return true;
8530 
8531   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8532     return false;
8533 
8534   // Check that the argument type matches the format specifier.
8535   const Expr *Ex = getDataArg(argIndex);
8536   if (!Ex)
8537     return true;
8538 
8539   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
8540 
8541   if (!AT.isValid()) {
8542     return true;
8543   }
8544 
8545   analyze_format_string::ArgType::MatchKind Match =
8546       AT.matchesType(S.Context, Ex->getType());
8547   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
8548   if (Match == analyze_format_string::ArgType::Match)
8549     return true;
8550 
8551   ScanfSpecifier fixedFS = FS;
8552   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
8553                                  S.getLangOpts(), S.Context);
8554 
8555   unsigned Diag =
8556       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
8557                : diag::warn_format_conversion_argument_type_mismatch;
8558 
8559   if (Success) {
8560     // Get the fix string from the fixed format specifier.
8561     SmallString<128> buf;
8562     llvm::raw_svector_ostream os(buf);
8563     fixedFS.toString(os);
8564 
8565     EmitFormatDiagnostic(
8566         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
8567                       << Ex->getType() << false << Ex->getSourceRange(),
8568         Ex->getBeginLoc(),
8569         /*IsStringLocation*/ false,
8570         getSpecifierRange(startSpecifier, specifierLen),
8571         FixItHint::CreateReplacement(
8572             getSpecifierRange(startSpecifier, specifierLen), os.str()));
8573   } else {
8574     EmitFormatDiagnostic(S.PDiag(Diag)
8575                              << AT.getRepresentativeTypeName(S.Context)
8576                              << Ex->getType() << false << Ex->getSourceRange(),
8577                          Ex->getBeginLoc(),
8578                          /*IsStringLocation*/ false,
8579                          getSpecifierRange(startSpecifier, specifierLen));
8580   }
8581 
8582   return true;
8583 }
8584 
8585 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
8586                               const Expr *OrigFormatExpr,
8587                               ArrayRef<const Expr *> Args,
8588                               bool HasVAListArg, unsigned format_idx,
8589                               unsigned firstDataArg,
8590                               Sema::FormatStringType Type,
8591                               bool inFunctionCall,
8592                               Sema::VariadicCallType CallType,
8593                               llvm::SmallBitVector &CheckedVarArgs,
8594                               UncoveredArgHandler &UncoveredArg,
8595                               bool IgnoreStringsWithoutSpecifiers) {
8596   // CHECK: is the format string a wide literal?
8597   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
8598     CheckFormatHandler::EmitFormatDiagnostic(
8599         S, inFunctionCall, Args[format_idx],
8600         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
8601         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8602     return;
8603   }
8604 
8605   // Str - The format string.  NOTE: this is NOT null-terminated!
8606   StringRef StrRef = FExpr->getString();
8607   const char *Str = StrRef.data();
8608   // Account for cases where the string literal is truncated in a declaration.
8609   const ConstantArrayType *T =
8610     S.Context.getAsConstantArrayType(FExpr->getType());
8611   assert(T && "String literal not of constant array type!");
8612   size_t TypeSize = T->getSize().getZExtValue();
8613   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8614   const unsigned numDataArgs = Args.size() - firstDataArg;
8615 
8616   if (IgnoreStringsWithoutSpecifiers &&
8617       !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
8618           Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
8619     return;
8620 
8621   // Emit a warning if the string literal is truncated and does not contain an
8622   // embedded null character.
8623   if (TypeSize <= StrRef.size() &&
8624       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
8625     CheckFormatHandler::EmitFormatDiagnostic(
8626         S, inFunctionCall, Args[format_idx],
8627         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
8628         FExpr->getBeginLoc(),
8629         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
8630     return;
8631   }
8632 
8633   // CHECK: empty format string?
8634   if (StrLen == 0 && numDataArgs > 0) {
8635     CheckFormatHandler::EmitFormatDiagnostic(
8636         S, inFunctionCall, Args[format_idx],
8637         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
8638         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8639     return;
8640   }
8641 
8642   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
8643       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
8644       Type == Sema::FST_OSTrace) {
8645     CheckPrintfHandler H(
8646         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
8647         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
8648         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
8649         CheckedVarArgs, UncoveredArg);
8650 
8651     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
8652                                                   S.getLangOpts(),
8653                                                   S.Context.getTargetInfo(),
8654                                             Type == Sema::FST_FreeBSDKPrintf))
8655       H.DoneProcessing();
8656   } else if (Type == Sema::FST_Scanf) {
8657     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
8658                         numDataArgs, Str, HasVAListArg, Args, format_idx,
8659                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
8660 
8661     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
8662                                                  S.getLangOpts(),
8663                                                  S.Context.getTargetInfo()))
8664       H.DoneProcessing();
8665   } // TODO: handle other formats
8666 }
8667 
8668 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
8669   // Str - The format string.  NOTE: this is NOT null-terminated!
8670   StringRef StrRef = FExpr->getString();
8671   const char *Str = StrRef.data();
8672   // Account for cases where the string literal is truncated in a declaration.
8673   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
8674   assert(T && "String literal not of constant array type!");
8675   size_t TypeSize = T->getSize().getZExtValue();
8676   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8677   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
8678                                                          getLangOpts(),
8679                                                          Context.getTargetInfo());
8680 }
8681 
8682 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
8683 
8684 // Returns the related absolute value function that is larger, of 0 if one
8685 // does not exist.
8686 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
8687   switch (AbsFunction) {
8688   default:
8689     return 0;
8690 
8691   case Builtin::BI__builtin_abs:
8692     return Builtin::BI__builtin_labs;
8693   case Builtin::BI__builtin_labs:
8694     return Builtin::BI__builtin_llabs;
8695   case Builtin::BI__builtin_llabs:
8696     return 0;
8697 
8698   case Builtin::BI__builtin_fabsf:
8699     return Builtin::BI__builtin_fabs;
8700   case Builtin::BI__builtin_fabs:
8701     return Builtin::BI__builtin_fabsl;
8702   case Builtin::BI__builtin_fabsl:
8703     return 0;
8704 
8705   case Builtin::BI__builtin_cabsf:
8706     return Builtin::BI__builtin_cabs;
8707   case Builtin::BI__builtin_cabs:
8708     return Builtin::BI__builtin_cabsl;
8709   case Builtin::BI__builtin_cabsl:
8710     return 0;
8711 
8712   case Builtin::BIabs:
8713     return Builtin::BIlabs;
8714   case Builtin::BIlabs:
8715     return Builtin::BIllabs;
8716   case Builtin::BIllabs:
8717     return 0;
8718 
8719   case Builtin::BIfabsf:
8720     return Builtin::BIfabs;
8721   case Builtin::BIfabs:
8722     return Builtin::BIfabsl;
8723   case Builtin::BIfabsl:
8724     return 0;
8725 
8726   case Builtin::BIcabsf:
8727    return Builtin::BIcabs;
8728   case Builtin::BIcabs:
8729     return Builtin::BIcabsl;
8730   case Builtin::BIcabsl:
8731     return 0;
8732   }
8733 }
8734 
8735 // Returns the argument type of the absolute value function.
8736 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
8737                                              unsigned AbsType) {
8738   if (AbsType == 0)
8739     return QualType();
8740 
8741   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
8742   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
8743   if (Error != ASTContext::GE_None)
8744     return QualType();
8745 
8746   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
8747   if (!FT)
8748     return QualType();
8749 
8750   if (FT->getNumParams() != 1)
8751     return QualType();
8752 
8753   return FT->getParamType(0);
8754 }
8755 
8756 // Returns the best absolute value function, or zero, based on type and
8757 // current absolute value function.
8758 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
8759                                    unsigned AbsFunctionKind) {
8760   unsigned BestKind = 0;
8761   uint64_t ArgSize = Context.getTypeSize(ArgType);
8762   for (unsigned Kind = AbsFunctionKind; Kind != 0;
8763        Kind = getLargerAbsoluteValueFunction(Kind)) {
8764     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
8765     if (Context.getTypeSize(ParamType) >= ArgSize) {
8766       if (BestKind == 0)
8767         BestKind = Kind;
8768       else if (Context.hasSameType(ParamType, ArgType)) {
8769         BestKind = Kind;
8770         break;
8771       }
8772     }
8773   }
8774   return BestKind;
8775 }
8776 
8777 enum AbsoluteValueKind {
8778   AVK_Integer,
8779   AVK_Floating,
8780   AVK_Complex
8781 };
8782 
8783 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
8784   if (T->isIntegralOrEnumerationType())
8785     return AVK_Integer;
8786   if (T->isRealFloatingType())
8787     return AVK_Floating;
8788   if (T->isAnyComplexType())
8789     return AVK_Complex;
8790 
8791   llvm_unreachable("Type not integer, floating, or complex");
8792 }
8793 
8794 // Changes the absolute value function to a different type.  Preserves whether
8795 // the function is a builtin.
8796 static unsigned changeAbsFunction(unsigned AbsKind,
8797                                   AbsoluteValueKind ValueKind) {
8798   switch (ValueKind) {
8799   case AVK_Integer:
8800     switch (AbsKind) {
8801     default:
8802       return 0;
8803     case Builtin::BI__builtin_fabsf:
8804     case Builtin::BI__builtin_fabs:
8805     case Builtin::BI__builtin_fabsl:
8806     case Builtin::BI__builtin_cabsf:
8807     case Builtin::BI__builtin_cabs:
8808     case Builtin::BI__builtin_cabsl:
8809       return Builtin::BI__builtin_abs;
8810     case Builtin::BIfabsf:
8811     case Builtin::BIfabs:
8812     case Builtin::BIfabsl:
8813     case Builtin::BIcabsf:
8814     case Builtin::BIcabs:
8815     case Builtin::BIcabsl:
8816       return Builtin::BIabs;
8817     }
8818   case AVK_Floating:
8819     switch (AbsKind) {
8820     default:
8821       return 0;
8822     case Builtin::BI__builtin_abs:
8823     case Builtin::BI__builtin_labs:
8824     case Builtin::BI__builtin_llabs:
8825     case Builtin::BI__builtin_cabsf:
8826     case Builtin::BI__builtin_cabs:
8827     case Builtin::BI__builtin_cabsl:
8828       return Builtin::BI__builtin_fabsf;
8829     case Builtin::BIabs:
8830     case Builtin::BIlabs:
8831     case Builtin::BIllabs:
8832     case Builtin::BIcabsf:
8833     case Builtin::BIcabs:
8834     case Builtin::BIcabsl:
8835       return Builtin::BIfabsf;
8836     }
8837   case AVK_Complex:
8838     switch (AbsKind) {
8839     default:
8840       return 0;
8841     case Builtin::BI__builtin_abs:
8842     case Builtin::BI__builtin_labs:
8843     case Builtin::BI__builtin_llabs:
8844     case Builtin::BI__builtin_fabsf:
8845     case Builtin::BI__builtin_fabs:
8846     case Builtin::BI__builtin_fabsl:
8847       return Builtin::BI__builtin_cabsf;
8848     case Builtin::BIabs:
8849     case Builtin::BIlabs:
8850     case Builtin::BIllabs:
8851     case Builtin::BIfabsf:
8852     case Builtin::BIfabs:
8853     case Builtin::BIfabsl:
8854       return Builtin::BIcabsf;
8855     }
8856   }
8857   llvm_unreachable("Unable to convert function");
8858 }
8859 
8860 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
8861   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
8862   if (!FnInfo)
8863     return 0;
8864 
8865   switch (FDecl->getBuiltinID()) {
8866   default:
8867     return 0;
8868   case Builtin::BI__builtin_abs:
8869   case Builtin::BI__builtin_fabs:
8870   case Builtin::BI__builtin_fabsf:
8871   case Builtin::BI__builtin_fabsl:
8872   case Builtin::BI__builtin_labs:
8873   case Builtin::BI__builtin_llabs:
8874   case Builtin::BI__builtin_cabs:
8875   case Builtin::BI__builtin_cabsf:
8876   case Builtin::BI__builtin_cabsl:
8877   case Builtin::BIabs:
8878   case Builtin::BIlabs:
8879   case Builtin::BIllabs:
8880   case Builtin::BIfabs:
8881   case Builtin::BIfabsf:
8882   case Builtin::BIfabsl:
8883   case Builtin::BIcabs:
8884   case Builtin::BIcabsf:
8885   case Builtin::BIcabsl:
8886     return FDecl->getBuiltinID();
8887   }
8888   llvm_unreachable("Unknown Builtin type");
8889 }
8890 
8891 // If the replacement is valid, emit a note with replacement function.
8892 // Additionally, suggest including the proper header if not already included.
8893 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
8894                             unsigned AbsKind, QualType ArgType) {
8895   bool EmitHeaderHint = true;
8896   const char *HeaderName = nullptr;
8897   const char *FunctionName = nullptr;
8898   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
8899     FunctionName = "std::abs";
8900     if (ArgType->isIntegralOrEnumerationType()) {
8901       HeaderName = "cstdlib";
8902     } else if (ArgType->isRealFloatingType()) {
8903       HeaderName = "cmath";
8904     } else {
8905       llvm_unreachable("Invalid Type");
8906     }
8907 
8908     // Lookup all std::abs
8909     if (NamespaceDecl *Std = S.getStdNamespace()) {
8910       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
8911       R.suppressDiagnostics();
8912       S.LookupQualifiedName(R, Std);
8913 
8914       for (const auto *I : R) {
8915         const FunctionDecl *FDecl = nullptr;
8916         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
8917           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
8918         } else {
8919           FDecl = dyn_cast<FunctionDecl>(I);
8920         }
8921         if (!FDecl)
8922           continue;
8923 
8924         // Found std::abs(), check that they are the right ones.
8925         if (FDecl->getNumParams() != 1)
8926           continue;
8927 
8928         // Check that the parameter type can handle the argument.
8929         QualType ParamType = FDecl->getParamDecl(0)->getType();
8930         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
8931             S.Context.getTypeSize(ArgType) <=
8932                 S.Context.getTypeSize(ParamType)) {
8933           // Found a function, don't need the header hint.
8934           EmitHeaderHint = false;
8935           break;
8936         }
8937       }
8938     }
8939   } else {
8940     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
8941     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
8942 
8943     if (HeaderName) {
8944       DeclarationName DN(&S.Context.Idents.get(FunctionName));
8945       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
8946       R.suppressDiagnostics();
8947       S.LookupName(R, S.getCurScope());
8948 
8949       if (R.isSingleResult()) {
8950         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
8951         if (FD && FD->getBuiltinID() == AbsKind) {
8952           EmitHeaderHint = false;
8953         } else {
8954           return;
8955         }
8956       } else if (!R.empty()) {
8957         return;
8958       }
8959     }
8960   }
8961 
8962   S.Diag(Loc, diag::note_replace_abs_function)
8963       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
8964 
8965   if (!HeaderName)
8966     return;
8967 
8968   if (!EmitHeaderHint)
8969     return;
8970 
8971   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
8972                                                     << FunctionName;
8973 }
8974 
8975 template <std::size_t StrLen>
8976 static bool IsStdFunction(const FunctionDecl *FDecl,
8977                           const char (&Str)[StrLen]) {
8978   if (!FDecl)
8979     return false;
8980   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
8981     return false;
8982   if (!FDecl->isInStdNamespace())
8983     return false;
8984 
8985   return true;
8986 }
8987 
8988 // Warn when using the wrong abs() function.
8989 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
8990                                       const FunctionDecl *FDecl) {
8991   if (Call->getNumArgs() != 1)
8992     return;
8993 
8994   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
8995   bool IsStdAbs = IsStdFunction(FDecl, "abs");
8996   if (AbsKind == 0 && !IsStdAbs)
8997     return;
8998 
8999   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9000   QualType ParamType = Call->getArg(0)->getType();
9001 
9002   // Unsigned types cannot be negative.  Suggest removing the absolute value
9003   // function call.
9004   if (ArgType->isUnsignedIntegerType()) {
9005     const char *FunctionName =
9006         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
9007     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
9008     Diag(Call->getExprLoc(), diag::note_remove_abs)
9009         << FunctionName
9010         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
9011     return;
9012   }
9013 
9014   // Taking the absolute value of a pointer is very suspicious, they probably
9015   // wanted to index into an array, dereference a pointer, call a function, etc.
9016   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
9017     unsigned DiagType = 0;
9018     if (ArgType->isFunctionType())
9019       DiagType = 1;
9020     else if (ArgType->isArrayType())
9021       DiagType = 2;
9022 
9023     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
9024     return;
9025   }
9026 
9027   // std::abs has overloads which prevent most of the absolute value problems
9028   // from occurring.
9029   if (IsStdAbs)
9030     return;
9031 
9032   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
9033   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
9034 
9035   // The argument and parameter are the same kind.  Check if they are the right
9036   // size.
9037   if (ArgValueKind == ParamValueKind) {
9038     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
9039       return;
9040 
9041     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
9042     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
9043         << FDecl << ArgType << ParamType;
9044 
9045     if (NewAbsKind == 0)
9046       return;
9047 
9048     emitReplacement(*this, Call->getExprLoc(),
9049                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9050     return;
9051   }
9052 
9053   // ArgValueKind != ParamValueKind
9054   // The wrong type of absolute value function was used.  Attempt to find the
9055   // proper one.
9056   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
9057   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
9058   if (NewAbsKind == 0)
9059     return;
9060 
9061   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
9062       << FDecl << ParamValueKind << ArgValueKind;
9063 
9064   emitReplacement(*this, Call->getExprLoc(),
9065                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9066 }
9067 
9068 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
9069 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
9070                                 const FunctionDecl *FDecl) {
9071   if (!Call || !FDecl) return;
9072 
9073   // Ignore template specializations and macros.
9074   if (inTemplateInstantiation()) return;
9075   if (Call->getExprLoc().isMacroID()) return;
9076 
9077   // Only care about the one template argument, two function parameter std::max
9078   if (Call->getNumArgs() != 2) return;
9079   if (!IsStdFunction(FDecl, "max")) return;
9080   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
9081   if (!ArgList) return;
9082   if (ArgList->size() != 1) return;
9083 
9084   // Check that template type argument is unsigned integer.
9085   const auto& TA = ArgList->get(0);
9086   if (TA.getKind() != TemplateArgument::Type) return;
9087   QualType ArgType = TA.getAsType();
9088   if (!ArgType->isUnsignedIntegerType()) return;
9089 
9090   // See if either argument is a literal zero.
9091   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
9092     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
9093     if (!MTE) return false;
9094     const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
9095     if (!Num) return false;
9096     if (Num->getValue() != 0) return false;
9097     return true;
9098   };
9099 
9100   const Expr *FirstArg = Call->getArg(0);
9101   const Expr *SecondArg = Call->getArg(1);
9102   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
9103   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
9104 
9105   // Only warn when exactly one argument is zero.
9106   if (IsFirstArgZero == IsSecondArgZero) return;
9107 
9108   SourceRange FirstRange = FirstArg->getSourceRange();
9109   SourceRange SecondRange = SecondArg->getSourceRange();
9110 
9111   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
9112 
9113   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
9114       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
9115 
9116   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
9117   SourceRange RemovalRange;
9118   if (IsFirstArgZero) {
9119     RemovalRange = SourceRange(FirstRange.getBegin(),
9120                                SecondRange.getBegin().getLocWithOffset(-1));
9121   } else {
9122     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
9123                                SecondRange.getEnd());
9124   }
9125 
9126   Diag(Call->getExprLoc(), diag::note_remove_max_call)
9127         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
9128         << FixItHint::CreateRemoval(RemovalRange);
9129 }
9130 
9131 //===--- CHECK: Standard memory functions ---------------------------------===//
9132 
9133 /// Takes the expression passed to the size_t parameter of functions
9134 /// such as memcmp, strncat, etc and warns if it's a comparison.
9135 ///
9136 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
9137 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
9138                                            IdentifierInfo *FnName,
9139                                            SourceLocation FnLoc,
9140                                            SourceLocation RParenLoc) {
9141   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
9142   if (!Size)
9143     return false;
9144 
9145   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
9146   if (!Size->isComparisonOp() && !Size->isLogicalOp())
9147     return false;
9148 
9149   SourceRange SizeRange = Size->getSourceRange();
9150   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
9151       << SizeRange << FnName;
9152   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
9153       << FnName
9154       << FixItHint::CreateInsertion(
9155              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
9156       << FixItHint::CreateRemoval(RParenLoc);
9157   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
9158       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
9159       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
9160                                     ")");
9161 
9162   return true;
9163 }
9164 
9165 /// Determine whether the given type is or contains a dynamic class type
9166 /// (e.g., whether it has a vtable).
9167 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
9168                                                      bool &IsContained) {
9169   // Look through array types while ignoring qualifiers.
9170   const Type *Ty = T->getBaseElementTypeUnsafe();
9171   IsContained = false;
9172 
9173   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
9174   RD = RD ? RD->getDefinition() : nullptr;
9175   if (!RD || RD->isInvalidDecl())
9176     return nullptr;
9177 
9178   if (RD->isDynamicClass())
9179     return RD;
9180 
9181   // Check all the fields.  If any bases were dynamic, the class is dynamic.
9182   // It's impossible for a class to transitively contain itself by value, so
9183   // infinite recursion is impossible.
9184   for (auto *FD : RD->fields()) {
9185     bool SubContained;
9186     if (const CXXRecordDecl *ContainedRD =
9187             getContainedDynamicClass(FD->getType(), SubContained)) {
9188       IsContained = true;
9189       return ContainedRD;
9190     }
9191   }
9192 
9193   return nullptr;
9194 }
9195 
9196 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
9197   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
9198     if (Unary->getKind() == UETT_SizeOf)
9199       return Unary;
9200   return nullptr;
9201 }
9202 
9203 /// If E is a sizeof expression, returns its argument expression,
9204 /// otherwise returns NULL.
9205 static const Expr *getSizeOfExprArg(const Expr *E) {
9206   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9207     if (!SizeOf->isArgumentType())
9208       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
9209   return nullptr;
9210 }
9211 
9212 /// If E is a sizeof expression, returns its argument type.
9213 static QualType getSizeOfArgType(const Expr *E) {
9214   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9215     return SizeOf->getTypeOfArgument();
9216   return QualType();
9217 }
9218 
9219 namespace {
9220 
9221 struct SearchNonTrivialToInitializeField
9222     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
9223   using Super =
9224       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
9225 
9226   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
9227 
9228   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
9229                      SourceLocation SL) {
9230     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9231       asDerived().visitArray(PDIK, AT, SL);
9232       return;
9233     }
9234 
9235     Super::visitWithKind(PDIK, FT, SL);
9236   }
9237 
9238   void visitARCStrong(QualType FT, SourceLocation SL) {
9239     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9240   }
9241   void visitARCWeak(QualType FT, SourceLocation SL) {
9242     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9243   }
9244   void visitStruct(QualType FT, SourceLocation SL) {
9245     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9246       visit(FD->getType(), FD->getLocation());
9247   }
9248   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
9249                   const ArrayType *AT, SourceLocation SL) {
9250     visit(getContext().getBaseElementType(AT), SL);
9251   }
9252   void visitTrivial(QualType FT, SourceLocation SL) {}
9253 
9254   static void diag(QualType RT, const Expr *E, Sema &S) {
9255     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
9256   }
9257 
9258   ASTContext &getContext() { return S.getASTContext(); }
9259 
9260   const Expr *E;
9261   Sema &S;
9262 };
9263 
9264 struct SearchNonTrivialToCopyField
9265     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
9266   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
9267 
9268   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
9269 
9270   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
9271                      SourceLocation SL) {
9272     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9273       asDerived().visitArray(PCK, AT, SL);
9274       return;
9275     }
9276 
9277     Super::visitWithKind(PCK, FT, SL);
9278   }
9279 
9280   void visitARCStrong(QualType FT, SourceLocation SL) {
9281     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9282   }
9283   void visitARCWeak(QualType FT, SourceLocation SL) {
9284     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9285   }
9286   void visitStruct(QualType FT, SourceLocation SL) {
9287     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9288       visit(FD->getType(), FD->getLocation());
9289   }
9290   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
9291                   SourceLocation SL) {
9292     visit(getContext().getBaseElementType(AT), SL);
9293   }
9294   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
9295                 SourceLocation SL) {}
9296   void visitTrivial(QualType FT, SourceLocation SL) {}
9297   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
9298 
9299   static void diag(QualType RT, const Expr *E, Sema &S) {
9300     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
9301   }
9302 
9303   ASTContext &getContext() { return S.getASTContext(); }
9304 
9305   const Expr *E;
9306   Sema &S;
9307 };
9308 
9309 }
9310 
9311 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
9312 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
9313   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
9314 
9315   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
9316     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
9317       return false;
9318 
9319     return doesExprLikelyComputeSize(BO->getLHS()) ||
9320            doesExprLikelyComputeSize(BO->getRHS());
9321   }
9322 
9323   return getAsSizeOfExpr(SizeofExpr) != nullptr;
9324 }
9325 
9326 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
9327 ///
9328 /// \code
9329 ///   #define MACRO 0
9330 ///   foo(MACRO);
9331 ///   foo(0);
9332 /// \endcode
9333 ///
9334 /// This should return true for the first call to foo, but not for the second
9335 /// (regardless of whether foo is a macro or function).
9336 static bool isArgumentExpandedFromMacro(SourceManager &SM,
9337                                         SourceLocation CallLoc,
9338                                         SourceLocation ArgLoc) {
9339   if (!CallLoc.isMacroID())
9340     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
9341 
9342   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
9343          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
9344 }
9345 
9346 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
9347 /// last two arguments transposed.
9348 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
9349   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
9350     return;
9351 
9352   const Expr *SizeArg =
9353     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
9354 
9355   auto isLiteralZero = [](const Expr *E) {
9356     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
9357   };
9358 
9359   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
9360   SourceLocation CallLoc = Call->getRParenLoc();
9361   SourceManager &SM = S.getSourceManager();
9362   if (isLiteralZero(SizeArg) &&
9363       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
9364 
9365     SourceLocation DiagLoc = SizeArg->getExprLoc();
9366 
9367     // Some platforms #define bzero to __builtin_memset. See if this is the
9368     // case, and if so, emit a better diagnostic.
9369     if (BId == Builtin::BIbzero ||
9370         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
9371                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
9372       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
9373       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
9374     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
9375       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
9376       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
9377     }
9378     return;
9379   }
9380 
9381   // If the second argument to a memset is a sizeof expression and the third
9382   // isn't, this is also likely an error. This should catch
9383   // 'memset(buf, sizeof(buf), 0xff)'.
9384   if (BId == Builtin::BImemset &&
9385       doesExprLikelyComputeSize(Call->getArg(1)) &&
9386       !doesExprLikelyComputeSize(Call->getArg(2))) {
9387     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
9388     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
9389     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
9390     return;
9391   }
9392 }
9393 
9394 /// Check for dangerous or invalid arguments to memset().
9395 ///
9396 /// This issues warnings on known problematic, dangerous or unspecified
9397 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
9398 /// function calls.
9399 ///
9400 /// \param Call The call expression to diagnose.
9401 void Sema::CheckMemaccessArguments(const CallExpr *Call,
9402                                    unsigned BId,
9403                                    IdentifierInfo *FnName) {
9404   assert(BId != 0);
9405 
9406   // It is possible to have a non-standard definition of memset.  Validate
9407   // we have enough arguments, and if not, abort further checking.
9408   unsigned ExpectedNumArgs =
9409       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
9410   if (Call->getNumArgs() < ExpectedNumArgs)
9411     return;
9412 
9413   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
9414                       BId == Builtin::BIstrndup ? 1 : 2);
9415   unsigned LenArg =
9416       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
9417   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
9418 
9419   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
9420                                      Call->getBeginLoc(), Call->getRParenLoc()))
9421     return;
9422 
9423   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
9424   CheckMemaccessSize(*this, BId, Call);
9425 
9426   // We have special checking when the length is a sizeof expression.
9427   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
9428   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
9429   llvm::FoldingSetNodeID SizeOfArgID;
9430 
9431   // Although widely used, 'bzero' is not a standard function. Be more strict
9432   // with the argument types before allowing diagnostics and only allow the
9433   // form bzero(ptr, sizeof(...)).
9434   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9435   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
9436     return;
9437 
9438   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
9439     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
9440     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
9441 
9442     QualType DestTy = Dest->getType();
9443     QualType PointeeTy;
9444     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
9445       PointeeTy = DestPtrTy->getPointeeType();
9446 
9447       // Never warn about void type pointers. This can be used to suppress
9448       // false positives.
9449       if (PointeeTy->isVoidType())
9450         continue;
9451 
9452       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
9453       // actually comparing the expressions for equality. Because computing the
9454       // expression IDs can be expensive, we only do this if the diagnostic is
9455       // enabled.
9456       if (SizeOfArg &&
9457           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
9458                            SizeOfArg->getExprLoc())) {
9459         // We only compute IDs for expressions if the warning is enabled, and
9460         // cache the sizeof arg's ID.
9461         if (SizeOfArgID == llvm::FoldingSetNodeID())
9462           SizeOfArg->Profile(SizeOfArgID, Context, true);
9463         llvm::FoldingSetNodeID DestID;
9464         Dest->Profile(DestID, Context, true);
9465         if (DestID == SizeOfArgID) {
9466           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
9467           //       over sizeof(src) as well.
9468           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
9469           StringRef ReadableName = FnName->getName();
9470 
9471           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
9472             if (UnaryOp->getOpcode() == UO_AddrOf)
9473               ActionIdx = 1; // If its an address-of operator, just remove it.
9474           if (!PointeeTy->isIncompleteType() &&
9475               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
9476             ActionIdx = 2; // If the pointee's size is sizeof(char),
9477                            // suggest an explicit length.
9478 
9479           // If the function is defined as a builtin macro, do not show macro
9480           // expansion.
9481           SourceLocation SL = SizeOfArg->getExprLoc();
9482           SourceRange DSR = Dest->getSourceRange();
9483           SourceRange SSR = SizeOfArg->getSourceRange();
9484           SourceManager &SM = getSourceManager();
9485 
9486           if (SM.isMacroArgExpansion(SL)) {
9487             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
9488             SL = SM.getSpellingLoc(SL);
9489             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
9490                              SM.getSpellingLoc(DSR.getEnd()));
9491             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
9492                              SM.getSpellingLoc(SSR.getEnd()));
9493           }
9494 
9495           DiagRuntimeBehavior(SL, SizeOfArg,
9496                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
9497                                 << ReadableName
9498                                 << PointeeTy
9499                                 << DestTy
9500                                 << DSR
9501                                 << SSR);
9502           DiagRuntimeBehavior(SL, SizeOfArg,
9503                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
9504                                 << ActionIdx
9505                                 << SSR);
9506 
9507           break;
9508         }
9509       }
9510 
9511       // Also check for cases where the sizeof argument is the exact same
9512       // type as the memory argument, and where it points to a user-defined
9513       // record type.
9514       if (SizeOfArgTy != QualType()) {
9515         if (PointeeTy->isRecordType() &&
9516             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
9517           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
9518                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
9519                                 << FnName << SizeOfArgTy << ArgIdx
9520                                 << PointeeTy << Dest->getSourceRange()
9521                                 << LenExpr->getSourceRange());
9522           break;
9523         }
9524       }
9525     } else if (DestTy->isArrayType()) {
9526       PointeeTy = DestTy;
9527     }
9528 
9529     if (PointeeTy == QualType())
9530       continue;
9531 
9532     // Always complain about dynamic classes.
9533     bool IsContained;
9534     if (const CXXRecordDecl *ContainedRD =
9535             getContainedDynamicClass(PointeeTy, IsContained)) {
9536 
9537       unsigned OperationType = 0;
9538       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
9539       // "overwritten" if we're warning about the destination for any call
9540       // but memcmp; otherwise a verb appropriate to the call.
9541       if (ArgIdx != 0 || IsCmp) {
9542         if (BId == Builtin::BImemcpy)
9543           OperationType = 1;
9544         else if(BId == Builtin::BImemmove)
9545           OperationType = 2;
9546         else if (IsCmp)
9547           OperationType = 3;
9548       }
9549 
9550       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9551                           PDiag(diag::warn_dyn_class_memaccess)
9552                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
9553                               << IsContained << ContainedRD << OperationType
9554                               << Call->getCallee()->getSourceRange());
9555     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
9556              BId != Builtin::BImemset)
9557       DiagRuntimeBehavior(
9558         Dest->getExprLoc(), Dest,
9559         PDiag(diag::warn_arc_object_memaccess)
9560           << ArgIdx << FnName << PointeeTy
9561           << Call->getCallee()->getSourceRange());
9562     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
9563       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
9564           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
9565         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9566                             PDiag(diag::warn_cstruct_memaccess)
9567                                 << ArgIdx << FnName << PointeeTy << 0);
9568         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
9569       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
9570                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
9571         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9572                             PDiag(diag::warn_cstruct_memaccess)
9573                                 << ArgIdx << FnName << PointeeTy << 1);
9574         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
9575       } else {
9576         continue;
9577       }
9578     } else
9579       continue;
9580 
9581     DiagRuntimeBehavior(
9582       Dest->getExprLoc(), Dest,
9583       PDiag(diag::note_bad_memaccess_silence)
9584         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
9585     break;
9586   }
9587 }
9588 
9589 // A little helper routine: ignore addition and subtraction of integer literals.
9590 // This intentionally does not ignore all integer constant expressions because
9591 // we don't want to remove sizeof().
9592 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
9593   Ex = Ex->IgnoreParenCasts();
9594 
9595   while (true) {
9596     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
9597     if (!BO || !BO->isAdditiveOp())
9598       break;
9599 
9600     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
9601     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
9602 
9603     if (isa<IntegerLiteral>(RHS))
9604       Ex = LHS;
9605     else if (isa<IntegerLiteral>(LHS))
9606       Ex = RHS;
9607     else
9608       break;
9609   }
9610 
9611   return Ex;
9612 }
9613 
9614 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
9615                                                       ASTContext &Context) {
9616   // Only handle constant-sized or VLAs, but not flexible members.
9617   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
9618     // Only issue the FIXIT for arrays of size > 1.
9619     if (CAT->getSize().getSExtValue() <= 1)
9620       return false;
9621   } else if (!Ty->isVariableArrayType()) {
9622     return false;
9623   }
9624   return true;
9625 }
9626 
9627 // Warn if the user has made the 'size' argument to strlcpy or strlcat
9628 // be the size of the source, instead of the destination.
9629 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
9630                                     IdentifierInfo *FnName) {
9631 
9632   // Don't crash if the user has the wrong number of arguments
9633   unsigned NumArgs = Call->getNumArgs();
9634   if ((NumArgs != 3) && (NumArgs != 4))
9635     return;
9636 
9637   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
9638   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
9639   const Expr *CompareWithSrc = nullptr;
9640 
9641   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
9642                                      Call->getBeginLoc(), Call->getRParenLoc()))
9643     return;
9644 
9645   // Look for 'strlcpy(dst, x, sizeof(x))'
9646   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
9647     CompareWithSrc = Ex;
9648   else {
9649     // Look for 'strlcpy(dst, x, strlen(x))'
9650     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
9651       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
9652           SizeCall->getNumArgs() == 1)
9653         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
9654     }
9655   }
9656 
9657   if (!CompareWithSrc)
9658     return;
9659 
9660   // Determine if the argument to sizeof/strlen is equal to the source
9661   // argument.  In principle there's all kinds of things you could do
9662   // here, for instance creating an == expression and evaluating it with
9663   // EvaluateAsBooleanCondition, but this uses a more direct technique:
9664   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
9665   if (!SrcArgDRE)
9666     return;
9667 
9668   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
9669   if (!CompareWithSrcDRE ||
9670       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
9671     return;
9672 
9673   const Expr *OriginalSizeArg = Call->getArg(2);
9674   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
9675       << OriginalSizeArg->getSourceRange() << FnName;
9676 
9677   // Output a FIXIT hint if the destination is an array (rather than a
9678   // pointer to an array).  This could be enhanced to handle some
9679   // pointers if we know the actual size, like if DstArg is 'array+2'
9680   // we could say 'sizeof(array)-2'.
9681   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
9682   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
9683     return;
9684 
9685   SmallString<128> sizeString;
9686   llvm::raw_svector_ostream OS(sizeString);
9687   OS << "sizeof(";
9688   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9689   OS << ")";
9690 
9691   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
9692       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
9693                                       OS.str());
9694 }
9695 
9696 /// Check if two expressions refer to the same declaration.
9697 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
9698   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
9699     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
9700       return D1->getDecl() == D2->getDecl();
9701   return false;
9702 }
9703 
9704 static const Expr *getStrlenExprArg(const Expr *E) {
9705   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
9706     const FunctionDecl *FD = CE->getDirectCallee();
9707     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
9708       return nullptr;
9709     return CE->getArg(0)->IgnoreParenCasts();
9710   }
9711   return nullptr;
9712 }
9713 
9714 // Warn on anti-patterns as the 'size' argument to strncat.
9715 // The correct size argument should look like following:
9716 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
9717 void Sema::CheckStrncatArguments(const CallExpr *CE,
9718                                  IdentifierInfo *FnName) {
9719   // Don't crash if the user has the wrong number of arguments.
9720   if (CE->getNumArgs() < 3)
9721     return;
9722   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
9723   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
9724   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
9725 
9726   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
9727                                      CE->getRParenLoc()))
9728     return;
9729 
9730   // Identify common expressions, which are wrongly used as the size argument
9731   // to strncat and may lead to buffer overflows.
9732   unsigned PatternType = 0;
9733   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
9734     // - sizeof(dst)
9735     if (referToTheSameDecl(SizeOfArg, DstArg))
9736       PatternType = 1;
9737     // - sizeof(src)
9738     else if (referToTheSameDecl(SizeOfArg, SrcArg))
9739       PatternType = 2;
9740   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
9741     if (BE->getOpcode() == BO_Sub) {
9742       const Expr *L = BE->getLHS()->IgnoreParenCasts();
9743       const Expr *R = BE->getRHS()->IgnoreParenCasts();
9744       // - sizeof(dst) - strlen(dst)
9745       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
9746           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
9747         PatternType = 1;
9748       // - sizeof(src) - (anything)
9749       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
9750         PatternType = 2;
9751     }
9752   }
9753 
9754   if (PatternType == 0)
9755     return;
9756 
9757   // Generate the diagnostic.
9758   SourceLocation SL = LenArg->getBeginLoc();
9759   SourceRange SR = LenArg->getSourceRange();
9760   SourceManager &SM = getSourceManager();
9761 
9762   // If the function is defined as a builtin macro, do not show macro expansion.
9763   if (SM.isMacroArgExpansion(SL)) {
9764     SL = SM.getSpellingLoc(SL);
9765     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
9766                      SM.getSpellingLoc(SR.getEnd()));
9767   }
9768 
9769   // Check if the destination is an array (rather than a pointer to an array).
9770   QualType DstTy = DstArg->getType();
9771   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
9772                                                                     Context);
9773   if (!isKnownSizeArray) {
9774     if (PatternType == 1)
9775       Diag(SL, diag::warn_strncat_wrong_size) << SR;
9776     else
9777       Diag(SL, diag::warn_strncat_src_size) << SR;
9778     return;
9779   }
9780 
9781   if (PatternType == 1)
9782     Diag(SL, diag::warn_strncat_large_size) << SR;
9783   else
9784     Diag(SL, diag::warn_strncat_src_size) << SR;
9785 
9786   SmallString<128> sizeString;
9787   llvm::raw_svector_ostream OS(sizeString);
9788   OS << "sizeof(";
9789   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9790   OS << ") - ";
9791   OS << "strlen(";
9792   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9793   OS << ") - 1";
9794 
9795   Diag(SL, diag::note_strncat_wrong_size)
9796     << FixItHint::CreateReplacement(SR, OS.str());
9797 }
9798 
9799 void
9800 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
9801                          SourceLocation ReturnLoc,
9802                          bool isObjCMethod,
9803                          const AttrVec *Attrs,
9804                          const FunctionDecl *FD) {
9805   // Check if the return value is null but should not be.
9806   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
9807        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
9808       CheckNonNullExpr(*this, RetValExp))
9809     Diag(ReturnLoc, diag::warn_null_ret)
9810       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
9811 
9812   // C++11 [basic.stc.dynamic.allocation]p4:
9813   //   If an allocation function declared with a non-throwing
9814   //   exception-specification fails to allocate storage, it shall return
9815   //   a null pointer. Any other allocation function that fails to allocate
9816   //   storage shall indicate failure only by throwing an exception [...]
9817   if (FD) {
9818     OverloadedOperatorKind Op = FD->getOverloadedOperator();
9819     if (Op == OO_New || Op == OO_Array_New) {
9820       const FunctionProtoType *Proto
9821         = FD->getType()->castAs<FunctionProtoType>();
9822       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
9823           CheckNonNullExpr(*this, RetValExp))
9824         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
9825           << FD << getLangOpts().CPlusPlus11;
9826     }
9827   }
9828 }
9829 
9830 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
9831 
9832 /// Check for comparisons of floating point operands using != and ==.
9833 /// Issue a warning if these are no self-comparisons, as they are not likely
9834 /// to do what the programmer intended.
9835 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
9836   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
9837   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
9838 
9839   // Special case: check for x == x (which is OK).
9840   // Do not emit warnings for such cases.
9841   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
9842     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
9843       if (DRL->getDecl() == DRR->getDecl())
9844         return;
9845 
9846   // Special case: check for comparisons against literals that can be exactly
9847   //  represented by APFloat.  In such cases, do not emit a warning.  This
9848   //  is a heuristic: often comparison against such literals are used to
9849   //  detect if a value in a variable has not changed.  This clearly can
9850   //  lead to false negatives.
9851   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
9852     if (FLL->isExact())
9853       return;
9854   } else
9855     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
9856       if (FLR->isExact())
9857         return;
9858 
9859   // Check for comparisons with builtin types.
9860   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
9861     if (CL->getBuiltinCallee())
9862       return;
9863 
9864   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
9865     if (CR->getBuiltinCallee())
9866       return;
9867 
9868   // Emit the diagnostic.
9869   Diag(Loc, diag::warn_floatingpoint_eq)
9870     << LHS->getSourceRange() << RHS->getSourceRange();
9871 }
9872 
9873 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
9874 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
9875 
9876 namespace {
9877 
9878 /// Structure recording the 'active' range of an integer-valued
9879 /// expression.
9880 struct IntRange {
9881   /// The number of bits active in the int.
9882   unsigned Width;
9883 
9884   /// True if the int is known not to have negative values.
9885   bool NonNegative;
9886 
9887   IntRange(unsigned Width, bool NonNegative)
9888       : Width(Width), NonNegative(NonNegative) {}
9889 
9890   /// Returns the range of the bool type.
9891   static IntRange forBoolType() {
9892     return IntRange(1, true);
9893   }
9894 
9895   /// Returns the range of an opaque value of the given integral type.
9896   static IntRange forValueOfType(ASTContext &C, QualType T) {
9897     return forValueOfCanonicalType(C,
9898                           T->getCanonicalTypeInternal().getTypePtr());
9899   }
9900 
9901   /// Returns the range of an opaque value of a canonical integral type.
9902   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
9903     assert(T->isCanonicalUnqualified());
9904 
9905     if (const VectorType *VT = dyn_cast<VectorType>(T))
9906       T = VT->getElementType().getTypePtr();
9907     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
9908       T = CT->getElementType().getTypePtr();
9909     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
9910       T = AT->getValueType().getTypePtr();
9911 
9912     if (!C.getLangOpts().CPlusPlus) {
9913       // For enum types in C code, use the underlying datatype.
9914       if (const EnumType *ET = dyn_cast<EnumType>(T))
9915         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
9916     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
9917       // For enum types in C++, use the known bit width of the enumerators.
9918       EnumDecl *Enum = ET->getDecl();
9919       // In C++11, enums can have a fixed underlying type. Use this type to
9920       // compute the range.
9921       if (Enum->isFixed()) {
9922         return IntRange(C.getIntWidth(QualType(T, 0)),
9923                         !ET->isSignedIntegerOrEnumerationType());
9924       }
9925 
9926       unsigned NumPositive = Enum->getNumPositiveBits();
9927       unsigned NumNegative = Enum->getNumNegativeBits();
9928 
9929       if (NumNegative == 0)
9930         return IntRange(NumPositive, true/*NonNegative*/);
9931       else
9932         return IntRange(std::max(NumPositive + 1, NumNegative),
9933                         false/*NonNegative*/);
9934     }
9935 
9936     if (const auto *EIT = dyn_cast<ExtIntType>(T))
9937       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
9938 
9939     const BuiltinType *BT = cast<BuiltinType>(T);
9940     assert(BT->isInteger());
9941 
9942     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
9943   }
9944 
9945   /// Returns the "target" range of a canonical integral type, i.e.
9946   /// the range of values expressible in the type.
9947   ///
9948   /// This matches forValueOfCanonicalType except that enums have the
9949   /// full range of their type, not the range of their enumerators.
9950   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
9951     assert(T->isCanonicalUnqualified());
9952 
9953     if (const VectorType *VT = dyn_cast<VectorType>(T))
9954       T = VT->getElementType().getTypePtr();
9955     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
9956       T = CT->getElementType().getTypePtr();
9957     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
9958       T = AT->getValueType().getTypePtr();
9959     if (const EnumType *ET = dyn_cast<EnumType>(T))
9960       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
9961 
9962     if (const auto *EIT = dyn_cast<ExtIntType>(T))
9963       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
9964 
9965     const BuiltinType *BT = cast<BuiltinType>(T);
9966     assert(BT->isInteger());
9967 
9968     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
9969   }
9970 
9971   /// Returns the supremum of two ranges: i.e. their conservative merge.
9972   static IntRange join(IntRange L, IntRange R) {
9973     return IntRange(std::max(L.Width, R.Width),
9974                     L.NonNegative && R.NonNegative);
9975   }
9976 
9977   /// Returns the infinum of two ranges: i.e. their aggressive merge.
9978   static IntRange meet(IntRange L, IntRange R) {
9979     return IntRange(std::min(L.Width, R.Width),
9980                     L.NonNegative || R.NonNegative);
9981   }
9982 };
9983 
9984 } // namespace
9985 
9986 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
9987                               unsigned MaxWidth) {
9988   if (value.isSigned() && value.isNegative())
9989     return IntRange(value.getMinSignedBits(), false);
9990 
9991   if (value.getBitWidth() > MaxWidth)
9992     value = value.trunc(MaxWidth);
9993 
9994   // isNonNegative() just checks the sign bit without considering
9995   // signedness.
9996   return IntRange(value.getActiveBits(), true);
9997 }
9998 
9999 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
10000                               unsigned MaxWidth) {
10001   if (result.isInt())
10002     return GetValueRange(C, result.getInt(), MaxWidth);
10003 
10004   if (result.isVector()) {
10005     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
10006     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
10007       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
10008       R = IntRange::join(R, El);
10009     }
10010     return R;
10011   }
10012 
10013   if (result.isComplexInt()) {
10014     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
10015     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
10016     return IntRange::join(R, I);
10017   }
10018 
10019   // This can happen with lossless casts to intptr_t of "based" lvalues.
10020   // Assume it might use arbitrary bits.
10021   // FIXME: The only reason we need to pass the type in here is to get
10022   // the sign right on this one case.  It would be nice if APValue
10023   // preserved this.
10024   assert(result.isLValue() || result.isAddrLabelDiff());
10025   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
10026 }
10027 
10028 static QualType GetExprType(const Expr *E) {
10029   QualType Ty = E->getType();
10030   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
10031     Ty = AtomicRHS->getValueType();
10032   return Ty;
10033 }
10034 
10035 /// Pseudo-evaluate the given integer expression, estimating the
10036 /// range of values it might take.
10037 ///
10038 /// \param MaxWidth - the width to which the value will be truncated
10039 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
10040                              bool InConstantContext) {
10041   E = E->IgnoreParens();
10042 
10043   // Try a full evaluation first.
10044   Expr::EvalResult result;
10045   if (E->EvaluateAsRValue(result, C, InConstantContext))
10046     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
10047 
10048   // I think we only want to look through implicit casts here; if the
10049   // user has an explicit widening cast, we should treat the value as
10050   // being of the new, wider type.
10051   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
10052     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
10053       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext);
10054 
10055     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
10056 
10057     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
10058                          CE->getCastKind() == CK_BooleanToSignedIntegral;
10059 
10060     // Assume that non-integer casts can span the full range of the type.
10061     if (!isIntegerCast)
10062       return OutputTypeRange;
10063 
10064     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
10065                                      std::min(MaxWidth, OutputTypeRange.Width),
10066                                      InConstantContext);
10067 
10068     // Bail out if the subexpr's range is as wide as the cast type.
10069     if (SubRange.Width >= OutputTypeRange.Width)
10070       return OutputTypeRange;
10071 
10072     // Otherwise, we take the smaller width, and we're non-negative if
10073     // either the output type or the subexpr is.
10074     return IntRange(SubRange.Width,
10075                     SubRange.NonNegative || OutputTypeRange.NonNegative);
10076   }
10077 
10078   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
10079     // If we can fold the condition, just take that operand.
10080     bool CondResult;
10081     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
10082       return GetExprRange(C,
10083                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
10084                           MaxWidth, InConstantContext);
10085 
10086     // Otherwise, conservatively merge.
10087     IntRange L =
10088         GetExprRange(C, CO->getTrueExpr(), MaxWidth, InConstantContext);
10089     IntRange R =
10090         GetExprRange(C, CO->getFalseExpr(), MaxWidth, InConstantContext);
10091     return IntRange::join(L, R);
10092   }
10093 
10094   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
10095     switch (BO->getOpcode()) {
10096     case BO_Cmp:
10097       llvm_unreachable("builtin <=> should have class type");
10098 
10099     // Boolean-valued operations are single-bit and positive.
10100     case BO_LAnd:
10101     case BO_LOr:
10102     case BO_LT:
10103     case BO_GT:
10104     case BO_LE:
10105     case BO_GE:
10106     case BO_EQ:
10107     case BO_NE:
10108       return IntRange::forBoolType();
10109 
10110     // The type of the assignments is the type of the LHS, so the RHS
10111     // is not necessarily the same type.
10112     case BO_MulAssign:
10113     case BO_DivAssign:
10114     case BO_RemAssign:
10115     case BO_AddAssign:
10116     case BO_SubAssign:
10117     case BO_XorAssign:
10118     case BO_OrAssign:
10119       // TODO: bitfields?
10120       return IntRange::forValueOfType(C, GetExprType(E));
10121 
10122     // Simple assignments just pass through the RHS, which will have
10123     // been coerced to the LHS type.
10124     case BO_Assign:
10125       // TODO: bitfields?
10126       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
10127 
10128     // Operations with opaque sources are black-listed.
10129     case BO_PtrMemD:
10130     case BO_PtrMemI:
10131       return IntRange::forValueOfType(C, GetExprType(E));
10132 
10133     // Bitwise-and uses the *infinum* of the two source ranges.
10134     case BO_And:
10135     case BO_AndAssign:
10136       return IntRange::meet(
10137           GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext),
10138           GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext));
10139 
10140     // Left shift gets black-listed based on a judgement call.
10141     case BO_Shl:
10142       // ...except that we want to treat '1 << (blah)' as logically
10143       // positive.  It's an important idiom.
10144       if (IntegerLiteral *I
10145             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
10146         if (I->getValue() == 1) {
10147           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
10148           return IntRange(R.Width, /*NonNegative*/ true);
10149         }
10150       }
10151       LLVM_FALLTHROUGH;
10152 
10153     case BO_ShlAssign:
10154       return IntRange::forValueOfType(C, GetExprType(E));
10155 
10156     // Right shift by a constant can narrow its left argument.
10157     case BO_Shr:
10158     case BO_ShrAssign: {
10159       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext);
10160 
10161       // If the shift amount is a positive constant, drop the width by
10162       // that much.
10163       llvm::APSInt shift;
10164       if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
10165           shift.isNonNegative()) {
10166         unsigned zext = shift.getZExtValue();
10167         if (zext >= L.Width)
10168           L.Width = (L.NonNegative ? 0 : 1);
10169         else
10170           L.Width -= zext;
10171       }
10172 
10173       return L;
10174     }
10175 
10176     // Comma acts as its right operand.
10177     case BO_Comma:
10178       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
10179 
10180     // Black-list pointer subtractions.
10181     case BO_Sub:
10182       if (BO->getLHS()->getType()->isPointerType())
10183         return IntRange::forValueOfType(C, GetExprType(E));
10184       break;
10185 
10186     // The width of a division result is mostly determined by the size
10187     // of the LHS.
10188     case BO_Div: {
10189       // Don't 'pre-truncate' the operands.
10190       unsigned opWidth = C.getIntWidth(GetExprType(E));
10191       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext);
10192 
10193       // If the divisor is constant, use that.
10194       llvm::APSInt divisor;
10195       if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
10196         unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
10197         if (log2 >= L.Width)
10198           L.Width = (L.NonNegative ? 0 : 1);
10199         else
10200           L.Width = std::min(L.Width - log2, MaxWidth);
10201         return L;
10202       }
10203 
10204       // Otherwise, just use the LHS's width.
10205       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext);
10206       return IntRange(L.Width, L.NonNegative && R.NonNegative);
10207     }
10208 
10209     // The result of a remainder can't be larger than the result of
10210     // either side.
10211     case BO_Rem: {
10212       // Don't 'pre-truncate' the operands.
10213       unsigned opWidth = C.getIntWidth(GetExprType(E));
10214       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext);
10215       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext);
10216 
10217       IntRange meet = IntRange::meet(L, R);
10218       meet.Width = std::min(meet.Width, MaxWidth);
10219       return meet;
10220     }
10221 
10222     // The default behavior is okay for these.
10223     case BO_Mul:
10224     case BO_Add:
10225     case BO_Xor:
10226     case BO_Or:
10227       break;
10228     }
10229 
10230     // The default case is to treat the operation as if it were closed
10231     // on the narrowest type that encompasses both operands.
10232     IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext);
10233     IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
10234     return IntRange::join(L, R);
10235   }
10236 
10237   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
10238     switch (UO->getOpcode()) {
10239     // Boolean-valued operations are white-listed.
10240     case UO_LNot:
10241       return IntRange::forBoolType();
10242 
10243     // Operations with opaque sources are black-listed.
10244     case UO_Deref:
10245     case UO_AddrOf: // should be impossible
10246       return IntRange::forValueOfType(C, GetExprType(E));
10247 
10248     default:
10249       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext);
10250     }
10251   }
10252 
10253   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
10254     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext);
10255 
10256   if (const auto *BitField = E->getSourceBitField())
10257     return IntRange(BitField->getBitWidthValue(C),
10258                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
10259 
10260   return IntRange::forValueOfType(C, GetExprType(E));
10261 }
10262 
10263 static IntRange GetExprRange(ASTContext &C, const Expr *E,
10264                              bool InConstantContext) {
10265   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext);
10266 }
10267 
10268 /// Checks whether the given value, which currently has the given
10269 /// source semantics, has the same value when coerced through the
10270 /// target semantics.
10271 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
10272                                  const llvm::fltSemantics &Src,
10273                                  const llvm::fltSemantics &Tgt) {
10274   llvm::APFloat truncated = value;
10275 
10276   bool ignored;
10277   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
10278   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
10279 
10280   return truncated.bitwiseIsEqual(value);
10281 }
10282 
10283 /// Checks whether the given value, which currently has the given
10284 /// source semantics, has the same value when coerced through the
10285 /// target semantics.
10286 ///
10287 /// The value might be a vector of floats (or a complex number).
10288 static bool IsSameFloatAfterCast(const APValue &value,
10289                                  const llvm::fltSemantics &Src,
10290                                  const llvm::fltSemantics &Tgt) {
10291   if (value.isFloat())
10292     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
10293 
10294   if (value.isVector()) {
10295     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
10296       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
10297         return false;
10298     return true;
10299   }
10300 
10301   assert(value.isComplexFloat());
10302   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
10303           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
10304 }
10305 
10306 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
10307                                        bool IsListInit = false);
10308 
10309 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
10310   // Suppress cases where we are comparing against an enum constant.
10311   if (const DeclRefExpr *DR =
10312       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
10313     if (isa<EnumConstantDecl>(DR->getDecl()))
10314       return true;
10315 
10316   // Suppress cases where the value is expanded from a macro, unless that macro
10317   // is how a language represents a boolean literal. This is the case in both C
10318   // and Objective-C.
10319   SourceLocation BeginLoc = E->getBeginLoc();
10320   if (BeginLoc.isMacroID()) {
10321     StringRef MacroName = Lexer::getImmediateMacroName(
10322         BeginLoc, S.getSourceManager(), S.getLangOpts());
10323     return MacroName != "YES" && MacroName != "NO" &&
10324            MacroName != "true" && MacroName != "false";
10325   }
10326 
10327   return false;
10328 }
10329 
10330 static bool isKnownToHaveUnsignedValue(Expr *E) {
10331   return E->getType()->isIntegerType() &&
10332          (!E->getType()->isSignedIntegerType() ||
10333           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
10334 }
10335 
10336 namespace {
10337 /// The promoted range of values of a type. In general this has the
10338 /// following structure:
10339 ///
10340 ///     |-----------| . . . |-----------|
10341 ///     ^           ^       ^           ^
10342 ///    Min       HoleMin  HoleMax      Max
10343 ///
10344 /// ... where there is only a hole if a signed type is promoted to unsigned
10345 /// (in which case Min and Max are the smallest and largest representable
10346 /// values).
10347 struct PromotedRange {
10348   // Min, or HoleMax if there is a hole.
10349   llvm::APSInt PromotedMin;
10350   // Max, or HoleMin if there is a hole.
10351   llvm::APSInt PromotedMax;
10352 
10353   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
10354     if (R.Width == 0)
10355       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
10356     else if (R.Width >= BitWidth && !Unsigned) {
10357       // Promotion made the type *narrower*. This happens when promoting
10358       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
10359       // Treat all values of 'signed int' as being in range for now.
10360       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
10361       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
10362     } else {
10363       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
10364                         .extOrTrunc(BitWidth);
10365       PromotedMin.setIsUnsigned(Unsigned);
10366 
10367       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
10368                         .extOrTrunc(BitWidth);
10369       PromotedMax.setIsUnsigned(Unsigned);
10370     }
10371   }
10372 
10373   // Determine whether this range is contiguous (has no hole).
10374   bool isContiguous() const { return PromotedMin <= PromotedMax; }
10375 
10376   // Where a constant value is within the range.
10377   enum ComparisonResult {
10378     LT = 0x1,
10379     LE = 0x2,
10380     GT = 0x4,
10381     GE = 0x8,
10382     EQ = 0x10,
10383     NE = 0x20,
10384     InRangeFlag = 0x40,
10385 
10386     Less = LE | LT | NE,
10387     Min = LE | InRangeFlag,
10388     InRange = InRangeFlag,
10389     Max = GE | InRangeFlag,
10390     Greater = GE | GT | NE,
10391 
10392     OnlyValue = LE | GE | EQ | InRangeFlag,
10393     InHole = NE
10394   };
10395 
10396   ComparisonResult compare(const llvm::APSInt &Value) const {
10397     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
10398            Value.isUnsigned() == PromotedMin.isUnsigned());
10399     if (!isContiguous()) {
10400       assert(Value.isUnsigned() && "discontiguous range for signed compare");
10401       if (Value.isMinValue()) return Min;
10402       if (Value.isMaxValue()) return Max;
10403       if (Value >= PromotedMin) return InRange;
10404       if (Value <= PromotedMax) return InRange;
10405       return InHole;
10406     }
10407 
10408     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
10409     case -1: return Less;
10410     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
10411     case 1:
10412       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
10413       case -1: return InRange;
10414       case 0: return Max;
10415       case 1: return Greater;
10416       }
10417     }
10418 
10419     llvm_unreachable("impossible compare result");
10420   }
10421 
10422   static llvm::Optional<StringRef>
10423   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
10424     if (Op == BO_Cmp) {
10425       ComparisonResult LTFlag = LT, GTFlag = GT;
10426       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
10427 
10428       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
10429       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
10430       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
10431       return llvm::None;
10432     }
10433 
10434     ComparisonResult TrueFlag, FalseFlag;
10435     if (Op == BO_EQ) {
10436       TrueFlag = EQ;
10437       FalseFlag = NE;
10438     } else if (Op == BO_NE) {
10439       TrueFlag = NE;
10440       FalseFlag = EQ;
10441     } else {
10442       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
10443         TrueFlag = LT;
10444         FalseFlag = GE;
10445       } else {
10446         TrueFlag = GT;
10447         FalseFlag = LE;
10448       }
10449       if (Op == BO_GE || Op == BO_LE)
10450         std::swap(TrueFlag, FalseFlag);
10451     }
10452     if (R & TrueFlag)
10453       return StringRef("true");
10454     if (R & FalseFlag)
10455       return StringRef("false");
10456     return llvm::None;
10457   }
10458 };
10459 }
10460 
10461 static bool HasEnumType(Expr *E) {
10462   // Strip off implicit integral promotions.
10463   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
10464     if (ICE->getCastKind() != CK_IntegralCast &&
10465         ICE->getCastKind() != CK_NoOp)
10466       break;
10467     E = ICE->getSubExpr();
10468   }
10469 
10470   return E->getType()->isEnumeralType();
10471 }
10472 
10473 static int classifyConstantValue(Expr *Constant) {
10474   // The values of this enumeration are used in the diagnostics
10475   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
10476   enum ConstantValueKind {
10477     Miscellaneous = 0,
10478     LiteralTrue,
10479     LiteralFalse
10480   };
10481   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
10482     return BL->getValue() ? ConstantValueKind::LiteralTrue
10483                           : ConstantValueKind::LiteralFalse;
10484   return ConstantValueKind::Miscellaneous;
10485 }
10486 
10487 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
10488                                         Expr *Constant, Expr *Other,
10489                                         const llvm::APSInt &Value,
10490                                         bool RhsConstant) {
10491   if (S.inTemplateInstantiation())
10492     return false;
10493 
10494   Expr *OriginalOther = Other;
10495 
10496   Constant = Constant->IgnoreParenImpCasts();
10497   Other = Other->IgnoreParenImpCasts();
10498 
10499   // Suppress warnings on tautological comparisons between values of the same
10500   // enumeration type. There are only two ways we could warn on this:
10501   //  - If the constant is outside the range of representable values of
10502   //    the enumeration. In such a case, we should warn about the cast
10503   //    to enumeration type, not about the comparison.
10504   //  - If the constant is the maximum / minimum in-range value. For an
10505   //    enumeratin type, such comparisons can be meaningful and useful.
10506   if (Constant->getType()->isEnumeralType() &&
10507       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
10508     return false;
10509 
10510   // TODO: Investigate using GetExprRange() to get tighter bounds
10511   // on the bit ranges.
10512   QualType OtherT = Other->getType();
10513   if (const auto *AT = OtherT->getAs<AtomicType>())
10514     OtherT = AT->getValueType();
10515   IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
10516 
10517   // Special case for ObjC BOOL on targets where its a typedef for a signed char
10518   // (Namely, macOS).
10519   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
10520                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
10521                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
10522 
10523   // Whether we're treating Other as being a bool because of the form of
10524   // expression despite it having another type (typically 'int' in C).
10525   bool OtherIsBooleanDespiteType =
10526       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
10527   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
10528     OtherRange = IntRange::forBoolType();
10529 
10530   // Determine the promoted range of the other type and see if a comparison of
10531   // the constant against that range is tautological.
10532   PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
10533                                    Value.isUnsigned());
10534   auto Cmp = OtherPromotedRange.compare(Value);
10535   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
10536   if (!Result)
10537     return false;
10538 
10539   // Suppress the diagnostic for an in-range comparison if the constant comes
10540   // from a macro or enumerator. We don't want to diagnose
10541   //
10542   //   some_long_value <= INT_MAX
10543   //
10544   // when sizeof(int) == sizeof(long).
10545   bool InRange = Cmp & PromotedRange::InRangeFlag;
10546   if (InRange && IsEnumConstOrFromMacro(S, Constant))
10547     return false;
10548 
10549   // If this is a comparison to an enum constant, include that
10550   // constant in the diagnostic.
10551   const EnumConstantDecl *ED = nullptr;
10552   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
10553     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
10554 
10555   // Should be enough for uint128 (39 decimal digits)
10556   SmallString<64> PrettySourceValue;
10557   llvm::raw_svector_ostream OS(PrettySourceValue);
10558   if (ED) {
10559     OS << '\'' << *ED << "' (" << Value << ")";
10560   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
10561                Constant->IgnoreParenImpCasts())) {
10562     OS << (BL->getValue() ? "YES" : "NO");
10563   } else {
10564     OS << Value;
10565   }
10566 
10567   if (IsObjCSignedCharBool) {
10568     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
10569                           S.PDiag(diag::warn_tautological_compare_objc_bool)
10570                               << OS.str() << *Result);
10571     return true;
10572   }
10573 
10574   // FIXME: We use a somewhat different formatting for the in-range cases and
10575   // cases involving boolean values for historical reasons. We should pick a
10576   // consistent way of presenting these diagnostics.
10577   if (!InRange || Other->isKnownToHaveBooleanValue()) {
10578 
10579     S.DiagRuntimeBehavior(
10580         E->getOperatorLoc(), E,
10581         S.PDiag(!InRange ? diag::warn_out_of_range_compare
10582                          : diag::warn_tautological_bool_compare)
10583             << OS.str() << classifyConstantValue(Constant) << OtherT
10584             << OtherIsBooleanDespiteType << *Result
10585             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
10586   } else {
10587     unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
10588                         ? (HasEnumType(OriginalOther)
10589                                ? diag::warn_unsigned_enum_always_true_comparison
10590                                : diag::warn_unsigned_always_true_comparison)
10591                         : diag::warn_tautological_constant_compare;
10592 
10593     S.Diag(E->getOperatorLoc(), Diag)
10594         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
10595         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
10596   }
10597 
10598   return true;
10599 }
10600 
10601 /// Analyze the operands of the given comparison.  Implements the
10602 /// fallback case from AnalyzeComparison.
10603 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
10604   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10605   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10606 }
10607 
10608 /// Implements -Wsign-compare.
10609 ///
10610 /// \param E the binary operator to check for warnings
10611 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
10612   // The type the comparison is being performed in.
10613   QualType T = E->getLHS()->getType();
10614 
10615   // Only analyze comparison operators where both sides have been converted to
10616   // the same type.
10617   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
10618     return AnalyzeImpConvsInComparison(S, E);
10619 
10620   // Don't analyze value-dependent comparisons directly.
10621   if (E->isValueDependent())
10622     return AnalyzeImpConvsInComparison(S, E);
10623 
10624   Expr *LHS = E->getLHS();
10625   Expr *RHS = E->getRHS();
10626 
10627   if (T->isIntegralType(S.Context)) {
10628     llvm::APSInt RHSValue;
10629     llvm::APSInt LHSValue;
10630 
10631     bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
10632     bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
10633 
10634     // We don't care about expressions whose result is a constant.
10635     if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
10636       return AnalyzeImpConvsInComparison(S, E);
10637 
10638     // We only care about expressions where just one side is literal
10639     if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
10640       // Is the constant on the RHS or LHS?
10641       const bool RhsConstant = IsRHSIntegralLiteral;
10642       Expr *Const = RhsConstant ? RHS : LHS;
10643       Expr *Other = RhsConstant ? LHS : RHS;
10644       const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
10645 
10646       // Check whether an integer constant comparison results in a value
10647       // of 'true' or 'false'.
10648       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
10649         return AnalyzeImpConvsInComparison(S, E);
10650     }
10651   }
10652 
10653   if (!T->hasUnsignedIntegerRepresentation()) {
10654     // We don't do anything special if this isn't an unsigned integral
10655     // comparison:  we're only interested in integral comparisons, and
10656     // signed comparisons only happen in cases we don't care to warn about.
10657     return AnalyzeImpConvsInComparison(S, E);
10658   }
10659 
10660   LHS = LHS->IgnoreParenImpCasts();
10661   RHS = RHS->IgnoreParenImpCasts();
10662 
10663   if (!S.getLangOpts().CPlusPlus) {
10664     // Avoid warning about comparison of integers with different signs when
10665     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
10666     // the type of `E`.
10667     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
10668       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10669     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
10670       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10671   }
10672 
10673   // Check to see if one of the (unmodified) operands is of different
10674   // signedness.
10675   Expr *signedOperand, *unsignedOperand;
10676   if (LHS->getType()->hasSignedIntegerRepresentation()) {
10677     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
10678            "unsigned comparison between two signed integer expressions?");
10679     signedOperand = LHS;
10680     unsignedOperand = RHS;
10681   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
10682     signedOperand = RHS;
10683     unsignedOperand = LHS;
10684   } else {
10685     return AnalyzeImpConvsInComparison(S, E);
10686   }
10687 
10688   // Otherwise, calculate the effective range of the signed operand.
10689   IntRange signedRange =
10690       GetExprRange(S.Context, signedOperand, S.isConstantEvaluated());
10691 
10692   // Go ahead and analyze implicit conversions in the operands.  Note
10693   // that we skip the implicit conversions on both sides.
10694   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
10695   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
10696 
10697   // If the signed range is non-negative, -Wsign-compare won't fire.
10698   if (signedRange.NonNegative)
10699     return;
10700 
10701   // For (in)equality comparisons, if the unsigned operand is a
10702   // constant which cannot collide with a overflowed signed operand,
10703   // then reinterpreting the signed operand as unsigned will not
10704   // change the result of the comparison.
10705   if (E->isEqualityOp()) {
10706     unsigned comparisonWidth = S.Context.getIntWidth(T);
10707     IntRange unsignedRange =
10708         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated());
10709 
10710     // We should never be unable to prove that the unsigned operand is
10711     // non-negative.
10712     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
10713 
10714     if (unsignedRange.Width < comparisonWidth)
10715       return;
10716   }
10717 
10718   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
10719                         S.PDiag(diag::warn_mixed_sign_comparison)
10720                             << LHS->getType() << RHS->getType()
10721                             << LHS->getSourceRange() << RHS->getSourceRange());
10722 }
10723 
10724 /// Analyzes an attempt to assign the given value to a bitfield.
10725 ///
10726 /// Returns true if there was something fishy about the attempt.
10727 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
10728                                       SourceLocation InitLoc) {
10729   assert(Bitfield->isBitField());
10730   if (Bitfield->isInvalidDecl())
10731     return false;
10732 
10733   // White-list bool bitfields.
10734   QualType BitfieldType = Bitfield->getType();
10735   if (BitfieldType->isBooleanType())
10736      return false;
10737 
10738   if (BitfieldType->isEnumeralType()) {
10739     EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
10740     // If the underlying enum type was not explicitly specified as an unsigned
10741     // type and the enum contain only positive values, MSVC++ will cause an
10742     // inconsistency by storing this as a signed type.
10743     if (S.getLangOpts().CPlusPlus11 &&
10744         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
10745         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
10746         BitfieldEnumDecl->getNumNegativeBits() == 0) {
10747       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
10748         << BitfieldEnumDecl->getNameAsString();
10749     }
10750   }
10751 
10752   if (Bitfield->getType()->isBooleanType())
10753     return false;
10754 
10755   // Ignore value- or type-dependent expressions.
10756   if (Bitfield->getBitWidth()->isValueDependent() ||
10757       Bitfield->getBitWidth()->isTypeDependent() ||
10758       Init->isValueDependent() ||
10759       Init->isTypeDependent())
10760     return false;
10761 
10762   Expr *OriginalInit = Init->IgnoreParenImpCasts();
10763   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
10764 
10765   Expr::EvalResult Result;
10766   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
10767                                    Expr::SE_AllowSideEffects)) {
10768     // The RHS is not constant.  If the RHS has an enum type, make sure the
10769     // bitfield is wide enough to hold all the values of the enum without
10770     // truncation.
10771     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
10772       EnumDecl *ED = EnumTy->getDecl();
10773       bool SignedBitfield = BitfieldType->isSignedIntegerType();
10774 
10775       // Enum types are implicitly signed on Windows, so check if there are any
10776       // negative enumerators to see if the enum was intended to be signed or
10777       // not.
10778       bool SignedEnum = ED->getNumNegativeBits() > 0;
10779 
10780       // Check for surprising sign changes when assigning enum values to a
10781       // bitfield of different signedness.  If the bitfield is signed and we
10782       // have exactly the right number of bits to store this unsigned enum,
10783       // suggest changing the enum to an unsigned type. This typically happens
10784       // on Windows where unfixed enums always use an underlying type of 'int'.
10785       unsigned DiagID = 0;
10786       if (SignedEnum && !SignedBitfield) {
10787         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
10788       } else if (SignedBitfield && !SignedEnum &&
10789                  ED->getNumPositiveBits() == FieldWidth) {
10790         DiagID = diag::warn_signed_bitfield_enum_conversion;
10791       }
10792 
10793       if (DiagID) {
10794         S.Diag(InitLoc, DiagID) << Bitfield << ED;
10795         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
10796         SourceRange TypeRange =
10797             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
10798         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
10799             << SignedEnum << TypeRange;
10800       }
10801 
10802       // Compute the required bitwidth. If the enum has negative values, we need
10803       // one more bit than the normal number of positive bits to represent the
10804       // sign bit.
10805       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
10806                                                   ED->getNumNegativeBits())
10807                                        : ED->getNumPositiveBits();
10808 
10809       // Check the bitwidth.
10810       if (BitsNeeded > FieldWidth) {
10811         Expr *WidthExpr = Bitfield->getBitWidth();
10812         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
10813             << Bitfield << ED;
10814         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
10815             << BitsNeeded << ED << WidthExpr->getSourceRange();
10816       }
10817     }
10818 
10819     return false;
10820   }
10821 
10822   llvm::APSInt Value = Result.Val.getInt();
10823 
10824   unsigned OriginalWidth = Value.getBitWidth();
10825 
10826   if (!Value.isSigned() || Value.isNegative())
10827     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
10828       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
10829         OriginalWidth = Value.getMinSignedBits();
10830 
10831   if (OriginalWidth <= FieldWidth)
10832     return false;
10833 
10834   // Compute the value which the bitfield will contain.
10835   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
10836   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
10837 
10838   // Check whether the stored value is equal to the original value.
10839   TruncatedValue = TruncatedValue.extend(OriginalWidth);
10840   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
10841     return false;
10842 
10843   // Special-case bitfields of width 1: booleans are naturally 0/1, and
10844   // therefore don't strictly fit into a signed bitfield of width 1.
10845   if (FieldWidth == 1 && Value == 1)
10846     return false;
10847 
10848   std::string PrettyValue = Value.toString(10);
10849   std::string PrettyTrunc = TruncatedValue.toString(10);
10850 
10851   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
10852     << PrettyValue << PrettyTrunc << OriginalInit->getType()
10853     << Init->getSourceRange();
10854 
10855   return true;
10856 }
10857 
10858 /// Analyze the given simple or compound assignment for warning-worthy
10859 /// operations.
10860 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
10861   // Just recurse on the LHS.
10862   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10863 
10864   // We want to recurse on the RHS as normal unless we're assigning to
10865   // a bitfield.
10866   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
10867     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
10868                                   E->getOperatorLoc())) {
10869       // Recurse, ignoring any implicit conversions on the RHS.
10870       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
10871                                         E->getOperatorLoc());
10872     }
10873   }
10874 
10875   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10876 
10877   // Diagnose implicitly sequentially-consistent atomic assignment.
10878   if (E->getLHS()->getType()->isAtomicType())
10879     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
10880 }
10881 
10882 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
10883 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
10884                             SourceLocation CContext, unsigned diag,
10885                             bool pruneControlFlow = false) {
10886   if (pruneControlFlow) {
10887     S.DiagRuntimeBehavior(E->getExprLoc(), E,
10888                           S.PDiag(diag)
10889                               << SourceType << T << E->getSourceRange()
10890                               << SourceRange(CContext));
10891     return;
10892   }
10893   S.Diag(E->getExprLoc(), diag)
10894     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
10895 }
10896 
10897 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
10898 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
10899                             SourceLocation CContext,
10900                             unsigned diag, bool pruneControlFlow = false) {
10901   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
10902 }
10903 
10904 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
10905   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
10906       S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
10907 }
10908 
10909 static void adornObjCBoolConversionDiagWithTernaryFixit(
10910     Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
10911   Expr *Ignored = SourceExpr->IgnoreImplicit();
10912   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
10913     Ignored = OVE->getSourceExpr();
10914   bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
10915                      isa<BinaryOperator>(Ignored) ||
10916                      isa<CXXOperatorCallExpr>(Ignored);
10917   SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
10918   if (NeedsParens)
10919     Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
10920             << FixItHint::CreateInsertion(EndLoc, ")");
10921   Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
10922 }
10923 
10924 /// Diagnose an implicit cast from a floating point value to an integer value.
10925 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
10926                                     SourceLocation CContext) {
10927   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
10928   const bool PruneWarnings = S.inTemplateInstantiation();
10929 
10930   Expr *InnerE = E->IgnoreParenImpCasts();
10931   // We also want to warn on, e.g., "int i = -1.234"
10932   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
10933     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
10934       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
10935 
10936   const bool IsLiteral =
10937       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
10938 
10939   llvm::APFloat Value(0.0);
10940   bool IsConstant =
10941     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
10942   if (!IsConstant) {
10943     if (isObjCSignedCharBool(S, T)) {
10944       return adornObjCBoolConversionDiagWithTernaryFixit(
10945           S, E,
10946           S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
10947               << E->getType());
10948     }
10949 
10950     return DiagnoseImpCast(S, E, T, CContext,
10951                            diag::warn_impcast_float_integer, PruneWarnings);
10952   }
10953 
10954   bool isExact = false;
10955 
10956   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
10957                             T->hasUnsignedIntegerRepresentation());
10958   llvm::APFloat::opStatus Result = Value.convertToInteger(
10959       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
10960 
10961   // FIXME: Force the precision of the source value down so we don't print
10962   // digits which are usually useless (we don't really care here if we
10963   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
10964   // would automatically print the shortest representation, but it's a bit
10965   // tricky to implement.
10966   SmallString<16> PrettySourceValue;
10967   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
10968   precision = (precision * 59 + 195) / 196;
10969   Value.toString(PrettySourceValue, precision);
10970 
10971   if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
10972     return adornObjCBoolConversionDiagWithTernaryFixit(
10973         S, E,
10974         S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
10975             << PrettySourceValue);
10976   }
10977 
10978   if (Result == llvm::APFloat::opOK && isExact) {
10979     if (IsLiteral) return;
10980     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
10981                            PruneWarnings);
10982   }
10983 
10984   // Conversion of a floating-point value to a non-bool integer where the
10985   // integral part cannot be represented by the integer type is undefined.
10986   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
10987     return DiagnoseImpCast(
10988         S, E, T, CContext,
10989         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
10990                   : diag::warn_impcast_float_to_integer_out_of_range,
10991         PruneWarnings);
10992 
10993   unsigned DiagID = 0;
10994   if (IsLiteral) {
10995     // Warn on floating point literal to integer.
10996     DiagID = diag::warn_impcast_literal_float_to_integer;
10997   } else if (IntegerValue == 0) {
10998     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
10999       return DiagnoseImpCast(S, E, T, CContext,
11000                              diag::warn_impcast_float_integer, PruneWarnings);
11001     }
11002     // Warn on non-zero to zero conversion.
11003     DiagID = diag::warn_impcast_float_to_integer_zero;
11004   } else {
11005     if (IntegerValue.isUnsigned()) {
11006       if (!IntegerValue.isMaxValue()) {
11007         return DiagnoseImpCast(S, E, T, CContext,
11008                                diag::warn_impcast_float_integer, PruneWarnings);
11009       }
11010     } else {  // IntegerValue.isSigned()
11011       if (!IntegerValue.isMaxSignedValue() &&
11012           !IntegerValue.isMinSignedValue()) {
11013         return DiagnoseImpCast(S, E, T, CContext,
11014                                diag::warn_impcast_float_integer, PruneWarnings);
11015       }
11016     }
11017     // Warn on evaluatable floating point expression to integer conversion.
11018     DiagID = diag::warn_impcast_float_to_integer;
11019   }
11020 
11021   SmallString<16> PrettyTargetValue;
11022   if (IsBool)
11023     PrettyTargetValue = Value.isZero() ? "false" : "true";
11024   else
11025     IntegerValue.toString(PrettyTargetValue);
11026 
11027   if (PruneWarnings) {
11028     S.DiagRuntimeBehavior(E->getExprLoc(), E,
11029                           S.PDiag(DiagID)
11030                               << E->getType() << T.getUnqualifiedType()
11031                               << PrettySourceValue << PrettyTargetValue
11032                               << E->getSourceRange() << SourceRange(CContext));
11033   } else {
11034     S.Diag(E->getExprLoc(), DiagID)
11035         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
11036         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
11037   }
11038 }
11039 
11040 /// Analyze the given compound assignment for the possible losing of
11041 /// floating-point precision.
11042 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
11043   assert(isa<CompoundAssignOperator>(E) &&
11044          "Must be compound assignment operation");
11045   // Recurse on the LHS and RHS in here
11046   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11047   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11048 
11049   if (E->getLHS()->getType()->isAtomicType())
11050     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
11051 
11052   // Now check the outermost expression
11053   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
11054   const auto *RBT = cast<CompoundAssignOperator>(E)
11055                         ->getComputationResultType()
11056                         ->getAs<BuiltinType>();
11057 
11058   // The below checks assume source is floating point.
11059   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
11060 
11061   // If source is floating point but target is an integer.
11062   if (ResultBT->isInteger())
11063     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
11064                            E->getExprLoc(), diag::warn_impcast_float_integer);
11065 
11066   if (!ResultBT->isFloatingPoint())
11067     return;
11068 
11069   // If both source and target are floating points, warn about losing precision.
11070   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
11071       QualType(ResultBT, 0), QualType(RBT, 0));
11072   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
11073     // warn about dropping FP rank.
11074     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
11075                     diag::warn_impcast_float_result_precision);
11076 }
11077 
11078 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
11079                                       IntRange Range) {
11080   if (!Range.Width) return "0";
11081 
11082   llvm::APSInt ValueInRange = Value;
11083   ValueInRange.setIsSigned(!Range.NonNegative);
11084   ValueInRange = ValueInRange.trunc(Range.Width);
11085   return ValueInRange.toString(10);
11086 }
11087 
11088 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
11089   if (!isa<ImplicitCastExpr>(Ex))
11090     return false;
11091 
11092   Expr *InnerE = Ex->IgnoreParenImpCasts();
11093   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
11094   const Type *Source =
11095     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
11096   if (Target->isDependentType())
11097     return false;
11098 
11099   const BuiltinType *FloatCandidateBT =
11100     dyn_cast<BuiltinType>(ToBool ? Source : Target);
11101   const Type *BoolCandidateType = ToBool ? Target : Source;
11102 
11103   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
11104           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
11105 }
11106 
11107 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
11108                                              SourceLocation CC) {
11109   unsigned NumArgs = TheCall->getNumArgs();
11110   for (unsigned i = 0; i < NumArgs; ++i) {
11111     Expr *CurrA = TheCall->getArg(i);
11112     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
11113       continue;
11114 
11115     bool IsSwapped = ((i > 0) &&
11116         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
11117     IsSwapped |= ((i < (NumArgs - 1)) &&
11118         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
11119     if (IsSwapped) {
11120       // Warn on this floating-point to bool conversion.
11121       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
11122                       CurrA->getType(), CC,
11123                       diag::warn_impcast_floating_point_to_bool);
11124     }
11125   }
11126 }
11127 
11128 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
11129                                    SourceLocation CC) {
11130   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
11131                         E->getExprLoc()))
11132     return;
11133 
11134   // Don't warn on functions which have return type nullptr_t.
11135   if (isa<CallExpr>(E))
11136     return;
11137 
11138   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
11139   const Expr::NullPointerConstantKind NullKind =
11140       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
11141   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
11142     return;
11143 
11144   // Return if target type is a safe conversion.
11145   if (T->isAnyPointerType() || T->isBlockPointerType() ||
11146       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
11147     return;
11148 
11149   SourceLocation Loc = E->getSourceRange().getBegin();
11150 
11151   // Venture through the macro stacks to get to the source of macro arguments.
11152   // The new location is a better location than the complete location that was
11153   // passed in.
11154   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
11155   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
11156 
11157   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
11158   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
11159     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
11160         Loc, S.SourceMgr, S.getLangOpts());
11161     if (MacroName == "NULL")
11162       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
11163   }
11164 
11165   // Only warn if the null and context location are in the same macro expansion.
11166   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
11167     return;
11168 
11169   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
11170       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
11171       << FixItHint::CreateReplacement(Loc,
11172                                       S.getFixItZeroLiteralForType(T, Loc));
11173 }
11174 
11175 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
11176                                   ObjCArrayLiteral *ArrayLiteral);
11177 
11178 static void
11179 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
11180                            ObjCDictionaryLiteral *DictionaryLiteral);
11181 
11182 /// Check a single element within a collection literal against the
11183 /// target element type.
11184 static void checkObjCCollectionLiteralElement(Sema &S,
11185                                               QualType TargetElementType,
11186                                               Expr *Element,
11187                                               unsigned ElementKind) {
11188   // Skip a bitcast to 'id' or qualified 'id'.
11189   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
11190     if (ICE->getCastKind() == CK_BitCast &&
11191         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
11192       Element = ICE->getSubExpr();
11193   }
11194 
11195   QualType ElementType = Element->getType();
11196   ExprResult ElementResult(Element);
11197   if (ElementType->getAs<ObjCObjectPointerType>() &&
11198       S.CheckSingleAssignmentConstraints(TargetElementType,
11199                                          ElementResult,
11200                                          false, false)
11201         != Sema::Compatible) {
11202     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
11203         << ElementType << ElementKind << TargetElementType
11204         << Element->getSourceRange();
11205   }
11206 
11207   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
11208     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
11209   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
11210     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
11211 }
11212 
11213 /// Check an Objective-C array literal being converted to the given
11214 /// target type.
11215 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
11216                                   ObjCArrayLiteral *ArrayLiteral) {
11217   if (!S.NSArrayDecl)
11218     return;
11219 
11220   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
11221   if (!TargetObjCPtr)
11222     return;
11223 
11224   if (TargetObjCPtr->isUnspecialized() ||
11225       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
11226         != S.NSArrayDecl->getCanonicalDecl())
11227     return;
11228 
11229   auto TypeArgs = TargetObjCPtr->getTypeArgs();
11230   if (TypeArgs.size() != 1)
11231     return;
11232 
11233   QualType TargetElementType = TypeArgs[0];
11234   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
11235     checkObjCCollectionLiteralElement(S, TargetElementType,
11236                                       ArrayLiteral->getElement(I),
11237                                       0);
11238   }
11239 }
11240 
11241 /// Check an Objective-C dictionary literal being converted to the given
11242 /// target type.
11243 static void
11244 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
11245                            ObjCDictionaryLiteral *DictionaryLiteral) {
11246   if (!S.NSDictionaryDecl)
11247     return;
11248 
11249   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
11250   if (!TargetObjCPtr)
11251     return;
11252 
11253   if (TargetObjCPtr->isUnspecialized() ||
11254       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
11255         != S.NSDictionaryDecl->getCanonicalDecl())
11256     return;
11257 
11258   auto TypeArgs = TargetObjCPtr->getTypeArgs();
11259   if (TypeArgs.size() != 2)
11260     return;
11261 
11262   QualType TargetKeyType = TypeArgs[0];
11263   QualType TargetObjectType = TypeArgs[1];
11264   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
11265     auto Element = DictionaryLiteral->getKeyValueElement(I);
11266     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
11267     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
11268   }
11269 }
11270 
11271 // Helper function to filter out cases for constant width constant conversion.
11272 // Don't warn on char array initialization or for non-decimal values.
11273 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
11274                                           SourceLocation CC) {
11275   // If initializing from a constant, and the constant starts with '0',
11276   // then it is a binary, octal, or hexadecimal.  Allow these constants
11277   // to fill all the bits, even if there is a sign change.
11278   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
11279     const char FirstLiteralCharacter =
11280         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
11281     if (FirstLiteralCharacter == '0')
11282       return false;
11283   }
11284 
11285   // If the CC location points to a '{', and the type is char, then assume
11286   // assume it is an array initialization.
11287   if (CC.isValid() && T->isCharType()) {
11288     const char FirstContextCharacter =
11289         S.getSourceManager().getCharacterData(CC)[0];
11290     if (FirstContextCharacter == '{')
11291       return false;
11292   }
11293 
11294   return true;
11295 }
11296 
11297 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
11298   const auto *IL = dyn_cast<IntegerLiteral>(E);
11299   if (!IL) {
11300     if (auto *UO = dyn_cast<UnaryOperator>(E)) {
11301       if (UO->getOpcode() == UO_Minus)
11302         return dyn_cast<IntegerLiteral>(UO->getSubExpr());
11303     }
11304   }
11305 
11306   return IL;
11307 }
11308 
11309 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
11310   E = E->IgnoreParenImpCasts();
11311   SourceLocation ExprLoc = E->getExprLoc();
11312 
11313   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11314     BinaryOperator::Opcode Opc = BO->getOpcode();
11315     Expr::EvalResult Result;
11316     // Do not diagnose unsigned shifts.
11317     if (Opc == BO_Shl) {
11318       const auto *LHS = getIntegerLiteral(BO->getLHS());
11319       const auto *RHS = getIntegerLiteral(BO->getRHS());
11320       if (LHS && LHS->getValue() == 0)
11321         S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
11322       else if (!E->isValueDependent() && LHS && RHS &&
11323                RHS->getValue().isNonNegative() &&
11324                E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
11325         S.Diag(ExprLoc, diag::warn_left_shift_always)
11326             << (Result.Val.getInt() != 0);
11327       else if (E->getType()->isSignedIntegerType())
11328         S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
11329     }
11330   }
11331 
11332   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11333     const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
11334     const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
11335     if (!LHS || !RHS)
11336       return;
11337     if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
11338         (RHS->getValue() == 0 || RHS->getValue() == 1))
11339       // Do not diagnose common idioms.
11340       return;
11341     if (LHS->getValue() != 0 && RHS->getValue() != 0)
11342       S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
11343   }
11344 }
11345 
11346 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
11347                                     SourceLocation CC,
11348                                     bool *ICContext = nullptr,
11349                                     bool IsListInit = false) {
11350   if (E->isTypeDependent() || E->isValueDependent()) return;
11351 
11352   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
11353   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
11354   if (Source == Target) return;
11355   if (Target->isDependentType()) return;
11356 
11357   // If the conversion context location is invalid don't complain. We also
11358   // don't want to emit a warning if the issue occurs from the expansion of
11359   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
11360   // delay this check as long as possible. Once we detect we are in that
11361   // scenario, we just return.
11362   if (CC.isInvalid())
11363     return;
11364 
11365   if (Source->isAtomicType())
11366     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
11367 
11368   // Diagnose implicit casts to bool.
11369   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
11370     if (isa<StringLiteral>(E))
11371       // Warn on string literal to bool.  Checks for string literals in logical
11372       // and expressions, for instance, assert(0 && "error here"), are
11373       // prevented by a check in AnalyzeImplicitConversions().
11374       return DiagnoseImpCast(S, E, T, CC,
11375                              diag::warn_impcast_string_literal_to_bool);
11376     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
11377         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
11378       // This covers the literal expressions that evaluate to Objective-C
11379       // objects.
11380       return DiagnoseImpCast(S, E, T, CC,
11381                              diag::warn_impcast_objective_c_literal_to_bool);
11382     }
11383     if (Source->isPointerType() || Source->canDecayToPointerType()) {
11384       // Warn on pointer to bool conversion that is always true.
11385       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
11386                                      SourceRange(CC));
11387     }
11388   }
11389 
11390   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
11391   // is a typedef for signed char (macOS), then that constant value has to be 1
11392   // or 0.
11393   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
11394     Expr::EvalResult Result;
11395     if (E->EvaluateAsInt(Result, S.getASTContext(),
11396                          Expr::SE_AllowSideEffects)) {
11397       if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
11398         adornObjCBoolConversionDiagWithTernaryFixit(
11399             S, E,
11400             S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
11401                 << Result.Val.getInt().toString(10));
11402       }
11403       return;
11404     }
11405   }
11406 
11407   // Check implicit casts from Objective-C collection literals to specialized
11408   // collection types, e.g., NSArray<NSString *> *.
11409   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
11410     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
11411   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
11412     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
11413 
11414   // Strip vector types.
11415   if (isa<VectorType>(Source)) {
11416     if (!isa<VectorType>(Target)) {
11417       if (S.SourceMgr.isInSystemMacro(CC))
11418         return;
11419       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
11420     }
11421 
11422     // If the vector cast is cast between two vectors of the same size, it is
11423     // a bitcast, not a conversion.
11424     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
11425       return;
11426 
11427     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
11428     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
11429   }
11430   if (auto VecTy = dyn_cast<VectorType>(Target))
11431     Target = VecTy->getElementType().getTypePtr();
11432 
11433   // Strip complex types.
11434   if (isa<ComplexType>(Source)) {
11435     if (!isa<ComplexType>(Target)) {
11436       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
11437         return;
11438 
11439       return DiagnoseImpCast(S, E, T, CC,
11440                              S.getLangOpts().CPlusPlus
11441                                  ? diag::err_impcast_complex_scalar
11442                                  : diag::warn_impcast_complex_scalar);
11443     }
11444 
11445     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
11446     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
11447   }
11448 
11449   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
11450   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
11451 
11452   // If the source is floating point...
11453   if (SourceBT && SourceBT->isFloatingPoint()) {
11454     // ...and the target is floating point...
11455     if (TargetBT && TargetBT->isFloatingPoint()) {
11456       // ...then warn if we're dropping FP rank.
11457 
11458       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
11459           QualType(SourceBT, 0), QualType(TargetBT, 0));
11460       if (Order > 0) {
11461         // Don't warn about float constants that are precisely
11462         // representable in the target type.
11463         Expr::EvalResult result;
11464         if (E->EvaluateAsRValue(result, S.Context)) {
11465           // Value might be a float, a float vector, or a float complex.
11466           if (IsSameFloatAfterCast(result.Val,
11467                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
11468                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
11469             return;
11470         }
11471 
11472         if (S.SourceMgr.isInSystemMacro(CC))
11473           return;
11474 
11475         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
11476       }
11477       // ... or possibly if we're increasing rank, too
11478       else if (Order < 0) {
11479         if (S.SourceMgr.isInSystemMacro(CC))
11480           return;
11481 
11482         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
11483       }
11484       return;
11485     }
11486 
11487     // If the target is integral, always warn.
11488     if (TargetBT && TargetBT->isInteger()) {
11489       if (S.SourceMgr.isInSystemMacro(CC))
11490         return;
11491 
11492       DiagnoseFloatingImpCast(S, E, T, CC);
11493     }
11494 
11495     // Detect the case where a call result is converted from floating-point to
11496     // to bool, and the final argument to the call is converted from bool, to
11497     // discover this typo:
11498     //
11499     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
11500     //
11501     // FIXME: This is an incredibly special case; is there some more general
11502     // way to detect this class of misplaced-parentheses bug?
11503     if (Target->isBooleanType() && isa<CallExpr>(E)) {
11504       // Check last argument of function call to see if it is an
11505       // implicit cast from a type matching the type the result
11506       // is being cast to.
11507       CallExpr *CEx = cast<CallExpr>(E);
11508       if (unsigned NumArgs = CEx->getNumArgs()) {
11509         Expr *LastA = CEx->getArg(NumArgs - 1);
11510         Expr *InnerE = LastA->IgnoreParenImpCasts();
11511         if (isa<ImplicitCastExpr>(LastA) &&
11512             InnerE->getType()->isBooleanType()) {
11513           // Warn on this floating-point to bool conversion
11514           DiagnoseImpCast(S, E, T, CC,
11515                           diag::warn_impcast_floating_point_to_bool);
11516         }
11517       }
11518     }
11519     return;
11520   }
11521 
11522   // Valid casts involving fixed point types should be accounted for here.
11523   if (Source->isFixedPointType()) {
11524     if (Target->isUnsaturatedFixedPointType()) {
11525       Expr::EvalResult Result;
11526       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
11527                                   S.isConstantEvaluated())) {
11528         APFixedPoint Value = Result.Val.getFixedPoint();
11529         APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
11530         APFixedPoint MinVal = S.Context.getFixedPointMin(T);
11531         if (Value > MaxVal || Value < MinVal) {
11532           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11533                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11534                                     << Value.toString() << T
11535                                     << E->getSourceRange()
11536                                     << clang::SourceRange(CC));
11537           return;
11538         }
11539       }
11540     } else if (Target->isIntegerType()) {
11541       Expr::EvalResult Result;
11542       if (!S.isConstantEvaluated() &&
11543           E->EvaluateAsFixedPoint(Result, S.Context,
11544                                   Expr::SE_AllowSideEffects)) {
11545         APFixedPoint FXResult = Result.Val.getFixedPoint();
11546 
11547         bool Overflowed;
11548         llvm::APSInt IntResult = FXResult.convertToInt(
11549             S.Context.getIntWidth(T),
11550             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
11551 
11552         if (Overflowed) {
11553           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11554                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11555                                     << FXResult.toString() << T
11556                                     << E->getSourceRange()
11557                                     << clang::SourceRange(CC));
11558           return;
11559         }
11560       }
11561     }
11562   } else if (Target->isUnsaturatedFixedPointType()) {
11563     if (Source->isIntegerType()) {
11564       Expr::EvalResult Result;
11565       if (!S.isConstantEvaluated() &&
11566           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
11567         llvm::APSInt Value = Result.Val.getInt();
11568 
11569         bool Overflowed;
11570         APFixedPoint IntResult = APFixedPoint::getFromIntValue(
11571             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
11572 
11573         if (Overflowed) {
11574           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11575                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11576                                     << Value.toString(/*Radix=*/10) << T
11577                                     << E->getSourceRange()
11578                                     << clang::SourceRange(CC));
11579           return;
11580         }
11581       }
11582     }
11583   }
11584 
11585   // If we are casting an integer type to a floating point type without
11586   // initialization-list syntax, we might lose accuracy if the floating
11587   // point type has a narrower significand than the integer type.
11588   if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
11589       TargetBT->isFloatingType() && !IsListInit) {
11590     // Determine the number of precision bits in the source integer type.
11591     IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated());
11592     unsigned int SourcePrecision = SourceRange.Width;
11593 
11594     // Determine the number of precision bits in the
11595     // target floating point type.
11596     unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
11597         S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
11598 
11599     if (SourcePrecision > 0 && TargetPrecision > 0 &&
11600         SourcePrecision > TargetPrecision) {
11601 
11602       llvm::APSInt SourceInt;
11603       if (E->isIntegerConstantExpr(SourceInt, S.Context)) {
11604         // If the source integer is a constant, convert it to the target
11605         // floating point type. Issue a warning if the value changes
11606         // during the whole conversion.
11607         llvm::APFloat TargetFloatValue(
11608             S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
11609         llvm::APFloat::opStatus ConversionStatus =
11610             TargetFloatValue.convertFromAPInt(
11611                 SourceInt, SourceBT->isSignedInteger(),
11612                 llvm::APFloat::rmNearestTiesToEven);
11613 
11614         if (ConversionStatus != llvm::APFloat::opOK) {
11615           std::string PrettySourceValue = SourceInt.toString(10);
11616           SmallString<32> PrettyTargetValue;
11617           TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
11618 
11619           S.DiagRuntimeBehavior(
11620               E->getExprLoc(), E,
11621               S.PDiag(diag::warn_impcast_integer_float_precision_constant)
11622                   << PrettySourceValue << PrettyTargetValue << E->getType() << T
11623                   << E->getSourceRange() << clang::SourceRange(CC));
11624         }
11625       } else {
11626         // Otherwise, the implicit conversion may lose precision.
11627         DiagnoseImpCast(S, E, T, CC,
11628                         diag::warn_impcast_integer_float_precision);
11629       }
11630     }
11631   }
11632 
11633   DiagnoseNullConversion(S, E, T, CC);
11634 
11635   S.DiscardMisalignedMemberAddress(Target, E);
11636 
11637   if (Target->isBooleanType())
11638     DiagnoseIntInBoolContext(S, E);
11639 
11640   if (!Source->isIntegerType() || !Target->isIntegerType())
11641     return;
11642 
11643   // TODO: remove this early return once the false positives for constant->bool
11644   // in templates, macros, etc, are reduced or removed.
11645   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
11646     return;
11647 
11648   if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
11649       !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
11650     return adornObjCBoolConversionDiagWithTernaryFixit(
11651         S, E,
11652         S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
11653             << E->getType());
11654   }
11655 
11656   IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated());
11657   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
11658 
11659   if (SourceRange.Width > TargetRange.Width) {
11660     // If the source is a constant, use a default-on diagnostic.
11661     // TODO: this should happen for bitfield stores, too.
11662     Expr::EvalResult Result;
11663     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
11664                          S.isConstantEvaluated())) {
11665       llvm::APSInt Value(32);
11666       Value = Result.Val.getInt();
11667 
11668       if (S.SourceMgr.isInSystemMacro(CC))
11669         return;
11670 
11671       std::string PrettySourceValue = Value.toString(10);
11672       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
11673 
11674       S.DiagRuntimeBehavior(
11675           E->getExprLoc(), E,
11676           S.PDiag(diag::warn_impcast_integer_precision_constant)
11677               << PrettySourceValue << PrettyTargetValue << E->getType() << T
11678               << E->getSourceRange() << clang::SourceRange(CC));
11679       return;
11680     }
11681 
11682     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
11683     if (S.SourceMgr.isInSystemMacro(CC))
11684       return;
11685 
11686     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
11687       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
11688                              /* pruneControlFlow */ true);
11689     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
11690   }
11691 
11692   if (TargetRange.Width > SourceRange.Width) {
11693     if (auto *UO = dyn_cast<UnaryOperator>(E))
11694       if (UO->getOpcode() == UO_Minus)
11695         if (Source->isUnsignedIntegerType()) {
11696           if (Target->isUnsignedIntegerType())
11697             return DiagnoseImpCast(S, E, T, CC,
11698                                    diag::warn_impcast_high_order_zero_bits);
11699           if (Target->isSignedIntegerType())
11700             return DiagnoseImpCast(S, E, T, CC,
11701                                    diag::warn_impcast_nonnegative_result);
11702         }
11703   }
11704 
11705   if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
11706       SourceRange.NonNegative && Source->isSignedIntegerType()) {
11707     // Warn when doing a signed to signed conversion, warn if the positive
11708     // source value is exactly the width of the target type, which will
11709     // cause a negative value to be stored.
11710 
11711     Expr::EvalResult Result;
11712     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
11713         !S.SourceMgr.isInSystemMacro(CC)) {
11714       llvm::APSInt Value = Result.Val.getInt();
11715       if (isSameWidthConstantConversion(S, E, T, CC)) {
11716         std::string PrettySourceValue = Value.toString(10);
11717         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
11718 
11719         S.DiagRuntimeBehavior(
11720             E->getExprLoc(), E,
11721             S.PDiag(diag::warn_impcast_integer_precision_constant)
11722                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
11723                 << E->getSourceRange() << clang::SourceRange(CC));
11724         return;
11725       }
11726     }
11727 
11728     // Fall through for non-constants to give a sign conversion warning.
11729   }
11730 
11731   if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
11732       (!TargetRange.NonNegative && SourceRange.NonNegative &&
11733        SourceRange.Width == TargetRange.Width)) {
11734     if (S.SourceMgr.isInSystemMacro(CC))
11735       return;
11736 
11737     unsigned DiagID = diag::warn_impcast_integer_sign;
11738 
11739     // Traditionally, gcc has warned about this under -Wsign-compare.
11740     // We also want to warn about it in -Wconversion.
11741     // So if -Wconversion is off, use a completely identical diagnostic
11742     // in the sign-compare group.
11743     // The conditional-checking code will
11744     if (ICContext) {
11745       DiagID = diag::warn_impcast_integer_sign_conditional;
11746       *ICContext = true;
11747     }
11748 
11749     return DiagnoseImpCast(S, E, T, CC, DiagID);
11750   }
11751 
11752   // Diagnose conversions between different enumeration types.
11753   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
11754   // type, to give us better diagnostics.
11755   QualType SourceType = E->getType();
11756   if (!S.getLangOpts().CPlusPlus) {
11757     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11758       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
11759         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
11760         SourceType = S.Context.getTypeDeclType(Enum);
11761         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
11762       }
11763   }
11764 
11765   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
11766     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
11767       if (SourceEnum->getDecl()->hasNameForLinkage() &&
11768           TargetEnum->getDecl()->hasNameForLinkage() &&
11769           SourceEnum != TargetEnum) {
11770         if (S.SourceMgr.isInSystemMacro(CC))
11771           return;
11772 
11773         return DiagnoseImpCast(S, E, SourceType, T, CC,
11774                                diag::warn_impcast_different_enum_types);
11775       }
11776 }
11777 
11778 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
11779                                      SourceLocation CC, QualType T);
11780 
11781 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
11782                                     SourceLocation CC, bool &ICContext) {
11783   E = E->IgnoreParenImpCasts();
11784 
11785   if (isa<ConditionalOperator>(E))
11786     return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
11787 
11788   AnalyzeImplicitConversions(S, E, CC);
11789   if (E->getType() != T)
11790     return CheckImplicitConversion(S, E, T, CC, &ICContext);
11791 }
11792 
11793 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
11794                                      SourceLocation CC, QualType T) {
11795   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
11796 
11797   bool Suspicious = false;
11798   CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
11799   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
11800 
11801   if (T->isBooleanType())
11802     DiagnoseIntInBoolContext(S, E);
11803 
11804   // If -Wconversion would have warned about either of the candidates
11805   // for a signedness conversion to the context type...
11806   if (!Suspicious) return;
11807 
11808   // ...but it's currently ignored...
11809   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
11810     return;
11811 
11812   // ...then check whether it would have warned about either of the
11813   // candidates for a signedness conversion to the condition type.
11814   if (E->getType() == T) return;
11815 
11816   Suspicious = false;
11817   CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
11818                           E->getType(), CC, &Suspicious);
11819   if (!Suspicious)
11820     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
11821                             E->getType(), CC, &Suspicious);
11822 }
11823 
11824 /// Check conversion of given expression to boolean.
11825 /// Input argument E is a logical expression.
11826 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
11827   if (S.getLangOpts().Bool)
11828     return;
11829   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
11830     return;
11831   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
11832 }
11833 
11834 namespace {
11835 struct AnalyzeImplicitConversionsWorkItem {
11836   Expr *E;
11837   SourceLocation CC;
11838   bool IsListInit;
11839 };
11840 }
11841 
11842 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
11843 /// that should be visited are added to WorkList.
11844 static void AnalyzeImplicitConversions(
11845     Sema &S, AnalyzeImplicitConversionsWorkItem Item,
11846     llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
11847   Expr *OrigE = Item.E;
11848   SourceLocation CC = Item.CC;
11849 
11850   QualType T = OrigE->getType();
11851   Expr *E = OrigE->IgnoreParenImpCasts();
11852 
11853   // Propagate whether we are in a C++ list initialization expression.
11854   // If so, we do not issue warnings for implicit int-float conversion
11855   // precision loss, because C++11 narrowing already handles it.
11856   bool IsListInit = Item.IsListInit ||
11857                     (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
11858 
11859   if (E->isTypeDependent() || E->isValueDependent())
11860     return;
11861 
11862   Expr *SourceExpr = E;
11863   // Examine, but don't traverse into the source expression of an
11864   // OpaqueValueExpr, since it may have multiple parents and we don't want to
11865   // emit duplicate diagnostics. Its fine to examine the form or attempt to
11866   // evaluate it in the context of checking the specific conversion to T though.
11867   if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
11868     if (auto *Src = OVE->getSourceExpr())
11869       SourceExpr = Src;
11870 
11871   if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
11872     if (UO->getOpcode() == UO_Not &&
11873         UO->getSubExpr()->isKnownToHaveBooleanValue())
11874       S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
11875           << OrigE->getSourceRange() << T->isBooleanType()
11876           << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
11877 
11878   // For conditional operators, we analyze the arguments as if they
11879   // were being fed directly into the output.
11880   if (auto *CO = dyn_cast<ConditionalOperator>(SourceExpr)) {
11881     CheckConditionalOperator(S, CO, CC, T);
11882     return;
11883   }
11884 
11885   // Check implicit argument conversions for function calls.
11886   if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
11887     CheckImplicitArgumentConversions(S, Call, CC);
11888 
11889   // Go ahead and check any implicit conversions we might have skipped.
11890   // The non-canonical typecheck is just an optimization;
11891   // CheckImplicitConversion will filter out dead implicit conversions.
11892   if (SourceExpr->getType() != T)
11893     CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit);
11894 
11895   // Now continue drilling into this expression.
11896 
11897   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
11898     // The bound subexpressions in a PseudoObjectExpr are not reachable
11899     // as transitive children.
11900     // FIXME: Use a more uniform representation for this.
11901     for (auto *SE : POE->semantics())
11902       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
11903         WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
11904   }
11905 
11906   // Skip past explicit casts.
11907   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
11908     E = CE->getSubExpr()->IgnoreParenImpCasts();
11909     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
11910       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
11911     WorkList.push_back({E, CC, IsListInit});
11912     return;
11913   }
11914 
11915   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11916     // Do a somewhat different check with comparison operators.
11917     if (BO->isComparisonOp())
11918       return AnalyzeComparison(S, BO);
11919 
11920     // And with simple assignments.
11921     if (BO->getOpcode() == BO_Assign)
11922       return AnalyzeAssignment(S, BO);
11923     // And with compound assignments.
11924     if (BO->isAssignmentOp())
11925       return AnalyzeCompoundAssignment(S, BO);
11926   }
11927 
11928   // These break the otherwise-useful invariant below.  Fortunately,
11929   // we don't really need to recurse into them, because any internal
11930   // expressions should have been analyzed already when they were
11931   // built into statements.
11932   if (isa<StmtExpr>(E)) return;
11933 
11934   // Don't descend into unevaluated contexts.
11935   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
11936 
11937   // Now just recurse over the expression's children.
11938   CC = E->getExprLoc();
11939   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
11940   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
11941   for (Stmt *SubStmt : E->children()) {
11942     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
11943     if (!ChildExpr)
11944       continue;
11945 
11946     if (IsLogicalAndOperator &&
11947         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
11948       // Ignore checking string literals that are in logical and operators.
11949       // This is a common pattern for asserts.
11950       continue;
11951     WorkList.push_back({ChildExpr, CC, IsListInit});
11952   }
11953 
11954   if (BO && BO->isLogicalOp()) {
11955     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
11956     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
11957       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
11958 
11959     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
11960     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
11961       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
11962   }
11963 
11964   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
11965     if (U->getOpcode() == UO_LNot) {
11966       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
11967     } else if (U->getOpcode() != UO_AddrOf) {
11968       if (U->getSubExpr()->getType()->isAtomicType())
11969         S.Diag(U->getSubExpr()->getBeginLoc(),
11970                diag::warn_atomic_implicit_seq_cst);
11971     }
11972   }
11973 }
11974 
11975 /// AnalyzeImplicitConversions - Find and report any interesting
11976 /// implicit conversions in the given expression.  There are a couple
11977 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
11978 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
11979                                        bool IsListInit/*= false*/) {
11980   llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
11981   WorkList.push_back({OrigE, CC, IsListInit});
11982   while (!WorkList.empty())
11983     AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
11984 }
11985 
11986 /// Diagnose integer type and any valid implicit conversion to it.
11987 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
11988   // Taking into account implicit conversions,
11989   // allow any integer.
11990   if (!E->getType()->isIntegerType()) {
11991     S.Diag(E->getBeginLoc(),
11992            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
11993     return true;
11994   }
11995   // Potentially emit standard warnings for implicit conversions if enabled
11996   // using -Wconversion.
11997   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
11998   return false;
11999 }
12000 
12001 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
12002 // Returns true when emitting a warning about taking the address of a reference.
12003 static bool CheckForReference(Sema &SemaRef, const Expr *E,
12004                               const PartialDiagnostic &PD) {
12005   E = E->IgnoreParenImpCasts();
12006 
12007   const FunctionDecl *FD = nullptr;
12008 
12009   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12010     if (!DRE->getDecl()->getType()->isReferenceType())
12011       return false;
12012   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
12013     if (!M->getMemberDecl()->getType()->isReferenceType())
12014       return false;
12015   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
12016     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
12017       return false;
12018     FD = Call->getDirectCallee();
12019   } else {
12020     return false;
12021   }
12022 
12023   SemaRef.Diag(E->getExprLoc(), PD);
12024 
12025   // If possible, point to location of function.
12026   if (FD) {
12027     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
12028   }
12029 
12030   return true;
12031 }
12032 
12033 // Returns true if the SourceLocation is expanded from any macro body.
12034 // Returns false if the SourceLocation is invalid, is from not in a macro
12035 // expansion, or is from expanded from a top-level macro argument.
12036 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
12037   if (Loc.isInvalid())
12038     return false;
12039 
12040   while (Loc.isMacroID()) {
12041     if (SM.isMacroBodyExpansion(Loc))
12042       return true;
12043     Loc = SM.getImmediateMacroCallerLoc(Loc);
12044   }
12045 
12046   return false;
12047 }
12048 
12049 /// Diagnose pointers that are always non-null.
12050 /// \param E the expression containing the pointer
12051 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
12052 /// compared to a null pointer
12053 /// \param IsEqual True when the comparison is equal to a null pointer
12054 /// \param Range Extra SourceRange to highlight in the diagnostic
12055 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
12056                                         Expr::NullPointerConstantKind NullKind,
12057                                         bool IsEqual, SourceRange Range) {
12058   if (!E)
12059     return;
12060 
12061   // Don't warn inside macros.
12062   if (E->getExprLoc().isMacroID()) {
12063     const SourceManager &SM = getSourceManager();
12064     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
12065         IsInAnyMacroBody(SM, Range.getBegin()))
12066       return;
12067   }
12068   E = E->IgnoreImpCasts();
12069 
12070   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
12071 
12072   if (isa<CXXThisExpr>(E)) {
12073     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
12074                                 : diag::warn_this_bool_conversion;
12075     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
12076     return;
12077   }
12078 
12079   bool IsAddressOf = false;
12080 
12081   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
12082     if (UO->getOpcode() != UO_AddrOf)
12083       return;
12084     IsAddressOf = true;
12085     E = UO->getSubExpr();
12086   }
12087 
12088   if (IsAddressOf) {
12089     unsigned DiagID = IsCompare
12090                           ? diag::warn_address_of_reference_null_compare
12091                           : diag::warn_address_of_reference_bool_conversion;
12092     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
12093                                          << IsEqual;
12094     if (CheckForReference(*this, E, PD)) {
12095       return;
12096     }
12097   }
12098 
12099   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
12100     bool IsParam = isa<NonNullAttr>(NonnullAttr);
12101     std::string Str;
12102     llvm::raw_string_ostream S(Str);
12103     E->printPretty(S, nullptr, getPrintingPolicy());
12104     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
12105                                 : diag::warn_cast_nonnull_to_bool;
12106     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
12107       << E->getSourceRange() << Range << IsEqual;
12108     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
12109   };
12110 
12111   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
12112   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
12113     if (auto *Callee = Call->getDirectCallee()) {
12114       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
12115         ComplainAboutNonnullParamOrCall(A);
12116         return;
12117       }
12118     }
12119   }
12120 
12121   // Expect to find a single Decl.  Skip anything more complicated.
12122   ValueDecl *D = nullptr;
12123   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
12124     D = R->getDecl();
12125   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
12126     D = M->getMemberDecl();
12127   }
12128 
12129   // Weak Decls can be null.
12130   if (!D || D->isWeak())
12131     return;
12132 
12133   // Check for parameter decl with nonnull attribute
12134   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
12135     if (getCurFunction() &&
12136         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
12137       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
12138         ComplainAboutNonnullParamOrCall(A);
12139         return;
12140       }
12141 
12142       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
12143         // Skip function template not specialized yet.
12144         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
12145           return;
12146         auto ParamIter = llvm::find(FD->parameters(), PV);
12147         assert(ParamIter != FD->param_end());
12148         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
12149 
12150         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
12151           if (!NonNull->args_size()) {
12152               ComplainAboutNonnullParamOrCall(NonNull);
12153               return;
12154           }
12155 
12156           for (const ParamIdx &ArgNo : NonNull->args()) {
12157             if (ArgNo.getASTIndex() == ParamNo) {
12158               ComplainAboutNonnullParamOrCall(NonNull);
12159               return;
12160             }
12161           }
12162         }
12163       }
12164     }
12165   }
12166 
12167   QualType T = D->getType();
12168   const bool IsArray = T->isArrayType();
12169   const bool IsFunction = T->isFunctionType();
12170 
12171   // Address of function is used to silence the function warning.
12172   if (IsAddressOf && IsFunction) {
12173     return;
12174   }
12175 
12176   // Found nothing.
12177   if (!IsAddressOf && !IsFunction && !IsArray)
12178     return;
12179 
12180   // Pretty print the expression for the diagnostic.
12181   std::string Str;
12182   llvm::raw_string_ostream S(Str);
12183   E->printPretty(S, nullptr, getPrintingPolicy());
12184 
12185   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
12186                               : diag::warn_impcast_pointer_to_bool;
12187   enum {
12188     AddressOf,
12189     FunctionPointer,
12190     ArrayPointer
12191   } DiagType;
12192   if (IsAddressOf)
12193     DiagType = AddressOf;
12194   else if (IsFunction)
12195     DiagType = FunctionPointer;
12196   else if (IsArray)
12197     DiagType = ArrayPointer;
12198   else
12199     llvm_unreachable("Could not determine diagnostic.");
12200   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
12201                                 << Range << IsEqual;
12202 
12203   if (!IsFunction)
12204     return;
12205 
12206   // Suggest '&' to silence the function warning.
12207   Diag(E->getExprLoc(), diag::note_function_warning_silence)
12208       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
12209 
12210   // Check to see if '()' fixit should be emitted.
12211   QualType ReturnType;
12212   UnresolvedSet<4> NonTemplateOverloads;
12213   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
12214   if (ReturnType.isNull())
12215     return;
12216 
12217   if (IsCompare) {
12218     // There are two cases here.  If there is null constant, the only suggest
12219     // for a pointer return type.  If the null is 0, then suggest if the return
12220     // type is a pointer or an integer type.
12221     if (!ReturnType->isPointerType()) {
12222       if (NullKind == Expr::NPCK_ZeroExpression ||
12223           NullKind == Expr::NPCK_ZeroLiteral) {
12224         if (!ReturnType->isIntegerType())
12225           return;
12226       } else {
12227         return;
12228       }
12229     }
12230   } else { // !IsCompare
12231     // For function to bool, only suggest if the function pointer has bool
12232     // return type.
12233     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
12234       return;
12235   }
12236   Diag(E->getExprLoc(), diag::note_function_to_function_call)
12237       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
12238 }
12239 
12240 /// Diagnoses "dangerous" implicit conversions within the given
12241 /// expression (which is a full expression).  Implements -Wconversion
12242 /// and -Wsign-compare.
12243 ///
12244 /// \param CC the "context" location of the implicit conversion, i.e.
12245 ///   the most location of the syntactic entity requiring the implicit
12246 ///   conversion
12247 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
12248   // Don't diagnose in unevaluated contexts.
12249   if (isUnevaluatedContext())
12250     return;
12251 
12252   // Don't diagnose for value- or type-dependent expressions.
12253   if (E->isTypeDependent() || E->isValueDependent())
12254     return;
12255 
12256   // Check for array bounds violations in cases where the check isn't triggered
12257   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
12258   // ArraySubscriptExpr is on the RHS of a variable initialization.
12259   CheckArrayAccess(E);
12260 
12261   // This is not the right CC for (e.g.) a variable initialization.
12262   AnalyzeImplicitConversions(*this, E, CC);
12263 }
12264 
12265 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
12266 /// Input argument E is a logical expression.
12267 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
12268   ::CheckBoolLikeConversion(*this, E, CC);
12269 }
12270 
12271 /// Diagnose when expression is an integer constant expression and its evaluation
12272 /// results in integer overflow
12273 void Sema::CheckForIntOverflow (Expr *E) {
12274   // Use a work list to deal with nested struct initializers.
12275   SmallVector<Expr *, 2> Exprs(1, E);
12276 
12277   do {
12278     Expr *OriginalE = Exprs.pop_back_val();
12279     Expr *E = OriginalE->IgnoreParenCasts();
12280 
12281     if (isa<BinaryOperator>(E)) {
12282       E->EvaluateForOverflow(Context);
12283       continue;
12284     }
12285 
12286     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
12287       Exprs.append(InitList->inits().begin(), InitList->inits().end());
12288     else if (isa<ObjCBoxedExpr>(OriginalE))
12289       E->EvaluateForOverflow(Context);
12290     else if (auto Call = dyn_cast<CallExpr>(E))
12291       Exprs.append(Call->arg_begin(), Call->arg_end());
12292     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
12293       Exprs.append(Message->arg_begin(), Message->arg_end());
12294   } while (!Exprs.empty());
12295 }
12296 
12297 namespace {
12298 
12299 /// Visitor for expressions which looks for unsequenced operations on the
12300 /// same object.
12301 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
12302   using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
12303 
12304   /// A tree of sequenced regions within an expression. Two regions are
12305   /// unsequenced if one is an ancestor or a descendent of the other. When we
12306   /// finish processing an expression with sequencing, such as a comma
12307   /// expression, we fold its tree nodes into its parent, since they are
12308   /// unsequenced with respect to nodes we will visit later.
12309   class SequenceTree {
12310     struct Value {
12311       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
12312       unsigned Parent : 31;
12313       unsigned Merged : 1;
12314     };
12315     SmallVector<Value, 8> Values;
12316 
12317   public:
12318     /// A region within an expression which may be sequenced with respect
12319     /// to some other region.
12320     class Seq {
12321       friend class SequenceTree;
12322 
12323       unsigned Index;
12324 
12325       explicit Seq(unsigned N) : Index(N) {}
12326 
12327     public:
12328       Seq() : Index(0) {}
12329     };
12330 
12331     SequenceTree() { Values.push_back(Value(0)); }
12332     Seq root() const { return Seq(0); }
12333 
12334     /// Create a new sequence of operations, which is an unsequenced
12335     /// subset of \p Parent. This sequence of operations is sequenced with
12336     /// respect to other children of \p Parent.
12337     Seq allocate(Seq Parent) {
12338       Values.push_back(Value(Parent.Index));
12339       return Seq(Values.size() - 1);
12340     }
12341 
12342     /// Merge a sequence of operations into its parent.
12343     void merge(Seq S) {
12344       Values[S.Index].Merged = true;
12345     }
12346 
12347     /// Determine whether two operations are unsequenced. This operation
12348     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
12349     /// should have been merged into its parent as appropriate.
12350     bool isUnsequenced(Seq Cur, Seq Old) {
12351       unsigned C = representative(Cur.Index);
12352       unsigned Target = representative(Old.Index);
12353       while (C >= Target) {
12354         if (C == Target)
12355           return true;
12356         C = Values[C].Parent;
12357       }
12358       return false;
12359     }
12360 
12361   private:
12362     /// Pick a representative for a sequence.
12363     unsigned representative(unsigned K) {
12364       if (Values[K].Merged)
12365         // Perform path compression as we go.
12366         return Values[K].Parent = representative(Values[K].Parent);
12367       return K;
12368     }
12369   };
12370 
12371   /// An object for which we can track unsequenced uses.
12372   using Object = const NamedDecl *;
12373 
12374   /// Different flavors of object usage which we track. We only track the
12375   /// least-sequenced usage of each kind.
12376   enum UsageKind {
12377     /// A read of an object. Multiple unsequenced reads are OK.
12378     UK_Use,
12379 
12380     /// A modification of an object which is sequenced before the value
12381     /// computation of the expression, such as ++n in C++.
12382     UK_ModAsValue,
12383 
12384     /// A modification of an object which is not sequenced before the value
12385     /// computation of the expression, such as n++.
12386     UK_ModAsSideEffect,
12387 
12388     UK_Count = UK_ModAsSideEffect + 1
12389   };
12390 
12391   /// Bundle together a sequencing region and the expression corresponding
12392   /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
12393   struct Usage {
12394     const Expr *UsageExpr;
12395     SequenceTree::Seq Seq;
12396 
12397     Usage() : UsageExpr(nullptr), Seq() {}
12398   };
12399 
12400   struct UsageInfo {
12401     Usage Uses[UK_Count];
12402 
12403     /// Have we issued a diagnostic for this object already?
12404     bool Diagnosed;
12405 
12406     UsageInfo() : Uses(), Diagnosed(false) {}
12407   };
12408   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
12409 
12410   Sema &SemaRef;
12411 
12412   /// Sequenced regions within the expression.
12413   SequenceTree Tree;
12414 
12415   /// Declaration modifications and references which we have seen.
12416   UsageInfoMap UsageMap;
12417 
12418   /// The region we are currently within.
12419   SequenceTree::Seq Region;
12420 
12421   /// Filled in with declarations which were modified as a side-effect
12422   /// (that is, post-increment operations).
12423   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
12424 
12425   /// Expressions to check later. We defer checking these to reduce
12426   /// stack usage.
12427   SmallVectorImpl<const Expr *> &WorkList;
12428 
12429   /// RAII object wrapping the visitation of a sequenced subexpression of an
12430   /// expression. At the end of this process, the side-effects of the evaluation
12431   /// become sequenced with respect to the value computation of the result, so
12432   /// we downgrade any UK_ModAsSideEffect within the evaluation to
12433   /// UK_ModAsValue.
12434   struct SequencedSubexpression {
12435     SequencedSubexpression(SequenceChecker &Self)
12436       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
12437       Self.ModAsSideEffect = &ModAsSideEffect;
12438     }
12439 
12440     ~SequencedSubexpression() {
12441       for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
12442         // Add a new usage with usage kind UK_ModAsValue, and then restore
12443         // the previous usage with UK_ModAsSideEffect (thus clearing it if
12444         // the previous one was empty).
12445         UsageInfo &UI = Self.UsageMap[M.first];
12446         auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
12447         Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
12448         SideEffectUsage = M.second;
12449       }
12450       Self.ModAsSideEffect = OldModAsSideEffect;
12451     }
12452 
12453     SequenceChecker &Self;
12454     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
12455     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
12456   };
12457 
12458   /// RAII object wrapping the visitation of a subexpression which we might
12459   /// choose to evaluate as a constant. If any subexpression is evaluated and
12460   /// found to be non-constant, this allows us to suppress the evaluation of
12461   /// the outer expression.
12462   class EvaluationTracker {
12463   public:
12464     EvaluationTracker(SequenceChecker &Self)
12465         : Self(Self), Prev(Self.EvalTracker) {
12466       Self.EvalTracker = this;
12467     }
12468 
12469     ~EvaluationTracker() {
12470       Self.EvalTracker = Prev;
12471       if (Prev)
12472         Prev->EvalOK &= EvalOK;
12473     }
12474 
12475     bool evaluate(const Expr *E, bool &Result) {
12476       if (!EvalOK || E->isValueDependent())
12477         return false;
12478       EvalOK = E->EvaluateAsBooleanCondition(
12479           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
12480       return EvalOK;
12481     }
12482 
12483   private:
12484     SequenceChecker &Self;
12485     EvaluationTracker *Prev;
12486     bool EvalOK = true;
12487   } *EvalTracker = nullptr;
12488 
12489   /// Find the object which is produced by the specified expression,
12490   /// if any.
12491   Object getObject(const Expr *E, bool Mod) const {
12492     E = E->IgnoreParenCasts();
12493     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
12494       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
12495         return getObject(UO->getSubExpr(), Mod);
12496     } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12497       if (BO->getOpcode() == BO_Comma)
12498         return getObject(BO->getRHS(), Mod);
12499       if (Mod && BO->isAssignmentOp())
12500         return getObject(BO->getLHS(), Mod);
12501     } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
12502       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
12503       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
12504         return ME->getMemberDecl();
12505     } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12506       // FIXME: If this is a reference, map through to its value.
12507       return DRE->getDecl();
12508     return nullptr;
12509   }
12510 
12511   /// Note that an object \p O was modified or used by an expression
12512   /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
12513   /// the object \p O as obtained via the \p UsageMap.
12514   void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
12515     // Get the old usage for the given object and usage kind.
12516     Usage &U = UI.Uses[UK];
12517     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
12518       // If we have a modification as side effect and are in a sequenced
12519       // subexpression, save the old Usage so that we can restore it later
12520       // in SequencedSubexpression::~SequencedSubexpression.
12521       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
12522         ModAsSideEffect->push_back(std::make_pair(O, U));
12523       // Then record the new usage with the current sequencing region.
12524       U.UsageExpr = UsageExpr;
12525       U.Seq = Region;
12526     }
12527   }
12528 
12529   /// Check whether a modification or use of an object \p O in an expression
12530   /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
12531   /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
12532   /// \p IsModMod is true when we are checking for a mod-mod unsequenced
12533   /// usage and false we are checking for a mod-use unsequenced usage.
12534   void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
12535                   UsageKind OtherKind, bool IsModMod) {
12536     if (UI.Diagnosed)
12537       return;
12538 
12539     const Usage &U = UI.Uses[OtherKind];
12540     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
12541       return;
12542 
12543     const Expr *Mod = U.UsageExpr;
12544     const Expr *ModOrUse = UsageExpr;
12545     if (OtherKind == UK_Use)
12546       std::swap(Mod, ModOrUse);
12547 
12548     SemaRef.DiagRuntimeBehavior(
12549         Mod->getExprLoc(), {Mod, ModOrUse},
12550         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
12551                                : diag::warn_unsequenced_mod_use)
12552             << O << SourceRange(ModOrUse->getExprLoc()));
12553     UI.Diagnosed = true;
12554   }
12555 
12556   // A note on note{Pre, Post}{Use, Mod}:
12557   //
12558   // (It helps to follow the algorithm with an expression such as
12559   //  "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
12560   //  operations before C++17 and both are well-defined in C++17).
12561   //
12562   // When visiting a node which uses/modify an object we first call notePreUse
12563   // or notePreMod before visiting its sub-expression(s). At this point the
12564   // children of the current node have not yet been visited and so the eventual
12565   // uses/modifications resulting from the children of the current node have not
12566   // been recorded yet.
12567   //
12568   // We then visit the children of the current node. After that notePostUse or
12569   // notePostMod is called. These will 1) detect an unsequenced modification
12570   // as side effect (as in "k++ + k") and 2) add a new usage with the
12571   // appropriate usage kind.
12572   //
12573   // We also have to be careful that some operation sequences modification as
12574   // side effect as well (for example: || or ,). To account for this we wrap
12575   // the visitation of such a sub-expression (for example: the LHS of || or ,)
12576   // with SequencedSubexpression. SequencedSubexpression is an RAII object
12577   // which record usages which are modifications as side effect, and then
12578   // downgrade them (or more accurately restore the previous usage which was a
12579   // modification as side effect) when exiting the scope of the sequenced
12580   // subexpression.
12581 
12582   void notePreUse(Object O, const Expr *UseExpr) {
12583     UsageInfo &UI = UsageMap[O];
12584     // Uses conflict with other modifications.
12585     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
12586   }
12587 
12588   void notePostUse(Object O, const Expr *UseExpr) {
12589     UsageInfo &UI = UsageMap[O];
12590     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
12591                /*IsModMod=*/false);
12592     addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
12593   }
12594 
12595   void notePreMod(Object O, const Expr *ModExpr) {
12596     UsageInfo &UI = UsageMap[O];
12597     // Modifications conflict with other modifications and with uses.
12598     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
12599     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
12600   }
12601 
12602   void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
12603     UsageInfo &UI = UsageMap[O];
12604     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
12605                /*IsModMod=*/true);
12606     addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
12607   }
12608 
12609 public:
12610   SequenceChecker(Sema &S, const Expr *E,
12611                   SmallVectorImpl<const Expr *> &WorkList)
12612       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
12613     Visit(E);
12614     // Silence a -Wunused-private-field since WorkList is now unused.
12615     // TODO: Evaluate if it can be used, and if not remove it.
12616     (void)this->WorkList;
12617   }
12618 
12619   void VisitStmt(const Stmt *S) {
12620     // Skip all statements which aren't expressions for now.
12621   }
12622 
12623   void VisitExpr(const Expr *E) {
12624     // By default, just recurse to evaluated subexpressions.
12625     Base::VisitStmt(E);
12626   }
12627 
12628   void VisitCastExpr(const CastExpr *E) {
12629     Object O = Object();
12630     if (E->getCastKind() == CK_LValueToRValue)
12631       O = getObject(E->getSubExpr(), false);
12632 
12633     if (O)
12634       notePreUse(O, E);
12635     VisitExpr(E);
12636     if (O)
12637       notePostUse(O, E);
12638   }
12639 
12640   void VisitSequencedExpressions(const Expr *SequencedBefore,
12641                                  const Expr *SequencedAfter) {
12642     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
12643     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
12644     SequenceTree::Seq OldRegion = Region;
12645 
12646     {
12647       SequencedSubexpression SeqBefore(*this);
12648       Region = BeforeRegion;
12649       Visit(SequencedBefore);
12650     }
12651 
12652     Region = AfterRegion;
12653     Visit(SequencedAfter);
12654 
12655     Region = OldRegion;
12656 
12657     Tree.merge(BeforeRegion);
12658     Tree.merge(AfterRegion);
12659   }
12660 
12661   void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
12662     // C++17 [expr.sub]p1:
12663     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
12664     //   expression E1 is sequenced before the expression E2.
12665     if (SemaRef.getLangOpts().CPlusPlus17)
12666       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
12667     else {
12668       Visit(ASE->getLHS());
12669       Visit(ASE->getRHS());
12670     }
12671   }
12672 
12673   void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
12674   void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
12675   void VisitBinPtrMem(const BinaryOperator *BO) {
12676     // C++17 [expr.mptr.oper]p4:
12677     //  Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
12678     //  the expression E1 is sequenced before the expression E2.
12679     if (SemaRef.getLangOpts().CPlusPlus17)
12680       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12681     else {
12682       Visit(BO->getLHS());
12683       Visit(BO->getRHS());
12684     }
12685   }
12686 
12687   void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
12688   void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
12689   void VisitBinShlShr(const BinaryOperator *BO) {
12690     // C++17 [expr.shift]p4:
12691     //  The expression E1 is sequenced before the expression E2.
12692     if (SemaRef.getLangOpts().CPlusPlus17)
12693       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12694     else {
12695       Visit(BO->getLHS());
12696       Visit(BO->getRHS());
12697     }
12698   }
12699 
12700   void VisitBinComma(const BinaryOperator *BO) {
12701     // C++11 [expr.comma]p1:
12702     //   Every value computation and side effect associated with the left
12703     //   expression is sequenced before every value computation and side
12704     //   effect associated with the right expression.
12705     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12706   }
12707 
12708   void VisitBinAssign(const BinaryOperator *BO) {
12709     SequenceTree::Seq RHSRegion;
12710     SequenceTree::Seq LHSRegion;
12711     if (SemaRef.getLangOpts().CPlusPlus17) {
12712       RHSRegion = Tree.allocate(Region);
12713       LHSRegion = Tree.allocate(Region);
12714     } else {
12715       RHSRegion = Region;
12716       LHSRegion = Region;
12717     }
12718     SequenceTree::Seq OldRegion = Region;
12719 
12720     // C++11 [expr.ass]p1:
12721     //  [...] the assignment is sequenced after the value computation
12722     //  of the right and left operands, [...]
12723     //
12724     // so check it before inspecting the operands and update the
12725     // map afterwards.
12726     Object O = getObject(BO->getLHS(), /*Mod=*/true);
12727     if (O)
12728       notePreMod(O, BO);
12729 
12730     if (SemaRef.getLangOpts().CPlusPlus17) {
12731       // C++17 [expr.ass]p1:
12732       //  [...] The right operand is sequenced before the left operand. [...]
12733       {
12734         SequencedSubexpression SeqBefore(*this);
12735         Region = RHSRegion;
12736         Visit(BO->getRHS());
12737       }
12738 
12739       Region = LHSRegion;
12740       Visit(BO->getLHS());
12741 
12742       if (O && isa<CompoundAssignOperator>(BO))
12743         notePostUse(O, BO);
12744 
12745     } else {
12746       // C++11 does not specify any sequencing between the LHS and RHS.
12747       Region = LHSRegion;
12748       Visit(BO->getLHS());
12749 
12750       if (O && isa<CompoundAssignOperator>(BO))
12751         notePostUse(O, BO);
12752 
12753       Region = RHSRegion;
12754       Visit(BO->getRHS());
12755     }
12756 
12757     // C++11 [expr.ass]p1:
12758     //  the assignment is sequenced [...] before the value computation of the
12759     //  assignment expression.
12760     // C11 6.5.16/3 has no such rule.
12761     Region = OldRegion;
12762     if (O)
12763       notePostMod(O, BO,
12764                   SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12765                                                   : UK_ModAsSideEffect);
12766     if (SemaRef.getLangOpts().CPlusPlus17) {
12767       Tree.merge(RHSRegion);
12768       Tree.merge(LHSRegion);
12769     }
12770   }
12771 
12772   void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
12773     VisitBinAssign(CAO);
12774   }
12775 
12776   void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12777   void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12778   void VisitUnaryPreIncDec(const UnaryOperator *UO) {
12779     Object O = getObject(UO->getSubExpr(), true);
12780     if (!O)
12781       return VisitExpr(UO);
12782 
12783     notePreMod(O, UO);
12784     Visit(UO->getSubExpr());
12785     // C++11 [expr.pre.incr]p1:
12786     //   the expression ++x is equivalent to x+=1
12787     notePostMod(O, UO,
12788                 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12789                                                 : UK_ModAsSideEffect);
12790   }
12791 
12792   void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12793   void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12794   void VisitUnaryPostIncDec(const UnaryOperator *UO) {
12795     Object O = getObject(UO->getSubExpr(), true);
12796     if (!O)
12797       return VisitExpr(UO);
12798 
12799     notePreMod(O, UO);
12800     Visit(UO->getSubExpr());
12801     notePostMod(O, UO, UK_ModAsSideEffect);
12802   }
12803 
12804   void VisitBinLOr(const BinaryOperator *BO) {
12805     // C++11 [expr.log.or]p2:
12806     //  If the second expression is evaluated, every value computation and
12807     //  side effect associated with the first expression is sequenced before
12808     //  every value computation and side effect associated with the
12809     //  second expression.
12810     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
12811     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
12812     SequenceTree::Seq OldRegion = Region;
12813 
12814     EvaluationTracker Eval(*this);
12815     {
12816       SequencedSubexpression Sequenced(*this);
12817       Region = LHSRegion;
12818       Visit(BO->getLHS());
12819     }
12820 
12821     // C++11 [expr.log.or]p1:
12822     //  [...] the second operand is not evaluated if the first operand
12823     //  evaluates to true.
12824     bool EvalResult = false;
12825     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
12826     bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
12827     if (ShouldVisitRHS) {
12828       Region = RHSRegion;
12829       Visit(BO->getRHS());
12830     }
12831 
12832     Region = OldRegion;
12833     Tree.merge(LHSRegion);
12834     Tree.merge(RHSRegion);
12835   }
12836 
12837   void VisitBinLAnd(const BinaryOperator *BO) {
12838     // C++11 [expr.log.and]p2:
12839     //  If the second expression is evaluated, every value computation and
12840     //  side effect associated with the first expression is sequenced before
12841     //  every value computation and side effect associated with the
12842     //  second expression.
12843     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
12844     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
12845     SequenceTree::Seq OldRegion = Region;
12846 
12847     EvaluationTracker Eval(*this);
12848     {
12849       SequencedSubexpression Sequenced(*this);
12850       Region = LHSRegion;
12851       Visit(BO->getLHS());
12852     }
12853 
12854     // C++11 [expr.log.and]p1:
12855     //  [...] the second operand is not evaluated if the first operand is false.
12856     bool EvalResult = false;
12857     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
12858     bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
12859     if (ShouldVisitRHS) {
12860       Region = RHSRegion;
12861       Visit(BO->getRHS());
12862     }
12863 
12864     Region = OldRegion;
12865     Tree.merge(LHSRegion);
12866     Tree.merge(RHSRegion);
12867   }
12868 
12869   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
12870     // C++11 [expr.cond]p1:
12871     //  [...] Every value computation and side effect associated with the first
12872     //  expression is sequenced before every value computation and side effect
12873     //  associated with the second or third expression.
12874     SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
12875 
12876     // No sequencing is specified between the true and false expression.
12877     // However since exactly one of both is going to be evaluated we can
12878     // consider them to be sequenced. This is needed to avoid warning on
12879     // something like "x ? y+= 1 : y += 2;" in the case where we will visit
12880     // both the true and false expressions because we can't evaluate x.
12881     // This will still allow us to detect an expression like (pre C++17)
12882     // "(x ? y += 1 : y += 2) = y".
12883     //
12884     // We don't wrap the visitation of the true and false expression with
12885     // SequencedSubexpression because we don't want to downgrade modifications
12886     // as side effect in the true and false expressions after the visition
12887     // is done. (for example in the expression "(x ? y++ : y++) + y" we should
12888     // not warn between the two "y++", but we should warn between the "y++"
12889     // and the "y".
12890     SequenceTree::Seq TrueRegion = Tree.allocate(Region);
12891     SequenceTree::Seq FalseRegion = Tree.allocate(Region);
12892     SequenceTree::Seq OldRegion = Region;
12893 
12894     EvaluationTracker Eval(*this);
12895     {
12896       SequencedSubexpression Sequenced(*this);
12897       Region = ConditionRegion;
12898       Visit(CO->getCond());
12899     }
12900 
12901     // C++11 [expr.cond]p1:
12902     // [...] The first expression is contextually converted to bool (Clause 4).
12903     // It is evaluated and if it is true, the result of the conditional
12904     // expression is the value of the second expression, otherwise that of the
12905     // third expression. Only one of the second and third expressions is
12906     // evaluated. [...]
12907     bool EvalResult = false;
12908     bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
12909     bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
12910     bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
12911     if (ShouldVisitTrueExpr) {
12912       Region = TrueRegion;
12913       Visit(CO->getTrueExpr());
12914     }
12915     if (ShouldVisitFalseExpr) {
12916       Region = FalseRegion;
12917       Visit(CO->getFalseExpr());
12918     }
12919 
12920     Region = OldRegion;
12921     Tree.merge(ConditionRegion);
12922     Tree.merge(TrueRegion);
12923     Tree.merge(FalseRegion);
12924   }
12925 
12926   void VisitCallExpr(const CallExpr *CE) {
12927     // C++11 [intro.execution]p15:
12928     //   When calling a function [...], every value computation and side effect
12929     //   associated with any argument expression, or with the postfix expression
12930     //   designating the called function, is sequenced before execution of every
12931     //   expression or statement in the body of the function [and thus before
12932     //   the value computation of its result].
12933     SequencedSubexpression Sequenced(*this);
12934     SemaRef.runWithSufficientStackSpace(CE->getExprLoc(),
12935                                         [&] { Base::VisitCallExpr(CE); });
12936 
12937     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
12938   }
12939 
12940   void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
12941     // This is a call, so all subexpressions are sequenced before the result.
12942     SequencedSubexpression Sequenced(*this);
12943 
12944     if (!CCE->isListInitialization())
12945       return VisitExpr(CCE);
12946 
12947     // In C++11, list initializations are sequenced.
12948     SmallVector<SequenceTree::Seq, 32> Elts;
12949     SequenceTree::Seq Parent = Region;
12950     for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
12951                                               E = CCE->arg_end();
12952          I != E; ++I) {
12953       Region = Tree.allocate(Parent);
12954       Elts.push_back(Region);
12955       Visit(*I);
12956     }
12957 
12958     // Forget that the initializers are sequenced.
12959     Region = Parent;
12960     for (unsigned I = 0; I < Elts.size(); ++I)
12961       Tree.merge(Elts[I]);
12962   }
12963 
12964   void VisitInitListExpr(const InitListExpr *ILE) {
12965     if (!SemaRef.getLangOpts().CPlusPlus11)
12966       return VisitExpr(ILE);
12967 
12968     // In C++11, list initializations are sequenced.
12969     SmallVector<SequenceTree::Seq, 32> Elts;
12970     SequenceTree::Seq Parent = Region;
12971     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
12972       const Expr *E = ILE->getInit(I);
12973       if (!E)
12974         continue;
12975       Region = Tree.allocate(Parent);
12976       Elts.push_back(Region);
12977       Visit(E);
12978     }
12979 
12980     // Forget that the initializers are sequenced.
12981     Region = Parent;
12982     for (unsigned I = 0; I < Elts.size(); ++I)
12983       Tree.merge(Elts[I]);
12984   }
12985 };
12986 
12987 } // namespace
12988 
12989 void Sema::CheckUnsequencedOperations(const Expr *E) {
12990   SmallVector<const Expr *, 8> WorkList;
12991   WorkList.push_back(E);
12992   while (!WorkList.empty()) {
12993     const Expr *Item = WorkList.pop_back_val();
12994     SequenceChecker(*this, Item, WorkList);
12995   }
12996 }
12997 
12998 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
12999                               bool IsConstexpr) {
13000   llvm::SaveAndRestore<bool> ConstantContext(
13001       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
13002   CheckImplicitConversions(E, CheckLoc);
13003   if (!E->isInstantiationDependent())
13004     CheckUnsequencedOperations(E);
13005   if (!IsConstexpr && !E->isValueDependent())
13006     CheckForIntOverflow(E);
13007   DiagnoseMisalignedMembers();
13008 }
13009 
13010 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
13011                                        FieldDecl *BitField,
13012                                        Expr *Init) {
13013   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
13014 }
13015 
13016 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
13017                                          SourceLocation Loc) {
13018   if (!PType->isVariablyModifiedType())
13019     return;
13020   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
13021     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
13022     return;
13023   }
13024   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
13025     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
13026     return;
13027   }
13028   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
13029     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
13030     return;
13031   }
13032 
13033   const ArrayType *AT = S.Context.getAsArrayType(PType);
13034   if (!AT)
13035     return;
13036 
13037   if (AT->getSizeModifier() != ArrayType::Star) {
13038     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
13039     return;
13040   }
13041 
13042   S.Diag(Loc, diag::err_array_star_in_function_definition);
13043 }
13044 
13045 /// CheckParmsForFunctionDef - Check that the parameters of the given
13046 /// function are appropriate for the definition of a function. This
13047 /// takes care of any checks that cannot be performed on the
13048 /// declaration itself, e.g., that the types of each of the function
13049 /// parameters are complete.
13050 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
13051                                     bool CheckParameterNames) {
13052   bool HasInvalidParm = false;
13053   for (ParmVarDecl *Param : Parameters) {
13054     // C99 6.7.5.3p4: the parameters in a parameter type list in a
13055     // function declarator that is part of a function definition of
13056     // that function shall not have incomplete type.
13057     //
13058     // This is also C++ [dcl.fct]p6.
13059     if (!Param->isInvalidDecl() &&
13060         RequireCompleteType(Param->getLocation(), Param->getType(),
13061                             diag::err_typecheck_decl_incomplete_type)) {
13062       Param->setInvalidDecl();
13063       HasInvalidParm = true;
13064     }
13065 
13066     // C99 6.9.1p5: If the declarator includes a parameter type list, the
13067     // declaration of each parameter shall include an identifier.
13068     if (CheckParameterNames && Param->getIdentifier() == nullptr &&
13069         !Param->isImplicit() && !getLangOpts().CPlusPlus) {
13070       // Diagnose this as an extension in C17 and earlier.
13071       if (!getLangOpts().C2x)
13072         Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
13073     }
13074 
13075     // C99 6.7.5.3p12:
13076     //   If the function declarator is not part of a definition of that
13077     //   function, parameters may have incomplete type and may use the [*]
13078     //   notation in their sequences of declarator specifiers to specify
13079     //   variable length array types.
13080     QualType PType = Param->getOriginalType();
13081     // FIXME: This diagnostic should point the '[*]' if source-location
13082     // information is added for it.
13083     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
13084 
13085     // If the parameter is a c++ class type and it has to be destructed in the
13086     // callee function, declare the destructor so that it can be called by the
13087     // callee function. Do not perform any direct access check on the dtor here.
13088     if (!Param->isInvalidDecl()) {
13089       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
13090         if (!ClassDecl->isInvalidDecl() &&
13091             !ClassDecl->hasIrrelevantDestructor() &&
13092             !ClassDecl->isDependentContext() &&
13093             ClassDecl->isParamDestroyedInCallee()) {
13094           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
13095           MarkFunctionReferenced(Param->getLocation(), Destructor);
13096           DiagnoseUseOfDecl(Destructor, Param->getLocation());
13097         }
13098       }
13099     }
13100 
13101     // Parameters with the pass_object_size attribute only need to be marked
13102     // constant at function definitions. Because we lack information about
13103     // whether we're on a declaration or definition when we're instantiating the
13104     // attribute, we need to check for constness here.
13105     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
13106       if (!Param->getType().isConstQualified())
13107         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
13108             << Attr->getSpelling() << 1;
13109 
13110     // Check for parameter names shadowing fields from the class.
13111     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
13112       // The owning context for the parameter should be the function, but we
13113       // want to see if this function's declaration context is a record.
13114       DeclContext *DC = Param->getDeclContext();
13115       if (DC && DC->isFunctionOrMethod()) {
13116         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
13117           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
13118                                      RD, /*DeclIsField*/ false);
13119       }
13120     }
13121   }
13122 
13123   return HasInvalidParm;
13124 }
13125 
13126 Optional<std::pair<CharUnits, CharUnits>>
13127 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx);
13128 
13129 /// Compute the alignment and offset of the base class object given the
13130 /// derived-to-base cast expression and the alignment and offset of the derived
13131 /// class object.
13132 static std::pair<CharUnits, CharUnits>
13133 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
13134                                    CharUnits BaseAlignment, CharUnits Offset,
13135                                    ASTContext &Ctx) {
13136   for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
13137        ++PathI) {
13138     const CXXBaseSpecifier *Base = *PathI;
13139     const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
13140     if (Base->isVirtual()) {
13141       // The complete object may have a lower alignment than the non-virtual
13142       // alignment of the base, in which case the base may be misaligned. Choose
13143       // the smaller of the non-virtual alignment and BaseAlignment, which is a
13144       // conservative lower bound of the complete object alignment.
13145       CharUnits NonVirtualAlignment =
13146           Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment();
13147       BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
13148       Offset = CharUnits::Zero();
13149     } else {
13150       const ASTRecordLayout &RL =
13151           Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
13152       Offset += RL.getBaseClassOffset(BaseDecl);
13153     }
13154     DerivedType = Base->getType();
13155   }
13156 
13157   return std::make_pair(BaseAlignment, Offset);
13158 }
13159 
13160 /// Compute the alignment and offset of a binary additive operator.
13161 static Optional<std::pair<CharUnits, CharUnits>>
13162 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
13163                                      bool IsSub, ASTContext &Ctx) {
13164   QualType PointeeType = PtrE->getType()->getPointeeType();
13165 
13166   if (!PointeeType->isConstantSizeType())
13167     return llvm::None;
13168 
13169   auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
13170 
13171   if (!P)
13172     return llvm::None;
13173 
13174   llvm::APSInt IdxRes;
13175   CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
13176   if (IntE->isIntegerConstantExpr(IdxRes, Ctx)) {
13177     CharUnits Offset = EltSize * IdxRes.getExtValue();
13178     if (IsSub)
13179       Offset = -Offset;
13180     return std::make_pair(P->first, P->second + Offset);
13181   }
13182 
13183   // If the integer expression isn't a constant expression, compute the lower
13184   // bound of the alignment using the alignment and offset of the pointer
13185   // expression and the element size.
13186   return std::make_pair(
13187       P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
13188       CharUnits::Zero());
13189 }
13190 
13191 /// This helper function takes an lvalue expression and returns the alignment of
13192 /// a VarDecl and a constant offset from the VarDecl.
13193 Optional<std::pair<CharUnits, CharUnits>>
13194 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) {
13195   E = E->IgnoreParens();
13196   switch (E->getStmtClass()) {
13197   default:
13198     break;
13199   case Stmt::CStyleCastExprClass:
13200   case Stmt::CXXStaticCastExprClass:
13201   case Stmt::ImplicitCastExprClass: {
13202     auto *CE = cast<CastExpr>(E);
13203     const Expr *From = CE->getSubExpr();
13204     switch (CE->getCastKind()) {
13205     default:
13206       break;
13207     case CK_NoOp:
13208       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
13209     case CK_UncheckedDerivedToBase:
13210     case CK_DerivedToBase: {
13211       auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
13212       if (!P)
13213         break;
13214       return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
13215                                                 P->second, Ctx);
13216     }
13217     }
13218     break;
13219   }
13220   case Stmt::ArraySubscriptExprClass: {
13221     auto *ASE = cast<ArraySubscriptExpr>(E);
13222     return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(),
13223                                                 false, Ctx);
13224   }
13225   case Stmt::DeclRefExprClass: {
13226     if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
13227       // FIXME: If VD is captured by copy or is an escaping __block variable,
13228       // use the alignment of VD's type.
13229       if (!VD->getType()->isReferenceType())
13230         return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
13231       if (VD->hasInit())
13232         return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
13233     }
13234     break;
13235   }
13236   case Stmt::MemberExprClass: {
13237     auto *ME = cast<MemberExpr>(E);
13238     if (ME->isArrow())
13239       break;
13240     auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
13241     if (!FD || FD->getType()->isReferenceType())
13242       break;
13243     auto P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
13244     if (!P)
13245       break;
13246     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
13247     uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
13248     return std::make_pair(P->first,
13249                           P->second + CharUnits::fromQuantity(Offset));
13250   }
13251   case Stmt::UnaryOperatorClass: {
13252     auto *UO = cast<UnaryOperator>(E);
13253     switch (UO->getOpcode()) {
13254     default:
13255       break;
13256     case UO_Deref:
13257       return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx);
13258     }
13259     break;
13260   }
13261   case Stmt::BinaryOperatorClass: {
13262     auto *BO = cast<BinaryOperator>(E);
13263     auto Opcode = BO->getOpcode();
13264     switch (Opcode) {
13265     default:
13266       break;
13267     case BO_Comma:
13268       return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx);
13269     }
13270     break;
13271   }
13272   }
13273   return llvm::None;
13274 }
13275 
13276 /// This helper function takes a pointer expression and returns the alignment of
13277 /// a VarDecl and a constant offset from the VarDecl.
13278 Optional<std::pair<CharUnits, CharUnits>>
13279 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) {
13280   E = E->IgnoreParens();
13281   switch (E->getStmtClass()) {
13282   default:
13283     break;
13284   case Stmt::CStyleCastExprClass:
13285   case Stmt::CXXStaticCastExprClass:
13286   case Stmt::ImplicitCastExprClass: {
13287     auto *CE = cast<CastExpr>(E);
13288     const Expr *From = CE->getSubExpr();
13289     switch (CE->getCastKind()) {
13290     default:
13291       break;
13292     case CK_NoOp:
13293       return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
13294     case CK_ArrayToPointerDecay:
13295       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
13296     case CK_UncheckedDerivedToBase:
13297     case CK_DerivedToBase: {
13298       auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
13299       if (!P)
13300         break;
13301       return getDerivedToBaseAlignmentAndOffset(
13302           CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
13303     }
13304     }
13305     break;
13306   }
13307   case Stmt::UnaryOperatorClass: {
13308     auto *UO = cast<UnaryOperator>(E);
13309     if (UO->getOpcode() == UO_AddrOf)
13310       return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx);
13311     break;
13312   }
13313   case Stmt::BinaryOperatorClass: {
13314     auto *BO = cast<BinaryOperator>(E);
13315     auto Opcode = BO->getOpcode();
13316     switch (Opcode) {
13317     default:
13318       break;
13319     case BO_Add:
13320     case BO_Sub: {
13321       const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
13322       if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
13323         std::swap(LHS, RHS);
13324       return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
13325                                                   Ctx);
13326     }
13327     case BO_Comma:
13328       return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
13329     }
13330     break;
13331   }
13332   }
13333   return llvm::None;
13334 }
13335 
13336 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
13337   // See if we can compute the alignment of a VarDecl and an offset from it.
13338   Optional<std::pair<CharUnits, CharUnits>> P =
13339       getBaseAlignmentAndOffsetFromPtr(E, S.Context);
13340 
13341   if (P)
13342     return P->first.alignmentAtOffset(P->second);
13343 
13344   // If that failed, return the type's alignment.
13345   return S.Context.getTypeAlignInChars(E->getType()->getPointeeType());
13346 }
13347 
13348 /// CheckCastAlign - Implements -Wcast-align, which warns when a
13349 /// pointer cast increases the alignment requirements.
13350 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
13351   // This is actually a lot of work to potentially be doing on every
13352   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
13353   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
13354     return;
13355 
13356   // Ignore dependent types.
13357   if (T->isDependentType() || Op->getType()->isDependentType())
13358     return;
13359 
13360   // Require that the destination be a pointer type.
13361   const PointerType *DestPtr = T->getAs<PointerType>();
13362   if (!DestPtr) return;
13363 
13364   // If the destination has alignment 1, we're done.
13365   QualType DestPointee = DestPtr->getPointeeType();
13366   if (DestPointee->isIncompleteType()) return;
13367   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
13368   if (DestAlign.isOne()) return;
13369 
13370   // Require that the source be a pointer type.
13371   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
13372   if (!SrcPtr) return;
13373   QualType SrcPointee = SrcPtr->getPointeeType();
13374 
13375   // Whitelist casts from cv void*.  We already implicitly
13376   // whitelisted casts to cv void*, since they have alignment 1.
13377   // Also whitelist casts involving incomplete types, which implicitly
13378   // includes 'void'.
13379   if (SrcPointee->isIncompleteType()) return;
13380 
13381   CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
13382 
13383   if (SrcAlign >= DestAlign) return;
13384 
13385   Diag(TRange.getBegin(), diag::warn_cast_align)
13386     << Op->getType() << T
13387     << static_cast<unsigned>(SrcAlign.getQuantity())
13388     << static_cast<unsigned>(DestAlign.getQuantity())
13389     << TRange << Op->getSourceRange();
13390 }
13391 
13392 /// Check whether this array fits the idiom of a size-one tail padded
13393 /// array member of a struct.
13394 ///
13395 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
13396 /// commonly used to emulate flexible arrays in C89 code.
13397 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
13398                                     const NamedDecl *ND) {
13399   if (Size != 1 || !ND) return false;
13400 
13401   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
13402   if (!FD) return false;
13403 
13404   // Don't consider sizes resulting from macro expansions or template argument
13405   // substitution to form C89 tail-padded arrays.
13406 
13407   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
13408   while (TInfo) {
13409     TypeLoc TL = TInfo->getTypeLoc();
13410     // Look through typedefs.
13411     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
13412       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
13413       TInfo = TDL->getTypeSourceInfo();
13414       continue;
13415     }
13416     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
13417       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
13418       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
13419         return false;
13420     }
13421     break;
13422   }
13423 
13424   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
13425   if (!RD) return false;
13426   if (RD->isUnion()) return false;
13427   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
13428     if (!CRD->isStandardLayout()) return false;
13429   }
13430 
13431   // See if this is the last field decl in the record.
13432   const Decl *D = FD;
13433   while ((D = D->getNextDeclInContext()))
13434     if (isa<FieldDecl>(D))
13435       return false;
13436   return true;
13437 }
13438 
13439 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
13440                             const ArraySubscriptExpr *ASE,
13441                             bool AllowOnePastEnd, bool IndexNegated) {
13442   // Already diagnosed by the constant evaluator.
13443   if (isConstantEvaluated())
13444     return;
13445 
13446   IndexExpr = IndexExpr->IgnoreParenImpCasts();
13447   if (IndexExpr->isValueDependent())
13448     return;
13449 
13450   const Type *EffectiveType =
13451       BaseExpr->getType()->getPointeeOrArrayElementType();
13452   BaseExpr = BaseExpr->IgnoreParenCasts();
13453   const ConstantArrayType *ArrayTy =
13454       Context.getAsConstantArrayType(BaseExpr->getType());
13455 
13456   if (!ArrayTy)
13457     return;
13458 
13459   const Type *BaseType = ArrayTy->getElementType().getTypePtr();
13460   if (EffectiveType->isDependentType() || BaseType->isDependentType())
13461     return;
13462 
13463   Expr::EvalResult Result;
13464   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
13465     return;
13466 
13467   llvm::APSInt index = Result.Val.getInt();
13468   if (IndexNegated)
13469     index = -index;
13470 
13471   const NamedDecl *ND = nullptr;
13472   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
13473     ND = DRE->getDecl();
13474   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
13475     ND = ME->getMemberDecl();
13476 
13477   if (index.isUnsigned() || !index.isNegative()) {
13478     // It is possible that the type of the base expression after
13479     // IgnoreParenCasts is incomplete, even though the type of the base
13480     // expression before IgnoreParenCasts is complete (see PR39746 for an
13481     // example). In this case we have no information about whether the array
13482     // access exceeds the array bounds. However we can still diagnose an array
13483     // access which precedes the array bounds.
13484     if (BaseType->isIncompleteType())
13485       return;
13486 
13487     llvm::APInt size = ArrayTy->getSize();
13488     if (!size.isStrictlyPositive())
13489       return;
13490 
13491     if (BaseType != EffectiveType) {
13492       // Make sure we're comparing apples to apples when comparing index to size
13493       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
13494       uint64_t array_typesize = Context.getTypeSize(BaseType);
13495       // Handle ptrarith_typesize being zero, such as when casting to void*
13496       if (!ptrarith_typesize) ptrarith_typesize = 1;
13497       if (ptrarith_typesize != array_typesize) {
13498         // There's a cast to a different size type involved
13499         uint64_t ratio = array_typesize / ptrarith_typesize;
13500         // TODO: Be smarter about handling cases where array_typesize is not a
13501         // multiple of ptrarith_typesize
13502         if (ptrarith_typesize * ratio == array_typesize)
13503           size *= llvm::APInt(size.getBitWidth(), ratio);
13504       }
13505     }
13506 
13507     if (size.getBitWidth() > index.getBitWidth())
13508       index = index.zext(size.getBitWidth());
13509     else if (size.getBitWidth() < index.getBitWidth())
13510       size = size.zext(index.getBitWidth());
13511 
13512     // For array subscripting the index must be less than size, but for pointer
13513     // arithmetic also allow the index (offset) to be equal to size since
13514     // computing the next address after the end of the array is legal and
13515     // commonly done e.g. in C++ iterators and range-based for loops.
13516     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
13517       return;
13518 
13519     // Also don't warn for arrays of size 1 which are members of some
13520     // structure. These are often used to approximate flexible arrays in C89
13521     // code.
13522     if (IsTailPaddedMemberArray(*this, size, ND))
13523       return;
13524 
13525     // Suppress the warning if the subscript expression (as identified by the
13526     // ']' location) and the index expression are both from macro expansions
13527     // within a system header.
13528     if (ASE) {
13529       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
13530           ASE->getRBracketLoc());
13531       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
13532         SourceLocation IndexLoc =
13533             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
13534         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
13535           return;
13536       }
13537     }
13538 
13539     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
13540     if (ASE)
13541       DiagID = diag::warn_array_index_exceeds_bounds;
13542 
13543     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
13544                         PDiag(DiagID) << index.toString(10, true)
13545                                       << size.toString(10, true)
13546                                       << (unsigned)size.getLimitedValue(~0U)
13547                                       << IndexExpr->getSourceRange());
13548   } else {
13549     unsigned DiagID = diag::warn_array_index_precedes_bounds;
13550     if (!ASE) {
13551       DiagID = diag::warn_ptr_arith_precedes_bounds;
13552       if (index.isNegative()) index = -index;
13553     }
13554 
13555     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
13556                         PDiag(DiagID) << index.toString(10, true)
13557                                       << IndexExpr->getSourceRange());
13558   }
13559 
13560   if (!ND) {
13561     // Try harder to find a NamedDecl to point at in the note.
13562     while (const ArraySubscriptExpr *ASE =
13563            dyn_cast<ArraySubscriptExpr>(BaseExpr))
13564       BaseExpr = ASE->getBase()->IgnoreParenCasts();
13565     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
13566       ND = DRE->getDecl();
13567     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
13568       ND = ME->getMemberDecl();
13569   }
13570 
13571   if (ND)
13572     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
13573                         PDiag(diag::note_array_declared_here)
13574                             << ND->getDeclName());
13575 }
13576 
13577 void Sema::CheckArrayAccess(const Expr *expr) {
13578   int AllowOnePastEnd = 0;
13579   while (expr) {
13580     expr = expr->IgnoreParenImpCasts();
13581     switch (expr->getStmtClass()) {
13582       case Stmt::ArraySubscriptExprClass: {
13583         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
13584         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
13585                          AllowOnePastEnd > 0);
13586         expr = ASE->getBase();
13587         break;
13588       }
13589       case Stmt::MemberExprClass: {
13590         expr = cast<MemberExpr>(expr)->getBase();
13591         break;
13592       }
13593       case Stmt::OMPArraySectionExprClass: {
13594         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
13595         if (ASE->getLowerBound())
13596           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
13597                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
13598         return;
13599       }
13600       case Stmt::UnaryOperatorClass: {
13601         // Only unwrap the * and & unary operators
13602         const UnaryOperator *UO = cast<UnaryOperator>(expr);
13603         expr = UO->getSubExpr();
13604         switch (UO->getOpcode()) {
13605           case UO_AddrOf:
13606             AllowOnePastEnd++;
13607             break;
13608           case UO_Deref:
13609             AllowOnePastEnd--;
13610             break;
13611           default:
13612             return;
13613         }
13614         break;
13615       }
13616       case Stmt::ConditionalOperatorClass: {
13617         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
13618         if (const Expr *lhs = cond->getLHS())
13619           CheckArrayAccess(lhs);
13620         if (const Expr *rhs = cond->getRHS())
13621           CheckArrayAccess(rhs);
13622         return;
13623       }
13624       case Stmt::CXXOperatorCallExprClass: {
13625         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
13626         for (const auto *Arg : OCE->arguments())
13627           CheckArrayAccess(Arg);
13628         return;
13629       }
13630       default:
13631         return;
13632     }
13633   }
13634 }
13635 
13636 //===--- CHECK: Objective-C retain cycles ----------------------------------//
13637 
13638 namespace {
13639 
13640 struct RetainCycleOwner {
13641   VarDecl *Variable = nullptr;
13642   SourceRange Range;
13643   SourceLocation Loc;
13644   bool Indirect = false;
13645 
13646   RetainCycleOwner() = default;
13647 
13648   void setLocsFrom(Expr *e) {
13649     Loc = e->getExprLoc();
13650     Range = e->getSourceRange();
13651   }
13652 };
13653 
13654 } // namespace
13655 
13656 /// Consider whether capturing the given variable can possibly lead to
13657 /// a retain cycle.
13658 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
13659   // In ARC, it's captured strongly iff the variable has __strong
13660   // lifetime.  In MRR, it's captured strongly if the variable is
13661   // __block and has an appropriate type.
13662   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
13663     return false;
13664 
13665   owner.Variable = var;
13666   if (ref)
13667     owner.setLocsFrom(ref);
13668   return true;
13669 }
13670 
13671 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
13672   while (true) {
13673     e = e->IgnoreParens();
13674     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
13675       switch (cast->getCastKind()) {
13676       case CK_BitCast:
13677       case CK_LValueBitCast:
13678       case CK_LValueToRValue:
13679       case CK_ARCReclaimReturnedObject:
13680         e = cast->getSubExpr();
13681         continue;
13682 
13683       default:
13684         return false;
13685       }
13686     }
13687 
13688     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
13689       ObjCIvarDecl *ivar = ref->getDecl();
13690       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
13691         return false;
13692 
13693       // Try to find a retain cycle in the base.
13694       if (!findRetainCycleOwner(S, ref->getBase(), owner))
13695         return false;
13696 
13697       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
13698       owner.Indirect = true;
13699       return true;
13700     }
13701 
13702     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
13703       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
13704       if (!var) return false;
13705       return considerVariable(var, ref, owner);
13706     }
13707 
13708     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
13709       if (member->isArrow()) return false;
13710 
13711       // Don't count this as an indirect ownership.
13712       e = member->getBase();
13713       continue;
13714     }
13715 
13716     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
13717       // Only pay attention to pseudo-objects on property references.
13718       ObjCPropertyRefExpr *pre
13719         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
13720                                               ->IgnoreParens());
13721       if (!pre) return false;
13722       if (pre->isImplicitProperty()) return false;
13723       ObjCPropertyDecl *property = pre->getExplicitProperty();
13724       if (!property->isRetaining() &&
13725           !(property->getPropertyIvarDecl() &&
13726             property->getPropertyIvarDecl()->getType()
13727               .getObjCLifetime() == Qualifiers::OCL_Strong))
13728           return false;
13729 
13730       owner.Indirect = true;
13731       if (pre->isSuperReceiver()) {
13732         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
13733         if (!owner.Variable)
13734           return false;
13735         owner.Loc = pre->getLocation();
13736         owner.Range = pre->getSourceRange();
13737         return true;
13738       }
13739       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
13740                               ->getSourceExpr());
13741       continue;
13742     }
13743 
13744     // Array ivars?
13745 
13746     return false;
13747   }
13748 }
13749 
13750 namespace {
13751 
13752   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
13753     ASTContext &Context;
13754     VarDecl *Variable;
13755     Expr *Capturer = nullptr;
13756     bool VarWillBeReased = false;
13757 
13758     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
13759         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
13760           Context(Context), Variable(variable) {}
13761 
13762     void VisitDeclRefExpr(DeclRefExpr *ref) {
13763       if (ref->getDecl() == Variable && !Capturer)
13764         Capturer = ref;
13765     }
13766 
13767     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
13768       if (Capturer) return;
13769       Visit(ref->getBase());
13770       if (Capturer && ref->isFreeIvar())
13771         Capturer = ref;
13772     }
13773 
13774     void VisitBlockExpr(BlockExpr *block) {
13775       // Look inside nested blocks
13776       if (block->getBlockDecl()->capturesVariable(Variable))
13777         Visit(block->getBlockDecl()->getBody());
13778     }
13779 
13780     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
13781       if (Capturer) return;
13782       if (OVE->getSourceExpr())
13783         Visit(OVE->getSourceExpr());
13784     }
13785 
13786     void VisitBinaryOperator(BinaryOperator *BinOp) {
13787       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
13788         return;
13789       Expr *LHS = BinOp->getLHS();
13790       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
13791         if (DRE->getDecl() != Variable)
13792           return;
13793         if (Expr *RHS = BinOp->getRHS()) {
13794           RHS = RHS->IgnoreParenCasts();
13795           llvm::APSInt Value;
13796           VarWillBeReased =
13797             (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
13798         }
13799       }
13800     }
13801   };
13802 
13803 } // namespace
13804 
13805 /// Check whether the given argument is a block which captures a
13806 /// variable.
13807 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
13808   assert(owner.Variable && owner.Loc.isValid());
13809 
13810   e = e->IgnoreParenCasts();
13811 
13812   // Look through [^{...} copy] and Block_copy(^{...}).
13813   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
13814     Selector Cmd = ME->getSelector();
13815     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
13816       e = ME->getInstanceReceiver();
13817       if (!e)
13818         return nullptr;
13819       e = e->IgnoreParenCasts();
13820     }
13821   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
13822     if (CE->getNumArgs() == 1) {
13823       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
13824       if (Fn) {
13825         const IdentifierInfo *FnI = Fn->getIdentifier();
13826         if (FnI && FnI->isStr("_Block_copy")) {
13827           e = CE->getArg(0)->IgnoreParenCasts();
13828         }
13829       }
13830     }
13831   }
13832 
13833   BlockExpr *block = dyn_cast<BlockExpr>(e);
13834   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
13835     return nullptr;
13836 
13837   FindCaptureVisitor visitor(S.Context, owner.Variable);
13838   visitor.Visit(block->getBlockDecl()->getBody());
13839   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
13840 }
13841 
13842 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
13843                                 RetainCycleOwner &owner) {
13844   assert(capturer);
13845   assert(owner.Variable && owner.Loc.isValid());
13846 
13847   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
13848     << owner.Variable << capturer->getSourceRange();
13849   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
13850     << owner.Indirect << owner.Range;
13851 }
13852 
13853 /// Check for a keyword selector that starts with the word 'add' or
13854 /// 'set'.
13855 static bool isSetterLikeSelector(Selector sel) {
13856   if (sel.isUnarySelector()) return false;
13857 
13858   StringRef str = sel.getNameForSlot(0);
13859   while (!str.empty() && str.front() == '_') str = str.substr(1);
13860   if (str.startswith("set"))
13861     str = str.substr(3);
13862   else if (str.startswith("add")) {
13863     // Specially whitelist 'addOperationWithBlock:'.
13864     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
13865       return false;
13866     str = str.substr(3);
13867   }
13868   else
13869     return false;
13870 
13871   if (str.empty()) return true;
13872   return !isLowercase(str.front());
13873 }
13874 
13875 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
13876                                                     ObjCMessageExpr *Message) {
13877   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
13878                                                 Message->getReceiverInterface(),
13879                                                 NSAPI::ClassId_NSMutableArray);
13880   if (!IsMutableArray) {
13881     return None;
13882   }
13883 
13884   Selector Sel = Message->getSelector();
13885 
13886   Optional<NSAPI::NSArrayMethodKind> MKOpt =
13887     S.NSAPIObj->getNSArrayMethodKind(Sel);
13888   if (!MKOpt) {
13889     return None;
13890   }
13891 
13892   NSAPI::NSArrayMethodKind MK = *MKOpt;
13893 
13894   switch (MK) {
13895     case NSAPI::NSMutableArr_addObject:
13896     case NSAPI::NSMutableArr_insertObjectAtIndex:
13897     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
13898       return 0;
13899     case NSAPI::NSMutableArr_replaceObjectAtIndex:
13900       return 1;
13901 
13902     default:
13903       return None;
13904   }
13905 
13906   return None;
13907 }
13908 
13909 static
13910 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
13911                                                   ObjCMessageExpr *Message) {
13912   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
13913                                             Message->getReceiverInterface(),
13914                                             NSAPI::ClassId_NSMutableDictionary);
13915   if (!IsMutableDictionary) {
13916     return None;
13917   }
13918 
13919   Selector Sel = Message->getSelector();
13920 
13921   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
13922     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
13923   if (!MKOpt) {
13924     return None;
13925   }
13926 
13927   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
13928 
13929   switch (MK) {
13930     case NSAPI::NSMutableDict_setObjectForKey:
13931     case NSAPI::NSMutableDict_setValueForKey:
13932     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
13933       return 0;
13934 
13935     default:
13936       return None;
13937   }
13938 
13939   return None;
13940 }
13941 
13942 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
13943   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
13944                                                 Message->getReceiverInterface(),
13945                                                 NSAPI::ClassId_NSMutableSet);
13946 
13947   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
13948                                             Message->getReceiverInterface(),
13949                                             NSAPI::ClassId_NSMutableOrderedSet);
13950   if (!IsMutableSet && !IsMutableOrderedSet) {
13951     return None;
13952   }
13953 
13954   Selector Sel = Message->getSelector();
13955 
13956   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
13957   if (!MKOpt) {
13958     return None;
13959   }
13960 
13961   NSAPI::NSSetMethodKind MK = *MKOpt;
13962 
13963   switch (MK) {
13964     case NSAPI::NSMutableSet_addObject:
13965     case NSAPI::NSOrderedSet_setObjectAtIndex:
13966     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
13967     case NSAPI::NSOrderedSet_insertObjectAtIndex:
13968       return 0;
13969     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
13970       return 1;
13971   }
13972 
13973   return None;
13974 }
13975 
13976 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
13977   if (!Message->isInstanceMessage()) {
13978     return;
13979   }
13980 
13981   Optional<int> ArgOpt;
13982 
13983   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
13984       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
13985       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
13986     return;
13987   }
13988 
13989   int ArgIndex = *ArgOpt;
13990 
13991   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
13992   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
13993     Arg = OE->getSourceExpr()->IgnoreImpCasts();
13994   }
13995 
13996   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
13997     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
13998       if (ArgRE->isObjCSelfExpr()) {
13999         Diag(Message->getSourceRange().getBegin(),
14000              diag::warn_objc_circular_container)
14001           << ArgRE->getDecl() << StringRef("'super'");
14002       }
14003     }
14004   } else {
14005     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
14006 
14007     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
14008       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
14009     }
14010 
14011     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
14012       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
14013         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
14014           ValueDecl *Decl = ReceiverRE->getDecl();
14015           Diag(Message->getSourceRange().getBegin(),
14016                diag::warn_objc_circular_container)
14017             << Decl << Decl;
14018           if (!ArgRE->isObjCSelfExpr()) {
14019             Diag(Decl->getLocation(),
14020                  diag::note_objc_circular_container_declared_here)
14021               << Decl;
14022           }
14023         }
14024       }
14025     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
14026       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
14027         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
14028           ObjCIvarDecl *Decl = IvarRE->getDecl();
14029           Diag(Message->getSourceRange().getBegin(),
14030                diag::warn_objc_circular_container)
14031             << Decl << Decl;
14032           Diag(Decl->getLocation(),
14033                diag::note_objc_circular_container_declared_here)
14034             << Decl;
14035         }
14036       }
14037     }
14038   }
14039 }
14040 
14041 /// Check a message send to see if it's likely to cause a retain cycle.
14042 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
14043   // Only check instance methods whose selector looks like a setter.
14044   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
14045     return;
14046 
14047   // Try to find a variable that the receiver is strongly owned by.
14048   RetainCycleOwner owner;
14049   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
14050     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
14051       return;
14052   } else {
14053     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
14054     owner.Variable = getCurMethodDecl()->getSelfDecl();
14055     owner.Loc = msg->getSuperLoc();
14056     owner.Range = msg->getSuperLoc();
14057   }
14058 
14059   // Check whether the receiver is captured by any of the arguments.
14060   const ObjCMethodDecl *MD = msg->getMethodDecl();
14061   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
14062     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
14063       // noescape blocks should not be retained by the method.
14064       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
14065         continue;
14066       return diagnoseRetainCycle(*this, capturer, owner);
14067     }
14068   }
14069 }
14070 
14071 /// Check a property assign to see if it's likely to cause a retain cycle.
14072 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
14073   RetainCycleOwner owner;
14074   if (!findRetainCycleOwner(*this, receiver, owner))
14075     return;
14076 
14077   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
14078     diagnoseRetainCycle(*this, capturer, owner);
14079 }
14080 
14081 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
14082   RetainCycleOwner Owner;
14083   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
14084     return;
14085 
14086   // Because we don't have an expression for the variable, we have to set the
14087   // location explicitly here.
14088   Owner.Loc = Var->getLocation();
14089   Owner.Range = Var->getSourceRange();
14090 
14091   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
14092     diagnoseRetainCycle(*this, Capturer, Owner);
14093 }
14094 
14095 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
14096                                      Expr *RHS, bool isProperty) {
14097   // Check if RHS is an Objective-C object literal, which also can get
14098   // immediately zapped in a weak reference.  Note that we explicitly
14099   // allow ObjCStringLiterals, since those are designed to never really die.
14100   RHS = RHS->IgnoreParenImpCasts();
14101 
14102   // This enum needs to match with the 'select' in
14103   // warn_objc_arc_literal_assign (off-by-1).
14104   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
14105   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
14106     return false;
14107 
14108   S.Diag(Loc, diag::warn_arc_literal_assign)
14109     << (unsigned) Kind
14110     << (isProperty ? 0 : 1)
14111     << RHS->getSourceRange();
14112 
14113   return true;
14114 }
14115 
14116 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
14117                                     Qualifiers::ObjCLifetime LT,
14118                                     Expr *RHS, bool isProperty) {
14119   // Strip off any implicit cast added to get to the one ARC-specific.
14120   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
14121     if (cast->getCastKind() == CK_ARCConsumeObject) {
14122       S.Diag(Loc, diag::warn_arc_retained_assign)
14123         << (LT == Qualifiers::OCL_ExplicitNone)
14124         << (isProperty ? 0 : 1)
14125         << RHS->getSourceRange();
14126       return true;
14127     }
14128     RHS = cast->getSubExpr();
14129   }
14130 
14131   if (LT == Qualifiers::OCL_Weak &&
14132       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
14133     return true;
14134 
14135   return false;
14136 }
14137 
14138 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
14139                               QualType LHS, Expr *RHS) {
14140   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
14141 
14142   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
14143     return false;
14144 
14145   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
14146     return true;
14147 
14148   return false;
14149 }
14150 
14151 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
14152                               Expr *LHS, Expr *RHS) {
14153   QualType LHSType;
14154   // PropertyRef on LHS type need be directly obtained from
14155   // its declaration as it has a PseudoType.
14156   ObjCPropertyRefExpr *PRE
14157     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
14158   if (PRE && !PRE->isImplicitProperty()) {
14159     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
14160     if (PD)
14161       LHSType = PD->getType();
14162   }
14163 
14164   if (LHSType.isNull())
14165     LHSType = LHS->getType();
14166 
14167   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
14168 
14169   if (LT == Qualifiers::OCL_Weak) {
14170     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
14171       getCurFunction()->markSafeWeakUse(LHS);
14172   }
14173 
14174   if (checkUnsafeAssigns(Loc, LHSType, RHS))
14175     return;
14176 
14177   // FIXME. Check for other life times.
14178   if (LT != Qualifiers::OCL_None)
14179     return;
14180 
14181   if (PRE) {
14182     if (PRE->isImplicitProperty())
14183       return;
14184     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
14185     if (!PD)
14186       return;
14187 
14188     unsigned Attributes = PD->getPropertyAttributes();
14189     if (Attributes & ObjCPropertyAttribute::kind_assign) {
14190       // when 'assign' attribute was not explicitly specified
14191       // by user, ignore it and rely on property type itself
14192       // for lifetime info.
14193       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
14194       if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
14195           LHSType->isObjCRetainableType())
14196         return;
14197 
14198       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
14199         if (cast->getCastKind() == CK_ARCConsumeObject) {
14200           Diag(Loc, diag::warn_arc_retained_property_assign)
14201           << RHS->getSourceRange();
14202           return;
14203         }
14204         RHS = cast->getSubExpr();
14205       }
14206     } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
14207       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
14208         return;
14209     }
14210   }
14211 }
14212 
14213 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
14214 
14215 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
14216                                         SourceLocation StmtLoc,
14217                                         const NullStmt *Body) {
14218   // Do not warn if the body is a macro that expands to nothing, e.g:
14219   //
14220   // #define CALL(x)
14221   // if (condition)
14222   //   CALL(0);
14223   if (Body->hasLeadingEmptyMacro())
14224     return false;
14225 
14226   // Get line numbers of statement and body.
14227   bool StmtLineInvalid;
14228   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
14229                                                       &StmtLineInvalid);
14230   if (StmtLineInvalid)
14231     return false;
14232 
14233   bool BodyLineInvalid;
14234   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
14235                                                       &BodyLineInvalid);
14236   if (BodyLineInvalid)
14237     return false;
14238 
14239   // Warn if null statement and body are on the same line.
14240   if (StmtLine != BodyLine)
14241     return false;
14242 
14243   return true;
14244 }
14245 
14246 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
14247                                  const Stmt *Body,
14248                                  unsigned DiagID) {
14249   // Since this is a syntactic check, don't emit diagnostic for template
14250   // instantiations, this just adds noise.
14251   if (CurrentInstantiationScope)
14252     return;
14253 
14254   // The body should be a null statement.
14255   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
14256   if (!NBody)
14257     return;
14258 
14259   // Do the usual checks.
14260   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
14261     return;
14262 
14263   Diag(NBody->getSemiLoc(), DiagID);
14264   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
14265 }
14266 
14267 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
14268                                  const Stmt *PossibleBody) {
14269   assert(!CurrentInstantiationScope); // Ensured by caller
14270 
14271   SourceLocation StmtLoc;
14272   const Stmt *Body;
14273   unsigned DiagID;
14274   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
14275     StmtLoc = FS->getRParenLoc();
14276     Body = FS->getBody();
14277     DiagID = diag::warn_empty_for_body;
14278   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
14279     StmtLoc = WS->getCond()->getSourceRange().getEnd();
14280     Body = WS->getBody();
14281     DiagID = diag::warn_empty_while_body;
14282   } else
14283     return; // Neither `for' nor `while'.
14284 
14285   // The body should be a null statement.
14286   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
14287   if (!NBody)
14288     return;
14289 
14290   // Skip expensive checks if diagnostic is disabled.
14291   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
14292     return;
14293 
14294   // Do the usual checks.
14295   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
14296     return;
14297 
14298   // `for(...);' and `while(...);' are popular idioms, so in order to keep
14299   // noise level low, emit diagnostics only if for/while is followed by a
14300   // CompoundStmt, e.g.:
14301   //    for (int i = 0; i < n; i++);
14302   //    {
14303   //      a(i);
14304   //    }
14305   // or if for/while is followed by a statement with more indentation
14306   // than for/while itself:
14307   //    for (int i = 0; i < n; i++);
14308   //      a(i);
14309   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
14310   if (!ProbableTypo) {
14311     bool BodyColInvalid;
14312     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
14313         PossibleBody->getBeginLoc(), &BodyColInvalid);
14314     if (BodyColInvalid)
14315       return;
14316 
14317     bool StmtColInvalid;
14318     unsigned StmtCol =
14319         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
14320     if (StmtColInvalid)
14321       return;
14322 
14323     if (BodyCol > StmtCol)
14324       ProbableTypo = true;
14325   }
14326 
14327   if (ProbableTypo) {
14328     Diag(NBody->getSemiLoc(), DiagID);
14329     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
14330   }
14331 }
14332 
14333 //===--- CHECK: Warn on self move with std::move. -------------------------===//
14334 
14335 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
14336 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
14337                              SourceLocation OpLoc) {
14338   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
14339     return;
14340 
14341   if (inTemplateInstantiation())
14342     return;
14343 
14344   // Strip parens and casts away.
14345   LHSExpr = LHSExpr->IgnoreParenImpCasts();
14346   RHSExpr = RHSExpr->IgnoreParenImpCasts();
14347 
14348   // Check for a call expression
14349   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
14350   if (!CE || CE->getNumArgs() != 1)
14351     return;
14352 
14353   // Check for a call to std::move
14354   if (!CE->isCallToStdMove())
14355     return;
14356 
14357   // Get argument from std::move
14358   RHSExpr = CE->getArg(0);
14359 
14360   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
14361   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
14362 
14363   // Two DeclRefExpr's, check that the decls are the same.
14364   if (LHSDeclRef && RHSDeclRef) {
14365     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
14366       return;
14367     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
14368         RHSDeclRef->getDecl()->getCanonicalDecl())
14369       return;
14370 
14371     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
14372                                         << LHSExpr->getSourceRange()
14373                                         << RHSExpr->getSourceRange();
14374     return;
14375   }
14376 
14377   // Member variables require a different approach to check for self moves.
14378   // MemberExpr's are the same if every nested MemberExpr refers to the same
14379   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
14380   // the base Expr's are CXXThisExpr's.
14381   const Expr *LHSBase = LHSExpr;
14382   const Expr *RHSBase = RHSExpr;
14383   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
14384   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
14385   if (!LHSME || !RHSME)
14386     return;
14387 
14388   while (LHSME && RHSME) {
14389     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
14390         RHSME->getMemberDecl()->getCanonicalDecl())
14391       return;
14392 
14393     LHSBase = LHSME->getBase();
14394     RHSBase = RHSME->getBase();
14395     LHSME = dyn_cast<MemberExpr>(LHSBase);
14396     RHSME = dyn_cast<MemberExpr>(RHSBase);
14397   }
14398 
14399   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
14400   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
14401   if (LHSDeclRef && RHSDeclRef) {
14402     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
14403       return;
14404     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
14405         RHSDeclRef->getDecl()->getCanonicalDecl())
14406       return;
14407 
14408     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
14409                                         << LHSExpr->getSourceRange()
14410                                         << RHSExpr->getSourceRange();
14411     return;
14412   }
14413 
14414   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
14415     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
14416                                         << LHSExpr->getSourceRange()
14417                                         << RHSExpr->getSourceRange();
14418 }
14419 
14420 //===--- Layout compatibility ----------------------------------------------//
14421 
14422 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
14423 
14424 /// Check if two enumeration types are layout-compatible.
14425 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
14426   // C++11 [dcl.enum] p8:
14427   // Two enumeration types are layout-compatible if they have the same
14428   // underlying type.
14429   return ED1->isComplete() && ED2->isComplete() &&
14430          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
14431 }
14432 
14433 /// Check if two fields are layout-compatible.
14434 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
14435                                FieldDecl *Field2) {
14436   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
14437     return false;
14438 
14439   if (Field1->isBitField() != Field2->isBitField())
14440     return false;
14441 
14442   if (Field1->isBitField()) {
14443     // Make sure that the bit-fields are the same length.
14444     unsigned Bits1 = Field1->getBitWidthValue(C);
14445     unsigned Bits2 = Field2->getBitWidthValue(C);
14446 
14447     if (Bits1 != Bits2)
14448       return false;
14449   }
14450 
14451   return true;
14452 }
14453 
14454 /// Check if two standard-layout structs are layout-compatible.
14455 /// (C++11 [class.mem] p17)
14456 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
14457                                      RecordDecl *RD2) {
14458   // If both records are C++ classes, check that base classes match.
14459   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
14460     // If one of records is a CXXRecordDecl we are in C++ mode,
14461     // thus the other one is a CXXRecordDecl, too.
14462     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
14463     // Check number of base classes.
14464     if (D1CXX->getNumBases() != D2CXX->getNumBases())
14465       return false;
14466 
14467     // Check the base classes.
14468     for (CXXRecordDecl::base_class_const_iterator
14469                Base1 = D1CXX->bases_begin(),
14470            BaseEnd1 = D1CXX->bases_end(),
14471               Base2 = D2CXX->bases_begin();
14472          Base1 != BaseEnd1;
14473          ++Base1, ++Base2) {
14474       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
14475         return false;
14476     }
14477   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
14478     // If only RD2 is a C++ class, it should have zero base classes.
14479     if (D2CXX->getNumBases() > 0)
14480       return false;
14481   }
14482 
14483   // Check the fields.
14484   RecordDecl::field_iterator Field2 = RD2->field_begin(),
14485                              Field2End = RD2->field_end(),
14486                              Field1 = RD1->field_begin(),
14487                              Field1End = RD1->field_end();
14488   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
14489     if (!isLayoutCompatible(C, *Field1, *Field2))
14490       return false;
14491   }
14492   if (Field1 != Field1End || Field2 != Field2End)
14493     return false;
14494 
14495   return true;
14496 }
14497 
14498 /// Check if two standard-layout unions are layout-compatible.
14499 /// (C++11 [class.mem] p18)
14500 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
14501                                     RecordDecl *RD2) {
14502   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
14503   for (auto *Field2 : RD2->fields())
14504     UnmatchedFields.insert(Field2);
14505 
14506   for (auto *Field1 : RD1->fields()) {
14507     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
14508         I = UnmatchedFields.begin(),
14509         E = UnmatchedFields.end();
14510 
14511     for ( ; I != E; ++I) {
14512       if (isLayoutCompatible(C, Field1, *I)) {
14513         bool Result = UnmatchedFields.erase(*I);
14514         (void) Result;
14515         assert(Result);
14516         break;
14517       }
14518     }
14519     if (I == E)
14520       return false;
14521   }
14522 
14523   return UnmatchedFields.empty();
14524 }
14525 
14526 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
14527                                RecordDecl *RD2) {
14528   if (RD1->isUnion() != RD2->isUnion())
14529     return false;
14530 
14531   if (RD1->isUnion())
14532     return isLayoutCompatibleUnion(C, RD1, RD2);
14533   else
14534     return isLayoutCompatibleStruct(C, RD1, RD2);
14535 }
14536 
14537 /// Check if two types are layout-compatible in C++11 sense.
14538 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
14539   if (T1.isNull() || T2.isNull())
14540     return false;
14541 
14542   // C++11 [basic.types] p11:
14543   // If two types T1 and T2 are the same type, then T1 and T2 are
14544   // layout-compatible types.
14545   if (C.hasSameType(T1, T2))
14546     return true;
14547 
14548   T1 = T1.getCanonicalType().getUnqualifiedType();
14549   T2 = T2.getCanonicalType().getUnqualifiedType();
14550 
14551   const Type::TypeClass TC1 = T1->getTypeClass();
14552   const Type::TypeClass TC2 = T2->getTypeClass();
14553 
14554   if (TC1 != TC2)
14555     return false;
14556 
14557   if (TC1 == Type::Enum) {
14558     return isLayoutCompatible(C,
14559                               cast<EnumType>(T1)->getDecl(),
14560                               cast<EnumType>(T2)->getDecl());
14561   } else if (TC1 == Type::Record) {
14562     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
14563       return false;
14564 
14565     return isLayoutCompatible(C,
14566                               cast<RecordType>(T1)->getDecl(),
14567                               cast<RecordType>(T2)->getDecl());
14568   }
14569 
14570   return false;
14571 }
14572 
14573 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
14574 
14575 /// Given a type tag expression find the type tag itself.
14576 ///
14577 /// \param TypeExpr Type tag expression, as it appears in user's code.
14578 ///
14579 /// \param VD Declaration of an identifier that appears in a type tag.
14580 ///
14581 /// \param MagicValue Type tag magic value.
14582 ///
14583 /// \param isConstantEvaluated wether the evalaution should be performed in
14584 
14585 /// constant context.
14586 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
14587                             const ValueDecl **VD, uint64_t *MagicValue,
14588                             bool isConstantEvaluated) {
14589   while(true) {
14590     if (!TypeExpr)
14591       return false;
14592 
14593     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
14594 
14595     switch (TypeExpr->getStmtClass()) {
14596     case Stmt::UnaryOperatorClass: {
14597       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
14598       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
14599         TypeExpr = UO->getSubExpr();
14600         continue;
14601       }
14602       return false;
14603     }
14604 
14605     case Stmt::DeclRefExprClass: {
14606       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
14607       *VD = DRE->getDecl();
14608       return true;
14609     }
14610 
14611     case Stmt::IntegerLiteralClass: {
14612       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
14613       llvm::APInt MagicValueAPInt = IL->getValue();
14614       if (MagicValueAPInt.getActiveBits() <= 64) {
14615         *MagicValue = MagicValueAPInt.getZExtValue();
14616         return true;
14617       } else
14618         return false;
14619     }
14620 
14621     case Stmt::BinaryConditionalOperatorClass:
14622     case Stmt::ConditionalOperatorClass: {
14623       const AbstractConditionalOperator *ACO =
14624           cast<AbstractConditionalOperator>(TypeExpr);
14625       bool Result;
14626       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
14627                                                      isConstantEvaluated)) {
14628         if (Result)
14629           TypeExpr = ACO->getTrueExpr();
14630         else
14631           TypeExpr = ACO->getFalseExpr();
14632         continue;
14633       }
14634       return false;
14635     }
14636 
14637     case Stmt::BinaryOperatorClass: {
14638       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
14639       if (BO->getOpcode() == BO_Comma) {
14640         TypeExpr = BO->getRHS();
14641         continue;
14642       }
14643       return false;
14644     }
14645 
14646     default:
14647       return false;
14648     }
14649   }
14650 }
14651 
14652 /// Retrieve the C type corresponding to type tag TypeExpr.
14653 ///
14654 /// \param TypeExpr Expression that specifies a type tag.
14655 ///
14656 /// \param MagicValues Registered magic values.
14657 ///
14658 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
14659 ///        kind.
14660 ///
14661 /// \param TypeInfo Information about the corresponding C type.
14662 ///
14663 /// \param isConstantEvaluated wether the evalaution should be performed in
14664 /// constant context.
14665 ///
14666 /// \returns true if the corresponding C type was found.
14667 static bool GetMatchingCType(
14668     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
14669     const ASTContext &Ctx,
14670     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
14671         *MagicValues,
14672     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
14673     bool isConstantEvaluated) {
14674   FoundWrongKind = false;
14675 
14676   // Variable declaration that has type_tag_for_datatype attribute.
14677   const ValueDecl *VD = nullptr;
14678 
14679   uint64_t MagicValue;
14680 
14681   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
14682     return false;
14683 
14684   if (VD) {
14685     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
14686       if (I->getArgumentKind() != ArgumentKind) {
14687         FoundWrongKind = true;
14688         return false;
14689       }
14690       TypeInfo.Type = I->getMatchingCType();
14691       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
14692       TypeInfo.MustBeNull = I->getMustBeNull();
14693       return true;
14694     }
14695     return false;
14696   }
14697 
14698   if (!MagicValues)
14699     return false;
14700 
14701   llvm::DenseMap<Sema::TypeTagMagicValue,
14702                  Sema::TypeTagData>::const_iterator I =
14703       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
14704   if (I == MagicValues->end())
14705     return false;
14706 
14707   TypeInfo = I->second;
14708   return true;
14709 }
14710 
14711 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
14712                                       uint64_t MagicValue, QualType Type,
14713                                       bool LayoutCompatible,
14714                                       bool MustBeNull) {
14715   if (!TypeTagForDatatypeMagicValues)
14716     TypeTagForDatatypeMagicValues.reset(
14717         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
14718 
14719   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
14720   (*TypeTagForDatatypeMagicValues)[Magic] =
14721       TypeTagData(Type, LayoutCompatible, MustBeNull);
14722 }
14723 
14724 static bool IsSameCharType(QualType T1, QualType T2) {
14725   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
14726   if (!BT1)
14727     return false;
14728 
14729   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
14730   if (!BT2)
14731     return false;
14732 
14733   BuiltinType::Kind T1Kind = BT1->getKind();
14734   BuiltinType::Kind T2Kind = BT2->getKind();
14735 
14736   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
14737          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
14738          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
14739          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
14740 }
14741 
14742 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
14743                                     const ArrayRef<const Expr *> ExprArgs,
14744                                     SourceLocation CallSiteLoc) {
14745   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
14746   bool IsPointerAttr = Attr->getIsPointer();
14747 
14748   // Retrieve the argument representing the 'type_tag'.
14749   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
14750   if (TypeTagIdxAST >= ExprArgs.size()) {
14751     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
14752         << 0 << Attr->getTypeTagIdx().getSourceIndex();
14753     return;
14754   }
14755   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
14756   bool FoundWrongKind;
14757   TypeTagData TypeInfo;
14758   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
14759                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
14760                         TypeInfo, isConstantEvaluated())) {
14761     if (FoundWrongKind)
14762       Diag(TypeTagExpr->getExprLoc(),
14763            diag::warn_type_tag_for_datatype_wrong_kind)
14764         << TypeTagExpr->getSourceRange();
14765     return;
14766   }
14767 
14768   // Retrieve the argument representing the 'arg_idx'.
14769   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
14770   if (ArgumentIdxAST >= ExprArgs.size()) {
14771     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
14772         << 1 << Attr->getArgumentIdx().getSourceIndex();
14773     return;
14774   }
14775   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
14776   if (IsPointerAttr) {
14777     // Skip implicit cast of pointer to `void *' (as a function argument).
14778     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
14779       if (ICE->getType()->isVoidPointerType() &&
14780           ICE->getCastKind() == CK_BitCast)
14781         ArgumentExpr = ICE->getSubExpr();
14782   }
14783   QualType ArgumentType = ArgumentExpr->getType();
14784 
14785   // Passing a `void*' pointer shouldn't trigger a warning.
14786   if (IsPointerAttr && ArgumentType->isVoidPointerType())
14787     return;
14788 
14789   if (TypeInfo.MustBeNull) {
14790     // Type tag with matching void type requires a null pointer.
14791     if (!ArgumentExpr->isNullPointerConstant(Context,
14792                                              Expr::NPC_ValueDependentIsNotNull)) {
14793       Diag(ArgumentExpr->getExprLoc(),
14794            diag::warn_type_safety_null_pointer_required)
14795           << ArgumentKind->getName()
14796           << ArgumentExpr->getSourceRange()
14797           << TypeTagExpr->getSourceRange();
14798     }
14799     return;
14800   }
14801 
14802   QualType RequiredType = TypeInfo.Type;
14803   if (IsPointerAttr)
14804     RequiredType = Context.getPointerType(RequiredType);
14805 
14806   bool mismatch = false;
14807   if (!TypeInfo.LayoutCompatible) {
14808     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
14809 
14810     // C++11 [basic.fundamental] p1:
14811     // Plain char, signed char, and unsigned char are three distinct types.
14812     //
14813     // But we treat plain `char' as equivalent to `signed char' or `unsigned
14814     // char' depending on the current char signedness mode.
14815     if (mismatch)
14816       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
14817                                            RequiredType->getPointeeType())) ||
14818           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
14819         mismatch = false;
14820   } else
14821     if (IsPointerAttr)
14822       mismatch = !isLayoutCompatible(Context,
14823                                      ArgumentType->getPointeeType(),
14824                                      RequiredType->getPointeeType());
14825     else
14826       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
14827 
14828   if (mismatch)
14829     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
14830         << ArgumentType << ArgumentKind
14831         << TypeInfo.LayoutCompatible << RequiredType
14832         << ArgumentExpr->getSourceRange()
14833         << TypeTagExpr->getSourceRange();
14834 }
14835 
14836 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
14837                                          CharUnits Alignment) {
14838   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
14839 }
14840 
14841 void Sema::DiagnoseMisalignedMembers() {
14842   for (MisalignedMember &m : MisalignedMembers) {
14843     const NamedDecl *ND = m.RD;
14844     if (ND->getName().empty()) {
14845       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
14846         ND = TD;
14847     }
14848     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
14849         << m.MD << ND << m.E->getSourceRange();
14850   }
14851   MisalignedMembers.clear();
14852 }
14853 
14854 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
14855   E = E->IgnoreParens();
14856   if (!T->isPointerType() && !T->isIntegerType())
14857     return;
14858   if (isa<UnaryOperator>(E) &&
14859       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
14860     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
14861     if (isa<MemberExpr>(Op)) {
14862       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
14863       if (MA != MisalignedMembers.end() &&
14864           (T->isIntegerType() ||
14865            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
14866                                    Context.getTypeAlignInChars(
14867                                        T->getPointeeType()) <= MA->Alignment))))
14868         MisalignedMembers.erase(MA);
14869     }
14870   }
14871 }
14872 
14873 void Sema::RefersToMemberWithReducedAlignment(
14874     Expr *E,
14875     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
14876         Action) {
14877   const auto *ME = dyn_cast<MemberExpr>(E);
14878   if (!ME)
14879     return;
14880 
14881   // No need to check expressions with an __unaligned-qualified type.
14882   if (E->getType().getQualifiers().hasUnaligned())
14883     return;
14884 
14885   // For a chain of MemberExpr like "a.b.c.d" this list
14886   // will keep FieldDecl's like [d, c, b].
14887   SmallVector<FieldDecl *, 4> ReverseMemberChain;
14888   const MemberExpr *TopME = nullptr;
14889   bool AnyIsPacked = false;
14890   do {
14891     QualType BaseType = ME->getBase()->getType();
14892     if (BaseType->isDependentType())
14893       return;
14894     if (ME->isArrow())
14895       BaseType = BaseType->getPointeeType();
14896     RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
14897     if (RD->isInvalidDecl())
14898       return;
14899 
14900     ValueDecl *MD = ME->getMemberDecl();
14901     auto *FD = dyn_cast<FieldDecl>(MD);
14902     // We do not care about non-data members.
14903     if (!FD || FD->isInvalidDecl())
14904       return;
14905 
14906     AnyIsPacked =
14907         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
14908     ReverseMemberChain.push_back(FD);
14909 
14910     TopME = ME;
14911     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
14912   } while (ME);
14913   assert(TopME && "We did not compute a topmost MemberExpr!");
14914 
14915   // Not the scope of this diagnostic.
14916   if (!AnyIsPacked)
14917     return;
14918 
14919   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
14920   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
14921   // TODO: The innermost base of the member expression may be too complicated.
14922   // For now, just disregard these cases. This is left for future
14923   // improvement.
14924   if (!DRE && !isa<CXXThisExpr>(TopBase))
14925       return;
14926 
14927   // Alignment expected by the whole expression.
14928   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
14929 
14930   // No need to do anything else with this case.
14931   if (ExpectedAlignment.isOne())
14932     return;
14933 
14934   // Synthesize offset of the whole access.
14935   CharUnits Offset;
14936   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
14937        I++) {
14938     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
14939   }
14940 
14941   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
14942   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
14943       ReverseMemberChain.back()->getParent()->getTypeForDecl());
14944 
14945   // The base expression of the innermost MemberExpr may give
14946   // stronger guarantees than the class containing the member.
14947   if (DRE && !TopME->isArrow()) {
14948     const ValueDecl *VD = DRE->getDecl();
14949     if (!VD->getType()->isReferenceType())
14950       CompleteObjectAlignment =
14951           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
14952   }
14953 
14954   // Check if the synthesized offset fulfills the alignment.
14955   if (Offset % ExpectedAlignment != 0 ||
14956       // It may fulfill the offset it but the effective alignment may still be
14957       // lower than the expected expression alignment.
14958       CompleteObjectAlignment < ExpectedAlignment) {
14959     // If this happens, we want to determine a sensible culprit of this.
14960     // Intuitively, watching the chain of member expressions from right to
14961     // left, we start with the required alignment (as required by the field
14962     // type) but some packed attribute in that chain has reduced the alignment.
14963     // It may happen that another packed structure increases it again. But if
14964     // we are here such increase has not been enough. So pointing the first
14965     // FieldDecl that either is packed or else its RecordDecl is,
14966     // seems reasonable.
14967     FieldDecl *FD = nullptr;
14968     CharUnits Alignment;
14969     for (FieldDecl *FDI : ReverseMemberChain) {
14970       if (FDI->hasAttr<PackedAttr>() ||
14971           FDI->getParent()->hasAttr<PackedAttr>()) {
14972         FD = FDI;
14973         Alignment = std::min(
14974             Context.getTypeAlignInChars(FD->getType()),
14975             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
14976         break;
14977       }
14978     }
14979     assert(FD && "We did not find a packed FieldDecl!");
14980     Action(E, FD->getParent(), FD, Alignment);
14981   }
14982 }
14983 
14984 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
14985   using namespace std::placeholders;
14986 
14987   RefersToMemberWithReducedAlignment(
14988       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
14989                      _2, _3, _4));
14990 }
14991