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/Stmt.h"
34 #include "clang/AST/TemplateBase.h"
35 #include "clang/AST/Type.h"
36 #include "clang/AST/TypeLoc.h"
37 #include "clang/AST/UnresolvedSet.h"
38 #include "clang/Basic/AddressSpaces.h"
39 #include "clang/Basic/CharInfo.h"
40 #include "clang/Basic/Diagnostic.h"
41 #include "clang/Basic/IdentifierTable.h"
42 #include "clang/Basic/LLVM.h"
43 #include "clang/Basic/LangOptions.h"
44 #include "clang/Basic/OpenCLOptions.h"
45 #include "clang/Basic/OperatorKinds.h"
46 #include "clang/Basic/PartialDiagnostic.h"
47 #include "clang/Basic/SourceLocation.h"
48 #include "clang/Basic/SourceManager.h"
49 #include "clang/Basic/Specifiers.h"
50 #include "clang/Basic/SyncScope.h"
51 #include "clang/Basic/TargetBuiltins.h"
52 #include "clang/Basic/TargetCXXABI.h"
53 #include "clang/Basic/TargetInfo.h"
54 #include "clang/Basic/TypeTraits.h"
55 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
56 #include "clang/Sema/Initialization.h"
57 #include "clang/Sema/Lookup.h"
58 #include "clang/Sema/Ownership.h"
59 #include "clang/Sema/Scope.h"
60 #include "clang/Sema/ScopeInfo.h"
61 #include "clang/Sema/Sema.h"
62 #include "clang/Sema/SemaInternal.h"
63 #include "llvm/ADT/APFloat.h"
64 #include "llvm/ADT/APInt.h"
65 #include "llvm/ADT/APSInt.h"
66 #include "llvm/ADT/ArrayRef.h"
67 #include "llvm/ADT/DenseMap.h"
68 #include "llvm/ADT/FoldingSet.h"
69 #include "llvm/ADT/None.h"
70 #include "llvm/ADT/Optional.h"
71 #include "llvm/ADT/STLExtras.h"
72 #include "llvm/ADT/SmallBitVector.h"
73 #include "llvm/ADT/SmallPtrSet.h"
74 #include "llvm/ADT/SmallString.h"
75 #include "llvm/ADT/SmallVector.h"
76 #include "llvm/ADT/StringRef.h"
77 #include "llvm/ADT/StringSwitch.h"
78 #include "llvm/ADT/Triple.h"
79 #include "llvm/Support/AtomicOrdering.h"
80 #include "llvm/Support/Casting.h"
81 #include "llvm/Support/Compiler.h"
82 #include "llvm/Support/ConvertUTF.h"
83 #include "llvm/Support/ErrorHandling.h"
84 #include "llvm/Support/Format.h"
85 #include "llvm/Support/Locale.h"
86 #include "llvm/Support/MathExtras.h"
87 #include "llvm/Support/SaveAndRestore.h"
88 #include "llvm/Support/raw_ostream.h"
89 #include <algorithm>
90 #include <cassert>
91 #include <cstddef>
92 #include <cstdint>
93 #include <functional>
94 #include <limits>
95 #include <string>
96 #include <tuple>
97 #include <utility>
98 
99 using namespace clang;
100 using namespace sema;
101 
102 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
103                                                     unsigned ByteNo) const {
104   return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
105                                Context.getTargetInfo());
106 }
107 
108 /// Checks that a call expression's argument count is the desired number.
109 /// This is useful when doing custom type-checking.  Returns true on error.
110 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
111   unsigned argCount = call->getNumArgs();
112   if (argCount == desiredArgCount) return false;
113 
114   if (argCount < desiredArgCount)
115     return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args)
116            << 0 /*function call*/ << desiredArgCount << argCount
117            << call->getSourceRange();
118 
119   // Highlight all the excess arguments.
120   SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(),
121                     call->getArg(argCount - 1)->getEndLoc());
122 
123   return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
124     << 0 /*function call*/ << desiredArgCount << argCount
125     << call->getArg(1)->getSourceRange();
126 }
127 
128 /// Check that the first argument to __builtin_annotation is an integer
129 /// and the second argument is a non-wide string literal.
130 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
131   if (checkArgCount(S, TheCall, 2))
132     return true;
133 
134   // First argument should be an integer.
135   Expr *ValArg = TheCall->getArg(0);
136   QualType Ty = ValArg->getType();
137   if (!Ty->isIntegerType()) {
138     S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
139         << ValArg->getSourceRange();
140     return true;
141   }
142 
143   // Second argument should be a constant string.
144   Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
145   StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
146   if (!Literal || !Literal->isAscii()) {
147     S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
148         << StrArg->getSourceRange();
149     return true;
150   }
151 
152   TheCall->setType(Ty);
153   return false;
154 }
155 
156 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
157   // We need at least one argument.
158   if (TheCall->getNumArgs() < 1) {
159     S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
160         << 0 << 1 << TheCall->getNumArgs()
161         << TheCall->getCallee()->getSourceRange();
162     return true;
163   }
164 
165   // All arguments should be wide string literals.
166   for (Expr *Arg : TheCall->arguments()) {
167     auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
168     if (!Literal || !Literal->isWide()) {
169       S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
170           << Arg->getSourceRange();
171       return true;
172     }
173   }
174 
175   return false;
176 }
177 
178 /// Check that the argument to __builtin_addressof is a glvalue, and set the
179 /// result type to the corresponding pointer type.
180 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
181   if (checkArgCount(S, TheCall, 1))
182     return true;
183 
184   ExprResult Arg(TheCall->getArg(0));
185   QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
186   if (ResultType.isNull())
187     return true;
188 
189   TheCall->setArg(0, Arg.get());
190   TheCall->setType(ResultType);
191   return false;
192 }
193 
194 /// Check the number of arguments and set the result type to
195 /// the argument type.
196 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
197   if (checkArgCount(S, TheCall, 1))
198     return true;
199 
200   TheCall->setType(TheCall->getArg(0)->getType());
201   return false;
202 }
203 
204 /// Check that the value argument for __builtin_is_aligned(value, alignment) and
205 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
206 /// type (but not a function pointer) and that the alignment is a power-of-two.
207 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
208   if (checkArgCount(S, TheCall, 2))
209     return true;
210 
211   clang::Expr *Source = TheCall->getArg(0);
212   bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
213 
214   auto IsValidIntegerType = [](QualType Ty) {
215     return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
216   };
217   QualType SrcTy = Source->getType();
218   // We should also be able to use it with arrays (but not functions!).
219   if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
220     SrcTy = S.Context.getDecayedType(SrcTy);
221   }
222   if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
223       SrcTy->isFunctionPointerType()) {
224     // FIXME: this is not quite the right error message since we don't allow
225     // floating point types, or member pointers.
226     S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand)
227         << SrcTy;
228     return true;
229   }
230 
231   clang::Expr *AlignOp = TheCall->getArg(1);
232   if (!IsValidIntegerType(AlignOp->getType())) {
233     S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int)
234         << AlignOp->getType();
235     return true;
236   }
237   Expr::EvalResult AlignResult;
238   unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1;
239   // We can't check validity of alignment if it is type dependent.
240   if (!AlignOp->isInstantiationDependent() &&
241       AlignOp->EvaluateAsInt(AlignResult, S.Context,
242                              Expr::SE_AllowSideEffects)) {
243     llvm::APSInt AlignValue = AlignResult.Val.getInt();
244     llvm::APSInt MaxValue(
245         llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits));
246     if (AlignValue < 1) {
247       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1;
248       return true;
249     }
250     if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) {
251       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big)
252           << MaxValue.toString(10);
253       return true;
254     }
255     if (!AlignValue.isPowerOf2()) {
256       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two);
257       return true;
258     }
259     if (AlignValue == 1) {
260       S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless)
261           << IsBooleanAlignBuiltin;
262     }
263   }
264 
265   ExprResult SrcArg = S.PerformCopyInitialization(
266       InitializedEntity::InitializeParameter(S.Context, SrcTy, false),
267       SourceLocation(), Source);
268   if (SrcArg.isInvalid())
269     return true;
270   TheCall->setArg(0, SrcArg.get());
271   ExprResult AlignArg =
272       S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
273                                       S.Context, AlignOp->getType(), false),
274                                   SourceLocation(), AlignOp);
275   if (AlignArg.isInvalid())
276     return true;
277   TheCall->setArg(1, AlignArg.get());
278   // For align_up/align_down, the return type is the same as the (potentially
279   // decayed) argument type including qualifiers. For is_aligned(), the result
280   // is always bool.
281   TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
282   return false;
283 }
284 
285 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
286   if (checkArgCount(S, TheCall, 3))
287     return true;
288 
289   // First two arguments should be integers.
290   for (unsigned I = 0; I < 2; ++I) {
291     ExprResult Arg = TheCall->getArg(I);
292     QualType Ty = Arg.get()->getType();
293     if (!Ty->isIntegerType()) {
294       S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
295           << Ty << Arg.get()->getSourceRange();
296       return true;
297     }
298     InitializedEntity Entity = InitializedEntity::InitializeParameter(
299         S.getASTContext(), Ty, /*consume*/ false);
300     Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
301     if (Arg.isInvalid())
302       return true;
303     TheCall->setArg(I, Arg.get());
304   }
305 
306   // Third argument should be a pointer to a non-const integer.
307   // IRGen correctly handles volatile, restrict, and address spaces, and
308   // the other qualifiers aren't possible.
309   {
310     ExprResult Arg = TheCall->getArg(2);
311     QualType Ty = Arg.get()->getType();
312     const auto *PtrTy = Ty->getAs<PointerType>();
313     if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
314           !PtrTy->getPointeeType().isConstQualified())) {
315       S.Diag(Arg.get()->getBeginLoc(),
316              diag::err_overflow_builtin_must_be_ptr_int)
317           << Ty << Arg.get()->getSourceRange();
318       return true;
319     }
320     InitializedEntity Entity = InitializedEntity::InitializeParameter(
321         S.getASTContext(), Ty, /*consume*/ false);
322     Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
323     if (Arg.isInvalid())
324       return true;
325     TheCall->setArg(2, Arg.get());
326   }
327   return false;
328 }
329 
330 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
331   if (checkArgCount(S, BuiltinCall, 2))
332     return true;
333 
334   SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
335   Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
336   Expr *Call = BuiltinCall->getArg(0);
337   Expr *Chain = BuiltinCall->getArg(1);
338 
339   if (Call->getStmtClass() != Stmt::CallExprClass) {
340     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
341         << Call->getSourceRange();
342     return true;
343   }
344 
345   auto CE = cast<CallExpr>(Call);
346   if (CE->getCallee()->getType()->isBlockPointerType()) {
347     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
348         << Call->getSourceRange();
349     return true;
350   }
351 
352   const Decl *TargetDecl = CE->getCalleeDecl();
353   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
354     if (FD->getBuiltinID()) {
355       S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
356           << Call->getSourceRange();
357       return true;
358     }
359 
360   if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
361     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
362         << Call->getSourceRange();
363     return true;
364   }
365 
366   ExprResult ChainResult = S.UsualUnaryConversions(Chain);
367   if (ChainResult.isInvalid())
368     return true;
369   if (!ChainResult.get()->getType()->isPointerType()) {
370     S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
371         << Chain->getSourceRange();
372     return true;
373   }
374 
375   QualType ReturnTy = CE->getCallReturnType(S.Context);
376   QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
377   QualType BuiltinTy = S.Context.getFunctionType(
378       ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
379   QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
380 
381   Builtin =
382       S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
383 
384   BuiltinCall->setType(CE->getType());
385   BuiltinCall->setValueKind(CE->getValueKind());
386   BuiltinCall->setObjectKind(CE->getObjectKind());
387   BuiltinCall->setCallee(Builtin);
388   BuiltinCall->setArg(1, ChainResult.get());
389 
390   return false;
391 }
392 
393 namespace {
394 
395 class EstimateSizeFormatHandler
396     : public analyze_format_string::FormatStringHandler {
397   size_t Size;
398 
399 public:
400   EstimateSizeFormatHandler(StringRef Format)
401       : Size(std::min(Format.find(0), Format.size()) +
402              1 /* null byte always written by sprintf */) {}
403 
404   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
405                              const char *, unsigned SpecifierLen) override {
406 
407     const size_t FieldWidth = computeFieldWidth(FS);
408     const size_t Precision = computePrecision(FS);
409 
410     // The actual format.
411     switch (FS.getConversionSpecifier().getKind()) {
412     // Just a char.
413     case analyze_format_string::ConversionSpecifier::cArg:
414     case analyze_format_string::ConversionSpecifier::CArg:
415       Size += std::max(FieldWidth, (size_t)1);
416       break;
417     // Just an integer.
418     case analyze_format_string::ConversionSpecifier::dArg:
419     case analyze_format_string::ConversionSpecifier::DArg:
420     case analyze_format_string::ConversionSpecifier::iArg:
421     case analyze_format_string::ConversionSpecifier::oArg:
422     case analyze_format_string::ConversionSpecifier::OArg:
423     case analyze_format_string::ConversionSpecifier::uArg:
424     case analyze_format_string::ConversionSpecifier::UArg:
425     case analyze_format_string::ConversionSpecifier::xArg:
426     case analyze_format_string::ConversionSpecifier::XArg:
427       Size += std::max(FieldWidth, Precision);
428       break;
429 
430     // %g style conversion switches between %f or %e style dynamically.
431     // %f always takes less space, so default to it.
432     case analyze_format_string::ConversionSpecifier::gArg:
433     case analyze_format_string::ConversionSpecifier::GArg:
434 
435     // Floating point number in the form '[+]ddd.ddd'.
436     case analyze_format_string::ConversionSpecifier::fArg:
437     case analyze_format_string::ConversionSpecifier::FArg:
438       Size += std::max(FieldWidth, 1 /* integer part */ +
439                                        (Precision ? 1 + Precision
440                                                   : 0) /* period + decimal */);
441       break;
442 
443     // Floating point number in the form '[-]d.ddde[+-]dd'.
444     case analyze_format_string::ConversionSpecifier::eArg:
445     case analyze_format_string::ConversionSpecifier::EArg:
446       Size +=
447           std::max(FieldWidth,
448                    1 /* integer part */ +
449                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
450                        1 /* e or E letter */ + 2 /* exponent */);
451       break;
452 
453     // Floating point number in the form '[-]0xh.hhhhp±dd'.
454     case analyze_format_string::ConversionSpecifier::aArg:
455     case analyze_format_string::ConversionSpecifier::AArg:
456       Size +=
457           std::max(FieldWidth,
458                    2 /* 0x */ + 1 /* integer part */ +
459                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
460                        1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
461       break;
462 
463     // Just a string.
464     case analyze_format_string::ConversionSpecifier::sArg:
465     case analyze_format_string::ConversionSpecifier::SArg:
466       Size += FieldWidth;
467       break;
468 
469     // Just a pointer in the form '0xddd'.
470     case analyze_format_string::ConversionSpecifier::pArg:
471       Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
472       break;
473 
474     // A plain percent.
475     case analyze_format_string::ConversionSpecifier::PercentArg:
476       Size += 1;
477       break;
478 
479     default:
480       break;
481     }
482 
483     Size += FS.hasPlusPrefix() || FS.hasSpacePrefix();
484 
485     if (FS.hasAlternativeForm()) {
486       switch (FS.getConversionSpecifier().getKind()) {
487       default:
488         break;
489       // Force a leading '0'.
490       case analyze_format_string::ConversionSpecifier::oArg:
491         Size += 1;
492         break;
493       // Force a leading '0x'.
494       case analyze_format_string::ConversionSpecifier::xArg:
495       case analyze_format_string::ConversionSpecifier::XArg:
496         Size += 2;
497         break;
498       // Force a period '.' before decimal, even if precision is 0.
499       case analyze_format_string::ConversionSpecifier::aArg:
500       case analyze_format_string::ConversionSpecifier::AArg:
501       case analyze_format_string::ConversionSpecifier::eArg:
502       case analyze_format_string::ConversionSpecifier::EArg:
503       case analyze_format_string::ConversionSpecifier::fArg:
504       case analyze_format_string::ConversionSpecifier::FArg:
505       case analyze_format_string::ConversionSpecifier::gArg:
506       case analyze_format_string::ConversionSpecifier::GArg:
507         Size += (Precision ? 0 : 1);
508         break;
509       }
510     }
511     assert(SpecifierLen <= Size && "no underflow");
512     Size -= SpecifierLen;
513     return true;
514   }
515 
516   size_t getSizeLowerBound() const { return Size; }
517 
518 private:
519   static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
520     const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
521     size_t FieldWidth = 0;
522     if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant)
523       FieldWidth = FW.getConstantAmount();
524     return FieldWidth;
525   }
526 
527   static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
528     const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
529     size_t Precision = 0;
530 
531     // See man 3 printf for default precision value based on the specifier.
532     switch (FW.getHowSpecified()) {
533     case analyze_format_string::OptionalAmount::NotSpecified:
534       switch (FS.getConversionSpecifier().getKind()) {
535       default:
536         break;
537       case analyze_format_string::ConversionSpecifier::dArg: // %d
538       case analyze_format_string::ConversionSpecifier::DArg: // %D
539       case analyze_format_string::ConversionSpecifier::iArg: // %i
540         Precision = 1;
541         break;
542       case analyze_format_string::ConversionSpecifier::oArg: // %d
543       case analyze_format_string::ConversionSpecifier::OArg: // %D
544       case analyze_format_string::ConversionSpecifier::uArg: // %d
545       case analyze_format_string::ConversionSpecifier::UArg: // %D
546       case analyze_format_string::ConversionSpecifier::xArg: // %d
547       case analyze_format_string::ConversionSpecifier::XArg: // %D
548         Precision = 1;
549         break;
550       case analyze_format_string::ConversionSpecifier::fArg: // %f
551       case analyze_format_string::ConversionSpecifier::FArg: // %F
552       case analyze_format_string::ConversionSpecifier::eArg: // %e
553       case analyze_format_string::ConversionSpecifier::EArg: // %E
554       case analyze_format_string::ConversionSpecifier::gArg: // %g
555       case analyze_format_string::ConversionSpecifier::GArg: // %G
556         Precision = 6;
557         break;
558       case analyze_format_string::ConversionSpecifier::pArg: // %d
559         Precision = 1;
560         break;
561       }
562       break;
563     case analyze_format_string::OptionalAmount::Constant:
564       Precision = FW.getConstantAmount();
565       break;
566     default:
567       break;
568     }
569     return Precision;
570   }
571 };
572 
573 } // namespace
574 
575 /// Check a call to BuiltinID for buffer overflows. If BuiltinID is a
576 /// __builtin_*_chk function, then use the object size argument specified in the
577 /// source. Otherwise, infer the object size using __builtin_object_size.
578 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
579                                                CallExpr *TheCall) {
580   // FIXME: There are some more useful checks we could be doing here:
581   //  - Evaluate strlen of strcpy arguments, use as object size.
582 
583   if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
584       isConstantEvaluated())
585     return;
586 
587   unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true);
588   if (!BuiltinID)
589     return;
590 
591   const TargetInfo &TI = getASTContext().getTargetInfo();
592   unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
593 
594   unsigned DiagID = 0;
595   bool IsChkVariant = false;
596   Optional<llvm::APSInt> UsedSize;
597   unsigned SizeIndex, ObjectIndex;
598   switch (BuiltinID) {
599   default:
600     return;
601   case Builtin::BIsprintf:
602   case Builtin::BI__builtin___sprintf_chk: {
603     size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
604     auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
605 
606     if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) {
607 
608       if (!Format->isAscii() && !Format->isUTF8())
609         return;
610 
611       StringRef FormatStrRef = Format->getString();
612       EstimateSizeFormatHandler H(FormatStrRef);
613       const char *FormatBytes = FormatStrRef.data();
614       const ConstantArrayType *T =
615           Context.getAsConstantArrayType(Format->getType());
616       assert(T && "String literal not of constant array type!");
617       size_t TypeSize = T->getSize().getZExtValue();
618 
619       // In case there's a null byte somewhere.
620       size_t StrLen =
621           std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
622       if (!analyze_format_string::ParsePrintfString(
623               H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
624               Context.getTargetInfo(), false)) {
625         DiagID = diag::warn_fortify_source_format_overflow;
626         UsedSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
627                        .extOrTrunc(SizeTypeWidth);
628         if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
629           IsChkVariant = true;
630           ObjectIndex = 2;
631         } else {
632           IsChkVariant = false;
633           ObjectIndex = 0;
634         }
635         break;
636       }
637     }
638     return;
639   }
640   case Builtin::BI__builtin___memcpy_chk:
641   case Builtin::BI__builtin___memmove_chk:
642   case Builtin::BI__builtin___memset_chk:
643   case Builtin::BI__builtin___strlcat_chk:
644   case Builtin::BI__builtin___strlcpy_chk:
645   case Builtin::BI__builtin___strncat_chk:
646   case Builtin::BI__builtin___strncpy_chk:
647   case Builtin::BI__builtin___stpncpy_chk:
648   case Builtin::BI__builtin___memccpy_chk:
649   case Builtin::BI__builtin___mempcpy_chk: {
650     DiagID = diag::warn_builtin_chk_overflow;
651     IsChkVariant = true;
652     SizeIndex = TheCall->getNumArgs() - 2;
653     ObjectIndex = TheCall->getNumArgs() - 1;
654     break;
655   }
656 
657   case Builtin::BI__builtin___snprintf_chk:
658   case Builtin::BI__builtin___vsnprintf_chk: {
659     DiagID = diag::warn_builtin_chk_overflow;
660     IsChkVariant = true;
661     SizeIndex = 1;
662     ObjectIndex = 3;
663     break;
664   }
665 
666   case Builtin::BIstrncat:
667   case Builtin::BI__builtin_strncat:
668   case Builtin::BIstrncpy:
669   case Builtin::BI__builtin_strncpy:
670   case Builtin::BIstpncpy:
671   case Builtin::BI__builtin_stpncpy: {
672     // Whether these functions overflow depends on the runtime strlen of the
673     // string, not just the buffer size, so emitting the "always overflow"
674     // diagnostic isn't quite right. We should still diagnose passing a buffer
675     // size larger than the destination buffer though; this is a runtime abort
676     // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
677     DiagID = diag::warn_fortify_source_size_mismatch;
678     SizeIndex = TheCall->getNumArgs() - 1;
679     ObjectIndex = 0;
680     break;
681   }
682 
683   case Builtin::BImemcpy:
684   case Builtin::BI__builtin_memcpy:
685   case Builtin::BImemmove:
686   case Builtin::BI__builtin_memmove:
687   case Builtin::BImemset:
688   case Builtin::BI__builtin_memset:
689   case Builtin::BImempcpy:
690   case Builtin::BI__builtin_mempcpy: {
691     DiagID = diag::warn_fortify_source_overflow;
692     SizeIndex = TheCall->getNumArgs() - 1;
693     ObjectIndex = 0;
694     break;
695   }
696   case Builtin::BIsnprintf:
697   case Builtin::BI__builtin_snprintf:
698   case Builtin::BIvsnprintf:
699   case Builtin::BI__builtin_vsnprintf: {
700     DiagID = diag::warn_fortify_source_size_mismatch;
701     SizeIndex = 1;
702     ObjectIndex = 0;
703     break;
704   }
705   }
706 
707   llvm::APSInt ObjectSize;
708   // For __builtin___*_chk, the object size is explicitly provided by the caller
709   // (usually using __builtin_object_size). Use that value to check this call.
710   if (IsChkVariant) {
711     Expr::EvalResult Result;
712     Expr *SizeArg = TheCall->getArg(ObjectIndex);
713     if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
714       return;
715     ObjectSize = Result.Val.getInt();
716 
717   // Otherwise, try to evaluate an imaginary call to __builtin_object_size.
718   } else {
719     // If the parameter has a pass_object_size attribute, then we should use its
720     // (potentially) more strict checking mode. Otherwise, conservatively assume
721     // type 0.
722     int BOSType = 0;
723     if (const auto *POS =
724             FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>())
725       BOSType = POS->getType();
726 
727     Expr *ObjArg = TheCall->getArg(ObjectIndex);
728     uint64_t Result;
729     if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
730       return;
731     // Get the object size in the target's size_t width.
732     ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
733   }
734 
735   // Evaluate the number of bytes of the object that this call will use.
736   if (!UsedSize) {
737     Expr::EvalResult Result;
738     Expr *UsedSizeArg = TheCall->getArg(SizeIndex);
739     if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext()))
740       return;
741     UsedSize = Result.Val.getInt().extOrTrunc(SizeTypeWidth);
742   }
743 
744   if (UsedSize.getValue().ule(ObjectSize))
745     return;
746 
747   StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
748   // Skim off the details of whichever builtin was called to produce a better
749   // diagnostic, as it's unlikley that the user wrote the __builtin explicitly.
750   if (IsChkVariant) {
751     FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
752     FunctionName = FunctionName.drop_back(std::strlen("_chk"));
753   } else if (FunctionName.startswith("__builtin_")) {
754     FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
755   }
756 
757   DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
758                       PDiag(DiagID)
759                           << FunctionName << ObjectSize.toString(/*Radix=*/10)
760                           << UsedSize.getValue().toString(/*Radix=*/10));
761 }
762 
763 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
764                                      Scope::ScopeFlags NeededScopeFlags,
765                                      unsigned DiagID) {
766   // Scopes aren't available during instantiation. Fortunately, builtin
767   // functions cannot be template args so they cannot be formed through template
768   // instantiation. Therefore checking once during the parse is sufficient.
769   if (SemaRef.inTemplateInstantiation())
770     return false;
771 
772   Scope *S = SemaRef.getCurScope();
773   while (S && !S->isSEHExceptScope())
774     S = S->getParent();
775   if (!S || !(S->getFlags() & NeededScopeFlags)) {
776     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
777     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
778         << DRE->getDecl()->getIdentifier();
779     return true;
780   }
781 
782   return false;
783 }
784 
785 static inline bool isBlockPointer(Expr *Arg) {
786   return Arg->getType()->isBlockPointerType();
787 }
788 
789 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
790 /// void*, which is a requirement of device side enqueue.
791 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
792   const BlockPointerType *BPT =
793       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
794   ArrayRef<QualType> Params =
795       BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes();
796   unsigned ArgCounter = 0;
797   bool IllegalParams = false;
798   // Iterate through the block parameters until either one is found that is not
799   // a local void*, or the block is valid.
800   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
801        I != E; ++I, ++ArgCounter) {
802     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
803         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
804             LangAS::opencl_local) {
805       // Get the location of the error. If a block literal has been passed
806       // (BlockExpr) then we can point straight to the offending argument,
807       // else we just point to the variable reference.
808       SourceLocation ErrorLoc;
809       if (isa<BlockExpr>(BlockArg)) {
810         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
811         ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
812       } else if (isa<DeclRefExpr>(BlockArg)) {
813         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
814       }
815       S.Diag(ErrorLoc,
816              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
817       IllegalParams = true;
818     }
819   }
820 
821   return IllegalParams;
822 }
823 
824 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
825   if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
826     S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
827         << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
828     return true;
829   }
830   return false;
831 }
832 
833 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
834   if (checkArgCount(S, TheCall, 2))
835     return true;
836 
837   if (checkOpenCLSubgroupExt(S, TheCall))
838     return true;
839 
840   // First argument is an ndrange_t type.
841   Expr *NDRangeArg = TheCall->getArg(0);
842   if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
843     S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
844         << TheCall->getDirectCallee() << "'ndrange_t'";
845     return true;
846   }
847 
848   Expr *BlockArg = TheCall->getArg(1);
849   if (!isBlockPointer(BlockArg)) {
850     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
851         << TheCall->getDirectCallee() << "block";
852     return true;
853   }
854   return checkOpenCLBlockArgs(S, BlockArg);
855 }
856 
857 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
858 /// get_kernel_work_group_size
859 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
860 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
861   if (checkArgCount(S, TheCall, 1))
862     return true;
863 
864   Expr *BlockArg = TheCall->getArg(0);
865   if (!isBlockPointer(BlockArg)) {
866     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
867         << TheCall->getDirectCallee() << "block";
868     return true;
869   }
870   return checkOpenCLBlockArgs(S, BlockArg);
871 }
872 
873 /// Diagnose integer type and any valid implicit conversion to it.
874 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
875                                       const QualType &IntType);
876 
877 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
878                                             unsigned Start, unsigned End) {
879   bool IllegalParams = false;
880   for (unsigned I = Start; I <= End; ++I)
881     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
882                                               S.Context.getSizeType());
883   return IllegalParams;
884 }
885 
886 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
887 /// 'local void*' parameter of passed block.
888 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
889                                            Expr *BlockArg,
890                                            unsigned NumNonVarArgs) {
891   const BlockPointerType *BPT =
892       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
893   unsigned NumBlockParams =
894       BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams();
895   unsigned TotalNumArgs = TheCall->getNumArgs();
896 
897   // For each argument passed to the block, a corresponding uint needs to
898   // be passed to describe the size of the local memory.
899   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
900     S.Diag(TheCall->getBeginLoc(),
901            diag::err_opencl_enqueue_kernel_local_size_args);
902     return true;
903   }
904 
905   // Check that the sizes of the local memory are specified by integers.
906   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
907                                          TotalNumArgs - 1);
908 }
909 
910 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
911 /// overload formats specified in Table 6.13.17.1.
912 /// int enqueue_kernel(queue_t queue,
913 ///                    kernel_enqueue_flags_t flags,
914 ///                    const ndrange_t ndrange,
915 ///                    void (^block)(void))
916 /// int enqueue_kernel(queue_t queue,
917 ///                    kernel_enqueue_flags_t flags,
918 ///                    const ndrange_t ndrange,
919 ///                    uint num_events_in_wait_list,
920 ///                    clk_event_t *event_wait_list,
921 ///                    clk_event_t *event_ret,
922 ///                    void (^block)(void))
923 /// int enqueue_kernel(queue_t queue,
924 ///                    kernel_enqueue_flags_t flags,
925 ///                    const ndrange_t ndrange,
926 ///                    void (^block)(local void*, ...),
927 ///                    uint size0, ...)
928 /// int enqueue_kernel(queue_t queue,
929 ///                    kernel_enqueue_flags_t flags,
930 ///                    const ndrange_t ndrange,
931 ///                    uint num_events_in_wait_list,
932 ///                    clk_event_t *event_wait_list,
933 ///                    clk_event_t *event_ret,
934 ///                    void (^block)(local void*, ...),
935 ///                    uint size0, ...)
936 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
937   unsigned NumArgs = TheCall->getNumArgs();
938 
939   if (NumArgs < 4) {
940     S.Diag(TheCall->getBeginLoc(),
941            diag::err_typecheck_call_too_few_args_at_least)
942         << 0 << 4 << NumArgs;
943     return true;
944   }
945 
946   Expr *Arg0 = TheCall->getArg(0);
947   Expr *Arg1 = TheCall->getArg(1);
948   Expr *Arg2 = TheCall->getArg(2);
949   Expr *Arg3 = TheCall->getArg(3);
950 
951   // First argument always needs to be a queue_t type.
952   if (!Arg0->getType()->isQueueT()) {
953     S.Diag(TheCall->getArg(0)->getBeginLoc(),
954            diag::err_opencl_builtin_expected_type)
955         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
956     return true;
957   }
958 
959   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
960   if (!Arg1->getType()->isIntegerType()) {
961     S.Diag(TheCall->getArg(1)->getBeginLoc(),
962            diag::err_opencl_builtin_expected_type)
963         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
964     return true;
965   }
966 
967   // Third argument is always an ndrange_t type.
968   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
969     S.Diag(TheCall->getArg(2)->getBeginLoc(),
970            diag::err_opencl_builtin_expected_type)
971         << TheCall->getDirectCallee() << "'ndrange_t'";
972     return true;
973   }
974 
975   // With four arguments, there is only one form that the function could be
976   // called in: no events and no variable arguments.
977   if (NumArgs == 4) {
978     // check that the last argument is the right block type.
979     if (!isBlockPointer(Arg3)) {
980       S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
981           << TheCall->getDirectCallee() << "block";
982       return true;
983     }
984     // we have a block type, check the prototype
985     const BlockPointerType *BPT =
986         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
987     if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) {
988       S.Diag(Arg3->getBeginLoc(),
989              diag::err_opencl_enqueue_kernel_blocks_no_args);
990       return true;
991     }
992     return false;
993   }
994   // we can have block + varargs.
995   if (isBlockPointer(Arg3))
996     return (checkOpenCLBlockArgs(S, Arg3) ||
997             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
998   // last two cases with either exactly 7 args or 7 args and varargs.
999   if (NumArgs >= 7) {
1000     // check common block argument.
1001     Expr *Arg6 = TheCall->getArg(6);
1002     if (!isBlockPointer(Arg6)) {
1003       S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1004           << TheCall->getDirectCallee() << "block";
1005       return true;
1006     }
1007     if (checkOpenCLBlockArgs(S, Arg6))
1008       return true;
1009 
1010     // Forth argument has to be any integer type.
1011     if (!Arg3->getType()->isIntegerType()) {
1012       S.Diag(TheCall->getArg(3)->getBeginLoc(),
1013              diag::err_opencl_builtin_expected_type)
1014           << TheCall->getDirectCallee() << "integer";
1015       return true;
1016     }
1017     // check remaining common arguments.
1018     Expr *Arg4 = TheCall->getArg(4);
1019     Expr *Arg5 = TheCall->getArg(5);
1020 
1021     // Fifth argument is always passed as a pointer to clk_event_t.
1022     if (!Arg4->isNullPointerConstant(S.Context,
1023                                      Expr::NPC_ValueDependentIsNotNull) &&
1024         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
1025       S.Diag(TheCall->getArg(4)->getBeginLoc(),
1026              diag::err_opencl_builtin_expected_type)
1027           << TheCall->getDirectCallee()
1028           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1029       return true;
1030     }
1031 
1032     // Sixth argument is always passed as a pointer to clk_event_t.
1033     if (!Arg5->isNullPointerConstant(S.Context,
1034                                      Expr::NPC_ValueDependentIsNotNull) &&
1035         !(Arg5->getType()->isPointerType() &&
1036           Arg5->getType()->getPointeeType()->isClkEventT())) {
1037       S.Diag(TheCall->getArg(5)->getBeginLoc(),
1038              diag::err_opencl_builtin_expected_type)
1039           << TheCall->getDirectCallee()
1040           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1041       return true;
1042     }
1043 
1044     if (NumArgs == 7)
1045       return false;
1046 
1047     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
1048   }
1049 
1050   // None of the specific case has been detected, give generic error
1051   S.Diag(TheCall->getBeginLoc(),
1052          diag::err_opencl_enqueue_kernel_incorrect_args);
1053   return true;
1054 }
1055 
1056 /// Returns OpenCL access qual.
1057 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
1058     return D->getAttr<OpenCLAccessAttr>();
1059 }
1060 
1061 /// Returns true if pipe element type is different from the pointer.
1062 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
1063   const Expr *Arg0 = Call->getArg(0);
1064   // First argument type should always be pipe.
1065   if (!Arg0->getType()->isPipeType()) {
1066     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1067         << Call->getDirectCallee() << Arg0->getSourceRange();
1068     return true;
1069   }
1070   OpenCLAccessAttr *AccessQual =
1071       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
1072   // Validates the access qualifier is compatible with the call.
1073   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
1074   // read_only and write_only, and assumed to be read_only if no qualifier is
1075   // specified.
1076   switch (Call->getDirectCallee()->getBuiltinID()) {
1077   case Builtin::BIread_pipe:
1078   case Builtin::BIreserve_read_pipe:
1079   case Builtin::BIcommit_read_pipe:
1080   case Builtin::BIwork_group_reserve_read_pipe:
1081   case Builtin::BIsub_group_reserve_read_pipe:
1082   case Builtin::BIwork_group_commit_read_pipe:
1083   case Builtin::BIsub_group_commit_read_pipe:
1084     if (!(!AccessQual || AccessQual->isReadOnly())) {
1085       S.Diag(Arg0->getBeginLoc(),
1086              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1087           << "read_only" << Arg0->getSourceRange();
1088       return true;
1089     }
1090     break;
1091   case Builtin::BIwrite_pipe:
1092   case Builtin::BIreserve_write_pipe:
1093   case Builtin::BIcommit_write_pipe:
1094   case Builtin::BIwork_group_reserve_write_pipe:
1095   case Builtin::BIsub_group_reserve_write_pipe:
1096   case Builtin::BIwork_group_commit_write_pipe:
1097   case Builtin::BIsub_group_commit_write_pipe:
1098     if (!(AccessQual && AccessQual->isWriteOnly())) {
1099       S.Diag(Arg0->getBeginLoc(),
1100              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1101           << "write_only" << Arg0->getSourceRange();
1102       return true;
1103     }
1104     break;
1105   default:
1106     break;
1107   }
1108   return false;
1109 }
1110 
1111 /// Returns true if pipe element type is different from the pointer.
1112 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
1113   const Expr *Arg0 = Call->getArg(0);
1114   const Expr *ArgIdx = Call->getArg(Idx);
1115   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
1116   const QualType EltTy = PipeTy->getElementType();
1117   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
1118   // The Idx argument should be a pointer and the type of the pointer and
1119   // the type of pipe element should also be the same.
1120   if (!ArgTy ||
1121       !S.Context.hasSameType(
1122           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
1123     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1124         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
1125         << ArgIdx->getType() << ArgIdx->getSourceRange();
1126     return true;
1127   }
1128   return false;
1129 }
1130 
1131 // Performs semantic analysis for the read/write_pipe call.
1132 // \param S Reference to the semantic analyzer.
1133 // \param Call A pointer to the builtin call.
1134 // \return True if a semantic error has been found, false otherwise.
1135 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
1136   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
1137   // functions have two forms.
1138   switch (Call->getNumArgs()) {
1139   case 2:
1140     if (checkOpenCLPipeArg(S, Call))
1141       return true;
1142     // The call with 2 arguments should be
1143     // read/write_pipe(pipe T, T*).
1144     // Check packet type T.
1145     if (checkOpenCLPipePacketType(S, Call, 1))
1146       return true;
1147     break;
1148 
1149   case 4: {
1150     if (checkOpenCLPipeArg(S, Call))
1151       return true;
1152     // The call with 4 arguments should be
1153     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
1154     // Check reserve_id_t.
1155     if (!Call->getArg(1)->getType()->isReserveIDT()) {
1156       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1157           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1158           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1159       return true;
1160     }
1161 
1162     // Check the index.
1163     const Expr *Arg2 = Call->getArg(2);
1164     if (!Arg2->getType()->isIntegerType() &&
1165         !Arg2->getType()->isUnsignedIntegerType()) {
1166       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1167           << Call->getDirectCallee() << S.Context.UnsignedIntTy
1168           << Arg2->getType() << Arg2->getSourceRange();
1169       return true;
1170     }
1171 
1172     // Check packet type T.
1173     if (checkOpenCLPipePacketType(S, Call, 3))
1174       return true;
1175   } break;
1176   default:
1177     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
1178         << Call->getDirectCallee() << Call->getSourceRange();
1179     return true;
1180   }
1181 
1182   return false;
1183 }
1184 
1185 // Performs a semantic analysis on the {work_group_/sub_group_
1186 //        /_}reserve_{read/write}_pipe
1187 // \param S Reference to the semantic analyzer.
1188 // \param Call The call to the builtin function to be analyzed.
1189 // \return True if a semantic error was found, false otherwise.
1190 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
1191   if (checkArgCount(S, Call, 2))
1192     return true;
1193 
1194   if (checkOpenCLPipeArg(S, Call))
1195     return true;
1196 
1197   // Check the reserve size.
1198   if (!Call->getArg(1)->getType()->isIntegerType() &&
1199       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
1200     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1201         << Call->getDirectCallee() << S.Context.UnsignedIntTy
1202         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1203     return true;
1204   }
1205 
1206   // Since return type of reserve_read/write_pipe built-in function is
1207   // reserve_id_t, which is not defined in the builtin def file , we used int
1208   // as return type and need to override the return type of these functions.
1209   Call->setType(S.Context.OCLReserveIDTy);
1210 
1211   return false;
1212 }
1213 
1214 // Performs a semantic analysis on {work_group_/sub_group_
1215 //        /_}commit_{read/write}_pipe
1216 // \param S Reference to the semantic analyzer.
1217 // \param Call The call to the builtin function to be analyzed.
1218 // \return True if a semantic error was found, false otherwise.
1219 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
1220   if (checkArgCount(S, Call, 2))
1221     return true;
1222 
1223   if (checkOpenCLPipeArg(S, Call))
1224     return true;
1225 
1226   // Check reserve_id_t.
1227   if (!Call->getArg(1)->getType()->isReserveIDT()) {
1228     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1229         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1230         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1231     return true;
1232   }
1233 
1234   return false;
1235 }
1236 
1237 // Performs a semantic analysis on the call to built-in Pipe
1238 //        Query Functions.
1239 // \param S Reference to the semantic analyzer.
1240 // \param Call The call to the builtin function to be analyzed.
1241 // \return True if a semantic error was found, false otherwise.
1242 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
1243   if (checkArgCount(S, Call, 1))
1244     return true;
1245 
1246   if (!Call->getArg(0)->getType()->isPipeType()) {
1247     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1248         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
1249     return true;
1250   }
1251 
1252   return false;
1253 }
1254 
1255 // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
1256 // Performs semantic analysis for the to_global/local/private call.
1257 // \param S Reference to the semantic analyzer.
1258 // \param BuiltinID ID of the builtin function.
1259 // \param Call A pointer to the builtin call.
1260 // \return True if a semantic error has been found, false otherwise.
1261 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
1262                                     CallExpr *Call) {
1263   if (Call->getNumArgs() != 1) {
1264     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_arg_num)
1265         << Call->getDirectCallee() << Call->getSourceRange();
1266     return true;
1267   }
1268 
1269   auto RT = Call->getArg(0)->getType();
1270   if (!RT->isPointerType() || RT->getPointeeType()
1271       .getAddressSpace() == LangAS::opencl_constant) {
1272     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
1273         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
1274     return true;
1275   }
1276 
1277   if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
1278     S.Diag(Call->getArg(0)->getBeginLoc(),
1279            diag::warn_opencl_generic_address_space_arg)
1280         << Call->getDirectCallee()->getNameInfo().getAsString()
1281         << Call->getArg(0)->getSourceRange();
1282   }
1283 
1284   RT = RT->getPointeeType();
1285   auto Qual = RT.getQualifiers();
1286   switch (BuiltinID) {
1287   case Builtin::BIto_global:
1288     Qual.setAddressSpace(LangAS::opencl_global);
1289     break;
1290   case Builtin::BIto_local:
1291     Qual.setAddressSpace(LangAS::opencl_local);
1292     break;
1293   case Builtin::BIto_private:
1294     Qual.setAddressSpace(LangAS::opencl_private);
1295     break;
1296   default:
1297     llvm_unreachable("Invalid builtin function");
1298   }
1299   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
1300       RT.getUnqualifiedType(), Qual)));
1301 
1302   return false;
1303 }
1304 
1305 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
1306   if (checkArgCount(S, TheCall, 1))
1307     return ExprError();
1308 
1309   // Compute __builtin_launder's parameter type from the argument.
1310   // The parameter type is:
1311   //  * The type of the argument if it's not an array or function type,
1312   //  Otherwise,
1313   //  * The decayed argument type.
1314   QualType ParamTy = [&]() {
1315     QualType ArgTy = TheCall->getArg(0)->getType();
1316     if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1317       return S.Context.getPointerType(Ty->getElementType());
1318     if (ArgTy->isFunctionType()) {
1319       return S.Context.getPointerType(ArgTy);
1320     }
1321     return ArgTy;
1322   }();
1323 
1324   TheCall->setType(ParamTy);
1325 
1326   auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
1327     if (!ParamTy->isPointerType())
1328       return 0;
1329     if (ParamTy->isFunctionPointerType())
1330       return 1;
1331     if (ParamTy->isVoidPointerType())
1332       return 2;
1333     return llvm::Optional<unsigned>{};
1334   }();
1335   if (DiagSelect.hasValue()) {
1336     S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1337         << DiagSelect.getValue() << TheCall->getSourceRange();
1338     return ExprError();
1339   }
1340 
1341   // We either have an incomplete class type, or we have a class template
1342   // whose instantiation has not been forced. Example:
1343   //
1344   //   template <class T> struct Foo { T value; };
1345   //   Foo<int> *p = nullptr;
1346   //   auto *d = __builtin_launder(p);
1347   if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1348                             diag::err_incomplete_type))
1349     return ExprError();
1350 
1351   assert(ParamTy->getPointeeType()->isObjectType() &&
1352          "Unhandled non-object pointer case");
1353 
1354   InitializedEntity Entity =
1355       InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
1356   ExprResult Arg =
1357       S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1358   if (Arg.isInvalid())
1359     return ExprError();
1360   TheCall->setArg(0, Arg.get());
1361 
1362   return TheCall;
1363 }
1364 
1365 // Emit an error and return true if the current architecture is not in the list
1366 // of supported architectures.
1367 static bool
1368 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1369                           ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
1370   llvm::Triple::ArchType CurArch =
1371       S.getASTContext().getTargetInfo().getTriple().getArch();
1372   if (llvm::is_contained(SupportedArchs, CurArch))
1373     return false;
1374   S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1375       << TheCall->getSourceRange();
1376   return true;
1377 }
1378 
1379 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
1380                                  SourceLocation CallSiteLoc);
1381 
1382 ExprResult
1383 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
1384                                CallExpr *TheCall) {
1385   ExprResult TheCallResult(TheCall);
1386 
1387   // Find out if any arguments are required to be integer constant expressions.
1388   unsigned ICEArguments = 0;
1389   ASTContext::GetBuiltinTypeError Error;
1390   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
1391   if (Error != ASTContext::GE_None)
1392     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
1393 
1394   // If any arguments are required to be ICE's, check and diagnose.
1395   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
1396     // Skip arguments not required to be ICE's.
1397     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
1398 
1399     llvm::APSInt Result;
1400     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
1401       return true;
1402     ICEArguments &= ~(1 << ArgNo);
1403   }
1404 
1405   switch (BuiltinID) {
1406   case Builtin::BI__builtin___CFStringMakeConstantString:
1407     assert(TheCall->getNumArgs() == 1 &&
1408            "Wrong # arguments to builtin CFStringMakeConstantString");
1409     if (CheckObjCString(TheCall->getArg(0)))
1410       return ExprError();
1411     break;
1412   case Builtin::BI__builtin_ms_va_start:
1413   case Builtin::BI__builtin_stdarg_start:
1414   case Builtin::BI__builtin_va_start:
1415     if (SemaBuiltinVAStart(BuiltinID, TheCall))
1416       return ExprError();
1417     break;
1418   case Builtin::BI__va_start: {
1419     switch (Context.getTargetInfo().getTriple().getArch()) {
1420     case llvm::Triple::aarch64:
1421     case llvm::Triple::arm:
1422     case llvm::Triple::thumb:
1423       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
1424         return ExprError();
1425       break;
1426     default:
1427       if (SemaBuiltinVAStart(BuiltinID, TheCall))
1428         return ExprError();
1429       break;
1430     }
1431     break;
1432   }
1433 
1434   // The acquire, release, and no fence variants are ARM and AArch64 only.
1435   case Builtin::BI_interlockedbittestandset_acq:
1436   case Builtin::BI_interlockedbittestandset_rel:
1437   case Builtin::BI_interlockedbittestandset_nf:
1438   case Builtin::BI_interlockedbittestandreset_acq:
1439   case Builtin::BI_interlockedbittestandreset_rel:
1440   case Builtin::BI_interlockedbittestandreset_nf:
1441     if (CheckBuiltinTargetSupport(
1442             *this, BuiltinID, TheCall,
1443             {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
1444       return ExprError();
1445     break;
1446 
1447   // The 64-bit bittest variants are x64, ARM, and AArch64 only.
1448   case Builtin::BI_bittest64:
1449   case Builtin::BI_bittestandcomplement64:
1450   case Builtin::BI_bittestandreset64:
1451   case Builtin::BI_bittestandset64:
1452   case Builtin::BI_interlockedbittestandreset64:
1453   case Builtin::BI_interlockedbittestandset64:
1454     if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
1455                                   {llvm::Triple::x86_64, llvm::Triple::arm,
1456                                    llvm::Triple::thumb, llvm::Triple::aarch64}))
1457       return ExprError();
1458     break;
1459 
1460   case Builtin::BI__builtin_isgreater:
1461   case Builtin::BI__builtin_isgreaterequal:
1462   case Builtin::BI__builtin_isless:
1463   case Builtin::BI__builtin_islessequal:
1464   case Builtin::BI__builtin_islessgreater:
1465   case Builtin::BI__builtin_isunordered:
1466     if (SemaBuiltinUnorderedCompare(TheCall))
1467       return ExprError();
1468     break;
1469   case Builtin::BI__builtin_fpclassify:
1470     if (SemaBuiltinFPClassification(TheCall, 6))
1471       return ExprError();
1472     break;
1473   case Builtin::BI__builtin_isfinite:
1474   case Builtin::BI__builtin_isinf:
1475   case Builtin::BI__builtin_isinf_sign:
1476   case Builtin::BI__builtin_isnan:
1477   case Builtin::BI__builtin_isnormal:
1478   case Builtin::BI__builtin_signbit:
1479   case Builtin::BI__builtin_signbitf:
1480   case Builtin::BI__builtin_signbitl:
1481     if (SemaBuiltinFPClassification(TheCall, 1))
1482       return ExprError();
1483     break;
1484   case Builtin::BI__builtin_shufflevector:
1485     return SemaBuiltinShuffleVector(TheCall);
1486     // TheCall will be freed by the smart pointer here, but that's fine, since
1487     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1488   case Builtin::BI__builtin_prefetch:
1489     if (SemaBuiltinPrefetch(TheCall))
1490       return ExprError();
1491     break;
1492   case Builtin::BI__builtin_alloca_with_align:
1493     if (SemaBuiltinAllocaWithAlign(TheCall))
1494       return ExprError();
1495     LLVM_FALLTHROUGH;
1496   case Builtin::BI__builtin_alloca:
1497     Diag(TheCall->getBeginLoc(), diag::warn_alloca)
1498         << TheCall->getDirectCallee();
1499     break;
1500   case Builtin::BI__assume:
1501   case Builtin::BI__builtin_assume:
1502     if (SemaBuiltinAssume(TheCall))
1503       return ExprError();
1504     break;
1505   case Builtin::BI__builtin_assume_aligned:
1506     if (SemaBuiltinAssumeAligned(TheCall))
1507       return ExprError();
1508     break;
1509   case Builtin::BI__builtin_dynamic_object_size:
1510   case Builtin::BI__builtin_object_size:
1511     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1512       return ExprError();
1513     break;
1514   case Builtin::BI__builtin_longjmp:
1515     if (SemaBuiltinLongjmp(TheCall))
1516       return ExprError();
1517     break;
1518   case Builtin::BI__builtin_setjmp:
1519     if (SemaBuiltinSetjmp(TheCall))
1520       return ExprError();
1521     break;
1522   case Builtin::BI_setjmp:
1523   case Builtin::BI_setjmpex:
1524     if (checkArgCount(*this, TheCall, 1))
1525       return true;
1526     break;
1527   case Builtin::BI__builtin_classify_type:
1528     if (checkArgCount(*this, TheCall, 1)) return true;
1529     TheCall->setType(Context.IntTy);
1530     break;
1531   case Builtin::BI__builtin_constant_p: {
1532     if (checkArgCount(*this, TheCall, 1)) return true;
1533     ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
1534     if (Arg.isInvalid()) return true;
1535     TheCall->setArg(0, Arg.get());
1536     TheCall->setType(Context.IntTy);
1537     break;
1538   }
1539   case Builtin::BI__builtin_launder:
1540     return SemaBuiltinLaunder(*this, TheCall);
1541   case Builtin::BI__sync_fetch_and_add:
1542   case Builtin::BI__sync_fetch_and_add_1:
1543   case Builtin::BI__sync_fetch_and_add_2:
1544   case Builtin::BI__sync_fetch_and_add_4:
1545   case Builtin::BI__sync_fetch_and_add_8:
1546   case Builtin::BI__sync_fetch_and_add_16:
1547   case Builtin::BI__sync_fetch_and_sub:
1548   case Builtin::BI__sync_fetch_and_sub_1:
1549   case Builtin::BI__sync_fetch_and_sub_2:
1550   case Builtin::BI__sync_fetch_and_sub_4:
1551   case Builtin::BI__sync_fetch_and_sub_8:
1552   case Builtin::BI__sync_fetch_and_sub_16:
1553   case Builtin::BI__sync_fetch_and_or:
1554   case Builtin::BI__sync_fetch_and_or_1:
1555   case Builtin::BI__sync_fetch_and_or_2:
1556   case Builtin::BI__sync_fetch_and_or_4:
1557   case Builtin::BI__sync_fetch_and_or_8:
1558   case Builtin::BI__sync_fetch_and_or_16:
1559   case Builtin::BI__sync_fetch_and_and:
1560   case Builtin::BI__sync_fetch_and_and_1:
1561   case Builtin::BI__sync_fetch_and_and_2:
1562   case Builtin::BI__sync_fetch_and_and_4:
1563   case Builtin::BI__sync_fetch_and_and_8:
1564   case Builtin::BI__sync_fetch_and_and_16:
1565   case Builtin::BI__sync_fetch_and_xor:
1566   case Builtin::BI__sync_fetch_and_xor_1:
1567   case Builtin::BI__sync_fetch_and_xor_2:
1568   case Builtin::BI__sync_fetch_and_xor_4:
1569   case Builtin::BI__sync_fetch_and_xor_8:
1570   case Builtin::BI__sync_fetch_and_xor_16:
1571   case Builtin::BI__sync_fetch_and_nand:
1572   case Builtin::BI__sync_fetch_and_nand_1:
1573   case Builtin::BI__sync_fetch_and_nand_2:
1574   case Builtin::BI__sync_fetch_and_nand_4:
1575   case Builtin::BI__sync_fetch_and_nand_8:
1576   case Builtin::BI__sync_fetch_and_nand_16:
1577   case Builtin::BI__sync_add_and_fetch:
1578   case Builtin::BI__sync_add_and_fetch_1:
1579   case Builtin::BI__sync_add_and_fetch_2:
1580   case Builtin::BI__sync_add_and_fetch_4:
1581   case Builtin::BI__sync_add_and_fetch_8:
1582   case Builtin::BI__sync_add_and_fetch_16:
1583   case Builtin::BI__sync_sub_and_fetch:
1584   case Builtin::BI__sync_sub_and_fetch_1:
1585   case Builtin::BI__sync_sub_and_fetch_2:
1586   case Builtin::BI__sync_sub_and_fetch_4:
1587   case Builtin::BI__sync_sub_and_fetch_8:
1588   case Builtin::BI__sync_sub_and_fetch_16:
1589   case Builtin::BI__sync_and_and_fetch:
1590   case Builtin::BI__sync_and_and_fetch_1:
1591   case Builtin::BI__sync_and_and_fetch_2:
1592   case Builtin::BI__sync_and_and_fetch_4:
1593   case Builtin::BI__sync_and_and_fetch_8:
1594   case Builtin::BI__sync_and_and_fetch_16:
1595   case Builtin::BI__sync_or_and_fetch:
1596   case Builtin::BI__sync_or_and_fetch_1:
1597   case Builtin::BI__sync_or_and_fetch_2:
1598   case Builtin::BI__sync_or_and_fetch_4:
1599   case Builtin::BI__sync_or_and_fetch_8:
1600   case Builtin::BI__sync_or_and_fetch_16:
1601   case Builtin::BI__sync_xor_and_fetch:
1602   case Builtin::BI__sync_xor_and_fetch_1:
1603   case Builtin::BI__sync_xor_and_fetch_2:
1604   case Builtin::BI__sync_xor_and_fetch_4:
1605   case Builtin::BI__sync_xor_and_fetch_8:
1606   case Builtin::BI__sync_xor_and_fetch_16:
1607   case Builtin::BI__sync_nand_and_fetch:
1608   case Builtin::BI__sync_nand_and_fetch_1:
1609   case Builtin::BI__sync_nand_and_fetch_2:
1610   case Builtin::BI__sync_nand_and_fetch_4:
1611   case Builtin::BI__sync_nand_and_fetch_8:
1612   case Builtin::BI__sync_nand_and_fetch_16:
1613   case Builtin::BI__sync_val_compare_and_swap:
1614   case Builtin::BI__sync_val_compare_and_swap_1:
1615   case Builtin::BI__sync_val_compare_and_swap_2:
1616   case Builtin::BI__sync_val_compare_and_swap_4:
1617   case Builtin::BI__sync_val_compare_and_swap_8:
1618   case Builtin::BI__sync_val_compare_and_swap_16:
1619   case Builtin::BI__sync_bool_compare_and_swap:
1620   case Builtin::BI__sync_bool_compare_and_swap_1:
1621   case Builtin::BI__sync_bool_compare_and_swap_2:
1622   case Builtin::BI__sync_bool_compare_and_swap_4:
1623   case Builtin::BI__sync_bool_compare_and_swap_8:
1624   case Builtin::BI__sync_bool_compare_and_swap_16:
1625   case Builtin::BI__sync_lock_test_and_set:
1626   case Builtin::BI__sync_lock_test_and_set_1:
1627   case Builtin::BI__sync_lock_test_and_set_2:
1628   case Builtin::BI__sync_lock_test_and_set_4:
1629   case Builtin::BI__sync_lock_test_and_set_8:
1630   case Builtin::BI__sync_lock_test_and_set_16:
1631   case Builtin::BI__sync_lock_release:
1632   case Builtin::BI__sync_lock_release_1:
1633   case Builtin::BI__sync_lock_release_2:
1634   case Builtin::BI__sync_lock_release_4:
1635   case Builtin::BI__sync_lock_release_8:
1636   case Builtin::BI__sync_lock_release_16:
1637   case Builtin::BI__sync_swap:
1638   case Builtin::BI__sync_swap_1:
1639   case Builtin::BI__sync_swap_2:
1640   case Builtin::BI__sync_swap_4:
1641   case Builtin::BI__sync_swap_8:
1642   case Builtin::BI__sync_swap_16:
1643     return SemaBuiltinAtomicOverloaded(TheCallResult);
1644   case Builtin::BI__sync_synchronize:
1645     Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1646         << TheCall->getCallee()->getSourceRange();
1647     break;
1648   case Builtin::BI__builtin_nontemporal_load:
1649   case Builtin::BI__builtin_nontemporal_store:
1650     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1651   case Builtin::BI__builtin_memcpy_inline: {
1652     clang::Expr *SizeOp = TheCall->getArg(2);
1653     // We warn about copying to or from `nullptr` pointers when `size` is
1654     // greater than 0. When `size` is value dependent we cannot evaluate its
1655     // value so we bail out.
1656     if (SizeOp->isValueDependent())
1657       break;
1658     if (!SizeOp->EvaluateKnownConstInt(Context).isNullValue()) {
1659       CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
1660       CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
1661     }
1662     break;
1663   }
1664 #define BUILTIN(ID, TYPE, ATTRS)
1665 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1666   case Builtin::BI##ID: \
1667     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1668 #include "clang/Basic/Builtins.def"
1669   case Builtin::BI__annotation:
1670     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1671       return ExprError();
1672     break;
1673   case Builtin::BI__builtin_annotation:
1674     if (SemaBuiltinAnnotation(*this, TheCall))
1675       return ExprError();
1676     break;
1677   case Builtin::BI__builtin_addressof:
1678     if (SemaBuiltinAddressof(*this, TheCall))
1679       return ExprError();
1680     break;
1681   case Builtin::BI__builtin_is_aligned:
1682   case Builtin::BI__builtin_align_up:
1683   case Builtin::BI__builtin_align_down:
1684     if (SemaBuiltinAlignment(*this, TheCall, BuiltinID))
1685       return ExprError();
1686     break;
1687   case Builtin::BI__builtin_add_overflow:
1688   case Builtin::BI__builtin_sub_overflow:
1689   case Builtin::BI__builtin_mul_overflow:
1690     if (SemaBuiltinOverflow(*this, TheCall))
1691       return ExprError();
1692     break;
1693   case Builtin::BI__builtin_operator_new:
1694   case Builtin::BI__builtin_operator_delete: {
1695     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1696     ExprResult Res =
1697         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1698     if (Res.isInvalid())
1699       CorrectDelayedTyposInExpr(TheCallResult.get());
1700     return Res;
1701   }
1702   case Builtin::BI__builtin_dump_struct: {
1703     // We first want to ensure we are called with 2 arguments
1704     if (checkArgCount(*this, TheCall, 2))
1705       return ExprError();
1706     // Ensure that the first argument is of type 'struct XX *'
1707     const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1708     const QualType PtrArgType = PtrArg->getType();
1709     if (!PtrArgType->isPointerType() ||
1710         !PtrArgType->getPointeeType()->isRecordType()) {
1711       Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1712           << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1713           << "structure pointer";
1714       return ExprError();
1715     }
1716 
1717     // Ensure that the second argument is of type 'FunctionType'
1718     const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1719     const QualType FnPtrArgType = FnPtrArg->getType();
1720     if (!FnPtrArgType->isPointerType()) {
1721       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1722           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1723           << FnPtrArgType << "'int (*)(const char *, ...)'";
1724       return ExprError();
1725     }
1726 
1727     const auto *FuncType =
1728         FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1729 
1730     if (!FuncType) {
1731       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1732           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1733           << FnPtrArgType << "'int (*)(const char *, ...)'";
1734       return ExprError();
1735     }
1736 
1737     if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1738       if (!FT->getNumParams()) {
1739         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1740             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1741             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1742         return ExprError();
1743       }
1744       QualType PT = FT->getParamType(0);
1745       if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1746           !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1747           !PT->getPointeeType().isConstQualified()) {
1748         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1749             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1750             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1751         return ExprError();
1752       }
1753     }
1754 
1755     TheCall->setType(Context.IntTy);
1756     break;
1757   }
1758   case Builtin::BI__builtin_preserve_access_index:
1759     if (SemaBuiltinPreserveAI(*this, TheCall))
1760       return ExprError();
1761     break;
1762   case Builtin::BI__builtin_call_with_static_chain:
1763     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1764       return ExprError();
1765     break;
1766   case Builtin::BI__exception_code:
1767   case Builtin::BI_exception_code:
1768     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1769                                  diag::err_seh___except_block))
1770       return ExprError();
1771     break;
1772   case Builtin::BI__exception_info:
1773   case Builtin::BI_exception_info:
1774     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1775                                  diag::err_seh___except_filter))
1776       return ExprError();
1777     break;
1778   case Builtin::BI__GetExceptionInfo:
1779     if (checkArgCount(*this, TheCall, 1))
1780       return ExprError();
1781 
1782     if (CheckCXXThrowOperand(
1783             TheCall->getBeginLoc(),
1784             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1785             TheCall))
1786       return ExprError();
1787 
1788     TheCall->setType(Context.VoidPtrTy);
1789     break;
1790   // OpenCL v2.0, s6.13.16 - Pipe functions
1791   case Builtin::BIread_pipe:
1792   case Builtin::BIwrite_pipe:
1793     // Since those two functions are declared with var args, we need a semantic
1794     // check for the argument.
1795     if (SemaBuiltinRWPipe(*this, TheCall))
1796       return ExprError();
1797     break;
1798   case Builtin::BIreserve_read_pipe:
1799   case Builtin::BIreserve_write_pipe:
1800   case Builtin::BIwork_group_reserve_read_pipe:
1801   case Builtin::BIwork_group_reserve_write_pipe:
1802     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1803       return ExprError();
1804     break;
1805   case Builtin::BIsub_group_reserve_read_pipe:
1806   case Builtin::BIsub_group_reserve_write_pipe:
1807     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1808         SemaBuiltinReserveRWPipe(*this, TheCall))
1809       return ExprError();
1810     break;
1811   case Builtin::BIcommit_read_pipe:
1812   case Builtin::BIcommit_write_pipe:
1813   case Builtin::BIwork_group_commit_read_pipe:
1814   case Builtin::BIwork_group_commit_write_pipe:
1815     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1816       return ExprError();
1817     break;
1818   case Builtin::BIsub_group_commit_read_pipe:
1819   case Builtin::BIsub_group_commit_write_pipe:
1820     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1821         SemaBuiltinCommitRWPipe(*this, TheCall))
1822       return ExprError();
1823     break;
1824   case Builtin::BIget_pipe_num_packets:
1825   case Builtin::BIget_pipe_max_packets:
1826     if (SemaBuiltinPipePackets(*this, TheCall))
1827       return ExprError();
1828     break;
1829   case Builtin::BIto_global:
1830   case Builtin::BIto_local:
1831   case Builtin::BIto_private:
1832     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1833       return ExprError();
1834     break;
1835   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1836   case Builtin::BIenqueue_kernel:
1837     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1838       return ExprError();
1839     break;
1840   case Builtin::BIget_kernel_work_group_size:
1841   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1842     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1843       return ExprError();
1844     break;
1845   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1846   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1847     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1848       return ExprError();
1849     break;
1850   case Builtin::BI__builtin_os_log_format:
1851     Cleanup.setExprNeedsCleanups(true);
1852     LLVM_FALLTHROUGH;
1853   case Builtin::BI__builtin_os_log_format_buffer_size:
1854     if (SemaBuiltinOSLogFormat(TheCall))
1855       return ExprError();
1856     break;
1857   case Builtin::BI__builtin_frame_address:
1858   case Builtin::BI__builtin_return_address:
1859     if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
1860       return ExprError();
1861 
1862     // -Wframe-address warning if non-zero passed to builtin
1863     // return/frame address.
1864     Expr::EvalResult Result;
1865     if (TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
1866         Result.Val.getInt() != 0)
1867       Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
1868           << ((BuiltinID == Builtin::BI__builtin_return_address)
1869                   ? "__builtin_return_address"
1870                   : "__builtin_frame_address")
1871           << TheCall->getSourceRange();
1872     break;
1873   }
1874 
1875   // Since the target specific builtins for each arch overlap, only check those
1876   // of the arch we are compiling for.
1877   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1878     switch (Context.getTargetInfo().getTriple().getArch()) {
1879       case llvm::Triple::arm:
1880       case llvm::Triple::armeb:
1881       case llvm::Triple::thumb:
1882       case llvm::Triple::thumbeb:
1883         if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1884           return ExprError();
1885         break;
1886       case llvm::Triple::aarch64:
1887       case llvm::Triple::aarch64_32:
1888       case llvm::Triple::aarch64_be:
1889         if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
1890           return ExprError();
1891         break;
1892       case llvm::Triple::bpfeb:
1893       case llvm::Triple::bpfel:
1894         if (CheckBPFBuiltinFunctionCall(BuiltinID, TheCall))
1895           return ExprError();
1896         break;
1897       case llvm::Triple::hexagon:
1898         if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall))
1899           return ExprError();
1900         break;
1901       case llvm::Triple::mips:
1902       case llvm::Triple::mipsel:
1903       case llvm::Triple::mips64:
1904       case llvm::Triple::mips64el:
1905         if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1906           return ExprError();
1907         break;
1908       case llvm::Triple::systemz:
1909         if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1910           return ExprError();
1911         break;
1912       case llvm::Triple::x86:
1913       case llvm::Triple::x86_64:
1914         if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1915           return ExprError();
1916         break;
1917       case llvm::Triple::ppc:
1918       case llvm::Triple::ppc64:
1919       case llvm::Triple::ppc64le:
1920         if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1921           return ExprError();
1922         break;
1923       case llvm::Triple::amdgcn:
1924         if (CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall))
1925           return ExprError();
1926         break;
1927       default:
1928         break;
1929     }
1930   }
1931 
1932   return TheCallResult;
1933 }
1934 
1935 // Get the valid immediate range for the specified NEON type code.
1936 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1937   NeonTypeFlags Type(t);
1938   int IsQuad = ForceQuad ? true : Type.isQuad();
1939   switch (Type.getEltType()) {
1940   case NeonTypeFlags::Int8:
1941   case NeonTypeFlags::Poly8:
1942     return shift ? 7 : (8 << IsQuad) - 1;
1943   case NeonTypeFlags::Int16:
1944   case NeonTypeFlags::Poly16:
1945     return shift ? 15 : (4 << IsQuad) - 1;
1946   case NeonTypeFlags::Int32:
1947     return shift ? 31 : (2 << IsQuad) - 1;
1948   case NeonTypeFlags::Int64:
1949   case NeonTypeFlags::Poly64:
1950     return shift ? 63 : (1 << IsQuad) - 1;
1951   case NeonTypeFlags::Poly128:
1952     return shift ? 127 : (1 << IsQuad) - 1;
1953   case NeonTypeFlags::Float16:
1954     assert(!shift && "cannot shift float types!");
1955     return (4 << IsQuad) - 1;
1956   case NeonTypeFlags::Float32:
1957     assert(!shift && "cannot shift float types!");
1958     return (2 << IsQuad) - 1;
1959   case NeonTypeFlags::Float64:
1960     assert(!shift && "cannot shift float types!");
1961     return (1 << IsQuad) - 1;
1962   }
1963   llvm_unreachable("Invalid NeonTypeFlag!");
1964 }
1965 
1966 /// getNeonEltType - Return the QualType corresponding to the elements of
1967 /// the vector type specified by the NeonTypeFlags.  This is used to check
1968 /// the pointer arguments for Neon load/store intrinsics.
1969 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
1970                                bool IsPolyUnsigned, bool IsInt64Long) {
1971   switch (Flags.getEltType()) {
1972   case NeonTypeFlags::Int8:
1973     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1974   case NeonTypeFlags::Int16:
1975     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1976   case NeonTypeFlags::Int32:
1977     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1978   case NeonTypeFlags::Int64:
1979     if (IsInt64Long)
1980       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1981     else
1982       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1983                                 : Context.LongLongTy;
1984   case NeonTypeFlags::Poly8:
1985     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
1986   case NeonTypeFlags::Poly16:
1987     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
1988   case NeonTypeFlags::Poly64:
1989     if (IsInt64Long)
1990       return Context.UnsignedLongTy;
1991     else
1992       return Context.UnsignedLongLongTy;
1993   case NeonTypeFlags::Poly128:
1994     break;
1995   case NeonTypeFlags::Float16:
1996     return Context.HalfTy;
1997   case NeonTypeFlags::Float32:
1998     return Context.FloatTy;
1999   case NeonTypeFlags::Float64:
2000     return Context.DoubleTy;
2001   }
2002   llvm_unreachable("Invalid NeonTypeFlag!");
2003 }
2004 
2005 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2006   // Range check SVE intrinsics that take immediate values.
2007   SmallVector<std::tuple<int,int,int>, 3> ImmChecks;
2008 
2009   switch (BuiltinID) {
2010   default:
2011     return false;
2012 #define GET_SVE_IMMEDIATE_CHECK
2013 #include "clang/Basic/arm_sve_sema_rangechecks.inc"
2014 #undef GET_SVE_IMMEDIATE_CHECK
2015   }
2016 
2017   // Perform all the immediate checks for this builtin call.
2018   bool HasError = false;
2019   for (auto &I : ImmChecks) {
2020     int ArgNum, CheckTy, ElementSizeInBits;
2021     std::tie(ArgNum, CheckTy, ElementSizeInBits) = I;
2022 
2023     typedef bool(*OptionSetCheckFnTy)(int64_t Value);
2024 
2025     // Function that checks whether the operand (ArgNum) is an immediate
2026     // that is one of the predefined values.
2027     auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm,
2028                                    int ErrDiag) -> bool {
2029       // We can't check the value of a dependent argument.
2030       Expr *Arg = TheCall->getArg(ArgNum);
2031       if (Arg->isTypeDependent() || Arg->isValueDependent())
2032         return false;
2033 
2034       // Check constant-ness first.
2035       llvm::APSInt Imm;
2036       if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm))
2037         return true;
2038 
2039       if (!CheckImm(Imm.getSExtValue()))
2040         return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange();
2041       return false;
2042     };
2043 
2044     switch ((SVETypeFlags::ImmCheckType)CheckTy) {
2045     case SVETypeFlags::ImmCheck0_31:
2046       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31))
2047         HasError = true;
2048       break;
2049     case SVETypeFlags::ImmCheck0_13:
2050       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13))
2051         HasError = true;
2052       break;
2053     case SVETypeFlags::ImmCheck1_16:
2054       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16))
2055         HasError = true;
2056       break;
2057     case SVETypeFlags::ImmCheck0_7:
2058       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7))
2059         HasError = true;
2060       break;
2061     case SVETypeFlags::ImmCheckExtract:
2062       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2063                                       (2048 / ElementSizeInBits) - 1))
2064         HasError = true;
2065       break;
2066     case SVETypeFlags::ImmCheckShiftRight:
2067       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits))
2068         HasError = true;
2069       break;
2070     case SVETypeFlags::ImmCheckShiftRightNarrow:
2071       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1,
2072                                       ElementSizeInBits / 2))
2073         HasError = true;
2074       break;
2075     case SVETypeFlags::ImmCheckShiftLeft:
2076       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2077                                       ElementSizeInBits - 1))
2078         HasError = true;
2079       break;
2080     case SVETypeFlags::ImmCheckLaneIndex:
2081       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2082                                       (128 / (1 * ElementSizeInBits)) - 1))
2083         HasError = true;
2084       break;
2085     case SVETypeFlags::ImmCheckLaneIndexCompRotate:
2086       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2087                                       (128 / (2 * ElementSizeInBits)) - 1))
2088         HasError = true;
2089       break;
2090     case SVETypeFlags::ImmCheckLaneIndexDot:
2091       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2092                                       (128 / (4 * ElementSizeInBits)) - 1))
2093         HasError = true;
2094       break;
2095     case SVETypeFlags::ImmCheckComplexRot90_270:
2096       if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; },
2097                               diag::err_rotation_argument_to_cadd))
2098         HasError = true;
2099       break;
2100     case SVETypeFlags::ImmCheckComplexRotAll90:
2101       if (CheckImmediateInSet(
2102               [](int64_t V) {
2103                 return V == 0 || V == 90 || V == 180 || V == 270;
2104               },
2105               diag::err_rotation_argument_to_cmla))
2106         HasError = true;
2107       break;
2108     }
2109   }
2110 
2111   return HasError;
2112 }
2113 
2114 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2115   llvm::APSInt Result;
2116   uint64_t mask = 0;
2117   unsigned TV = 0;
2118   int PtrArgNum = -1;
2119   bool HasConstPtr = false;
2120   switch (BuiltinID) {
2121 #define GET_NEON_OVERLOAD_CHECK
2122 #include "clang/Basic/arm_neon.inc"
2123 #include "clang/Basic/arm_fp16.inc"
2124 #undef GET_NEON_OVERLOAD_CHECK
2125   }
2126 
2127   // For NEON intrinsics which are overloaded on vector element type, validate
2128   // the immediate which specifies which variant to emit.
2129   unsigned ImmArg = TheCall->getNumArgs()-1;
2130   if (mask) {
2131     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
2132       return true;
2133 
2134     TV = Result.getLimitedValue(64);
2135     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
2136       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
2137              << TheCall->getArg(ImmArg)->getSourceRange();
2138   }
2139 
2140   if (PtrArgNum >= 0) {
2141     // Check that pointer arguments have the specified type.
2142     Expr *Arg = TheCall->getArg(PtrArgNum);
2143     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
2144       Arg = ICE->getSubExpr();
2145     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
2146     QualType RHSTy = RHS.get()->getType();
2147 
2148     llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
2149     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
2150                           Arch == llvm::Triple::aarch64_32 ||
2151                           Arch == llvm::Triple::aarch64_be;
2152     bool IsInt64Long =
2153         Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
2154     QualType EltTy =
2155         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
2156     if (HasConstPtr)
2157       EltTy = EltTy.withConst();
2158     QualType LHSTy = Context.getPointerType(EltTy);
2159     AssignConvertType ConvTy;
2160     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
2161     if (RHS.isInvalid())
2162       return true;
2163     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
2164                                  RHS.get(), AA_Assigning))
2165       return true;
2166   }
2167 
2168   // For NEON intrinsics which take an immediate value as part of the
2169   // instruction, range check them here.
2170   unsigned i = 0, l = 0, u = 0;
2171   switch (BuiltinID) {
2172   default:
2173     return false;
2174   #define GET_NEON_IMMEDIATE_CHECK
2175   #include "clang/Basic/arm_neon.inc"
2176   #include "clang/Basic/arm_fp16.inc"
2177   #undef GET_NEON_IMMEDIATE_CHECK
2178   }
2179 
2180   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2181 }
2182 
2183 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2184   switch (BuiltinID) {
2185   default:
2186     return false;
2187   #include "clang/Basic/arm_mve_builtin_sema.inc"
2188   }
2189 }
2190 
2191 bool Sema::CheckCDEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2192   bool Err = false;
2193   switch (BuiltinID) {
2194   default:
2195     return false;
2196 #include "clang/Basic/arm_cde_builtin_sema.inc"
2197   }
2198 
2199   if (Err)
2200     return true;
2201 
2202   return CheckARMCoprocessorImmediate(TheCall->getArg(0), /*WantCDE*/ true);
2203 }
2204 
2205 bool Sema::CheckARMCoprocessorImmediate(const Expr *CoprocArg, bool WantCDE) {
2206   if (isConstantEvaluated())
2207     return false;
2208 
2209   // We can't check the value of a dependent argument.
2210   if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent())
2211     return false;
2212 
2213   llvm::APSInt CoprocNoAP;
2214   bool IsICE = CoprocArg->isIntegerConstantExpr(CoprocNoAP, Context);
2215   (void)IsICE;
2216   assert(IsICE && "Coprocossor immediate is not a constant expression");
2217   int64_t CoprocNo = CoprocNoAP.getExtValue();
2218   assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative");
2219 
2220   uint32_t CDECoprocMask = Context.getTargetInfo().getARMCDECoprocMask();
2221   bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo));
2222 
2223   if (IsCDECoproc != WantCDE)
2224     return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc)
2225            << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange();
2226 
2227   return false;
2228 }
2229 
2230 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
2231                                         unsigned MaxWidth) {
2232   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
2233           BuiltinID == ARM::BI__builtin_arm_ldaex ||
2234           BuiltinID == ARM::BI__builtin_arm_strex ||
2235           BuiltinID == ARM::BI__builtin_arm_stlex ||
2236           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2237           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2238           BuiltinID == AArch64::BI__builtin_arm_strex ||
2239           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
2240          "unexpected ARM builtin");
2241   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
2242                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
2243                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2244                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
2245 
2246   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2247 
2248   // Ensure that we have the proper number of arguments.
2249   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
2250     return true;
2251 
2252   // Inspect the pointer argument of the atomic builtin.  This should always be
2253   // a pointer type, whose element is an integral scalar or pointer type.
2254   // Because it is a pointer type, we don't have to worry about any implicit
2255   // casts here.
2256   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
2257   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
2258   if (PointerArgRes.isInvalid())
2259     return true;
2260   PointerArg = PointerArgRes.get();
2261 
2262   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2263   if (!pointerType) {
2264     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
2265         << PointerArg->getType() << PointerArg->getSourceRange();
2266     return true;
2267   }
2268 
2269   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
2270   // task is to insert the appropriate casts into the AST. First work out just
2271   // what the appropriate type is.
2272   QualType ValType = pointerType->getPointeeType();
2273   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
2274   if (IsLdrex)
2275     AddrType.addConst();
2276 
2277   // Issue a warning if the cast is dodgy.
2278   CastKind CastNeeded = CK_NoOp;
2279   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
2280     CastNeeded = CK_BitCast;
2281     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
2282         << PointerArg->getType() << Context.getPointerType(AddrType)
2283         << AA_Passing << PointerArg->getSourceRange();
2284   }
2285 
2286   // Finally, do the cast and replace the argument with the corrected version.
2287   AddrType = Context.getPointerType(AddrType);
2288   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
2289   if (PointerArgRes.isInvalid())
2290     return true;
2291   PointerArg = PointerArgRes.get();
2292 
2293   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
2294 
2295   // In general, we allow ints, floats and pointers to be loaded and stored.
2296   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2297       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
2298     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
2299         << PointerArg->getType() << PointerArg->getSourceRange();
2300     return true;
2301   }
2302 
2303   // But ARM doesn't have instructions to deal with 128-bit versions.
2304   if (Context.getTypeSize(ValType) > MaxWidth) {
2305     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
2306     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
2307         << PointerArg->getType() << PointerArg->getSourceRange();
2308     return true;
2309   }
2310 
2311   switch (ValType.getObjCLifetime()) {
2312   case Qualifiers::OCL_None:
2313   case Qualifiers::OCL_ExplicitNone:
2314     // okay
2315     break;
2316 
2317   case Qualifiers::OCL_Weak:
2318   case Qualifiers::OCL_Strong:
2319   case Qualifiers::OCL_Autoreleasing:
2320     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
2321         << ValType << PointerArg->getSourceRange();
2322     return true;
2323   }
2324 
2325   if (IsLdrex) {
2326     TheCall->setType(ValType);
2327     return false;
2328   }
2329 
2330   // Initialize the argument to be stored.
2331   ExprResult ValArg = TheCall->getArg(0);
2332   InitializedEntity Entity = InitializedEntity::InitializeParameter(
2333       Context, ValType, /*consume*/ false);
2334   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2335   if (ValArg.isInvalid())
2336     return true;
2337   TheCall->setArg(0, ValArg.get());
2338 
2339   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
2340   // but the custom checker bypasses all default analysis.
2341   TheCall->setType(Context.IntTy);
2342   return false;
2343 }
2344 
2345 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2346   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
2347       BuiltinID == ARM::BI__builtin_arm_ldaex ||
2348       BuiltinID == ARM::BI__builtin_arm_strex ||
2349       BuiltinID == ARM::BI__builtin_arm_stlex) {
2350     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
2351   }
2352 
2353   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
2354     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2355       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
2356   }
2357 
2358   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2359       BuiltinID == ARM::BI__builtin_arm_wsr64)
2360     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
2361 
2362   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
2363       BuiltinID == ARM::BI__builtin_arm_rsrp ||
2364       BuiltinID == ARM::BI__builtin_arm_wsr ||
2365       BuiltinID == ARM::BI__builtin_arm_wsrp)
2366     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2367 
2368   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
2369     return true;
2370   if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
2371     return true;
2372   if (CheckCDEBuiltinFunctionCall(BuiltinID, TheCall))
2373     return true;
2374 
2375   // For intrinsics which take an immediate value as part of the instruction,
2376   // range check them here.
2377   // FIXME: VFP Intrinsics should error if VFP not present.
2378   switch (BuiltinID) {
2379   default: return false;
2380   case ARM::BI__builtin_arm_ssat:
2381     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
2382   case ARM::BI__builtin_arm_usat:
2383     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
2384   case ARM::BI__builtin_arm_ssat16:
2385     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
2386   case ARM::BI__builtin_arm_usat16:
2387     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2388   case ARM::BI__builtin_arm_vcvtr_f:
2389   case ARM::BI__builtin_arm_vcvtr_d:
2390     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
2391   case ARM::BI__builtin_arm_dmb:
2392   case ARM::BI__builtin_arm_dsb:
2393   case ARM::BI__builtin_arm_isb:
2394   case ARM::BI__builtin_arm_dbg:
2395     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
2396   case ARM::BI__builtin_arm_cdp:
2397   case ARM::BI__builtin_arm_cdp2:
2398   case ARM::BI__builtin_arm_mcr:
2399   case ARM::BI__builtin_arm_mcr2:
2400   case ARM::BI__builtin_arm_mrc:
2401   case ARM::BI__builtin_arm_mrc2:
2402   case ARM::BI__builtin_arm_mcrr:
2403   case ARM::BI__builtin_arm_mcrr2:
2404   case ARM::BI__builtin_arm_mrrc:
2405   case ARM::BI__builtin_arm_mrrc2:
2406   case ARM::BI__builtin_arm_ldc:
2407   case ARM::BI__builtin_arm_ldcl:
2408   case ARM::BI__builtin_arm_ldc2:
2409   case ARM::BI__builtin_arm_ldc2l:
2410   case ARM::BI__builtin_arm_stc:
2411   case ARM::BI__builtin_arm_stcl:
2412   case ARM::BI__builtin_arm_stc2:
2413   case ARM::BI__builtin_arm_stc2l:
2414     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) ||
2415            CheckARMCoprocessorImmediate(TheCall->getArg(0), /*WantCDE*/ false);
2416   }
2417 }
2418 
2419 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
2420                                          CallExpr *TheCall) {
2421   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2422       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2423       BuiltinID == AArch64::BI__builtin_arm_strex ||
2424       BuiltinID == AArch64::BI__builtin_arm_stlex) {
2425     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
2426   }
2427 
2428   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
2429     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2430       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
2431       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
2432       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
2433   }
2434 
2435   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2436       BuiltinID == AArch64::BI__builtin_arm_wsr64)
2437     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2438 
2439   // Memory Tagging Extensions (MTE) Intrinsics
2440   if (BuiltinID == AArch64::BI__builtin_arm_irg ||
2441       BuiltinID == AArch64::BI__builtin_arm_addg ||
2442       BuiltinID == AArch64::BI__builtin_arm_gmi ||
2443       BuiltinID == AArch64::BI__builtin_arm_ldg ||
2444       BuiltinID == AArch64::BI__builtin_arm_stg ||
2445       BuiltinID == AArch64::BI__builtin_arm_subp) {
2446     return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
2447   }
2448 
2449   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
2450       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2451       BuiltinID == AArch64::BI__builtin_arm_wsr ||
2452       BuiltinID == AArch64::BI__builtin_arm_wsrp)
2453     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2454 
2455   // Only check the valid encoding range. Any constant in this range would be
2456   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
2457   // an exception for incorrect registers. This matches MSVC behavior.
2458   if (BuiltinID == AArch64::BI_ReadStatusReg ||
2459       BuiltinID == AArch64::BI_WriteStatusReg)
2460     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
2461 
2462   if (BuiltinID == AArch64::BI__getReg)
2463     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
2464 
2465   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
2466     return true;
2467 
2468   if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall))
2469     return true;
2470 
2471   // For intrinsics which take an immediate value as part of the instruction,
2472   // range check them here.
2473   unsigned i = 0, l = 0, u = 0;
2474   switch (BuiltinID) {
2475   default: return false;
2476   case AArch64::BI__builtin_arm_dmb:
2477   case AArch64::BI__builtin_arm_dsb:
2478   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
2479   case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
2480   }
2481 
2482   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2483 }
2484 
2485 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
2486                                        CallExpr *TheCall) {
2487   assert(BuiltinID == BPF::BI__builtin_preserve_field_info &&
2488          "unexpected ARM builtin");
2489 
2490   if (checkArgCount(*this, TheCall, 2))
2491     return true;
2492 
2493   // The first argument needs to be a record field access.
2494   // If it is an array element access, we delay decision
2495   // to BPF backend to check whether the access is a
2496   // field access or not.
2497   Expr *Arg = TheCall->getArg(0);
2498   if (Arg->getType()->getAsPlaceholderType() ||
2499       (Arg->IgnoreParens()->getObjectKind() != OK_BitField &&
2500        !dyn_cast<MemberExpr>(Arg->IgnoreParens()) &&
2501        !dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens()))) {
2502     Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_field)
2503         << 1 << Arg->getSourceRange();
2504     return true;
2505   }
2506 
2507   // The second argument needs to be a constant int
2508   llvm::APSInt Value;
2509   if (!TheCall->getArg(1)->isIntegerConstantExpr(Value, Context)) {
2510     Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_const)
2511         << 2 << Arg->getSourceRange();
2512     return true;
2513   }
2514 
2515   TheCall->setType(Context.UnsignedIntTy);
2516   return false;
2517 }
2518 
2519 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2520   struct ArgInfo {
2521     uint8_t OpNum;
2522     bool IsSigned;
2523     uint8_t BitWidth;
2524     uint8_t Align;
2525   };
2526   struct BuiltinInfo {
2527     unsigned BuiltinID;
2528     ArgInfo Infos[2];
2529   };
2530 
2531   static BuiltinInfo Infos[] = {
2532     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
2533     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
2534     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
2535     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  1 }} },
2536     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
2537     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
2538     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
2539     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
2540     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
2541     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
2542     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
2543 
2544     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
2545     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
2546     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
2547     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
2548     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
2549     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
2550     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
2551     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
2552     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
2553     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
2554     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
2555 
2556     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
2557     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
2558     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
2559     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
2560     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
2561     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
2562     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
2563     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
2564     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
2565     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
2566     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
2567     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
2568     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
2569     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
2570     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
2571     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
2572     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
2573     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
2574     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
2575     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
2576     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
2577     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
2578     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
2579     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
2580     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
2581     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
2582     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
2583     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
2584     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
2585     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
2586     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
2587     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
2588     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
2589     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
2590     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
2591     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
2592     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
2593     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
2594     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
2595     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
2596     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
2597     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
2598     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
2599     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
2600     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
2601     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
2602     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
2603     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
2604     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
2605     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
2606     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
2607     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
2608                                                       {{ 1, false, 6,  0 }} },
2609     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
2610     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
2611     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
2612     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
2613     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
2614     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
2615     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
2616                                                       {{ 1, false, 5,  0 }} },
2617     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
2618     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
2619     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
2620     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
2621     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
2622     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
2623                                                        { 2, false, 5,  0 }} },
2624     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
2625                                                        { 2, false, 6,  0 }} },
2626     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
2627                                                        { 3, false, 5,  0 }} },
2628     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
2629                                                        { 3, false, 6,  0 }} },
2630     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
2631     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
2632     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
2633     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
2634     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
2635     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
2636     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
2637     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
2638     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
2639     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
2640     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
2641     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
2642     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
2643     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
2644     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
2645     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
2646                                                       {{ 2, false, 4,  0 },
2647                                                        { 3, false, 5,  0 }} },
2648     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
2649                                                       {{ 2, false, 4,  0 },
2650                                                        { 3, false, 5,  0 }} },
2651     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
2652                                                       {{ 2, false, 4,  0 },
2653                                                        { 3, false, 5,  0 }} },
2654     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
2655                                                       {{ 2, false, 4,  0 },
2656                                                        { 3, false, 5,  0 }} },
2657     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
2658     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
2659     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
2660     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
2661     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
2662     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
2663     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
2664     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
2665     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
2666     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
2667     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
2668                                                        { 2, false, 5,  0 }} },
2669     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
2670                                                        { 2, false, 6,  0 }} },
2671     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
2672     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
2673     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
2674     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
2675     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
2676     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
2677     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
2678     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
2679     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
2680                                                       {{ 1, false, 4,  0 }} },
2681     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
2682     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
2683                                                       {{ 1, false, 4,  0 }} },
2684     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
2685     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
2686     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
2687     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
2688     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
2689     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
2690     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
2691     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
2692     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
2693     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
2694     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
2695     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
2696     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
2697     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
2698     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
2699     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
2700     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
2701     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
2702     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
2703     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
2704                                                       {{ 3, false, 1,  0 }} },
2705     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
2706     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
2707     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
2708     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
2709                                                       {{ 3, false, 1,  0 }} },
2710     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
2711     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
2712     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
2713     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
2714                                                       {{ 3, false, 1,  0 }} },
2715   };
2716 
2717   // Use a dynamically initialized static to sort the table exactly once on
2718   // first run.
2719   static const bool SortOnce =
2720       (llvm::sort(Infos,
2721                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
2722                    return LHS.BuiltinID < RHS.BuiltinID;
2723                  }),
2724        true);
2725   (void)SortOnce;
2726 
2727   const BuiltinInfo *F = llvm::partition_point(
2728       Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
2729   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
2730     return false;
2731 
2732   bool Error = false;
2733 
2734   for (const ArgInfo &A : F->Infos) {
2735     // Ignore empty ArgInfo elements.
2736     if (A.BitWidth == 0)
2737       continue;
2738 
2739     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
2740     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
2741     if (!A.Align) {
2742       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
2743     } else {
2744       unsigned M = 1 << A.Align;
2745       Min *= M;
2746       Max *= M;
2747       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
2748                SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
2749     }
2750   }
2751   return Error;
2752 }
2753 
2754 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
2755                                            CallExpr *TheCall) {
2756   return CheckHexagonBuiltinArgument(BuiltinID, TheCall);
2757 }
2758 
2759 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2760   return CheckMipsBuiltinCpu(BuiltinID, TheCall) ||
2761          CheckMipsBuiltinArgument(BuiltinID, TheCall);
2762 }
2763 
2764 bool Sema::CheckMipsBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) {
2765   const TargetInfo &TI = Context.getTargetInfo();
2766 
2767   if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
2768       BuiltinID <= Mips::BI__builtin_mips_lwx) {
2769     if (!TI.hasFeature("dsp"))
2770       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
2771   }
2772 
2773   if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
2774       BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
2775     if (!TI.hasFeature("dspr2"))
2776       return Diag(TheCall->getBeginLoc(),
2777                   diag::err_mips_builtin_requires_dspr2);
2778   }
2779 
2780   if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
2781       BuiltinID <= Mips::BI__builtin_msa_xori_b) {
2782     if (!TI.hasFeature("msa"))
2783       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
2784   }
2785 
2786   return false;
2787 }
2788 
2789 // CheckMipsBuiltinArgument - Checks the constant value passed to the
2790 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
2791 // ordering for DSP is unspecified. MSA is ordered by the data format used
2792 // by the underlying instruction i.e., df/m, df/n and then by size.
2793 //
2794 // FIXME: The size tests here should instead be tablegen'd along with the
2795 //        definitions from include/clang/Basic/BuiltinsMips.def.
2796 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
2797 //        be too.
2798 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2799   unsigned i = 0, l = 0, u = 0, m = 0;
2800   switch (BuiltinID) {
2801   default: return false;
2802   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
2803   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
2804   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
2805   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
2806   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
2807   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
2808   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
2809   // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
2810   // df/m field.
2811   // These intrinsics take an unsigned 3 bit immediate.
2812   case Mips::BI__builtin_msa_bclri_b:
2813   case Mips::BI__builtin_msa_bnegi_b:
2814   case Mips::BI__builtin_msa_bseti_b:
2815   case Mips::BI__builtin_msa_sat_s_b:
2816   case Mips::BI__builtin_msa_sat_u_b:
2817   case Mips::BI__builtin_msa_slli_b:
2818   case Mips::BI__builtin_msa_srai_b:
2819   case Mips::BI__builtin_msa_srari_b:
2820   case Mips::BI__builtin_msa_srli_b:
2821   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
2822   case Mips::BI__builtin_msa_binsli_b:
2823   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
2824   // These intrinsics take an unsigned 4 bit immediate.
2825   case Mips::BI__builtin_msa_bclri_h:
2826   case Mips::BI__builtin_msa_bnegi_h:
2827   case Mips::BI__builtin_msa_bseti_h:
2828   case Mips::BI__builtin_msa_sat_s_h:
2829   case Mips::BI__builtin_msa_sat_u_h:
2830   case Mips::BI__builtin_msa_slli_h:
2831   case Mips::BI__builtin_msa_srai_h:
2832   case Mips::BI__builtin_msa_srari_h:
2833   case Mips::BI__builtin_msa_srli_h:
2834   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
2835   case Mips::BI__builtin_msa_binsli_h:
2836   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
2837   // These intrinsics take an unsigned 5 bit immediate.
2838   // The first block of intrinsics actually have an unsigned 5 bit field,
2839   // not a df/n field.
2840   case Mips::BI__builtin_msa_cfcmsa:
2841   case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
2842   case Mips::BI__builtin_msa_clei_u_b:
2843   case Mips::BI__builtin_msa_clei_u_h:
2844   case Mips::BI__builtin_msa_clei_u_w:
2845   case Mips::BI__builtin_msa_clei_u_d:
2846   case Mips::BI__builtin_msa_clti_u_b:
2847   case Mips::BI__builtin_msa_clti_u_h:
2848   case Mips::BI__builtin_msa_clti_u_w:
2849   case Mips::BI__builtin_msa_clti_u_d:
2850   case Mips::BI__builtin_msa_maxi_u_b:
2851   case Mips::BI__builtin_msa_maxi_u_h:
2852   case Mips::BI__builtin_msa_maxi_u_w:
2853   case Mips::BI__builtin_msa_maxi_u_d:
2854   case Mips::BI__builtin_msa_mini_u_b:
2855   case Mips::BI__builtin_msa_mini_u_h:
2856   case Mips::BI__builtin_msa_mini_u_w:
2857   case Mips::BI__builtin_msa_mini_u_d:
2858   case Mips::BI__builtin_msa_addvi_b:
2859   case Mips::BI__builtin_msa_addvi_h:
2860   case Mips::BI__builtin_msa_addvi_w:
2861   case Mips::BI__builtin_msa_addvi_d:
2862   case Mips::BI__builtin_msa_bclri_w:
2863   case Mips::BI__builtin_msa_bnegi_w:
2864   case Mips::BI__builtin_msa_bseti_w:
2865   case Mips::BI__builtin_msa_sat_s_w:
2866   case Mips::BI__builtin_msa_sat_u_w:
2867   case Mips::BI__builtin_msa_slli_w:
2868   case Mips::BI__builtin_msa_srai_w:
2869   case Mips::BI__builtin_msa_srari_w:
2870   case Mips::BI__builtin_msa_srli_w:
2871   case Mips::BI__builtin_msa_srlri_w:
2872   case Mips::BI__builtin_msa_subvi_b:
2873   case Mips::BI__builtin_msa_subvi_h:
2874   case Mips::BI__builtin_msa_subvi_w:
2875   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
2876   case Mips::BI__builtin_msa_binsli_w:
2877   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
2878   // These intrinsics take an unsigned 6 bit immediate.
2879   case Mips::BI__builtin_msa_bclri_d:
2880   case Mips::BI__builtin_msa_bnegi_d:
2881   case Mips::BI__builtin_msa_bseti_d:
2882   case Mips::BI__builtin_msa_sat_s_d:
2883   case Mips::BI__builtin_msa_sat_u_d:
2884   case Mips::BI__builtin_msa_slli_d:
2885   case Mips::BI__builtin_msa_srai_d:
2886   case Mips::BI__builtin_msa_srari_d:
2887   case Mips::BI__builtin_msa_srli_d:
2888   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
2889   case Mips::BI__builtin_msa_binsli_d:
2890   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
2891   // These intrinsics take a signed 5 bit immediate.
2892   case Mips::BI__builtin_msa_ceqi_b:
2893   case Mips::BI__builtin_msa_ceqi_h:
2894   case Mips::BI__builtin_msa_ceqi_w:
2895   case Mips::BI__builtin_msa_ceqi_d:
2896   case Mips::BI__builtin_msa_clti_s_b:
2897   case Mips::BI__builtin_msa_clti_s_h:
2898   case Mips::BI__builtin_msa_clti_s_w:
2899   case Mips::BI__builtin_msa_clti_s_d:
2900   case Mips::BI__builtin_msa_clei_s_b:
2901   case Mips::BI__builtin_msa_clei_s_h:
2902   case Mips::BI__builtin_msa_clei_s_w:
2903   case Mips::BI__builtin_msa_clei_s_d:
2904   case Mips::BI__builtin_msa_maxi_s_b:
2905   case Mips::BI__builtin_msa_maxi_s_h:
2906   case Mips::BI__builtin_msa_maxi_s_w:
2907   case Mips::BI__builtin_msa_maxi_s_d:
2908   case Mips::BI__builtin_msa_mini_s_b:
2909   case Mips::BI__builtin_msa_mini_s_h:
2910   case Mips::BI__builtin_msa_mini_s_w:
2911   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
2912   // These intrinsics take an unsigned 8 bit immediate.
2913   case Mips::BI__builtin_msa_andi_b:
2914   case Mips::BI__builtin_msa_nori_b:
2915   case Mips::BI__builtin_msa_ori_b:
2916   case Mips::BI__builtin_msa_shf_b:
2917   case Mips::BI__builtin_msa_shf_h:
2918   case Mips::BI__builtin_msa_shf_w:
2919   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
2920   case Mips::BI__builtin_msa_bseli_b:
2921   case Mips::BI__builtin_msa_bmnzi_b:
2922   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
2923   // df/n format
2924   // These intrinsics take an unsigned 4 bit immediate.
2925   case Mips::BI__builtin_msa_copy_s_b:
2926   case Mips::BI__builtin_msa_copy_u_b:
2927   case Mips::BI__builtin_msa_insve_b:
2928   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
2929   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
2930   // These intrinsics take an unsigned 3 bit immediate.
2931   case Mips::BI__builtin_msa_copy_s_h:
2932   case Mips::BI__builtin_msa_copy_u_h:
2933   case Mips::BI__builtin_msa_insve_h:
2934   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
2935   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
2936   // These intrinsics take an unsigned 2 bit immediate.
2937   case Mips::BI__builtin_msa_copy_s_w:
2938   case Mips::BI__builtin_msa_copy_u_w:
2939   case Mips::BI__builtin_msa_insve_w:
2940   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
2941   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
2942   // These intrinsics take an unsigned 1 bit immediate.
2943   case Mips::BI__builtin_msa_copy_s_d:
2944   case Mips::BI__builtin_msa_copy_u_d:
2945   case Mips::BI__builtin_msa_insve_d:
2946   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
2947   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
2948   // Memory offsets and immediate loads.
2949   // These intrinsics take a signed 10 bit immediate.
2950   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
2951   case Mips::BI__builtin_msa_ldi_h:
2952   case Mips::BI__builtin_msa_ldi_w:
2953   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
2954   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
2955   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
2956   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
2957   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
2958   case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break;
2959   case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break;
2960   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
2961   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
2962   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
2963   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
2964   case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break;
2965   case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break;
2966   }
2967 
2968   if (!m)
2969     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2970 
2971   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
2972          SemaBuiltinConstantArgMultiple(TheCall, i, m);
2973 }
2974 
2975 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2976   unsigned i = 0, l = 0, u = 0;
2977   bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
2978                       BuiltinID == PPC::BI__builtin_divdeu ||
2979                       BuiltinID == PPC::BI__builtin_bpermd;
2980   bool IsTarget64Bit = Context.getTargetInfo()
2981                               .getTypeWidth(Context
2982                                             .getTargetInfo()
2983                                             .getIntPtrType()) == 64;
2984   bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
2985                        BuiltinID == PPC::BI__builtin_divweu ||
2986                        BuiltinID == PPC::BI__builtin_divde ||
2987                        BuiltinID == PPC::BI__builtin_divdeu;
2988 
2989   if (Is64BitBltin && !IsTarget64Bit)
2990     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
2991            << TheCall->getSourceRange();
2992 
2993   if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
2994       (BuiltinID == PPC::BI__builtin_bpermd &&
2995        !Context.getTargetInfo().hasFeature("bpermd")))
2996     return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
2997            << TheCall->getSourceRange();
2998 
2999   auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool {
3000     if (!Context.getTargetInfo().hasFeature("vsx"))
3001       return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3002              << TheCall->getSourceRange();
3003     return false;
3004   };
3005 
3006   switch (BuiltinID) {
3007   default: return false;
3008   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3009   case PPC::BI__builtin_altivec_crypto_vshasigmad:
3010     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3011            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3012   case PPC::BI__builtin_altivec_dss:
3013     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
3014   case PPC::BI__builtin_tbegin:
3015   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
3016   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
3017   case PPC::BI__builtin_tabortwc:
3018   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
3019   case PPC::BI__builtin_tabortwci:
3020   case PPC::BI__builtin_tabortdci:
3021     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3022            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
3023   case PPC::BI__builtin_altivec_dst:
3024   case PPC::BI__builtin_altivec_dstt:
3025   case PPC::BI__builtin_altivec_dstst:
3026   case PPC::BI__builtin_altivec_dststt:
3027     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
3028   case PPC::BI__builtin_vsx_xxpermdi:
3029   case PPC::BI__builtin_vsx_xxsldwi:
3030     return SemaBuiltinVSX(TheCall);
3031   case PPC::BI__builtin_unpack_vector_int128:
3032     return SemaVSXCheck(TheCall) ||
3033            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3034   case PPC::BI__builtin_pack_vector_int128:
3035     return SemaVSXCheck(TheCall);
3036   }
3037   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3038 }
3039 
3040 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID,
3041                                           CallExpr *TheCall) {
3042   switch (BuiltinID) {
3043   case AMDGPU::BI__builtin_amdgcn_fence: {
3044     ExprResult Arg = TheCall->getArg(0);
3045     auto ArgExpr = Arg.get();
3046     Expr::EvalResult ArgResult;
3047 
3048     if (!ArgExpr->EvaluateAsInt(ArgResult, Context))
3049       return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int)
3050              << ArgExpr->getType();
3051     int ord = ArgResult.Val.getInt().getZExtValue();
3052 
3053     // Check valididty of memory ordering as per C11 / C++11's memody model.
3054     switch (static_cast<llvm::AtomicOrderingCABI>(ord)) {
3055     case llvm::AtomicOrderingCABI::acquire:
3056     case llvm::AtomicOrderingCABI::release:
3057     case llvm::AtomicOrderingCABI::acq_rel:
3058     case llvm::AtomicOrderingCABI::seq_cst:
3059       break;
3060     default: {
3061       return Diag(ArgExpr->getBeginLoc(),
3062                   diag::warn_atomic_op_has_invalid_memory_order)
3063              << ArgExpr->getSourceRange();
3064     }
3065     }
3066 
3067     Arg = TheCall->getArg(1);
3068     ArgExpr = Arg.get();
3069     Expr::EvalResult ArgResult1;
3070     // Check that sync scope is a constant literal
3071     if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Expr::EvaluateForCodeGen,
3072                                          Context))
3073       return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal)
3074              << ArgExpr->getType();
3075   } break;
3076   }
3077   return false;
3078 }
3079 
3080 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3081                                            CallExpr *TheCall) {
3082   if (BuiltinID == SystemZ::BI__builtin_tabort) {
3083     Expr *Arg = TheCall->getArg(0);
3084     llvm::APSInt AbortCode(32);
3085     if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
3086         AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
3087       return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
3088              << Arg->getSourceRange();
3089   }
3090 
3091   // For intrinsics which take an immediate value as part of the instruction,
3092   // range check them here.
3093   unsigned i = 0, l = 0, u = 0;
3094   switch (BuiltinID) {
3095   default: return false;
3096   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3097   case SystemZ::BI__builtin_s390_verimb:
3098   case SystemZ::BI__builtin_s390_verimh:
3099   case SystemZ::BI__builtin_s390_verimf:
3100   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
3101   case SystemZ::BI__builtin_s390_vfaeb:
3102   case SystemZ::BI__builtin_s390_vfaeh:
3103   case SystemZ::BI__builtin_s390_vfaef:
3104   case SystemZ::BI__builtin_s390_vfaebs:
3105   case SystemZ::BI__builtin_s390_vfaehs:
3106   case SystemZ::BI__builtin_s390_vfaefs:
3107   case SystemZ::BI__builtin_s390_vfaezb:
3108   case SystemZ::BI__builtin_s390_vfaezh:
3109   case SystemZ::BI__builtin_s390_vfaezf:
3110   case SystemZ::BI__builtin_s390_vfaezbs:
3111   case SystemZ::BI__builtin_s390_vfaezhs:
3112   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
3113   case SystemZ::BI__builtin_s390_vfisb:
3114   case SystemZ::BI__builtin_s390_vfidb:
3115     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3116            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3117   case SystemZ::BI__builtin_s390_vftcisb:
3118   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3119   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3120   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3121   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3122   case SystemZ::BI__builtin_s390_vstrcb:
3123   case SystemZ::BI__builtin_s390_vstrch:
3124   case SystemZ::BI__builtin_s390_vstrcf:
3125   case SystemZ::BI__builtin_s390_vstrczb:
3126   case SystemZ::BI__builtin_s390_vstrczh:
3127   case SystemZ::BI__builtin_s390_vstrczf:
3128   case SystemZ::BI__builtin_s390_vstrcbs:
3129   case SystemZ::BI__builtin_s390_vstrchs:
3130   case SystemZ::BI__builtin_s390_vstrcfs:
3131   case SystemZ::BI__builtin_s390_vstrczbs:
3132   case SystemZ::BI__builtin_s390_vstrczhs:
3133   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
3134   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3135   case SystemZ::BI__builtin_s390_vfminsb:
3136   case SystemZ::BI__builtin_s390_vfmaxsb:
3137   case SystemZ::BI__builtin_s390_vfmindb:
3138   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
3139   case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
3140   case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
3141   }
3142   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3143 }
3144 
3145 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3146 /// This checks that the target supports __builtin_cpu_supports and
3147 /// that the string argument is constant and valid.
3148 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
3149   Expr *Arg = TheCall->getArg(0);
3150 
3151   // Check if the argument is a string literal.
3152   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3153     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3154            << Arg->getSourceRange();
3155 
3156   // Check the contents of the string.
3157   StringRef Feature =
3158       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3159   if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
3160     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
3161            << Arg->getSourceRange();
3162   return false;
3163 }
3164 
3165 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3166 /// This checks that the target supports __builtin_cpu_is and
3167 /// that the string argument is constant and valid.
3168 static bool SemaBuiltinCpuIs(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().validateCpuIs(Feature))
3180     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
3181            << Arg->getSourceRange();
3182   return false;
3183 }
3184 
3185 // Check if the rounding mode is legal.
3186 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3187   // Indicates if this instruction has rounding control or just SAE.
3188   bool HasRC = false;
3189 
3190   unsigned ArgNum = 0;
3191   switch (BuiltinID) {
3192   default:
3193     return false;
3194   case X86::BI__builtin_ia32_vcvttsd2si32:
3195   case X86::BI__builtin_ia32_vcvttsd2si64:
3196   case X86::BI__builtin_ia32_vcvttsd2usi32:
3197   case X86::BI__builtin_ia32_vcvttsd2usi64:
3198   case X86::BI__builtin_ia32_vcvttss2si32:
3199   case X86::BI__builtin_ia32_vcvttss2si64:
3200   case X86::BI__builtin_ia32_vcvttss2usi32:
3201   case X86::BI__builtin_ia32_vcvttss2usi64:
3202     ArgNum = 1;
3203     break;
3204   case X86::BI__builtin_ia32_maxpd512:
3205   case X86::BI__builtin_ia32_maxps512:
3206   case X86::BI__builtin_ia32_minpd512:
3207   case X86::BI__builtin_ia32_minps512:
3208     ArgNum = 2;
3209     break;
3210   case X86::BI__builtin_ia32_cvtps2pd512_mask:
3211   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
3212   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
3213   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
3214   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
3215   case X86::BI__builtin_ia32_cvttps2dq512_mask:
3216   case X86::BI__builtin_ia32_cvttps2qq512_mask:
3217   case X86::BI__builtin_ia32_cvttps2udq512_mask:
3218   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
3219   case X86::BI__builtin_ia32_exp2pd_mask:
3220   case X86::BI__builtin_ia32_exp2ps_mask:
3221   case X86::BI__builtin_ia32_getexppd512_mask:
3222   case X86::BI__builtin_ia32_getexpps512_mask:
3223   case X86::BI__builtin_ia32_rcp28pd_mask:
3224   case X86::BI__builtin_ia32_rcp28ps_mask:
3225   case X86::BI__builtin_ia32_rsqrt28pd_mask:
3226   case X86::BI__builtin_ia32_rsqrt28ps_mask:
3227   case X86::BI__builtin_ia32_vcomisd:
3228   case X86::BI__builtin_ia32_vcomiss:
3229   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
3230     ArgNum = 3;
3231     break;
3232   case X86::BI__builtin_ia32_cmppd512_mask:
3233   case X86::BI__builtin_ia32_cmpps512_mask:
3234   case X86::BI__builtin_ia32_cmpsd_mask:
3235   case X86::BI__builtin_ia32_cmpss_mask:
3236   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
3237   case X86::BI__builtin_ia32_getexpsd128_round_mask:
3238   case X86::BI__builtin_ia32_getexpss128_round_mask:
3239   case X86::BI__builtin_ia32_getmantpd512_mask:
3240   case X86::BI__builtin_ia32_getmantps512_mask:
3241   case X86::BI__builtin_ia32_maxsd_round_mask:
3242   case X86::BI__builtin_ia32_maxss_round_mask:
3243   case X86::BI__builtin_ia32_minsd_round_mask:
3244   case X86::BI__builtin_ia32_minss_round_mask:
3245   case X86::BI__builtin_ia32_rcp28sd_round_mask:
3246   case X86::BI__builtin_ia32_rcp28ss_round_mask:
3247   case X86::BI__builtin_ia32_reducepd512_mask:
3248   case X86::BI__builtin_ia32_reduceps512_mask:
3249   case X86::BI__builtin_ia32_rndscalepd_mask:
3250   case X86::BI__builtin_ia32_rndscaleps_mask:
3251   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
3252   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
3253     ArgNum = 4;
3254     break;
3255   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3256   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3257   case X86::BI__builtin_ia32_fixupimmps512_mask:
3258   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3259   case X86::BI__builtin_ia32_fixupimmsd_mask:
3260   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3261   case X86::BI__builtin_ia32_fixupimmss_mask:
3262   case X86::BI__builtin_ia32_fixupimmss_maskz:
3263   case X86::BI__builtin_ia32_getmantsd_round_mask:
3264   case X86::BI__builtin_ia32_getmantss_round_mask:
3265   case X86::BI__builtin_ia32_rangepd512_mask:
3266   case X86::BI__builtin_ia32_rangeps512_mask:
3267   case X86::BI__builtin_ia32_rangesd128_round_mask:
3268   case X86::BI__builtin_ia32_rangess128_round_mask:
3269   case X86::BI__builtin_ia32_reducesd_mask:
3270   case X86::BI__builtin_ia32_reducess_mask:
3271   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3272   case X86::BI__builtin_ia32_rndscaless_round_mask:
3273     ArgNum = 5;
3274     break;
3275   case X86::BI__builtin_ia32_vcvtsd2si64:
3276   case X86::BI__builtin_ia32_vcvtsd2si32:
3277   case X86::BI__builtin_ia32_vcvtsd2usi32:
3278   case X86::BI__builtin_ia32_vcvtsd2usi64:
3279   case X86::BI__builtin_ia32_vcvtss2si32:
3280   case X86::BI__builtin_ia32_vcvtss2si64:
3281   case X86::BI__builtin_ia32_vcvtss2usi32:
3282   case X86::BI__builtin_ia32_vcvtss2usi64:
3283   case X86::BI__builtin_ia32_sqrtpd512:
3284   case X86::BI__builtin_ia32_sqrtps512:
3285     ArgNum = 1;
3286     HasRC = true;
3287     break;
3288   case X86::BI__builtin_ia32_addpd512:
3289   case X86::BI__builtin_ia32_addps512:
3290   case X86::BI__builtin_ia32_divpd512:
3291   case X86::BI__builtin_ia32_divps512:
3292   case X86::BI__builtin_ia32_mulpd512:
3293   case X86::BI__builtin_ia32_mulps512:
3294   case X86::BI__builtin_ia32_subpd512:
3295   case X86::BI__builtin_ia32_subps512:
3296   case X86::BI__builtin_ia32_cvtsi2sd64:
3297   case X86::BI__builtin_ia32_cvtsi2ss32:
3298   case X86::BI__builtin_ia32_cvtsi2ss64:
3299   case X86::BI__builtin_ia32_cvtusi2sd64:
3300   case X86::BI__builtin_ia32_cvtusi2ss32:
3301   case X86::BI__builtin_ia32_cvtusi2ss64:
3302     ArgNum = 2;
3303     HasRC = true;
3304     break;
3305   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
3306   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
3307   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
3308   case X86::BI__builtin_ia32_cvtpd2dq512_mask:
3309   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
3310   case X86::BI__builtin_ia32_cvtpd2udq512_mask:
3311   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
3312   case X86::BI__builtin_ia32_cvtps2dq512_mask:
3313   case X86::BI__builtin_ia32_cvtps2qq512_mask:
3314   case X86::BI__builtin_ia32_cvtps2udq512_mask:
3315   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
3316   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
3317   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
3318   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
3319   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
3320     ArgNum = 3;
3321     HasRC = true;
3322     break;
3323   case X86::BI__builtin_ia32_addss_round_mask:
3324   case X86::BI__builtin_ia32_addsd_round_mask:
3325   case X86::BI__builtin_ia32_divss_round_mask:
3326   case X86::BI__builtin_ia32_divsd_round_mask:
3327   case X86::BI__builtin_ia32_mulss_round_mask:
3328   case X86::BI__builtin_ia32_mulsd_round_mask:
3329   case X86::BI__builtin_ia32_subss_round_mask:
3330   case X86::BI__builtin_ia32_subsd_round_mask:
3331   case X86::BI__builtin_ia32_scalefpd512_mask:
3332   case X86::BI__builtin_ia32_scalefps512_mask:
3333   case X86::BI__builtin_ia32_scalefsd_round_mask:
3334   case X86::BI__builtin_ia32_scalefss_round_mask:
3335   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
3336   case X86::BI__builtin_ia32_sqrtsd_round_mask:
3337   case X86::BI__builtin_ia32_sqrtss_round_mask:
3338   case X86::BI__builtin_ia32_vfmaddsd3_mask:
3339   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
3340   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
3341   case X86::BI__builtin_ia32_vfmaddss3_mask:
3342   case X86::BI__builtin_ia32_vfmaddss3_maskz:
3343   case X86::BI__builtin_ia32_vfmaddss3_mask3:
3344   case X86::BI__builtin_ia32_vfmaddpd512_mask:
3345   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
3346   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
3347   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
3348   case X86::BI__builtin_ia32_vfmaddps512_mask:
3349   case X86::BI__builtin_ia32_vfmaddps512_maskz:
3350   case X86::BI__builtin_ia32_vfmaddps512_mask3:
3351   case X86::BI__builtin_ia32_vfmsubps512_mask3:
3352   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
3353   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
3354   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
3355   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
3356   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
3357   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
3358   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
3359   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
3360     ArgNum = 4;
3361     HasRC = true;
3362     break;
3363   }
3364 
3365   llvm::APSInt Result;
3366 
3367   // We can't check the value of a dependent argument.
3368   Expr *Arg = TheCall->getArg(ArgNum);
3369   if (Arg->isTypeDependent() || Arg->isValueDependent())
3370     return false;
3371 
3372   // Check constant-ness first.
3373   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3374     return true;
3375 
3376   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
3377   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
3378   // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
3379   // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
3380   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
3381       Result == 8/*ROUND_NO_EXC*/ ||
3382       (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
3383       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
3384     return false;
3385 
3386   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
3387          << Arg->getSourceRange();
3388 }
3389 
3390 // Check if the gather/scatter scale is legal.
3391 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
3392                                              CallExpr *TheCall) {
3393   unsigned ArgNum = 0;
3394   switch (BuiltinID) {
3395   default:
3396     return false;
3397   case X86::BI__builtin_ia32_gatherpfdpd:
3398   case X86::BI__builtin_ia32_gatherpfdps:
3399   case X86::BI__builtin_ia32_gatherpfqpd:
3400   case X86::BI__builtin_ia32_gatherpfqps:
3401   case X86::BI__builtin_ia32_scatterpfdpd:
3402   case X86::BI__builtin_ia32_scatterpfdps:
3403   case X86::BI__builtin_ia32_scatterpfqpd:
3404   case X86::BI__builtin_ia32_scatterpfqps:
3405     ArgNum = 3;
3406     break;
3407   case X86::BI__builtin_ia32_gatherd_pd:
3408   case X86::BI__builtin_ia32_gatherd_pd256:
3409   case X86::BI__builtin_ia32_gatherq_pd:
3410   case X86::BI__builtin_ia32_gatherq_pd256:
3411   case X86::BI__builtin_ia32_gatherd_ps:
3412   case X86::BI__builtin_ia32_gatherd_ps256:
3413   case X86::BI__builtin_ia32_gatherq_ps:
3414   case X86::BI__builtin_ia32_gatherq_ps256:
3415   case X86::BI__builtin_ia32_gatherd_q:
3416   case X86::BI__builtin_ia32_gatherd_q256:
3417   case X86::BI__builtin_ia32_gatherq_q:
3418   case X86::BI__builtin_ia32_gatherq_q256:
3419   case X86::BI__builtin_ia32_gatherd_d:
3420   case X86::BI__builtin_ia32_gatherd_d256:
3421   case X86::BI__builtin_ia32_gatherq_d:
3422   case X86::BI__builtin_ia32_gatherq_d256:
3423   case X86::BI__builtin_ia32_gather3div2df:
3424   case X86::BI__builtin_ia32_gather3div2di:
3425   case X86::BI__builtin_ia32_gather3div4df:
3426   case X86::BI__builtin_ia32_gather3div4di:
3427   case X86::BI__builtin_ia32_gather3div4sf:
3428   case X86::BI__builtin_ia32_gather3div4si:
3429   case X86::BI__builtin_ia32_gather3div8sf:
3430   case X86::BI__builtin_ia32_gather3div8si:
3431   case X86::BI__builtin_ia32_gather3siv2df:
3432   case X86::BI__builtin_ia32_gather3siv2di:
3433   case X86::BI__builtin_ia32_gather3siv4df:
3434   case X86::BI__builtin_ia32_gather3siv4di:
3435   case X86::BI__builtin_ia32_gather3siv4sf:
3436   case X86::BI__builtin_ia32_gather3siv4si:
3437   case X86::BI__builtin_ia32_gather3siv8sf:
3438   case X86::BI__builtin_ia32_gather3siv8si:
3439   case X86::BI__builtin_ia32_gathersiv8df:
3440   case X86::BI__builtin_ia32_gathersiv16sf:
3441   case X86::BI__builtin_ia32_gatherdiv8df:
3442   case X86::BI__builtin_ia32_gatherdiv16sf:
3443   case X86::BI__builtin_ia32_gathersiv8di:
3444   case X86::BI__builtin_ia32_gathersiv16si:
3445   case X86::BI__builtin_ia32_gatherdiv8di:
3446   case X86::BI__builtin_ia32_gatherdiv16si:
3447   case X86::BI__builtin_ia32_scatterdiv2df:
3448   case X86::BI__builtin_ia32_scatterdiv2di:
3449   case X86::BI__builtin_ia32_scatterdiv4df:
3450   case X86::BI__builtin_ia32_scatterdiv4di:
3451   case X86::BI__builtin_ia32_scatterdiv4sf:
3452   case X86::BI__builtin_ia32_scatterdiv4si:
3453   case X86::BI__builtin_ia32_scatterdiv8sf:
3454   case X86::BI__builtin_ia32_scatterdiv8si:
3455   case X86::BI__builtin_ia32_scattersiv2df:
3456   case X86::BI__builtin_ia32_scattersiv2di:
3457   case X86::BI__builtin_ia32_scattersiv4df:
3458   case X86::BI__builtin_ia32_scattersiv4di:
3459   case X86::BI__builtin_ia32_scattersiv4sf:
3460   case X86::BI__builtin_ia32_scattersiv4si:
3461   case X86::BI__builtin_ia32_scattersiv8sf:
3462   case X86::BI__builtin_ia32_scattersiv8si:
3463   case X86::BI__builtin_ia32_scattersiv8df:
3464   case X86::BI__builtin_ia32_scattersiv16sf:
3465   case X86::BI__builtin_ia32_scatterdiv8df:
3466   case X86::BI__builtin_ia32_scatterdiv16sf:
3467   case X86::BI__builtin_ia32_scattersiv8di:
3468   case X86::BI__builtin_ia32_scattersiv16si:
3469   case X86::BI__builtin_ia32_scatterdiv8di:
3470   case X86::BI__builtin_ia32_scatterdiv16si:
3471     ArgNum = 4;
3472     break;
3473   }
3474 
3475   llvm::APSInt Result;
3476 
3477   // We can't check the value of a dependent argument.
3478   Expr *Arg = TheCall->getArg(ArgNum);
3479   if (Arg->isTypeDependent() || Arg->isValueDependent())
3480     return false;
3481 
3482   // Check constant-ness first.
3483   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3484     return true;
3485 
3486   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
3487     return false;
3488 
3489   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
3490          << Arg->getSourceRange();
3491 }
3492 
3493 static bool isX86_32Builtin(unsigned BuiltinID) {
3494   // These builtins only work on x86-32 targets.
3495   switch (BuiltinID) {
3496   case X86::BI__builtin_ia32_readeflags_u32:
3497   case X86::BI__builtin_ia32_writeeflags_u32:
3498     return true;
3499   }
3500 
3501   return false;
3502 }
3503 
3504 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3505   if (BuiltinID == X86::BI__builtin_cpu_supports)
3506     return SemaBuiltinCpuSupports(*this, TheCall);
3507 
3508   if (BuiltinID == X86::BI__builtin_cpu_is)
3509     return SemaBuiltinCpuIs(*this, TheCall);
3510 
3511   // Check for 32-bit only builtins on a 64-bit target.
3512   const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3513   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
3514     return Diag(TheCall->getCallee()->getBeginLoc(),
3515                 diag::err_32_bit_builtin_64_bit_tgt);
3516 
3517   // If the intrinsic has rounding or SAE make sure its valid.
3518   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
3519     return true;
3520 
3521   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
3522   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
3523     return true;
3524 
3525   // For intrinsics which take an immediate value as part of the instruction,
3526   // range check them here.
3527   int i = 0, l = 0, u = 0;
3528   switch (BuiltinID) {
3529   default:
3530     return false;
3531   case X86::BI__builtin_ia32_vec_ext_v2si:
3532   case X86::BI__builtin_ia32_vec_ext_v2di:
3533   case X86::BI__builtin_ia32_vextractf128_pd256:
3534   case X86::BI__builtin_ia32_vextractf128_ps256:
3535   case X86::BI__builtin_ia32_vextractf128_si256:
3536   case X86::BI__builtin_ia32_extract128i256:
3537   case X86::BI__builtin_ia32_extractf64x4_mask:
3538   case X86::BI__builtin_ia32_extracti64x4_mask:
3539   case X86::BI__builtin_ia32_extractf32x8_mask:
3540   case X86::BI__builtin_ia32_extracti32x8_mask:
3541   case X86::BI__builtin_ia32_extractf64x2_256_mask:
3542   case X86::BI__builtin_ia32_extracti64x2_256_mask:
3543   case X86::BI__builtin_ia32_extractf32x4_256_mask:
3544   case X86::BI__builtin_ia32_extracti32x4_256_mask:
3545     i = 1; l = 0; u = 1;
3546     break;
3547   case X86::BI__builtin_ia32_vec_set_v2di:
3548   case X86::BI__builtin_ia32_vinsertf128_pd256:
3549   case X86::BI__builtin_ia32_vinsertf128_ps256:
3550   case X86::BI__builtin_ia32_vinsertf128_si256:
3551   case X86::BI__builtin_ia32_insert128i256:
3552   case X86::BI__builtin_ia32_insertf32x8:
3553   case X86::BI__builtin_ia32_inserti32x8:
3554   case X86::BI__builtin_ia32_insertf64x4:
3555   case X86::BI__builtin_ia32_inserti64x4:
3556   case X86::BI__builtin_ia32_insertf64x2_256:
3557   case X86::BI__builtin_ia32_inserti64x2_256:
3558   case X86::BI__builtin_ia32_insertf32x4_256:
3559   case X86::BI__builtin_ia32_inserti32x4_256:
3560     i = 2; l = 0; u = 1;
3561     break;
3562   case X86::BI__builtin_ia32_vpermilpd:
3563   case X86::BI__builtin_ia32_vec_ext_v4hi:
3564   case X86::BI__builtin_ia32_vec_ext_v4si:
3565   case X86::BI__builtin_ia32_vec_ext_v4sf:
3566   case X86::BI__builtin_ia32_vec_ext_v4di:
3567   case X86::BI__builtin_ia32_extractf32x4_mask:
3568   case X86::BI__builtin_ia32_extracti32x4_mask:
3569   case X86::BI__builtin_ia32_extractf64x2_512_mask:
3570   case X86::BI__builtin_ia32_extracti64x2_512_mask:
3571     i = 1; l = 0; u = 3;
3572     break;
3573   case X86::BI_mm_prefetch:
3574   case X86::BI__builtin_ia32_vec_ext_v8hi:
3575   case X86::BI__builtin_ia32_vec_ext_v8si:
3576     i = 1; l = 0; u = 7;
3577     break;
3578   case X86::BI__builtin_ia32_sha1rnds4:
3579   case X86::BI__builtin_ia32_blendpd:
3580   case X86::BI__builtin_ia32_shufpd:
3581   case X86::BI__builtin_ia32_vec_set_v4hi:
3582   case X86::BI__builtin_ia32_vec_set_v4si:
3583   case X86::BI__builtin_ia32_vec_set_v4di:
3584   case X86::BI__builtin_ia32_shuf_f32x4_256:
3585   case X86::BI__builtin_ia32_shuf_f64x2_256:
3586   case X86::BI__builtin_ia32_shuf_i32x4_256:
3587   case X86::BI__builtin_ia32_shuf_i64x2_256:
3588   case X86::BI__builtin_ia32_insertf64x2_512:
3589   case X86::BI__builtin_ia32_inserti64x2_512:
3590   case X86::BI__builtin_ia32_insertf32x4:
3591   case X86::BI__builtin_ia32_inserti32x4:
3592     i = 2; l = 0; u = 3;
3593     break;
3594   case X86::BI__builtin_ia32_vpermil2pd:
3595   case X86::BI__builtin_ia32_vpermil2pd256:
3596   case X86::BI__builtin_ia32_vpermil2ps:
3597   case X86::BI__builtin_ia32_vpermil2ps256:
3598     i = 3; l = 0; u = 3;
3599     break;
3600   case X86::BI__builtin_ia32_cmpb128_mask:
3601   case X86::BI__builtin_ia32_cmpw128_mask:
3602   case X86::BI__builtin_ia32_cmpd128_mask:
3603   case X86::BI__builtin_ia32_cmpq128_mask:
3604   case X86::BI__builtin_ia32_cmpb256_mask:
3605   case X86::BI__builtin_ia32_cmpw256_mask:
3606   case X86::BI__builtin_ia32_cmpd256_mask:
3607   case X86::BI__builtin_ia32_cmpq256_mask:
3608   case X86::BI__builtin_ia32_cmpb512_mask:
3609   case X86::BI__builtin_ia32_cmpw512_mask:
3610   case X86::BI__builtin_ia32_cmpd512_mask:
3611   case X86::BI__builtin_ia32_cmpq512_mask:
3612   case X86::BI__builtin_ia32_ucmpb128_mask:
3613   case X86::BI__builtin_ia32_ucmpw128_mask:
3614   case X86::BI__builtin_ia32_ucmpd128_mask:
3615   case X86::BI__builtin_ia32_ucmpq128_mask:
3616   case X86::BI__builtin_ia32_ucmpb256_mask:
3617   case X86::BI__builtin_ia32_ucmpw256_mask:
3618   case X86::BI__builtin_ia32_ucmpd256_mask:
3619   case X86::BI__builtin_ia32_ucmpq256_mask:
3620   case X86::BI__builtin_ia32_ucmpb512_mask:
3621   case X86::BI__builtin_ia32_ucmpw512_mask:
3622   case X86::BI__builtin_ia32_ucmpd512_mask:
3623   case X86::BI__builtin_ia32_ucmpq512_mask:
3624   case X86::BI__builtin_ia32_vpcomub:
3625   case X86::BI__builtin_ia32_vpcomuw:
3626   case X86::BI__builtin_ia32_vpcomud:
3627   case X86::BI__builtin_ia32_vpcomuq:
3628   case X86::BI__builtin_ia32_vpcomb:
3629   case X86::BI__builtin_ia32_vpcomw:
3630   case X86::BI__builtin_ia32_vpcomd:
3631   case X86::BI__builtin_ia32_vpcomq:
3632   case X86::BI__builtin_ia32_vec_set_v8hi:
3633   case X86::BI__builtin_ia32_vec_set_v8si:
3634     i = 2; l = 0; u = 7;
3635     break;
3636   case X86::BI__builtin_ia32_vpermilpd256:
3637   case X86::BI__builtin_ia32_roundps:
3638   case X86::BI__builtin_ia32_roundpd:
3639   case X86::BI__builtin_ia32_roundps256:
3640   case X86::BI__builtin_ia32_roundpd256:
3641   case X86::BI__builtin_ia32_getmantpd128_mask:
3642   case X86::BI__builtin_ia32_getmantpd256_mask:
3643   case X86::BI__builtin_ia32_getmantps128_mask:
3644   case X86::BI__builtin_ia32_getmantps256_mask:
3645   case X86::BI__builtin_ia32_getmantpd512_mask:
3646   case X86::BI__builtin_ia32_getmantps512_mask:
3647   case X86::BI__builtin_ia32_vec_ext_v16qi:
3648   case X86::BI__builtin_ia32_vec_ext_v16hi:
3649     i = 1; l = 0; u = 15;
3650     break;
3651   case X86::BI__builtin_ia32_pblendd128:
3652   case X86::BI__builtin_ia32_blendps:
3653   case X86::BI__builtin_ia32_blendpd256:
3654   case X86::BI__builtin_ia32_shufpd256:
3655   case X86::BI__builtin_ia32_roundss:
3656   case X86::BI__builtin_ia32_roundsd:
3657   case X86::BI__builtin_ia32_rangepd128_mask:
3658   case X86::BI__builtin_ia32_rangepd256_mask:
3659   case X86::BI__builtin_ia32_rangepd512_mask:
3660   case X86::BI__builtin_ia32_rangeps128_mask:
3661   case X86::BI__builtin_ia32_rangeps256_mask:
3662   case X86::BI__builtin_ia32_rangeps512_mask:
3663   case X86::BI__builtin_ia32_getmantsd_round_mask:
3664   case X86::BI__builtin_ia32_getmantss_round_mask:
3665   case X86::BI__builtin_ia32_vec_set_v16qi:
3666   case X86::BI__builtin_ia32_vec_set_v16hi:
3667     i = 2; l = 0; u = 15;
3668     break;
3669   case X86::BI__builtin_ia32_vec_ext_v32qi:
3670     i = 1; l = 0; u = 31;
3671     break;
3672   case X86::BI__builtin_ia32_cmpps:
3673   case X86::BI__builtin_ia32_cmpss:
3674   case X86::BI__builtin_ia32_cmppd:
3675   case X86::BI__builtin_ia32_cmpsd:
3676   case X86::BI__builtin_ia32_cmpps256:
3677   case X86::BI__builtin_ia32_cmppd256:
3678   case X86::BI__builtin_ia32_cmpps128_mask:
3679   case X86::BI__builtin_ia32_cmppd128_mask:
3680   case X86::BI__builtin_ia32_cmpps256_mask:
3681   case X86::BI__builtin_ia32_cmppd256_mask:
3682   case X86::BI__builtin_ia32_cmpps512_mask:
3683   case X86::BI__builtin_ia32_cmppd512_mask:
3684   case X86::BI__builtin_ia32_cmpsd_mask:
3685   case X86::BI__builtin_ia32_cmpss_mask:
3686   case X86::BI__builtin_ia32_vec_set_v32qi:
3687     i = 2; l = 0; u = 31;
3688     break;
3689   case X86::BI__builtin_ia32_permdf256:
3690   case X86::BI__builtin_ia32_permdi256:
3691   case X86::BI__builtin_ia32_permdf512:
3692   case X86::BI__builtin_ia32_permdi512:
3693   case X86::BI__builtin_ia32_vpermilps:
3694   case X86::BI__builtin_ia32_vpermilps256:
3695   case X86::BI__builtin_ia32_vpermilpd512:
3696   case X86::BI__builtin_ia32_vpermilps512:
3697   case X86::BI__builtin_ia32_pshufd:
3698   case X86::BI__builtin_ia32_pshufd256:
3699   case X86::BI__builtin_ia32_pshufd512:
3700   case X86::BI__builtin_ia32_pshufhw:
3701   case X86::BI__builtin_ia32_pshufhw256:
3702   case X86::BI__builtin_ia32_pshufhw512:
3703   case X86::BI__builtin_ia32_pshuflw:
3704   case X86::BI__builtin_ia32_pshuflw256:
3705   case X86::BI__builtin_ia32_pshuflw512:
3706   case X86::BI__builtin_ia32_vcvtps2ph:
3707   case X86::BI__builtin_ia32_vcvtps2ph_mask:
3708   case X86::BI__builtin_ia32_vcvtps2ph256:
3709   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
3710   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
3711   case X86::BI__builtin_ia32_rndscaleps_128_mask:
3712   case X86::BI__builtin_ia32_rndscalepd_128_mask:
3713   case X86::BI__builtin_ia32_rndscaleps_256_mask:
3714   case X86::BI__builtin_ia32_rndscalepd_256_mask:
3715   case X86::BI__builtin_ia32_rndscaleps_mask:
3716   case X86::BI__builtin_ia32_rndscalepd_mask:
3717   case X86::BI__builtin_ia32_reducepd128_mask:
3718   case X86::BI__builtin_ia32_reducepd256_mask:
3719   case X86::BI__builtin_ia32_reducepd512_mask:
3720   case X86::BI__builtin_ia32_reduceps128_mask:
3721   case X86::BI__builtin_ia32_reduceps256_mask:
3722   case X86::BI__builtin_ia32_reduceps512_mask:
3723   case X86::BI__builtin_ia32_prold512:
3724   case X86::BI__builtin_ia32_prolq512:
3725   case X86::BI__builtin_ia32_prold128:
3726   case X86::BI__builtin_ia32_prold256:
3727   case X86::BI__builtin_ia32_prolq128:
3728   case X86::BI__builtin_ia32_prolq256:
3729   case X86::BI__builtin_ia32_prord512:
3730   case X86::BI__builtin_ia32_prorq512:
3731   case X86::BI__builtin_ia32_prord128:
3732   case X86::BI__builtin_ia32_prord256:
3733   case X86::BI__builtin_ia32_prorq128:
3734   case X86::BI__builtin_ia32_prorq256:
3735   case X86::BI__builtin_ia32_fpclasspd128_mask:
3736   case X86::BI__builtin_ia32_fpclasspd256_mask:
3737   case X86::BI__builtin_ia32_fpclassps128_mask:
3738   case X86::BI__builtin_ia32_fpclassps256_mask:
3739   case X86::BI__builtin_ia32_fpclassps512_mask:
3740   case X86::BI__builtin_ia32_fpclasspd512_mask:
3741   case X86::BI__builtin_ia32_fpclasssd_mask:
3742   case X86::BI__builtin_ia32_fpclassss_mask:
3743   case X86::BI__builtin_ia32_pslldqi128_byteshift:
3744   case X86::BI__builtin_ia32_pslldqi256_byteshift:
3745   case X86::BI__builtin_ia32_pslldqi512_byteshift:
3746   case X86::BI__builtin_ia32_psrldqi128_byteshift:
3747   case X86::BI__builtin_ia32_psrldqi256_byteshift:
3748   case X86::BI__builtin_ia32_psrldqi512_byteshift:
3749   case X86::BI__builtin_ia32_kshiftliqi:
3750   case X86::BI__builtin_ia32_kshiftlihi:
3751   case X86::BI__builtin_ia32_kshiftlisi:
3752   case X86::BI__builtin_ia32_kshiftlidi:
3753   case X86::BI__builtin_ia32_kshiftriqi:
3754   case X86::BI__builtin_ia32_kshiftrihi:
3755   case X86::BI__builtin_ia32_kshiftrisi:
3756   case X86::BI__builtin_ia32_kshiftridi:
3757     i = 1; l = 0; u = 255;
3758     break;
3759   case X86::BI__builtin_ia32_vperm2f128_pd256:
3760   case X86::BI__builtin_ia32_vperm2f128_ps256:
3761   case X86::BI__builtin_ia32_vperm2f128_si256:
3762   case X86::BI__builtin_ia32_permti256:
3763   case X86::BI__builtin_ia32_pblendw128:
3764   case X86::BI__builtin_ia32_pblendw256:
3765   case X86::BI__builtin_ia32_blendps256:
3766   case X86::BI__builtin_ia32_pblendd256:
3767   case X86::BI__builtin_ia32_palignr128:
3768   case X86::BI__builtin_ia32_palignr256:
3769   case X86::BI__builtin_ia32_palignr512:
3770   case X86::BI__builtin_ia32_alignq512:
3771   case X86::BI__builtin_ia32_alignd512:
3772   case X86::BI__builtin_ia32_alignd128:
3773   case X86::BI__builtin_ia32_alignd256:
3774   case X86::BI__builtin_ia32_alignq128:
3775   case X86::BI__builtin_ia32_alignq256:
3776   case X86::BI__builtin_ia32_vcomisd:
3777   case X86::BI__builtin_ia32_vcomiss:
3778   case X86::BI__builtin_ia32_shuf_f32x4:
3779   case X86::BI__builtin_ia32_shuf_f64x2:
3780   case X86::BI__builtin_ia32_shuf_i32x4:
3781   case X86::BI__builtin_ia32_shuf_i64x2:
3782   case X86::BI__builtin_ia32_shufpd512:
3783   case X86::BI__builtin_ia32_shufps:
3784   case X86::BI__builtin_ia32_shufps256:
3785   case X86::BI__builtin_ia32_shufps512:
3786   case X86::BI__builtin_ia32_dbpsadbw128:
3787   case X86::BI__builtin_ia32_dbpsadbw256:
3788   case X86::BI__builtin_ia32_dbpsadbw512:
3789   case X86::BI__builtin_ia32_vpshldd128:
3790   case X86::BI__builtin_ia32_vpshldd256:
3791   case X86::BI__builtin_ia32_vpshldd512:
3792   case X86::BI__builtin_ia32_vpshldq128:
3793   case X86::BI__builtin_ia32_vpshldq256:
3794   case X86::BI__builtin_ia32_vpshldq512:
3795   case X86::BI__builtin_ia32_vpshldw128:
3796   case X86::BI__builtin_ia32_vpshldw256:
3797   case X86::BI__builtin_ia32_vpshldw512:
3798   case X86::BI__builtin_ia32_vpshrdd128:
3799   case X86::BI__builtin_ia32_vpshrdd256:
3800   case X86::BI__builtin_ia32_vpshrdd512:
3801   case X86::BI__builtin_ia32_vpshrdq128:
3802   case X86::BI__builtin_ia32_vpshrdq256:
3803   case X86::BI__builtin_ia32_vpshrdq512:
3804   case X86::BI__builtin_ia32_vpshrdw128:
3805   case X86::BI__builtin_ia32_vpshrdw256:
3806   case X86::BI__builtin_ia32_vpshrdw512:
3807     i = 2; l = 0; u = 255;
3808     break;
3809   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3810   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3811   case X86::BI__builtin_ia32_fixupimmps512_mask:
3812   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3813   case X86::BI__builtin_ia32_fixupimmsd_mask:
3814   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3815   case X86::BI__builtin_ia32_fixupimmss_mask:
3816   case X86::BI__builtin_ia32_fixupimmss_maskz:
3817   case X86::BI__builtin_ia32_fixupimmpd128_mask:
3818   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
3819   case X86::BI__builtin_ia32_fixupimmpd256_mask:
3820   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
3821   case X86::BI__builtin_ia32_fixupimmps128_mask:
3822   case X86::BI__builtin_ia32_fixupimmps128_maskz:
3823   case X86::BI__builtin_ia32_fixupimmps256_mask:
3824   case X86::BI__builtin_ia32_fixupimmps256_maskz:
3825   case X86::BI__builtin_ia32_pternlogd512_mask:
3826   case X86::BI__builtin_ia32_pternlogd512_maskz:
3827   case X86::BI__builtin_ia32_pternlogq512_mask:
3828   case X86::BI__builtin_ia32_pternlogq512_maskz:
3829   case X86::BI__builtin_ia32_pternlogd128_mask:
3830   case X86::BI__builtin_ia32_pternlogd128_maskz:
3831   case X86::BI__builtin_ia32_pternlogd256_mask:
3832   case X86::BI__builtin_ia32_pternlogd256_maskz:
3833   case X86::BI__builtin_ia32_pternlogq128_mask:
3834   case X86::BI__builtin_ia32_pternlogq128_maskz:
3835   case X86::BI__builtin_ia32_pternlogq256_mask:
3836   case X86::BI__builtin_ia32_pternlogq256_maskz:
3837     i = 3; l = 0; u = 255;
3838     break;
3839   case X86::BI__builtin_ia32_gatherpfdpd:
3840   case X86::BI__builtin_ia32_gatherpfdps:
3841   case X86::BI__builtin_ia32_gatherpfqpd:
3842   case X86::BI__builtin_ia32_gatherpfqps:
3843   case X86::BI__builtin_ia32_scatterpfdpd:
3844   case X86::BI__builtin_ia32_scatterpfdps:
3845   case X86::BI__builtin_ia32_scatterpfqpd:
3846   case X86::BI__builtin_ia32_scatterpfqps:
3847     i = 4; l = 2; u = 3;
3848     break;
3849   case X86::BI__builtin_ia32_reducesd_mask:
3850   case X86::BI__builtin_ia32_reducess_mask:
3851   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3852   case X86::BI__builtin_ia32_rndscaless_round_mask:
3853     i = 4; l = 0; u = 255;
3854     break;
3855   }
3856 
3857   // Note that we don't force a hard error on the range check here, allowing
3858   // template-generated or macro-generated dead code to potentially have out-of-
3859   // range values. These need to code generate, but don't need to necessarily
3860   // make any sense. We use a warning that defaults to an error.
3861   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
3862 }
3863 
3864 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
3865 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
3866 /// Returns true when the format fits the function and the FormatStringInfo has
3867 /// been populated.
3868 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
3869                                FormatStringInfo *FSI) {
3870   FSI->HasVAListArg = Format->getFirstArg() == 0;
3871   FSI->FormatIdx = Format->getFormatIdx() - 1;
3872   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
3873 
3874   // The way the format attribute works in GCC, the implicit this argument
3875   // of member functions is counted. However, it doesn't appear in our own
3876   // lists, so decrement format_idx in that case.
3877   if (IsCXXMember) {
3878     if(FSI->FormatIdx == 0)
3879       return false;
3880     --FSI->FormatIdx;
3881     if (FSI->FirstDataArg != 0)
3882       --FSI->FirstDataArg;
3883   }
3884   return true;
3885 }
3886 
3887 /// Checks if a the given expression evaluates to null.
3888 ///
3889 /// Returns true if the value evaluates to null.
3890 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
3891   // If the expression has non-null type, it doesn't evaluate to null.
3892   if (auto nullability
3893         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
3894     if (*nullability == NullabilityKind::NonNull)
3895       return false;
3896   }
3897 
3898   // As a special case, transparent unions initialized with zero are
3899   // considered null for the purposes of the nonnull attribute.
3900   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
3901     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
3902       if (const CompoundLiteralExpr *CLE =
3903           dyn_cast<CompoundLiteralExpr>(Expr))
3904         if (const InitListExpr *ILE =
3905             dyn_cast<InitListExpr>(CLE->getInitializer()))
3906           Expr = ILE->getInit(0);
3907   }
3908 
3909   bool Result;
3910   return (!Expr->isValueDependent() &&
3911           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
3912           !Result);
3913 }
3914 
3915 static void CheckNonNullArgument(Sema &S,
3916                                  const Expr *ArgExpr,
3917                                  SourceLocation CallSiteLoc) {
3918   if (CheckNonNullExpr(S, ArgExpr))
3919     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
3920                           S.PDiag(diag::warn_null_arg)
3921                               << ArgExpr->getSourceRange());
3922 }
3923 
3924 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
3925   FormatStringInfo FSI;
3926   if ((GetFormatStringType(Format) == FST_NSString) &&
3927       getFormatStringInfo(Format, false, &FSI)) {
3928     Idx = FSI.FormatIdx;
3929     return true;
3930   }
3931   return false;
3932 }
3933 
3934 /// Diagnose use of %s directive in an NSString which is being passed
3935 /// as formatting string to formatting method.
3936 static void
3937 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
3938                                         const NamedDecl *FDecl,
3939                                         Expr **Args,
3940                                         unsigned NumArgs) {
3941   unsigned Idx = 0;
3942   bool Format = false;
3943   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
3944   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
3945     Idx = 2;
3946     Format = true;
3947   }
3948   else
3949     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
3950       if (S.GetFormatNSStringIdx(I, Idx)) {
3951         Format = true;
3952         break;
3953       }
3954     }
3955   if (!Format || NumArgs <= Idx)
3956     return;
3957   const Expr *FormatExpr = Args[Idx];
3958   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
3959     FormatExpr = CSCE->getSubExpr();
3960   const StringLiteral *FormatString;
3961   if (const ObjCStringLiteral *OSL =
3962       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
3963     FormatString = OSL->getString();
3964   else
3965     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
3966   if (!FormatString)
3967     return;
3968   if (S.FormatStringHasSArg(FormatString)) {
3969     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
3970       << "%s" << 1 << 1;
3971     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
3972       << FDecl->getDeclName();
3973   }
3974 }
3975 
3976 /// Determine whether the given type has a non-null nullability annotation.
3977 static bool isNonNullType(ASTContext &ctx, QualType type) {
3978   if (auto nullability = type->getNullability(ctx))
3979     return *nullability == NullabilityKind::NonNull;
3980 
3981   return false;
3982 }
3983 
3984 static void CheckNonNullArguments(Sema &S,
3985                                   const NamedDecl *FDecl,
3986                                   const FunctionProtoType *Proto,
3987                                   ArrayRef<const Expr *> Args,
3988                                   SourceLocation CallSiteLoc) {
3989   assert((FDecl || Proto) && "Need a function declaration or prototype");
3990 
3991   // Already checked by by constant evaluator.
3992   if (S.isConstantEvaluated())
3993     return;
3994   // Check the attributes attached to the method/function itself.
3995   llvm::SmallBitVector NonNullArgs;
3996   if (FDecl) {
3997     // Handle the nonnull attribute on the function/method declaration itself.
3998     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
3999       if (!NonNull->args_size()) {
4000         // Easy case: all pointer arguments are nonnull.
4001         for (const auto *Arg : Args)
4002           if (S.isValidPointerAttrType(Arg->getType()))
4003             CheckNonNullArgument(S, Arg, CallSiteLoc);
4004         return;
4005       }
4006 
4007       for (const ParamIdx &Idx : NonNull->args()) {
4008         unsigned IdxAST = Idx.getASTIndex();
4009         if (IdxAST >= Args.size())
4010           continue;
4011         if (NonNullArgs.empty())
4012           NonNullArgs.resize(Args.size());
4013         NonNullArgs.set(IdxAST);
4014       }
4015     }
4016   }
4017 
4018   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4019     // Handle the nonnull attribute on the parameters of the
4020     // function/method.
4021     ArrayRef<ParmVarDecl*> parms;
4022     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4023       parms = FD->parameters();
4024     else
4025       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4026 
4027     unsigned ParamIndex = 0;
4028     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4029          I != E; ++I, ++ParamIndex) {
4030       const ParmVarDecl *PVD = *I;
4031       if (PVD->hasAttr<NonNullAttr>() ||
4032           isNonNullType(S.Context, PVD->getType())) {
4033         if (NonNullArgs.empty())
4034           NonNullArgs.resize(Args.size());
4035 
4036         NonNullArgs.set(ParamIndex);
4037       }
4038     }
4039   } else {
4040     // If we have a non-function, non-method declaration but no
4041     // function prototype, try to dig out the function prototype.
4042     if (!Proto) {
4043       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4044         QualType type = VD->getType().getNonReferenceType();
4045         if (auto pointerType = type->getAs<PointerType>())
4046           type = pointerType->getPointeeType();
4047         else if (auto blockType = type->getAs<BlockPointerType>())
4048           type = blockType->getPointeeType();
4049         // FIXME: data member pointers?
4050 
4051         // Dig out the function prototype, if there is one.
4052         Proto = type->getAs<FunctionProtoType>();
4053       }
4054     }
4055 
4056     // Fill in non-null argument information from the nullability
4057     // information on the parameter types (if we have them).
4058     if (Proto) {
4059       unsigned Index = 0;
4060       for (auto paramType : Proto->getParamTypes()) {
4061         if (isNonNullType(S.Context, paramType)) {
4062           if (NonNullArgs.empty())
4063             NonNullArgs.resize(Args.size());
4064 
4065           NonNullArgs.set(Index);
4066         }
4067 
4068         ++Index;
4069       }
4070     }
4071   }
4072 
4073   // Check for non-null arguments.
4074   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4075        ArgIndex != ArgIndexEnd; ++ArgIndex) {
4076     if (NonNullArgs[ArgIndex])
4077       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
4078   }
4079 }
4080 
4081 /// Handles the checks for format strings, non-POD arguments to vararg
4082 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
4083 /// attributes.
4084 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
4085                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
4086                      bool IsMemberFunction, SourceLocation Loc,
4087                      SourceRange Range, VariadicCallType CallType) {
4088   // FIXME: We should check as much as we can in the template definition.
4089   if (CurContext->isDependentContext())
4090     return;
4091 
4092   // Printf and scanf checking.
4093   llvm::SmallBitVector CheckedVarArgs;
4094   if (FDecl) {
4095     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4096       // Only create vector if there are format attributes.
4097       CheckedVarArgs.resize(Args.size());
4098 
4099       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4100                            CheckedVarArgs);
4101     }
4102   }
4103 
4104   // Refuse POD arguments that weren't caught by the format string
4105   // checks above.
4106   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4107   if (CallType != VariadicDoesNotApply &&
4108       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4109     unsigned NumParams = Proto ? Proto->getNumParams()
4110                        : FDecl && isa<FunctionDecl>(FDecl)
4111                            ? cast<FunctionDecl>(FDecl)->getNumParams()
4112                        : FDecl && isa<ObjCMethodDecl>(FDecl)
4113                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
4114                        : 0;
4115 
4116     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4117       // Args[ArgIdx] can be null in malformed code.
4118       if (const Expr *Arg = Args[ArgIdx]) {
4119         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4120           checkVariadicArgument(Arg, CallType);
4121       }
4122     }
4123   }
4124 
4125   if (FDecl || Proto) {
4126     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4127 
4128     // Type safety checking.
4129     if (FDecl) {
4130       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4131         CheckArgumentWithTypeTag(I, Args, Loc);
4132     }
4133   }
4134 
4135   if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
4136     auto *AA = FDecl->getAttr<AllocAlignAttr>();
4137     const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
4138     if (!Arg->isValueDependent()) {
4139       Expr::EvalResult Align;
4140       if (Arg->EvaluateAsInt(Align, Context)) {
4141         const llvm::APSInt &I = Align.Val.getInt();
4142         if (!I.isPowerOf2())
4143           Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
4144               << Arg->getSourceRange();
4145 
4146         if (I > Sema::MaximumAlignment)
4147           Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
4148               << Arg->getSourceRange() << Sema::MaximumAlignment;
4149       }
4150     }
4151   }
4152 
4153   if (FD)
4154     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4155 }
4156 
4157 /// CheckConstructorCall - Check a constructor call for correctness and safety
4158 /// properties not enforced by the C type system.
4159 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
4160                                 ArrayRef<const Expr *> Args,
4161                                 const FunctionProtoType *Proto,
4162                                 SourceLocation Loc) {
4163   VariadicCallType CallType =
4164     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4165   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4166             Loc, SourceRange(), CallType);
4167 }
4168 
4169 /// CheckFunctionCall - Check a direct function call for various correctness
4170 /// and safety properties not strictly enforced by the C type system.
4171 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
4172                              const FunctionProtoType *Proto) {
4173   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4174                               isa<CXXMethodDecl>(FDecl);
4175   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4176                           IsMemberOperatorCall;
4177   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4178                                                   TheCall->getCallee());
4179   Expr** Args = TheCall->getArgs();
4180   unsigned NumArgs = TheCall->getNumArgs();
4181 
4182   Expr *ImplicitThis = nullptr;
4183   if (IsMemberOperatorCall) {
4184     // If this is a call to a member operator, hide the first argument
4185     // from checkCall.
4186     // FIXME: Our choice of AST representation here is less than ideal.
4187     ImplicitThis = Args[0];
4188     ++Args;
4189     --NumArgs;
4190   } else if (IsMemberFunction)
4191     ImplicitThis =
4192         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4193 
4194   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
4195             IsMemberFunction, TheCall->getRParenLoc(),
4196             TheCall->getCallee()->getSourceRange(), CallType);
4197 
4198   IdentifierInfo *FnInfo = FDecl->getIdentifier();
4199   // None of the checks below are needed for functions that don't have
4200   // simple names (e.g., C++ conversion functions).
4201   if (!FnInfo)
4202     return false;
4203 
4204   CheckAbsoluteValueFunction(TheCall, FDecl);
4205   CheckMaxUnsignedZero(TheCall, FDecl);
4206 
4207   if (getLangOpts().ObjC)
4208     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
4209 
4210   unsigned CMId = FDecl->getMemoryFunctionKind();
4211   if (CMId == 0)
4212     return false;
4213 
4214   // Handle memory setting and copying functions.
4215   if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
4216     CheckStrlcpycatArguments(TheCall, FnInfo);
4217   else if (CMId == Builtin::BIstrncat)
4218     CheckStrncatArguments(TheCall, FnInfo);
4219   else
4220     CheckMemaccessArguments(TheCall, CMId, FnInfo);
4221 
4222   return false;
4223 }
4224 
4225 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
4226                                ArrayRef<const Expr *> Args) {
4227   VariadicCallType CallType =
4228       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
4229 
4230   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
4231             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
4232             CallType);
4233 
4234   return false;
4235 }
4236 
4237 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4238                             const FunctionProtoType *Proto) {
4239   QualType Ty;
4240   if (const auto *V = dyn_cast<VarDecl>(NDecl))
4241     Ty = V->getType().getNonReferenceType();
4242   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4243     Ty = F->getType().getNonReferenceType();
4244   else
4245     return false;
4246 
4247   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4248       !Ty->isFunctionProtoType())
4249     return false;
4250 
4251   VariadicCallType CallType;
4252   if (!Proto || !Proto->isVariadic()) {
4253     CallType = VariadicDoesNotApply;
4254   } else if (Ty->isBlockPointerType()) {
4255     CallType = VariadicBlock;
4256   } else { // Ty->isFunctionPointerType()
4257     CallType = VariadicFunction;
4258   }
4259 
4260   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4261             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4262             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4263             TheCall->getCallee()->getSourceRange(), CallType);
4264 
4265   return false;
4266 }
4267 
4268 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
4269 /// such as function pointers returned from functions.
4270 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4271   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4272                                                   TheCall->getCallee());
4273   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4274             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4275             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4276             TheCall->getCallee()->getSourceRange(), CallType);
4277 
4278   return false;
4279 }
4280 
4281 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4282   if (!llvm::isValidAtomicOrderingCABI(Ordering))
4283     return false;
4284 
4285   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4286   switch (Op) {
4287   case AtomicExpr::AO__c11_atomic_init:
4288   case AtomicExpr::AO__opencl_atomic_init:
4289     llvm_unreachable("There is no ordering argument for an init");
4290 
4291   case AtomicExpr::AO__c11_atomic_load:
4292   case AtomicExpr::AO__opencl_atomic_load:
4293   case AtomicExpr::AO__atomic_load_n:
4294   case AtomicExpr::AO__atomic_load:
4295     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4296            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4297 
4298   case AtomicExpr::AO__c11_atomic_store:
4299   case AtomicExpr::AO__opencl_atomic_store:
4300   case AtomicExpr::AO__atomic_store:
4301   case AtomicExpr::AO__atomic_store_n:
4302     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4303            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4304            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4305 
4306   default:
4307     return true;
4308   }
4309 }
4310 
4311 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
4312                                          AtomicExpr::AtomicOp Op) {
4313   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4314   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4315   MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
4316   return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
4317                          DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
4318                          Op);
4319 }
4320 
4321 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
4322                                  SourceLocation RParenLoc, MultiExprArg Args,
4323                                  AtomicExpr::AtomicOp Op,
4324                                  AtomicArgumentOrder ArgOrder) {
4325   // All the non-OpenCL operations take one of the following forms.
4326   // The OpenCL operations take the __c11 forms with one extra argument for
4327   // synchronization scope.
4328   enum {
4329     // C    __c11_atomic_init(A *, C)
4330     Init,
4331 
4332     // C    __c11_atomic_load(A *, int)
4333     Load,
4334 
4335     // void __atomic_load(A *, CP, int)
4336     LoadCopy,
4337 
4338     // void __atomic_store(A *, CP, int)
4339     Copy,
4340 
4341     // C    __c11_atomic_add(A *, M, int)
4342     Arithmetic,
4343 
4344     // C    __atomic_exchange_n(A *, CP, int)
4345     Xchg,
4346 
4347     // void __atomic_exchange(A *, C *, CP, int)
4348     GNUXchg,
4349 
4350     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4351     C11CmpXchg,
4352 
4353     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4354     GNUCmpXchg
4355   } Form = Init;
4356 
4357   const unsigned NumForm = GNUCmpXchg + 1;
4358   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
4359   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
4360   // where:
4361   //   C is an appropriate type,
4362   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4363   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4364   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4365   //   the int parameters are for orderings.
4366 
4367   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4368       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4369       "need to update code for modified forms");
4370   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
4371                     AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
4372                         AtomicExpr::AO__atomic_load,
4373                 "need to update code for modified C11 atomics");
4374   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
4375                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
4376   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
4377                Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
4378                IsOpenCL;
4379   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4380              Op == AtomicExpr::AO__atomic_store_n ||
4381              Op == AtomicExpr::AO__atomic_exchange_n ||
4382              Op == AtomicExpr::AO__atomic_compare_exchange_n;
4383   bool IsAddSub = false;
4384 
4385   switch (Op) {
4386   case AtomicExpr::AO__c11_atomic_init:
4387   case AtomicExpr::AO__opencl_atomic_init:
4388     Form = Init;
4389     break;
4390 
4391   case AtomicExpr::AO__c11_atomic_load:
4392   case AtomicExpr::AO__opencl_atomic_load:
4393   case AtomicExpr::AO__atomic_load_n:
4394     Form = Load;
4395     break;
4396 
4397   case AtomicExpr::AO__atomic_load:
4398     Form = LoadCopy;
4399     break;
4400 
4401   case AtomicExpr::AO__c11_atomic_store:
4402   case AtomicExpr::AO__opencl_atomic_store:
4403   case AtomicExpr::AO__atomic_store:
4404   case AtomicExpr::AO__atomic_store_n:
4405     Form = Copy;
4406     break;
4407 
4408   case AtomicExpr::AO__c11_atomic_fetch_add:
4409   case AtomicExpr::AO__c11_atomic_fetch_sub:
4410   case AtomicExpr::AO__opencl_atomic_fetch_add:
4411   case AtomicExpr::AO__opencl_atomic_fetch_sub:
4412   case AtomicExpr::AO__atomic_fetch_add:
4413   case AtomicExpr::AO__atomic_fetch_sub:
4414   case AtomicExpr::AO__atomic_add_fetch:
4415   case AtomicExpr::AO__atomic_sub_fetch:
4416     IsAddSub = true;
4417     LLVM_FALLTHROUGH;
4418   case AtomicExpr::AO__c11_atomic_fetch_and:
4419   case AtomicExpr::AO__c11_atomic_fetch_or:
4420   case AtomicExpr::AO__c11_atomic_fetch_xor:
4421   case AtomicExpr::AO__opencl_atomic_fetch_and:
4422   case AtomicExpr::AO__opencl_atomic_fetch_or:
4423   case AtomicExpr::AO__opencl_atomic_fetch_xor:
4424   case AtomicExpr::AO__atomic_fetch_and:
4425   case AtomicExpr::AO__atomic_fetch_or:
4426   case AtomicExpr::AO__atomic_fetch_xor:
4427   case AtomicExpr::AO__atomic_fetch_nand:
4428   case AtomicExpr::AO__atomic_and_fetch:
4429   case AtomicExpr::AO__atomic_or_fetch:
4430   case AtomicExpr::AO__atomic_xor_fetch:
4431   case AtomicExpr::AO__atomic_nand_fetch:
4432   case AtomicExpr::AO__c11_atomic_fetch_min:
4433   case AtomicExpr::AO__c11_atomic_fetch_max:
4434   case AtomicExpr::AO__opencl_atomic_fetch_min:
4435   case AtomicExpr::AO__opencl_atomic_fetch_max:
4436   case AtomicExpr::AO__atomic_min_fetch:
4437   case AtomicExpr::AO__atomic_max_fetch:
4438   case AtomicExpr::AO__atomic_fetch_min:
4439   case AtomicExpr::AO__atomic_fetch_max:
4440     Form = Arithmetic;
4441     break;
4442 
4443   case AtomicExpr::AO__c11_atomic_exchange:
4444   case AtomicExpr::AO__opencl_atomic_exchange:
4445   case AtomicExpr::AO__atomic_exchange_n:
4446     Form = Xchg;
4447     break;
4448 
4449   case AtomicExpr::AO__atomic_exchange:
4450     Form = GNUXchg;
4451     break;
4452 
4453   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
4454   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
4455   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
4456   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
4457     Form = C11CmpXchg;
4458     break;
4459 
4460   case AtomicExpr::AO__atomic_compare_exchange:
4461   case AtomicExpr::AO__atomic_compare_exchange_n:
4462     Form = GNUCmpXchg;
4463     break;
4464   }
4465 
4466   unsigned AdjustedNumArgs = NumArgs[Form];
4467   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
4468     ++AdjustedNumArgs;
4469   // Check we have the right number of arguments.
4470   if (Args.size() < AdjustedNumArgs) {
4471     Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
4472         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4473         << ExprRange;
4474     return ExprError();
4475   } else if (Args.size() > AdjustedNumArgs) {
4476     Diag(Args[AdjustedNumArgs]->getBeginLoc(),
4477          diag::err_typecheck_call_too_many_args)
4478         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4479         << ExprRange;
4480     return ExprError();
4481   }
4482 
4483   // Inspect the first argument of the atomic operation.
4484   Expr *Ptr = Args[0];
4485   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
4486   if (ConvertedPtr.isInvalid())
4487     return ExprError();
4488 
4489   Ptr = ConvertedPtr.get();
4490   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
4491   if (!pointerType) {
4492     Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
4493         << Ptr->getType() << Ptr->getSourceRange();
4494     return ExprError();
4495   }
4496 
4497   // For a __c11 builtin, this should be a pointer to an _Atomic type.
4498   QualType AtomTy = pointerType->getPointeeType(); // 'A'
4499   QualType ValType = AtomTy; // 'C'
4500   if (IsC11) {
4501     if (!AtomTy->isAtomicType()) {
4502       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
4503           << Ptr->getType() << Ptr->getSourceRange();
4504       return ExprError();
4505     }
4506     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
4507         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
4508       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
4509           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
4510           << Ptr->getSourceRange();
4511       return ExprError();
4512     }
4513     ValType = AtomTy->castAs<AtomicType>()->getValueType();
4514   } else if (Form != Load && Form != LoadCopy) {
4515     if (ValType.isConstQualified()) {
4516       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
4517           << Ptr->getType() << Ptr->getSourceRange();
4518       return ExprError();
4519     }
4520   }
4521 
4522   // For an arithmetic operation, the implied arithmetic must be well-formed.
4523   if (Form == Arithmetic) {
4524     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
4525     if (IsAddSub && !ValType->isIntegerType()
4526         && !ValType->isPointerType()) {
4527       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4528           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4529       return ExprError();
4530     }
4531     if (!IsAddSub && !ValType->isIntegerType()) {
4532       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
4533           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4534       return ExprError();
4535     }
4536     if (IsC11 && ValType->isPointerType() &&
4537         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
4538                             diag::err_incomplete_type)) {
4539       return ExprError();
4540     }
4541   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
4542     // For __atomic_*_n operations, the value type must be a scalar integral or
4543     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
4544     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4545         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4546     return ExprError();
4547   }
4548 
4549   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
4550       !AtomTy->isScalarType()) {
4551     // For GNU atomics, require a trivially-copyable type. This is not part of
4552     // the GNU atomics specification, but we enforce it for sanity.
4553     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
4554         << Ptr->getType() << Ptr->getSourceRange();
4555     return ExprError();
4556   }
4557 
4558   switch (ValType.getObjCLifetime()) {
4559   case Qualifiers::OCL_None:
4560   case Qualifiers::OCL_ExplicitNone:
4561     // okay
4562     break;
4563 
4564   case Qualifiers::OCL_Weak:
4565   case Qualifiers::OCL_Strong:
4566   case Qualifiers::OCL_Autoreleasing:
4567     // FIXME: Can this happen? By this point, ValType should be known
4568     // to be trivially copyable.
4569     Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
4570         << ValType << Ptr->getSourceRange();
4571     return ExprError();
4572   }
4573 
4574   // All atomic operations have an overload which takes a pointer to a volatile
4575   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
4576   // into the result or the other operands. Similarly atomic_load takes a
4577   // pointer to a const 'A'.
4578   ValType.removeLocalVolatile();
4579   ValType.removeLocalConst();
4580   QualType ResultType = ValType;
4581   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
4582       Form == Init)
4583     ResultType = Context.VoidTy;
4584   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
4585     ResultType = Context.BoolTy;
4586 
4587   // The type of a parameter passed 'by value'. In the GNU atomics, such
4588   // arguments are actually passed as pointers.
4589   QualType ByValType = ValType; // 'CP'
4590   bool IsPassedByAddress = false;
4591   if (!IsC11 && !IsN) {
4592     ByValType = Ptr->getType();
4593     IsPassedByAddress = true;
4594   }
4595 
4596   SmallVector<Expr *, 5> APIOrderedArgs;
4597   if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
4598     APIOrderedArgs.push_back(Args[0]);
4599     switch (Form) {
4600     case Init:
4601     case Load:
4602       APIOrderedArgs.push_back(Args[1]); // Val1/Order
4603       break;
4604     case LoadCopy:
4605     case Copy:
4606     case Arithmetic:
4607     case Xchg:
4608       APIOrderedArgs.push_back(Args[2]); // Val1
4609       APIOrderedArgs.push_back(Args[1]); // Order
4610       break;
4611     case GNUXchg:
4612       APIOrderedArgs.push_back(Args[2]); // Val1
4613       APIOrderedArgs.push_back(Args[3]); // Val2
4614       APIOrderedArgs.push_back(Args[1]); // Order
4615       break;
4616     case C11CmpXchg:
4617       APIOrderedArgs.push_back(Args[2]); // Val1
4618       APIOrderedArgs.push_back(Args[4]); // Val2
4619       APIOrderedArgs.push_back(Args[1]); // Order
4620       APIOrderedArgs.push_back(Args[3]); // OrderFail
4621       break;
4622     case GNUCmpXchg:
4623       APIOrderedArgs.push_back(Args[2]); // Val1
4624       APIOrderedArgs.push_back(Args[4]); // Val2
4625       APIOrderedArgs.push_back(Args[5]); // Weak
4626       APIOrderedArgs.push_back(Args[1]); // Order
4627       APIOrderedArgs.push_back(Args[3]); // OrderFail
4628       break;
4629     }
4630   } else
4631     APIOrderedArgs.append(Args.begin(), Args.end());
4632 
4633   // The first argument's non-CV pointer type is used to deduce the type of
4634   // subsequent arguments, except for:
4635   //  - weak flag (always converted to bool)
4636   //  - memory order (always converted to int)
4637   //  - scope  (always converted to int)
4638   for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
4639     QualType Ty;
4640     if (i < NumVals[Form] + 1) {
4641       switch (i) {
4642       case 0:
4643         // The first argument is always a pointer. It has a fixed type.
4644         // It is always dereferenced, a nullptr is undefined.
4645         CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4646         // Nothing else to do: we already know all we want about this pointer.
4647         continue;
4648       case 1:
4649         // The second argument is the non-atomic operand. For arithmetic, this
4650         // is always passed by value, and for a compare_exchange it is always
4651         // passed by address. For the rest, GNU uses by-address and C11 uses
4652         // by-value.
4653         assert(Form != Load);
4654         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
4655           Ty = ValType;
4656         else if (Form == Copy || Form == Xchg) {
4657           if (IsPassedByAddress) {
4658             // The value pointer is always dereferenced, a nullptr is undefined.
4659             CheckNonNullArgument(*this, APIOrderedArgs[i],
4660                                  ExprRange.getBegin());
4661           }
4662           Ty = ByValType;
4663         } else if (Form == Arithmetic)
4664           Ty = Context.getPointerDiffType();
4665         else {
4666           Expr *ValArg = APIOrderedArgs[i];
4667           // The value pointer is always dereferenced, a nullptr is undefined.
4668           CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
4669           LangAS AS = LangAS::Default;
4670           // Keep address space of non-atomic pointer type.
4671           if (const PointerType *PtrTy =
4672                   ValArg->getType()->getAs<PointerType>()) {
4673             AS = PtrTy->getPointeeType().getAddressSpace();
4674           }
4675           Ty = Context.getPointerType(
4676               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
4677         }
4678         break;
4679       case 2:
4680         // The third argument to compare_exchange / GNU exchange is the desired
4681         // value, either by-value (for the C11 and *_n variant) or as a pointer.
4682         if (IsPassedByAddress)
4683           CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4684         Ty = ByValType;
4685         break;
4686       case 3:
4687         // The fourth argument to GNU compare_exchange is a 'weak' flag.
4688         Ty = Context.BoolTy;
4689         break;
4690       }
4691     } else {
4692       // The order(s) and scope are always converted to int.
4693       Ty = Context.IntTy;
4694     }
4695 
4696     InitializedEntity Entity =
4697         InitializedEntity::InitializeParameter(Context, Ty, false);
4698     ExprResult Arg = APIOrderedArgs[i];
4699     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4700     if (Arg.isInvalid())
4701       return true;
4702     APIOrderedArgs[i] = Arg.get();
4703   }
4704 
4705   // Permute the arguments into a 'consistent' order.
4706   SmallVector<Expr*, 5> SubExprs;
4707   SubExprs.push_back(Ptr);
4708   switch (Form) {
4709   case Init:
4710     // Note, AtomicExpr::getVal1() has a special case for this atomic.
4711     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4712     break;
4713   case Load:
4714     SubExprs.push_back(APIOrderedArgs[1]); // Order
4715     break;
4716   case LoadCopy:
4717   case Copy:
4718   case Arithmetic:
4719   case Xchg:
4720     SubExprs.push_back(APIOrderedArgs[2]); // Order
4721     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4722     break;
4723   case GNUXchg:
4724     // Note, AtomicExpr::getVal2() has a special case for this atomic.
4725     SubExprs.push_back(APIOrderedArgs[3]); // Order
4726     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4727     SubExprs.push_back(APIOrderedArgs[2]); // Val2
4728     break;
4729   case C11CmpXchg:
4730     SubExprs.push_back(APIOrderedArgs[3]); // Order
4731     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4732     SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
4733     SubExprs.push_back(APIOrderedArgs[2]); // Val2
4734     break;
4735   case GNUCmpXchg:
4736     SubExprs.push_back(APIOrderedArgs[4]); // Order
4737     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4738     SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
4739     SubExprs.push_back(APIOrderedArgs[2]); // Val2
4740     SubExprs.push_back(APIOrderedArgs[3]); // Weak
4741     break;
4742   }
4743 
4744   if (SubExprs.size() >= 2 && Form != Init) {
4745     llvm::APSInt Result(32);
4746     if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
4747         !isValidOrderingForOp(Result.getSExtValue(), Op))
4748       Diag(SubExprs[1]->getBeginLoc(),
4749            diag::warn_atomic_op_has_invalid_memory_order)
4750           << SubExprs[1]->getSourceRange();
4751   }
4752 
4753   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
4754     auto *Scope = Args[Args.size() - 1];
4755     llvm::APSInt Result(32);
4756     if (Scope->isIntegerConstantExpr(Result, Context) &&
4757         !ScopeModel->isValid(Result.getZExtValue())) {
4758       Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
4759           << Scope->getSourceRange();
4760     }
4761     SubExprs.push_back(Scope);
4762   }
4763 
4764   AtomicExpr *AE = new (Context)
4765       AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
4766 
4767   if ((Op == AtomicExpr::AO__c11_atomic_load ||
4768        Op == AtomicExpr::AO__c11_atomic_store ||
4769        Op == AtomicExpr::AO__opencl_atomic_load ||
4770        Op == AtomicExpr::AO__opencl_atomic_store ) &&
4771       Context.AtomicUsesUnsupportedLibcall(AE))
4772     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
4773         << ((Op == AtomicExpr::AO__c11_atomic_load ||
4774              Op == AtomicExpr::AO__opencl_atomic_load)
4775                 ? 0
4776                 : 1);
4777 
4778   return AE;
4779 }
4780 
4781 /// checkBuiltinArgument - Given a call to a builtin function, perform
4782 /// normal type-checking on the given argument, updating the call in
4783 /// place.  This is useful when a builtin function requires custom
4784 /// type-checking for some of its arguments but not necessarily all of
4785 /// them.
4786 ///
4787 /// Returns true on error.
4788 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
4789   FunctionDecl *Fn = E->getDirectCallee();
4790   assert(Fn && "builtin call without direct callee!");
4791 
4792   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
4793   InitializedEntity Entity =
4794     InitializedEntity::InitializeParameter(S.Context, Param);
4795 
4796   ExprResult Arg = E->getArg(0);
4797   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
4798   if (Arg.isInvalid())
4799     return true;
4800 
4801   E->setArg(ArgIndex, Arg.get());
4802   return false;
4803 }
4804 
4805 /// We have a call to a function like __sync_fetch_and_add, which is an
4806 /// overloaded function based on the pointer type of its first argument.
4807 /// The main BuildCallExpr routines have already promoted the types of
4808 /// arguments because all of these calls are prototyped as void(...).
4809 ///
4810 /// This function goes through and does final semantic checking for these
4811 /// builtins, as well as generating any warnings.
4812 ExprResult
4813 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
4814   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
4815   Expr *Callee = TheCall->getCallee();
4816   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
4817   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4818 
4819   // Ensure that we have at least one argument to do type inference from.
4820   if (TheCall->getNumArgs() < 1) {
4821     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
4822         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
4823     return ExprError();
4824   }
4825 
4826   // Inspect the first argument of the atomic builtin.  This should always be
4827   // a pointer type, whose element is an integral scalar or pointer type.
4828   // Because it is a pointer type, we don't have to worry about any implicit
4829   // casts here.
4830   // FIXME: We don't allow floating point scalars as input.
4831   Expr *FirstArg = TheCall->getArg(0);
4832   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
4833   if (FirstArgResult.isInvalid())
4834     return ExprError();
4835   FirstArg = FirstArgResult.get();
4836   TheCall->setArg(0, FirstArg);
4837 
4838   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
4839   if (!pointerType) {
4840     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
4841         << FirstArg->getType() << FirstArg->getSourceRange();
4842     return ExprError();
4843   }
4844 
4845   QualType ValType = pointerType->getPointeeType();
4846   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
4847       !ValType->isBlockPointerType()) {
4848     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
4849         << FirstArg->getType() << FirstArg->getSourceRange();
4850     return ExprError();
4851   }
4852 
4853   if (ValType.isConstQualified()) {
4854     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
4855         << FirstArg->getType() << FirstArg->getSourceRange();
4856     return ExprError();
4857   }
4858 
4859   switch (ValType.getObjCLifetime()) {
4860   case Qualifiers::OCL_None:
4861   case Qualifiers::OCL_ExplicitNone:
4862     // okay
4863     break;
4864 
4865   case Qualifiers::OCL_Weak:
4866   case Qualifiers::OCL_Strong:
4867   case Qualifiers::OCL_Autoreleasing:
4868     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
4869         << ValType << FirstArg->getSourceRange();
4870     return ExprError();
4871   }
4872 
4873   // Strip any qualifiers off ValType.
4874   ValType = ValType.getUnqualifiedType();
4875 
4876   // The majority of builtins return a value, but a few have special return
4877   // types, so allow them to override appropriately below.
4878   QualType ResultType = ValType;
4879 
4880   // We need to figure out which concrete builtin this maps onto.  For example,
4881   // __sync_fetch_and_add with a 2 byte object turns into
4882   // __sync_fetch_and_add_2.
4883 #define BUILTIN_ROW(x) \
4884   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
4885     Builtin::BI##x##_8, Builtin::BI##x##_16 }
4886 
4887   static const unsigned BuiltinIndices[][5] = {
4888     BUILTIN_ROW(__sync_fetch_and_add),
4889     BUILTIN_ROW(__sync_fetch_and_sub),
4890     BUILTIN_ROW(__sync_fetch_and_or),
4891     BUILTIN_ROW(__sync_fetch_and_and),
4892     BUILTIN_ROW(__sync_fetch_and_xor),
4893     BUILTIN_ROW(__sync_fetch_and_nand),
4894 
4895     BUILTIN_ROW(__sync_add_and_fetch),
4896     BUILTIN_ROW(__sync_sub_and_fetch),
4897     BUILTIN_ROW(__sync_and_and_fetch),
4898     BUILTIN_ROW(__sync_or_and_fetch),
4899     BUILTIN_ROW(__sync_xor_and_fetch),
4900     BUILTIN_ROW(__sync_nand_and_fetch),
4901 
4902     BUILTIN_ROW(__sync_val_compare_and_swap),
4903     BUILTIN_ROW(__sync_bool_compare_and_swap),
4904     BUILTIN_ROW(__sync_lock_test_and_set),
4905     BUILTIN_ROW(__sync_lock_release),
4906     BUILTIN_ROW(__sync_swap)
4907   };
4908 #undef BUILTIN_ROW
4909 
4910   // Determine the index of the size.
4911   unsigned SizeIndex;
4912   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
4913   case 1: SizeIndex = 0; break;
4914   case 2: SizeIndex = 1; break;
4915   case 4: SizeIndex = 2; break;
4916   case 8: SizeIndex = 3; break;
4917   case 16: SizeIndex = 4; break;
4918   default:
4919     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
4920         << FirstArg->getType() << FirstArg->getSourceRange();
4921     return ExprError();
4922   }
4923 
4924   // Each of these builtins has one pointer argument, followed by some number of
4925   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
4926   // that we ignore.  Find out which row of BuiltinIndices to read from as well
4927   // as the number of fixed args.
4928   unsigned BuiltinID = FDecl->getBuiltinID();
4929   unsigned BuiltinIndex, NumFixed = 1;
4930   bool WarnAboutSemanticsChange = false;
4931   switch (BuiltinID) {
4932   default: llvm_unreachable("Unknown overloaded atomic builtin!");
4933   case Builtin::BI__sync_fetch_and_add:
4934   case Builtin::BI__sync_fetch_and_add_1:
4935   case Builtin::BI__sync_fetch_and_add_2:
4936   case Builtin::BI__sync_fetch_and_add_4:
4937   case Builtin::BI__sync_fetch_and_add_8:
4938   case Builtin::BI__sync_fetch_and_add_16:
4939     BuiltinIndex = 0;
4940     break;
4941 
4942   case Builtin::BI__sync_fetch_and_sub:
4943   case Builtin::BI__sync_fetch_and_sub_1:
4944   case Builtin::BI__sync_fetch_and_sub_2:
4945   case Builtin::BI__sync_fetch_and_sub_4:
4946   case Builtin::BI__sync_fetch_and_sub_8:
4947   case Builtin::BI__sync_fetch_and_sub_16:
4948     BuiltinIndex = 1;
4949     break;
4950 
4951   case Builtin::BI__sync_fetch_and_or:
4952   case Builtin::BI__sync_fetch_and_or_1:
4953   case Builtin::BI__sync_fetch_and_or_2:
4954   case Builtin::BI__sync_fetch_and_or_4:
4955   case Builtin::BI__sync_fetch_and_or_8:
4956   case Builtin::BI__sync_fetch_and_or_16:
4957     BuiltinIndex = 2;
4958     break;
4959 
4960   case Builtin::BI__sync_fetch_and_and:
4961   case Builtin::BI__sync_fetch_and_and_1:
4962   case Builtin::BI__sync_fetch_and_and_2:
4963   case Builtin::BI__sync_fetch_and_and_4:
4964   case Builtin::BI__sync_fetch_and_and_8:
4965   case Builtin::BI__sync_fetch_and_and_16:
4966     BuiltinIndex = 3;
4967     break;
4968 
4969   case Builtin::BI__sync_fetch_and_xor:
4970   case Builtin::BI__sync_fetch_and_xor_1:
4971   case Builtin::BI__sync_fetch_and_xor_2:
4972   case Builtin::BI__sync_fetch_and_xor_4:
4973   case Builtin::BI__sync_fetch_and_xor_8:
4974   case Builtin::BI__sync_fetch_and_xor_16:
4975     BuiltinIndex = 4;
4976     break;
4977 
4978   case Builtin::BI__sync_fetch_and_nand:
4979   case Builtin::BI__sync_fetch_and_nand_1:
4980   case Builtin::BI__sync_fetch_and_nand_2:
4981   case Builtin::BI__sync_fetch_and_nand_4:
4982   case Builtin::BI__sync_fetch_and_nand_8:
4983   case Builtin::BI__sync_fetch_and_nand_16:
4984     BuiltinIndex = 5;
4985     WarnAboutSemanticsChange = true;
4986     break;
4987 
4988   case Builtin::BI__sync_add_and_fetch:
4989   case Builtin::BI__sync_add_and_fetch_1:
4990   case Builtin::BI__sync_add_and_fetch_2:
4991   case Builtin::BI__sync_add_and_fetch_4:
4992   case Builtin::BI__sync_add_and_fetch_8:
4993   case Builtin::BI__sync_add_and_fetch_16:
4994     BuiltinIndex = 6;
4995     break;
4996 
4997   case Builtin::BI__sync_sub_and_fetch:
4998   case Builtin::BI__sync_sub_and_fetch_1:
4999   case Builtin::BI__sync_sub_and_fetch_2:
5000   case Builtin::BI__sync_sub_and_fetch_4:
5001   case Builtin::BI__sync_sub_and_fetch_8:
5002   case Builtin::BI__sync_sub_and_fetch_16:
5003     BuiltinIndex = 7;
5004     break;
5005 
5006   case Builtin::BI__sync_and_and_fetch:
5007   case Builtin::BI__sync_and_and_fetch_1:
5008   case Builtin::BI__sync_and_and_fetch_2:
5009   case Builtin::BI__sync_and_and_fetch_4:
5010   case Builtin::BI__sync_and_and_fetch_8:
5011   case Builtin::BI__sync_and_and_fetch_16:
5012     BuiltinIndex = 8;
5013     break;
5014 
5015   case Builtin::BI__sync_or_and_fetch:
5016   case Builtin::BI__sync_or_and_fetch_1:
5017   case Builtin::BI__sync_or_and_fetch_2:
5018   case Builtin::BI__sync_or_and_fetch_4:
5019   case Builtin::BI__sync_or_and_fetch_8:
5020   case Builtin::BI__sync_or_and_fetch_16:
5021     BuiltinIndex = 9;
5022     break;
5023 
5024   case Builtin::BI__sync_xor_and_fetch:
5025   case Builtin::BI__sync_xor_and_fetch_1:
5026   case Builtin::BI__sync_xor_and_fetch_2:
5027   case Builtin::BI__sync_xor_and_fetch_4:
5028   case Builtin::BI__sync_xor_and_fetch_8:
5029   case Builtin::BI__sync_xor_and_fetch_16:
5030     BuiltinIndex = 10;
5031     break;
5032 
5033   case Builtin::BI__sync_nand_and_fetch:
5034   case Builtin::BI__sync_nand_and_fetch_1:
5035   case Builtin::BI__sync_nand_and_fetch_2:
5036   case Builtin::BI__sync_nand_and_fetch_4:
5037   case Builtin::BI__sync_nand_and_fetch_8:
5038   case Builtin::BI__sync_nand_and_fetch_16:
5039     BuiltinIndex = 11;
5040     WarnAboutSemanticsChange = true;
5041     break;
5042 
5043   case Builtin::BI__sync_val_compare_and_swap:
5044   case Builtin::BI__sync_val_compare_and_swap_1:
5045   case Builtin::BI__sync_val_compare_and_swap_2:
5046   case Builtin::BI__sync_val_compare_and_swap_4:
5047   case Builtin::BI__sync_val_compare_and_swap_8:
5048   case Builtin::BI__sync_val_compare_and_swap_16:
5049     BuiltinIndex = 12;
5050     NumFixed = 2;
5051     break;
5052 
5053   case Builtin::BI__sync_bool_compare_and_swap:
5054   case Builtin::BI__sync_bool_compare_and_swap_1:
5055   case Builtin::BI__sync_bool_compare_and_swap_2:
5056   case Builtin::BI__sync_bool_compare_and_swap_4:
5057   case Builtin::BI__sync_bool_compare_and_swap_8:
5058   case Builtin::BI__sync_bool_compare_and_swap_16:
5059     BuiltinIndex = 13;
5060     NumFixed = 2;
5061     ResultType = Context.BoolTy;
5062     break;
5063 
5064   case Builtin::BI__sync_lock_test_and_set:
5065   case Builtin::BI__sync_lock_test_and_set_1:
5066   case Builtin::BI__sync_lock_test_and_set_2:
5067   case Builtin::BI__sync_lock_test_and_set_4:
5068   case Builtin::BI__sync_lock_test_and_set_8:
5069   case Builtin::BI__sync_lock_test_and_set_16:
5070     BuiltinIndex = 14;
5071     break;
5072 
5073   case Builtin::BI__sync_lock_release:
5074   case Builtin::BI__sync_lock_release_1:
5075   case Builtin::BI__sync_lock_release_2:
5076   case Builtin::BI__sync_lock_release_4:
5077   case Builtin::BI__sync_lock_release_8:
5078   case Builtin::BI__sync_lock_release_16:
5079     BuiltinIndex = 15;
5080     NumFixed = 0;
5081     ResultType = Context.VoidTy;
5082     break;
5083 
5084   case Builtin::BI__sync_swap:
5085   case Builtin::BI__sync_swap_1:
5086   case Builtin::BI__sync_swap_2:
5087   case Builtin::BI__sync_swap_4:
5088   case Builtin::BI__sync_swap_8:
5089   case Builtin::BI__sync_swap_16:
5090     BuiltinIndex = 16;
5091     break;
5092   }
5093 
5094   // Now that we know how many fixed arguments we expect, first check that we
5095   // have at least that many.
5096   if (TheCall->getNumArgs() < 1+NumFixed) {
5097     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5098         << 0 << 1 + NumFixed << TheCall->getNumArgs()
5099         << Callee->getSourceRange();
5100     return ExprError();
5101   }
5102 
5103   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5104       << Callee->getSourceRange();
5105 
5106   if (WarnAboutSemanticsChange) {
5107     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
5108         << Callee->getSourceRange();
5109   }
5110 
5111   // Get the decl for the concrete builtin from this, we can tell what the
5112   // concrete integer type we should convert to is.
5113   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5114   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
5115   FunctionDecl *NewBuiltinDecl;
5116   if (NewBuiltinID == BuiltinID)
5117     NewBuiltinDecl = FDecl;
5118   else {
5119     // Perform builtin lookup to avoid redeclaring it.
5120     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
5121     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5122     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5123     assert(Res.getFoundDecl());
5124     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
5125     if (!NewBuiltinDecl)
5126       return ExprError();
5127   }
5128 
5129   // The first argument --- the pointer --- has a fixed type; we
5130   // deduce the types of the rest of the arguments accordingly.  Walk
5131   // the remaining arguments, converting them to the deduced value type.
5132   for (unsigned i = 0; i != NumFixed; ++i) {
5133     ExprResult Arg = TheCall->getArg(i+1);
5134 
5135     // GCC does an implicit conversion to the pointer or integer ValType.  This
5136     // can fail in some cases (1i -> int**), check for this error case now.
5137     // Initialize the argument.
5138     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5139                                                    ValType, /*consume*/ false);
5140     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5141     if (Arg.isInvalid())
5142       return ExprError();
5143 
5144     // Okay, we have something that *can* be converted to the right type.  Check
5145     // to see if there is a potentially weird extension going on here.  This can
5146     // happen when you do an atomic operation on something like an char* and
5147     // pass in 42.  The 42 gets converted to char.  This is even more strange
5148     // for things like 45.123 -> char, etc.
5149     // FIXME: Do this check.
5150     TheCall->setArg(i+1, Arg.get());
5151   }
5152 
5153   // Create a new DeclRefExpr to refer to the new decl.
5154   DeclRefExpr *NewDRE = DeclRefExpr::Create(
5155       Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
5156       /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
5157       DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
5158 
5159   // Set the callee in the CallExpr.
5160   // FIXME: This loses syntactic information.
5161   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5162   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5163                                               CK_BuiltinFnToFnPtr);
5164   TheCall->setCallee(PromotedCall.get());
5165 
5166   // Change the result type of the call to match the original value type. This
5167   // is arbitrary, but the codegen for these builtins ins design to handle it
5168   // gracefully.
5169   TheCall->setType(ResultType);
5170 
5171   return TheCallResult;
5172 }
5173 
5174 /// SemaBuiltinNontemporalOverloaded - We have a call to
5175 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
5176 /// overloaded function based on the pointer type of its last argument.
5177 ///
5178 /// This function goes through and does final semantic checking for these
5179 /// builtins.
5180 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5181   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5182   DeclRefExpr *DRE =
5183       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5184   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5185   unsigned BuiltinID = FDecl->getBuiltinID();
5186   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5187           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5188          "Unexpected nontemporal load/store builtin!");
5189   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5190   unsigned numArgs = isStore ? 2 : 1;
5191 
5192   // Ensure that we have the proper number of arguments.
5193   if (checkArgCount(*this, TheCall, numArgs))
5194     return ExprError();
5195 
5196   // Inspect the last argument of the nontemporal builtin.  This should always
5197   // be a pointer type, from which we imply the type of the memory access.
5198   // Because it is a pointer type, we don't have to worry about any implicit
5199   // casts here.
5200   Expr *PointerArg = TheCall->getArg(numArgs - 1);
5201   ExprResult PointerArgResult =
5202       DefaultFunctionArrayLvalueConversion(PointerArg);
5203 
5204   if (PointerArgResult.isInvalid())
5205     return ExprError();
5206   PointerArg = PointerArgResult.get();
5207   TheCall->setArg(numArgs - 1, PointerArg);
5208 
5209   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5210   if (!pointerType) {
5211     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
5212         << PointerArg->getType() << PointerArg->getSourceRange();
5213     return ExprError();
5214   }
5215 
5216   QualType ValType = pointerType->getPointeeType();
5217 
5218   // Strip any qualifiers off ValType.
5219   ValType = ValType.getUnqualifiedType();
5220   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5221       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5222       !ValType->isVectorType()) {
5223     Diag(DRE->getBeginLoc(),
5224          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5225         << PointerArg->getType() << PointerArg->getSourceRange();
5226     return ExprError();
5227   }
5228 
5229   if (!isStore) {
5230     TheCall->setType(ValType);
5231     return TheCallResult;
5232   }
5233 
5234   ExprResult ValArg = TheCall->getArg(0);
5235   InitializedEntity Entity = InitializedEntity::InitializeParameter(
5236       Context, ValType, /*consume*/ false);
5237   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
5238   if (ValArg.isInvalid())
5239     return ExprError();
5240 
5241   TheCall->setArg(0, ValArg.get());
5242   TheCall->setType(Context.VoidTy);
5243   return TheCallResult;
5244 }
5245 
5246 /// CheckObjCString - Checks that the argument to the builtin
5247 /// CFString constructor is correct
5248 /// Note: It might also make sense to do the UTF-16 conversion here (would
5249 /// simplify the backend).
5250 bool Sema::CheckObjCString(Expr *Arg) {
5251   Arg = Arg->IgnoreParenCasts();
5252   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
5253 
5254   if (!Literal || !Literal->isAscii()) {
5255     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
5256         << Arg->getSourceRange();
5257     return true;
5258   }
5259 
5260   if (Literal->containsNonAsciiOrNull()) {
5261     StringRef String = Literal->getString();
5262     unsigned NumBytes = String.size();
5263     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
5264     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
5265     llvm::UTF16 *ToPtr = &ToBuf[0];
5266 
5267     llvm::ConversionResult Result =
5268         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
5269                                  ToPtr + NumBytes, llvm::strictConversion);
5270     // Check for conversion failure.
5271     if (Result != llvm::conversionOK)
5272       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
5273           << Arg->getSourceRange();
5274   }
5275   return false;
5276 }
5277 
5278 /// CheckObjCString - Checks that the format string argument to the os_log()
5279 /// and os_trace() functions is correct, and converts it to const char *.
5280 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5281   Arg = Arg->IgnoreParenCasts();
5282   auto *Literal = dyn_cast<StringLiteral>(Arg);
5283   if (!Literal) {
5284     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
5285       Literal = ObjcLiteral->getString();
5286     }
5287   }
5288 
5289   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
5290     return ExprError(
5291         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
5292         << Arg->getSourceRange());
5293   }
5294 
5295   ExprResult Result(Literal);
5296   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
5297   InitializedEntity Entity =
5298       InitializedEntity::InitializeParameter(Context, ResultTy, false);
5299   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
5300   return Result;
5301 }
5302 
5303 /// Check that the user is calling the appropriate va_start builtin for the
5304 /// target and calling convention.
5305 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5306   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5307   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
5308   bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
5309                     TT.getArch() == llvm::Triple::aarch64_32);
5310   bool IsWindows = TT.isOSWindows();
5311   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5312   if (IsX64 || IsAArch64) {
5313     CallingConv CC = CC_C;
5314     if (const FunctionDecl *FD = S.getCurFunctionDecl())
5315       CC = FD->getType()->castAs<FunctionType>()->getCallConv();
5316     if (IsMSVAStart) {
5317       // Don't allow this in System V ABI functions.
5318       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
5319         return S.Diag(Fn->getBeginLoc(),
5320                       diag::err_ms_va_start_used_in_sysv_function);
5321     } else {
5322       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
5323       // On x64 Windows, don't allow this in System V ABI functions.
5324       // (Yes, that means there's no corresponding way to support variadic
5325       // System V ABI functions on Windows.)
5326       if ((IsWindows && CC == CC_X86_64SysV) ||
5327           (!IsWindows && CC == CC_Win64))
5328         return S.Diag(Fn->getBeginLoc(),
5329                       diag::err_va_start_used_in_wrong_abi_function)
5330                << !IsWindows;
5331     }
5332     return false;
5333   }
5334 
5335   if (IsMSVAStart)
5336     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
5337   return false;
5338 }
5339 
5340 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
5341                                              ParmVarDecl **LastParam = nullptr) {
5342   // Determine whether the current function, block, or obj-c method is variadic
5343   // and get its parameter list.
5344   bool IsVariadic = false;
5345   ArrayRef<ParmVarDecl *> Params;
5346   DeclContext *Caller = S.CurContext;
5347   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
5348     IsVariadic = Block->isVariadic();
5349     Params = Block->parameters();
5350   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
5351     IsVariadic = FD->isVariadic();
5352     Params = FD->parameters();
5353   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
5354     IsVariadic = MD->isVariadic();
5355     // FIXME: This isn't correct for methods (results in bogus warning).
5356     Params = MD->parameters();
5357   } else if (isa<CapturedDecl>(Caller)) {
5358     // We don't support va_start in a CapturedDecl.
5359     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
5360     return true;
5361   } else {
5362     // This must be some other declcontext that parses exprs.
5363     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
5364     return true;
5365   }
5366 
5367   if (!IsVariadic) {
5368     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
5369     return true;
5370   }
5371 
5372   if (LastParam)
5373     *LastParam = Params.empty() ? nullptr : Params.back();
5374 
5375   return false;
5376 }
5377 
5378 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
5379 /// for validity.  Emit an error and return true on failure; return false
5380 /// on success.
5381 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5382   Expr *Fn = TheCall->getCallee();
5383 
5384   if (checkVAStartABI(*this, BuiltinID, Fn))
5385     return true;
5386 
5387   if (TheCall->getNumArgs() > 2) {
5388     Diag(TheCall->getArg(2)->getBeginLoc(),
5389          diag::err_typecheck_call_too_many_args)
5390         << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5391         << Fn->getSourceRange()
5392         << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5393                        (*(TheCall->arg_end() - 1))->getEndLoc());
5394     return true;
5395   }
5396 
5397   if (TheCall->getNumArgs() < 2) {
5398     return Diag(TheCall->getEndLoc(),
5399                 diag::err_typecheck_call_too_few_args_at_least)
5400            << 0 /*function call*/ << 2 << TheCall->getNumArgs();
5401   }
5402 
5403   // Type-check the first argument normally.
5404   if (checkBuiltinArgument(*this, TheCall, 0))
5405     return true;
5406 
5407   // Check that the current function is variadic, and get its last parameter.
5408   ParmVarDecl *LastParam;
5409   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
5410     return true;
5411 
5412   // Verify that the second argument to the builtin is the last argument of the
5413   // current function or method.
5414   bool SecondArgIsLastNamedArgument = false;
5415   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
5416 
5417   // These are valid if SecondArgIsLastNamedArgument is false after the next
5418   // block.
5419   QualType Type;
5420   SourceLocation ParamLoc;
5421   bool IsCRegister = false;
5422 
5423   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
5424     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
5425       SecondArgIsLastNamedArgument = PV == LastParam;
5426 
5427       Type = PV->getType();
5428       ParamLoc = PV->getLocation();
5429       IsCRegister =
5430           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
5431     }
5432   }
5433 
5434   if (!SecondArgIsLastNamedArgument)
5435     Diag(TheCall->getArg(1)->getBeginLoc(),
5436          diag::warn_second_arg_of_va_start_not_last_named_param);
5437   else if (IsCRegister || Type->isReferenceType() ||
5438            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
5439              // Promotable integers are UB, but enumerations need a bit of
5440              // extra checking to see what their promotable type actually is.
5441              if (!Type->isPromotableIntegerType())
5442                return false;
5443              if (!Type->isEnumeralType())
5444                return true;
5445              const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
5446              return !(ED &&
5447                       Context.typesAreCompatible(ED->getPromotionType(), Type));
5448            }()) {
5449     unsigned Reason = 0;
5450     if (Type->isReferenceType())  Reason = 1;
5451     else if (IsCRegister)         Reason = 2;
5452     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
5453     Diag(ParamLoc, diag::note_parameter_type) << Type;
5454   }
5455 
5456   TheCall->setType(Context.VoidTy);
5457   return false;
5458 }
5459 
5460 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
5461   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
5462   //                 const char *named_addr);
5463 
5464   Expr *Func = Call->getCallee();
5465 
5466   if (Call->getNumArgs() < 3)
5467     return Diag(Call->getEndLoc(),
5468                 diag::err_typecheck_call_too_few_args_at_least)
5469            << 0 /*function call*/ << 3 << Call->getNumArgs();
5470 
5471   // Type-check the first argument normally.
5472   if (checkBuiltinArgument(*this, Call, 0))
5473     return true;
5474 
5475   // Check that the current function is variadic.
5476   if (checkVAStartIsInVariadicFunction(*this, Func))
5477     return true;
5478 
5479   // __va_start on Windows does not validate the parameter qualifiers
5480 
5481   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
5482   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
5483 
5484   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
5485   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
5486 
5487   const QualType &ConstCharPtrTy =
5488       Context.getPointerType(Context.CharTy.withConst());
5489   if (!Arg1Ty->isPointerType() ||
5490       Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
5491     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5492         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
5493         << 0                                      /* qualifier difference */
5494         << 3                                      /* parameter mismatch */
5495         << 2 << Arg1->getType() << ConstCharPtrTy;
5496 
5497   const QualType SizeTy = Context.getSizeType();
5498   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
5499     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5500         << Arg2->getType() << SizeTy << 1 /* different class */
5501         << 0                              /* qualifier difference */
5502         << 3                              /* parameter mismatch */
5503         << 3 << Arg2->getType() << SizeTy;
5504 
5505   return false;
5506 }
5507 
5508 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
5509 /// friends.  This is declared to take (...), so we have to check everything.
5510 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
5511   if (TheCall->getNumArgs() < 2)
5512     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5513            << 0 << 2 << TheCall->getNumArgs() /*function call*/;
5514   if (TheCall->getNumArgs() > 2)
5515     return Diag(TheCall->getArg(2)->getBeginLoc(),
5516                 diag::err_typecheck_call_too_many_args)
5517            << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5518            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5519                           (*(TheCall->arg_end() - 1))->getEndLoc());
5520 
5521   ExprResult OrigArg0 = TheCall->getArg(0);
5522   ExprResult OrigArg1 = TheCall->getArg(1);
5523 
5524   // Do standard promotions between the two arguments, returning their common
5525   // type.
5526   QualType Res = UsualArithmeticConversions(
5527       OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
5528   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
5529     return true;
5530 
5531   // Make sure any conversions are pushed back into the call; this is
5532   // type safe since unordered compare builtins are declared as "_Bool
5533   // foo(...)".
5534   TheCall->setArg(0, OrigArg0.get());
5535   TheCall->setArg(1, OrigArg1.get());
5536 
5537   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
5538     return false;
5539 
5540   // If the common type isn't a real floating type, then the arguments were
5541   // invalid for this operation.
5542   if (Res.isNull() || !Res->isRealFloatingType())
5543     return Diag(OrigArg0.get()->getBeginLoc(),
5544                 diag::err_typecheck_call_invalid_ordered_compare)
5545            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
5546            << SourceRange(OrigArg0.get()->getBeginLoc(),
5547                           OrigArg1.get()->getEndLoc());
5548 
5549   return false;
5550 }
5551 
5552 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
5553 /// __builtin_isnan and friends.  This is declared to take (...), so we have
5554 /// to check everything. We expect the last argument to be a floating point
5555 /// value.
5556 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
5557   if (TheCall->getNumArgs() < NumArgs)
5558     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5559            << 0 << NumArgs << TheCall->getNumArgs() /*function call*/;
5560   if (TheCall->getNumArgs() > NumArgs)
5561     return Diag(TheCall->getArg(NumArgs)->getBeginLoc(),
5562                 diag::err_typecheck_call_too_many_args)
5563            << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
5564            << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(),
5565                           (*(TheCall->arg_end() - 1))->getEndLoc());
5566 
5567   // __builtin_fpclassify is the only case where NumArgs != 1, so we can count
5568   // on all preceding parameters just being int.  Try all of those.
5569   for (unsigned i = 0; i < NumArgs - 1; ++i) {
5570     Expr *Arg = TheCall->getArg(i);
5571 
5572     if (Arg->isTypeDependent())
5573       return false;
5574 
5575     ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);
5576 
5577     if (Res.isInvalid())
5578       return true;
5579     TheCall->setArg(i, Res.get());
5580   }
5581 
5582   Expr *OrigArg = TheCall->getArg(NumArgs-1);
5583 
5584   if (OrigArg->isTypeDependent())
5585     return false;
5586 
5587   // Usual Unary Conversions will convert half to float, which we want for
5588   // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
5589   // type how it is, but do normal L->Rvalue conversions.
5590   if (Context.getTargetInfo().useFP16ConversionIntrinsics())
5591     OrigArg = UsualUnaryConversions(OrigArg).get();
5592   else
5593     OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
5594   TheCall->setArg(NumArgs - 1, OrigArg);
5595 
5596   // This operation requires a non-_Complex floating-point number.
5597   if (!OrigArg->getType()->isRealFloatingType())
5598     return Diag(OrigArg->getBeginLoc(),
5599                 diag::err_typecheck_call_invalid_unary_fp)
5600            << OrigArg->getType() << OrigArg->getSourceRange();
5601 
5602   return false;
5603 }
5604 
5605 // Customized Sema Checking for VSX builtins that have the following signature:
5606 // vector [...] builtinName(vector [...], vector [...], const int);
5607 // Which takes the same type of vectors (any legal vector type) for the first
5608 // two arguments and takes compile time constant for the third argument.
5609 // Example builtins are :
5610 // vector double vec_xxpermdi(vector double, vector double, int);
5611 // vector short vec_xxsldwi(vector short, vector short, int);
5612 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
5613   unsigned ExpectedNumArgs = 3;
5614   if (TheCall->getNumArgs() < ExpectedNumArgs)
5615     return Diag(TheCall->getEndLoc(),
5616                 diag::err_typecheck_call_too_few_args_at_least)
5617            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5618            << TheCall->getSourceRange();
5619 
5620   if (TheCall->getNumArgs() > ExpectedNumArgs)
5621     return Diag(TheCall->getEndLoc(),
5622                 diag::err_typecheck_call_too_many_args_at_most)
5623            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5624            << TheCall->getSourceRange();
5625 
5626   // Check the third argument is a compile time constant
5627   llvm::APSInt Value;
5628   if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
5629     return Diag(TheCall->getBeginLoc(),
5630                 diag::err_vsx_builtin_nonconstant_argument)
5631            << 3 /* argument index */ << TheCall->getDirectCallee()
5632            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5633                           TheCall->getArg(2)->getEndLoc());
5634 
5635   QualType Arg1Ty = TheCall->getArg(0)->getType();
5636   QualType Arg2Ty = TheCall->getArg(1)->getType();
5637 
5638   // Check the type of argument 1 and argument 2 are vectors.
5639   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
5640   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
5641       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
5642     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
5643            << TheCall->getDirectCallee()
5644            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5645                           TheCall->getArg(1)->getEndLoc());
5646   }
5647 
5648   // Check the first two arguments are the same type.
5649   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
5650     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
5651            << TheCall->getDirectCallee()
5652            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5653                           TheCall->getArg(1)->getEndLoc());
5654   }
5655 
5656   // When default clang type checking is turned off and the customized type
5657   // checking is used, the returning type of the function must be explicitly
5658   // set. Otherwise it is _Bool by default.
5659   TheCall->setType(Arg1Ty);
5660 
5661   return false;
5662 }
5663 
5664 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
5665 // This is declared to take (...), so we have to check everything.
5666 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
5667   if (TheCall->getNumArgs() < 2)
5668     return ExprError(Diag(TheCall->getEndLoc(),
5669                           diag::err_typecheck_call_too_few_args_at_least)
5670                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5671                      << TheCall->getSourceRange());
5672 
5673   // Determine which of the following types of shufflevector we're checking:
5674   // 1) unary, vector mask: (lhs, mask)
5675   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
5676   QualType resType = TheCall->getArg(0)->getType();
5677   unsigned numElements = 0;
5678 
5679   if (!TheCall->getArg(0)->isTypeDependent() &&
5680       !TheCall->getArg(1)->isTypeDependent()) {
5681     QualType LHSType = TheCall->getArg(0)->getType();
5682     QualType RHSType = TheCall->getArg(1)->getType();
5683 
5684     if (!LHSType->isVectorType() || !RHSType->isVectorType())
5685       return ExprError(
5686           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
5687           << TheCall->getDirectCallee()
5688           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5689                          TheCall->getArg(1)->getEndLoc()));
5690 
5691     numElements = LHSType->castAs<VectorType>()->getNumElements();
5692     unsigned numResElements = TheCall->getNumArgs() - 2;
5693 
5694     // Check to see if we have a call with 2 vector arguments, the unary shuffle
5695     // with mask.  If so, verify that RHS is an integer vector type with the
5696     // same number of elts as lhs.
5697     if (TheCall->getNumArgs() == 2) {
5698       if (!RHSType->hasIntegerRepresentation() ||
5699           RHSType->castAs<VectorType>()->getNumElements() != numElements)
5700         return ExprError(Diag(TheCall->getBeginLoc(),
5701                               diag::err_vec_builtin_incompatible_vector)
5702                          << TheCall->getDirectCallee()
5703                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
5704                                         TheCall->getArg(1)->getEndLoc()));
5705     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
5706       return ExprError(Diag(TheCall->getBeginLoc(),
5707                             diag::err_vec_builtin_incompatible_vector)
5708                        << TheCall->getDirectCallee()
5709                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5710                                       TheCall->getArg(1)->getEndLoc()));
5711     } else if (numElements != numResElements) {
5712       QualType eltType = LHSType->castAs<VectorType>()->getElementType();
5713       resType = Context.getVectorType(eltType, numResElements,
5714                                       VectorType::GenericVector);
5715     }
5716   }
5717 
5718   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
5719     if (TheCall->getArg(i)->isTypeDependent() ||
5720         TheCall->getArg(i)->isValueDependent())
5721       continue;
5722 
5723     llvm::APSInt Result(32);
5724     if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
5725       return ExprError(Diag(TheCall->getBeginLoc(),
5726                             diag::err_shufflevector_nonconstant_argument)
5727                        << TheCall->getArg(i)->getSourceRange());
5728 
5729     // Allow -1 which will be translated to undef in the IR.
5730     if (Result.isSigned() && Result.isAllOnesValue())
5731       continue;
5732 
5733     if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
5734       return ExprError(Diag(TheCall->getBeginLoc(),
5735                             diag::err_shufflevector_argument_too_large)
5736                        << TheCall->getArg(i)->getSourceRange());
5737   }
5738 
5739   SmallVector<Expr*, 32> exprs;
5740 
5741   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
5742     exprs.push_back(TheCall->getArg(i));
5743     TheCall->setArg(i, nullptr);
5744   }
5745 
5746   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
5747                                          TheCall->getCallee()->getBeginLoc(),
5748                                          TheCall->getRParenLoc());
5749 }
5750 
5751 /// SemaConvertVectorExpr - Handle __builtin_convertvector
5752 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
5753                                        SourceLocation BuiltinLoc,
5754                                        SourceLocation RParenLoc) {
5755   ExprValueKind VK = VK_RValue;
5756   ExprObjectKind OK = OK_Ordinary;
5757   QualType DstTy = TInfo->getType();
5758   QualType SrcTy = E->getType();
5759 
5760   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
5761     return ExprError(Diag(BuiltinLoc,
5762                           diag::err_convertvector_non_vector)
5763                      << E->getSourceRange());
5764   if (!DstTy->isVectorType() && !DstTy->isDependentType())
5765     return ExprError(Diag(BuiltinLoc,
5766                           diag::err_convertvector_non_vector_type));
5767 
5768   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
5769     unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
5770     unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
5771     if (SrcElts != DstElts)
5772       return ExprError(Diag(BuiltinLoc,
5773                             diag::err_convertvector_incompatible_vector)
5774                        << E->getSourceRange());
5775   }
5776 
5777   return new (Context)
5778       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5779 }
5780 
5781 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
5782 // This is declared to take (const void*, ...) and can take two
5783 // optional constant int args.
5784 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
5785   unsigned NumArgs = TheCall->getNumArgs();
5786 
5787   if (NumArgs > 3)
5788     return Diag(TheCall->getEndLoc(),
5789                 diag::err_typecheck_call_too_many_args_at_most)
5790            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
5791 
5792   // Argument 0 is checked for us and the remaining arguments must be
5793   // constant integers.
5794   for (unsigned i = 1; i != NumArgs; ++i)
5795     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
5796       return true;
5797 
5798   return false;
5799 }
5800 
5801 /// SemaBuiltinAssume - Handle __assume (MS Extension).
5802 // __assume does not evaluate its arguments, and should warn if its argument
5803 // has side effects.
5804 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
5805   Expr *Arg = TheCall->getArg(0);
5806   if (Arg->isInstantiationDependent()) return false;
5807 
5808   if (Arg->HasSideEffects(Context))
5809     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
5810         << Arg->getSourceRange()
5811         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
5812 
5813   return false;
5814 }
5815 
5816 /// Handle __builtin_alloca_with_align. This is declared
5817 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
5818 /// than 8.
5819 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
5820   // The alignment must be a constant integer.
5821   Expr *Arg = TheCall->getArg(1);
5822 
5823   // We can't check the value of a dependent argument.
5824   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
5825     if (const auto *UE =
5826             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
5827       if (UE->getKind() == UETT_AlignOf ||
5828           UE->getKind() == UETT_PreferredAlignOf)
5829         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
5830             << Arg->getSourceRange();
5831 
5832     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
5833 
5834     if (!Result.isPowerOf2())
5835       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5836              << Arg->getSourceRange();
5837 
5838     if (Result < Context.getCharWidth())
5839       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
5840              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
5841 
5842     if (Result > std::numeric_limits<int32_t>::max())
5843       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
5844              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
5845   }
5846 
5847   return false;
5848 }
5849 
5850 /// Handle __builtin_assume_aligned. This is declared
5851 /// as (const void*, size_t, ...) and can take one optional constant int arg.
5852 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
5853   unsigned NumArgs = TheCall->getNumArgs();
5854 
5855   if (NumArgs > 3)
5856     return Diag(TheCall->getEndLoc(),
5857                 diag::err_typecheck_call_too_many_args_at_most)
5858            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
5859 
5860   // The alignment must be a constant integer.
5861   Expr *Arg = TheCall->getArg(1);
5862 
5863   // We can't check the value of a dependent argument.
5864   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
5865     llvm::APSInt Result;
5866     if (SemaBuiltinConstantArg(TheCall, 1, Result))
5867       return true;
5868 
5869     if (!Result.isPowerOf2())
5870       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5871              << Arg->getSourceRange();
5872 
5873     if (Result > Sema::MaximumAlignment)
5874       Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
5875           << Arg->getSourceRange() << Sema::MaximumAlignment;
5876   }
5877 
5878   if (NumArgs > 2) {
5879     ExprResult Arg(TheCall->getArg(2));
5880     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5881       Context.getSizeType(), false);
5882     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5883     if (Arg.isInvalid()) return true;
5884     TheCall->setArg(2, Arg.get());
5885   }
5886 
5887   return false;
5888 }
5889 
5890 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
5891   unsigned BuiltinID =
5892       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
5893   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
5894 
5895   unsigned NumArgs = TheCall->getNumArgs();
5896   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
5897   if (NumArgs < NumRequiredArgs) {
5898     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5899            << 0 /* function call */ << NumRequiredArgs << NumArgs
5900            << TheCall->getSourceRange();
5901   }
5902   if (NumArgs >= NumRequiredArgs + 0x100) {
5903     return Diag(TheCall->getEndLoc(),
5904                 diag::err_typecheck_call_too_many_args_at_most)
5905            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
5906            << TheCall->getSourceRange();
5907   }
5908   unsigned i = 0;
5909 
5910   // For formatting call, check buffer arg.
5911   if (!IsSizeCall) {
5912     ExprResult Arg(TheCall->getArg(i));
5913     InitializedEntity Entity = InitializedEntity::InitializeParameter(
5914         Context, Context.VoidPtrTy, false);
5915     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5916     if (Arg.isInvalid())
5917       return true;
5918     TheCall->setArg(i, Arg.get());
5919     i++;
5920   }
5921 
5922   // Check string literal arg.
5923   unsigned FormatIdx = i;
5924   {
5925     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
5926     if (Arg.isInvalid())
5927       return true;
5928     TheCall->setArg(i, Arg.get());
5929     i++;
5930   }
5931 
5932   // Make sure variadic args are scalar.
5933   unsigned FirstDataArg = i;
5934   while (i < NumArgs) {
5935     ExprResult Arg = DefaultVariadicArgumentPromotion(
5936         TheCall->getArg(i), VariadicFunction, nullptr);
5937     if (Arg.isInvalid())
5938       return true;
5939     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
5940     if (ArgSize.getQuantity() >= 0x100) {
5941       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
5942              << i << (int)ArgSize.getQuantity() << 0xff
5943              << TheCall->getSourceRange();
5944     }
5945     TheCall->setArg(i, Arg.get());
5946     i++;
5947   }
5948 
5949   // Check formatting specifiers. NOTE: We're only doing this for the non-size
5950   // call to avoid duplicate diagnostics.
5951   if (!IsSizeCall) {
5952     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
5953     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
5954     bool Success = CheckFormatArguments(
5955         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
5956         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
5957         CheckedVarArgs);
5958     if (!Success)
5959       return true;
5960   }
5961 
5962   if (IsSizeCall) {
5963     TheCall->setType(Context.getSizeType());
5964   } else {
5965     TheCall->setType(Context.VoidPtrTy);
5966   }
5967   return false;
5968 }
5969 
5970 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
5971 /// TheCall is a constant expression.
5972 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
5973                                   llvm::APSInt &Result) {
5974   Expr *Arg = TheCall->getArg(ArgNum);
5975   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5976   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5977 
5978   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
5979 
5980   if (!Arg->isIntegerConstantExpr(Result, Context))
5981     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
5982            << FDecl->getDeclName() << Arg->getSourceRange();
5983 
5984   return false;
5985 }
5986 
5987 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
5988 /// TheCall is a constant expression in the range [Low, High].
5989 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
5990                                        int Low, int High, bool RangeIsError) {
5991   if (isConstantEvaluated())
5992     return false;
5993   llvm::APSInt Result;
5994 
5995   // We can't check the value of a dependent argument.
5996   Expr *Arg = TheCall->getArg(ArgNum);
5997   if (Arg->isTypeDependent() || Arg->isValueDependent())
5998     return false;
5999 
6000   // Check constant-ness first.
6001   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6002     return true;
6003 
6004   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6005     if (RangeIsError)
6006       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
6007              << Result.toString(10) << Low << High << Arg->getSourceRange();
6008     else
6009       // Defer the warning until we know if the code will be emitted so that
6010       // dead code can ignore this.
6011       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6012                           PDiag(diag::warn_argument_invalid_range)
6013                               << Result.toString(10) << Low << High
6014                               << Arg->getSourceRange());
6015   }
6016 
6017   return false;
6018 }
6019 
6020 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
6021 /// TheCall is a constant expression is a multiple of Num..
6022 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
6023                                           unsigned Num) {
6024   llvm::APSInt Result;
6025 
6026   // We can't check the value of a dependent argument.
6027   Expr *Arg = TheCall->getArg(ArgNum);
6028   if (Arg->isTypeDependent() || Arg->isValueDependent())
6029     return false;
6030 
6031   // Check constant-ness first.
6032   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6033     return true;
6034 
6035   if (Result.getSExtValue() % Num != 0)
6036     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6037            << Num << Arg->getSourceRange();
6038 
6039   return false;
6040 }
6041 
6042 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
6043 /// constant expression representing a power of 2.
6044 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
6045   llvm::APSInt Result;
6046 
6047   // We can't check the value of a dependent argument.
6048   Expr *Arg = TheCall->getArg(ArgNum);
6049   if (Arg->isTypeDependent() || Arg->isValueDependent())
6050     return false;
6051 
6052   // Check constant-ness first.
6053   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6054     return true;
6055 
6056   // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
6057   // and only if x is a power of 2.
6058   if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
6059     return false;
6060 
6061   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
6062          << Arg->getSourceRange();
6063 }
6064 
6065 static bool IsShiftedByte(llvm::APSInt Value) {
6066   if (Value.isNegative())
6067     return false;
6068 
6069   // Check if it's a shifted byte, by shifting it down
6070   while (true) {
6071     // If the value fits in the bottom byte, the check passes.
6072     if (Value < 0x100)
6073       return true;
6074 
6075     // Otherwise, if the value has _any_ bits in the bottom byte, the check
6076     // fails.
6077     if ((Value & 0xFF) != 0)
6078       return false;
6079 
6080     // If the bottom 8 bits are all 0, but something above that is nonzero,
6081     // then shifting the value right by 8 bits won't affect whether it's a
6082     // shifted byte or not. So do that, and go round again.
6083     Value >>= 8;
6084   }
6085 }
6086 
6087 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
6088 /// a constant expression representing an arbitrary byte value shifted left by
6089 /// a multiple of 8 bits.
6090 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
6091                                              unsigned ArgBits) {
6092   llvm::APSInt Result;
6093 
6094   // We can't check the value of a dependent argument.
6095   Expr *Arg = TheCall->getArg(ArgNum);
6096   if (Arg->isTypeDependent() || Arg->isValueDependent())
6097     return false;
6098 
6099   // Check constant-ness first.
6100   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6101     return true;
6102 
6103   // Truncate to the given size.
6104   Result = Result.getLoBits(ArgBits);
6105   Result.setIsUnsigned(true);
6106 
6107   if (IsShiftedByte(Result))
6108     return false;
6109 
6110   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
6111          << Arg->getSourceRange();
6112 }
6113 
6114 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
6115 /// TheCall is a constant expression representing either a shifted byte value,
6116 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
6117 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
6118 /// Arm MVE intrinsics.
6119 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
6120                                                    int ArgNum,
6121                                                    unsigned ArgBits) {
6122   llvm::APSInt Result;
6123 
6124   // We can't check the value of a dependent argument.
6125   Expr *Arg = TheCall->getArg(ArgNum);
6126   if (Arg->isTypeDependent() || Arg->isValueDependent())
6127     return false;
6128 
6129   // Check constant-ness first.
6130   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6131     return true;
6132 
6133   // Truncate to the given size.
6134   Result = Result.getLoBits(ArgBits);
6135   Result.setIsUnsigned(true);
6136 
6137   // Check to see if it's in either of the required forms.
6138   if (IsShiftedByte(Result) ||
6139       (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
6140     return false;
6141 
6142   return Diag(TheCall->getBeginLoc(),
6143               diag::err_argument_not_shifted_byte_or_xxff)
6144          << Arg->getSourceRange();
6145 }
6146 
6147 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
6148 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
6149   if (BuiltinID == AArch64::BI__builtin_arm_irg) {
6150     if (checkArgCount(*this, TheCall, 2))
6151       return true;
6152     Expr *Arg0 = TheCall->getArg(0);
6153     Expr *Arg1 = TheCall->getArg(1);
6154 
6155     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6156     if (FirstArg.isInvalid())
6157       return true;
6158     QualType FirstArgType = FirstArg.get()->getType();
6159     if (!FirstArgType->isAnyPointerType())
6160       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6161                << "first" << FirstArgType << Arg0->getSourceRange();
6162     TheCall->setArg(0, FirstArg.get());
6163 
6164     ExprResult SecArg = DefaultLvalueConversion(Arg1);
6165     if (SecArg.isInvalid())
6166       return true;
6167     QualType SecArgType = SecArg.get()->getType();
6168     if (!SecArgType->isIntegerType())
6169       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6170                << "second" << SecArgType << Arg1->getSourceRange();
6171 
6172     // Derive the return type from the pointer argument.
6173     TheCall->setType(FirstArgType);
6174     return false;
6175   }
6176 
6177   if (BuiltinID == AArch64::BI__builtin_arm_addg) {
6178     if (checkArgCount(*this, TheCall, 2))
6179       return true;
6180 
6181     Expr *Arg0 = TheCall->getArg(0);
6182     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6183     if (FirstArg.isInvalid())
6184       return true;
6185     QualType FirstArgType = FirstArg.get()->getType();
6186     if (!FirstArgType->isAnyPointerType())
6187       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6188                << "first" << FirstArgType << Arg0->getSourceRange();
6189     TheCall->setArg(0, FirstArg.get());
6190 
6191     // Derive the return type from the pointer argument.
6192     TheCall->setType(FirstArgType);
6193 
6194     // Second arg must be an constant in range [0,15]
6195     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6196   }
6197 
6198   if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
6199     if (checkArgCount(*this, TheCall, 2))
6200       return true;
6201     Expr *Arg0 = TheCall->getArg(0);
6202     Expr *Arg1 = TheCall->getArg(1);
6203 
6204     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6205     if (FirstArg.isInvalid())
6206       return true;
6207     QualType FirstArgType = FirstArg.get()->getType();
6208     if (!FirstArgType->isAnyPointerType())
6209       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6210                << "first" << FirstArgType << Arg0->getSourceRange();
6211 
6212     QualType SecArgType = Arg1->getType();
6213     if (!SecArgType->isIntegerType())
6214       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6215                << "second" << SecArgType << Arg1->getSourceRange();
6216     TheCall->setType(Context.IntTy);
6217     return false;
6218   }
6219 
6220   if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
6221       BuiltinID == AArch64::BI__builtin_arm_stg) {
6222     if (checkArgCount(*this, TheCall, 1))
6223       return true;
6224     Expr *Arg0 = TheCall->getArg(0);
6225     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6226     if (FirstArg.isInvalid())
6227       return true;
6228 
6229     QualType FirstArgType = FirstArg.get()->getType();
6230     if (!FirstArgType->isAnyPointerType())
6231       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6232                << "first" << FirstArgType << Arg0->getSourceRange();
6233     TheCall->setArg(0, FirstArg.get());
6234 
6235     // Derive the return type from the pointer argument.
6236     if (BuiltinID == AArch64::BI__builtin_arm_ldg)
6237       TheCall->setType(FirstArgType);
6238     return false;
6239   }
6240 
6241   if (BuiltinID == AArch64::BI__builtin_arm_subp) {
6242     Expr *ArgA = TheCall->getArg(0);
6243     Expr *ArgB = TheCall->getArg(1);
6244 
6245     ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
6246     ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
6247 
6248     if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
6249       return true;
6250 
6251     QualType ArgTypeA = ArgExprA.get()->getType();
6252     QualType ArgTypeB = ArgExprB.get()->getType();
6253 
6254     auto isNull = [&] (Expr *E) -> bool {
6255       return E->isNullPointerConstant(
6256                         Context, Expr::NPC_ValueDependentIsNotNull); };
6257 
6258     // argument should be either a pointer or null
6259     if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
6260       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6261         << "first" << ArgTypeA << ArgA->getSourceRange();
6262 
6263     if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
6264       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6265         << "second" << ArgTypeB << ArgB->getSourceRange();
6266 
6267     // Ensure Pointee types are compatible
6268     if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
6269         ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
6270       QualType pointeeA = ArgTypeA->getPointeeType();
6271       QualType pointeeB = ArgTypeB->getPointeeType();
6272       if (!Context.typesAreCompatible(
6273              Context.getCanonicalType(pointeeA).getUnqualifiedType(),
6274              Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
6275         return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
6276           << ArgTypeA <<  ArgTypeB << ArgA->getSourceRange()
6277           << ArgB->getSourceRange();
6278       }
6279     }
6280 
6281     // at least one argument should be pointer type
6282     if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
6283       return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
6284         <<  ArgTypeA << ArgTypeB << ArgA->getSourceRange();
6285 
6286     if (isNull(ArgA)) // adopt type of the other pointer
6287       ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
6288 
6289     if (isNull(ArgB))
6290       ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
6291 
6292     TheCall->setArg(0, ArgExprA.get());
6293     TheCall->setArg(1, ArgExprB.get());
6294     TheCall->setType(Context.LongLongTy);
6295     return false;
6296   }
6297   assert(false && "Unhandled ARM MTE intrinsic");
6298   return true;
6299 }
6300 
6301 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
6302 /// TheCall is an ARM/AArch64 special register string literal.
6303 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
6304                                     int ArgNum, unsigned ExpectedFieldNum,
6305                                     bool AllowName) {
6306   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
6307                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
6308                       BuiltinID == ARM::BI__builtin_arm_rsr ||
6309                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
6310                       BuiltinID == ARM::BI__builtin_arm_wsr ||
6311                       BuiltinID == ARM::BI__builtin_arm_wsrp;
6312   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
6313                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
6314                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
6315                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
6316                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
6317                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
6318   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
6319 
6320   // We can't check the value of a dependent argument.
6321   Expr *Arg = TheCall->getArg(ArgNum);
6322   if (Arg->isTypeDependent() || Arg->isValueDependent())
6323     return false;
6324 
6325   // Check if the argument is a string literal.
6326   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
6327     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
6328            << Arg->getSourceRange();
6329 
6330   // Check the type of special register given.
6331   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
6332   SmallVector<StringRef, 6> Fields;
6333   Reg.split(Fields, ":");
6334 
6335   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
6336     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6337            << Arg->getSourceRange();
6338 
6339   // If the string is the name of a register then we cannot check that it is
6340   // valid here but if the string is of one the forms described in ACLE then we
6341   // can check that the supplied fields are integers and within the valid
6342   // ranges.
6343   if (Fields.size() > 1) {
6344     bool FiveFields = Fields.size() == 5;
6345 
6346     bool ValidString = true;
6347     if (IsARMBuiltin) {
6348       ValidString &= Fields[0].startswith_lower("cp") ||
6349                      Fields[0].startswith_lower("p");
6350       if (ValidString)
6351         Fields[0] =
6352           Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
6353 
6354       ValidString &= Fields[2].startswith_lower("c");
6355       if (ValidString)
6356         Fields[2] = Fields[2].drop_front(1);
6357 
6358       if (FiveFields) {
6359         ValidString &= Fields[3].startswith_lower("c");
6360         if (ValidString)
6361           Fields[3] = Fields[3].drop_front(1);
6362       }
6363     }
6364 
6365     SmallVector<int, 5> Ranges;
6366     if (FiveFields)
6367       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
6368     else
6369       Ranges.append({15, 7, 15});
6370 
6371     for (unsigned i=0; i<Fields.size(); ++i) {
6372       int IntField;
6373       ValidString &= !Fields[i].getAsInteger(10, IntField);
6374       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
6375     }
6376 
6377     if (!ValidString)
6378       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6379              << Arg->getSourceRange();
6380   } else if (IsAArch64Builtin && Fields.size() == 1) {
6381     // If the register name is one of those that appear in the condition below
6382     // and the special register builtin being used is one of the write builtins,
6383     // then we require that the argument provided for writing to the register
6384     // is an integer constant expression. This is because it will be lowered to
6385     // an MSR (immediate) instruction, so we need to know the immediate at
6386     // compile time.
6387     if (TheCall->getNumArgs() != 2)
6388       return false;
6389 
6390     std::string RegLower = Reg.lower();
6391     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
6392         RegLower != "pan" && RegLower != "uao")
6393       return false;
6394 
6395     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6396   }
6397 
6398   return false;
6399 }
6400 
6401 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
6402 /// This checks that the target supports __builtin_longjmp and
6403 /// that val is a constant 1.
6404 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
6405   if (!Context.getTargetInfo().hasSjLjLowering())
6406     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
6407            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6408 
6409   Expr *Arg = TheCall->getArg(1);
6410   llvm::APSInt Result;
6411 
6412   // TODO: This is less than ideal. Overload this to take a value.
6413   if (SemaBuiltinConstantArg(TheCall, 1, Result))
6414     return true;
6415 
6416   if (Result != 1)
6417     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
6418            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
6419 
6420   return false;
6421 }
6422 
6423 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
6424 /// This checks that the target supports __builtin_setjmp.
6425 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
6426   if (!Context.getTargetInfo().hasSjLjLowering())
6427     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
6428            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6429   return false;
6430 }
6431 
6432 namespace {
6433 
6434 class UncoveredArgHandler {
6435   enum { Unknown = -1, AllCovered = -2 };
6436 
6437   signed FirstUncoveredArg = Unknown;
6438   SmallVector<const Expr *, 4> DiagnosticExprs;
6439 
6440 public:
6441   UncoveredArgHandler() = default;
6442 
6443   bool hasUncoveredArg() const {
6444     return (FirstUncoveredArg >= 0);
6445   }
6446 
6447   unsigned getUncoveredArg() const {
6448     assert(hasUncoveredArg() && "no uncovered argument");
6449     return FirstUncoveredArg;
6450   }
6451 
6452   void setAllCovered() {
6453     // A string has been found with all arguments covered, so clear out
6454     // the diagnostics.
6455     DiagnosticExprs.clear();
6456     FirstUncoveredArg = AllCovered;
6457   }
6458 
6459   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
6460     assert(NewFirstUncoveredArg >= 0 && "Outside range");
6461 
6462     // Don't update if a previous string covers all arguments.
6463     if (FirstUncoveredArg == AllCovered)
6464       return;
6465 
6466     // UncoveredArgHandler tracks the highest uncovered argument index
6467     // and with it all the strings that match this index.
6468     if (NewFirstUncoveredArg == FirstUncoveredArg)
6469       DiagnosticExprs.push_back(StrExpr);
6470     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
6471       DiagnosticExprs.clear();
6472       DiagnosticExprs.push_back(StrExpr);
6473       FirstUncoveredArg = NewFirstUncoveredArg;
6474     }
6475   }
6476 
6477   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
6478 };
6479 
6480 enum StringLiteralCheckType {
6481   SLCT_NotALiteral,
6482   SLCT_UncheckedLiteral,
6483   SLCT_CheckedLiteral
6484 };
6485 
6486 } // namespace
6487 
6488 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
6489                                      BinaryOperatorKind BinOpKind,
6490                                      bool AddendIsRight) {
6491   unsigned BitWidth = Offset.getBitWidth();
6492   unsigned AddendBitWidth = Addend.getBitWidth();
6493   // There might be negative interim results.
6494   if (Addend.isUnsigned()) {
6495     Addend = Addend.zext(++AddendBitWidth);
6496     Addend.setIsSigned(true);
6497   }
6498   // Adjust the bit width of the APSInts.
6499   if (AddendBitWidth > BitWidth) {
6500     Offset = Offset.sext(AddendBitWidth);
6501     BitWidth = AddendBitWidth;
6502   } else if (BitWidth > AddendBitWidth) {
6503     Addend = Addend.sext(BitWidth);
6504   }
6505 
6506   bool Ov = false;
6507   llvm::APSInt ResOffset = Offset;
6508   if (BinOpKind == BO_Add)
6509     ResOffset = Offset.sadd_ov(Addend, Ov);
6510   else {
6511     assert(AddendIsRight && BinOpKind == BO_Sub &&
6512            "operator must be add or sub with addend on the right");
6513     ResOffset = Offset.ssub_ov(Addend, Ov);
6514   }
6515 
6516   // We add an offset to a pointer here so we should support an offset as big as
6517   // possible.
6518   if (Ov) {
6519     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
6520            "index (intermediate) result too big");
6521     Offset = Offset.sext(2 * BitWidth);
6522     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
6523     return;
6524   }
6525 
6526   Offset = ResOffset;
6527 }
6528 
6529 namespace {
6530 
6531 // This is a wrapper class around StringLiteral to support offsetted string
6532 // literals as format strings. It takes the offset into account when returning
6533 // the string and its length or the source locations to display notes correctly.
6534 class FormatStringLiteral {
6535   const StringLiteral *FExpr;
6536   int64_t Offset;
6537 
6538  public:
6539   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
6540       : FExpr(fexpr), Offset(Offset) {}
6541 
6542   StringRef getString() const {
6543     return FExpr->getString().drop_front(Offset);
6544   }
6545 
6546   unsigned getByteLength() const {
6547     return FExpr->getByteLength() - getCharByteWidth() * Offset;
6548   }
6549 
6550   unsigned getLength() const { return FExpr->getLength() - Offset; }
6551   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
6552 
6553   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
6554 
6555   QualType getType() const { return FExpr->getType(); }
6556 
6557   bool isAscii() const { return FExpr->isAscii(); }
6558   bool isWide() const { return FExpr->isWide(); }
6559   bool isUTF8() const { return FExpr->isUTF8(); }
6560   bool isUTF16() const { return FExpr->isUTF16(); }
6561   bool isUTF32() const { return FExpr->isUTF32(); }
6562   bool isPascal() const { return FExpr->isPascal(); }
6563 
6564   SourceLocation getLocationOfByte(
6565       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
6566       const TargetInfo &Target, unsigned *StartToken = nullptr,
6567       unsigned *StartTokenByteOffset = nullptr) const {
6568     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
6569                                     StartToken, StartTokenByteOffset);
6570   }
6571 
6572   SourceLocation getBeginLoc() const LLVM_READONLY {
6573     return FExpr->getBeginLoc().getLocWithOffset(Offset);
6574   }
6575 
6576   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
6577 };
6578 
6579 }  // namespace
6580 
6581 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
6582                               const Expr *OrigFormatExpr,
6583                               ArrayRef<const Expr *> Args,
6584                               bool HasVAListArg, unsigned format_idx,
6585                               unsigned firstDataArg,
6586                               Sema::FormatStringType Type,
6587                               bool inFunctionCall,
6588                               Sema::VariadicCallType CallType,
6589                               llvm::SmallBitVector &CheckedVarArgs,
6590                               UncoveredArgHandler &UncoveredArg,
6591                               bool IgnoreStringsWithoutSpecifiers);
6592 
6593 // Determine if an expression is a string literal or constant string.
6594 // If this function returns false on the arguments to a function expecting a
6595 // format string, we will usually need to emit a warning.
6596 // True string literals are then checked by CheckFormatString.
6597 static StringLiteralCheckType
6598 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
6599                       bool HasVAListArg, unsigned format_idx,
6600                       unsigned firstDataArg, Sema::FormatStringType Type,
6601                       Sema::VariadicCallType CallType, bool InFunctionCall,
6602                       llvm::SmallBitVector &CheckedVarArgs,
6603                       UncoveredArgHandler &UncoveredArg,
6604                       llvm::APSInt Offset,
6605                       bool IgnoreStringsWithoutSpecifiers = false) {
6606   if (S.isConstantEvaluated())
6607     return SLCT_NotALiteral;
6608  tryAgain:
6609   assert(Offset.isSigned() && "invalid offset");
6610 
6611   if (E->isTypeDependent() || E->isValueDependent())
6612     return SLCT_NotALiteral;
6613 
6614   E = E->IgnoreParenCasts();
6615 
6616   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
6617     // Technically -Wformat-nonliteral does not warn about this case.
6618     // The behavior of printf and friends in this case is implementation
6619     // dependent.  Ideally if the format string cannot be null then
6620     // it should have a 'nonnull' attribute in the function prototype.
6621     return SLCT_UncheckedLiteral;
6622 
6623   switch (E->getStmtClass()) {
6624   case Stmt::BinaryConditionalOperatorClass:
6625   case Stmt::ConditionalOperatorClass: {
6626     // The expression is a literal if both sub-expressions were, and it was
6627     // completely checked only if both sub-expressions were checked.
6628     const AbstractConditionalOperator *C =
6629         cast<AbstractConditionalOperator>(E);
6630 
6631     // Determine whether it is necessary to check both sub-expressions, for
6632     // example, because the condition expression is a constant that can be
6633     // evaluated at compile time.
6634     bool CheckLeft = true, CheckRight = true;
6635 
6636     bool Cond;
6637     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
6638                                                  S.isConstantEvaluated())) {
6639       if (Cond)
6640         CheckRight = false;
6641       else
6642         CheckLeft = false;
6643     }
6644 
6645     // We need to maintain the offsets for the right and the left hand side
6646     // separately to check if every possible indexed expression is a valid
6647     // string literal. They might have different offsets for different string
6648     // literals in the end.
6649     StringLiteralCheckType Left;
6650     if (!CheckLeft)
6651       Left = SLCT_UncheckedLiteral;
6652     else {
6653       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
6654                                    HasVAListArg, format_idx, firstDataArg,
6655                                    Type, CallType, InFunctionCall,
6656                                    CheckedVarArgs, UncoveredArg, Offset,
6657                                    IgnoreStringsWithoutSpecifiers);
6658       if (Left == SLCT_NotALiteral || !CheckRight) {
6659         return Left;
6660       }
6661     }
6662 
6663     StringLiteralCheckType Right = checkFormatStringExpr(
6664         S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
6665         Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6666         IgnoreStringsWithoutSpecifiers);
6667 
6668     return (CheckLeft && Left < Right) ? Left : Right;
6669   }
6670 
6671   case Stmt::ImplicitCastExprClass:
6672     E = cast<ImplicitCastExpr>(E)->getSubExpr();
6673     goto tryAgain;
6674 
6675   case Stmt::OpaqueValueExprClass:
6676     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
6677       E = src;
6678       goto tryAgain;
6679     }
6680     return SLCT_NotALiteral;
6681 
6682   case Stmt::PredefinedExprClass:
6683     // While __func__, etc., are technically not string literals, they
6684     // cannot contain format specifiers and thus are not a security
6685     // liability.
6686     return SLCT_UncheckedLiteral;
6687 
6688   case Stmt::DeclRefExprClass: {
6689     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6690 
6691     // As an exception, do not flag errors for variables binding to
6692     // const string literals.
6693     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
6694       bool isConstant = false;
6695       QualType T = DR->getType();
6696 
6697       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
6698         isConstant = AT->getElementType().isConstant(S.Context);
6699       } else if (const PointerType *PT = T->getAs<PointerType>()) {
6700         isConstant = T.isConstant(S.Context) &&
6701                      PT->getPointeeType().isConstant(S.Context);
6702       } else if (T->isObjCObjectPointerType()) {
6703         // In ObjC, there is usually no "const ObjectPointer" type,
6704         // so don't check if the pointee type is constant.
6705         isConstant = T.isConstant(S.Context);
6706       }
6707 
6708       if (isConstant) {
6709         if (const Expr *Init = VD->getAnyInitializer()) {
6710           // Look through initializers like const char c[] = { "foo" }
6711           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
6712             if (InitList->isStringLiteralInit())
6713               Init = InitList->getInit(0)->IgnoreParenImpCasts();
6714           }
6715           return checkFormatStringExpr(S, Init, Args,
6716                                        HasVAListArg, format_idx,
6717                                        firstDataArg, Type, CallType,
6718                                        /*InFunctionCall*/ false, CheckedVarArgs,
6719                                        UncoveredArg, Offset);
6720         }
6721       }
6722 
6723       // For vprintf* functions (i.e., HasVAListArg==true), we add a
6724       // special check to see if the format string is a function parameter
6725       // of the function calling the printf function.  If the function
6726       // has an attribute indicating it is a printf-like function, then we
6727       // should suppress warnings concerning non-literals being used in a call
6728       // to a vprintf function.  For example:
6729       //
6730       // void
6731       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
6732       //      va_list ap;
6733       //      va_start(ap, fmt);
6734       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
6735       //      ...
6736       // }
6737       if (HasVAListArg) {
6738         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
6739           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
6740             int PVIndex = PV->getFunctionScopeIndex() + 1;
6741             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
6742               // adjust for implicit parameter
6743               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6744                 if (MD->isInstance())
6745                   ++PVIndex;
6746               // We also check if the formats are compatible.
6747               // We can't pass a 'scanf' string to a 'printf' function.
6748               if (PVIndex == PVFormat->getFormatIdx() &&
6749                   Type == S.GetFormatStringType(PVFormat))
6750                 return SLCT_UncheckedLiteral;
6751             }
6752           }
6753         }
6754       }
6755     }
6756 
6757     return SLCT_NotALiteral;
6758   }
6759 
6760   case Stmt::CallExprClass:
6761   case Stmt::CXXMemberCallExprClass: {
6762     const CallExpr *CE = cast<CallExpr>(E);
6763     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
6764       bool IsFirst = true;
6765       StringLiteralCheckType CommonResult;
6766       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
6767         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
6768         StringLiteralCheckType Result = checkFormatStringExpr(
6769             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
6770             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6771             IgnoreStringsWithoutSpecifiers);
6772         if (IsFirst) {
6773           CommonResult = Result;
6774           IsFirst = false;
6775         }
6776       }
6777       if (!IsFirst)
6778         return CommonResult;
6779 
6780       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
6781         unsigned BuiltinID = FD->getBuiltinID();
6782         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
6783             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
6784           const Expr *Arg = CE->getArg(0);
6785           return checkFormatStringExpr(S, Arg, Args,
6786                                        HasVAListArg, format_idx,
6787                                        firstDataArg, Type, CallType,
6788                                        InFunctionCall, CheckedVarArgs,
6789                                        UncoveredArg, Offset,
6790                                        IgnoreStringsWithoutSpecifiers);
6791         }
6792       }
6793     }
6794 
6795     return SLCT_NotALiteral;
6796   }
6797   case Stmt::ObjCMessageExprClass: {
6798     const auto *ME = cast<ObjCMessageExpr>(E);
6799     if (const auto *MD = ME->getMethodDecl()) {
6800       if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
6801         // As a special case heuristic, if we're using the method -[NSBundle
6802         // localizedStringForKey:value:table:], ignore any key strings that lack
6803         // format specifiers. The idea is that if the key doesn't have any
6804         // format specifiers then its probably just a key to map to the
6805         // localized strings. If it does have format specifiers though, then its
6806         // likely that the text of the key is the format string in the
6807         // programmer's language, and should be checked.
6808         const ObjCInterfaceDecl *IFace;
6809         if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
6810             IFace->getIdentifier()->isStr("NSBundle") &&
6811             MD->getSelector().isKeywordSelector(
6812                 {"localizedStringForKey", "value", "table"})) {
6813           IgnoreStringsWithoutSpecifiers = true;
6814         }
6815 
6816         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
6817         return checkFormatStringExpr(
6818             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
6819             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6820             IgnoreStringsWithoutSpecifiers);
6821       }
6822     }
6823 
6824     return SLCT_NotALiteral;
6825   }
6826   case Stmt::ObjCStringLiteralClass:
6827   case Stmt::StringLiteralClass: {
6828     const StringLiteral *StrE = nullptr;
6829 
6830     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
6831       StrE = ObjCFExpr->getString();
6832     else
6833       StrE = cast<StringLiteral>(E);
6834 
6835     if (StrE) {
6836       if (Offset.isNegative() || Offset > StrE->getLength()) {
6837         // TODO: It would be better to have an explicit warning for out of
6838         // bounds literals.
6839         return SLCT_NotALiteral;
6840       }
6841       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
6842       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
6843                         firstDataArg, Type, InFunctionCall, CallType,
6844                         CheckedVarArgs, UncoveredArg,
6845                         IgnoreStringsWithoutSpecifiers);
6846       return SLCT_CheckedLiteral;
6847     }
6848 
6849     return SLCT_NotALiteral;
6850   }
6851   case Stmt::BinaryOperatorClass: {
6852     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
6853 
6854     // A string literal + an int offset is still a string literal.
6855     if (BinOp->isAdditiveOp()) {
6856       Expr::EvalResult LResult, RResult;
6857 
6858       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
6859           LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
6860       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
6861           RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
6862 
6863       if (LIsInt != RIsInt) {
6864         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
6865 
6866         if (LIsInt) {
6867           if (BinOpKind == BO_Add) {
6868             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
6869             E = BinOp->getRHS();
6870             goto tryAgain;
6871           }
6872         } else {
6873           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
6874           E = BinOp->getLHS();
6875           goto tryAgain;
6876         }
6877       }
6878     }
6879 
6880     return SLCT_NotALiteral;
6881   }
6882   case Stmt::UnaryOperatorClass: {
6883     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
6884     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
6885     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
6886       Expr::EvalResult IndexResult;
6887       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
6888                                        Expr::SE_NoSideEffects,
6889                                        S.isConstantEvaluated())) {
6890         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
6891                    /*RHS is int*/ true);
6892         E = ASE->getBase();
6893         goto tryAgain;
6894       }
6895     }
6896 
6897     return SLCT_NotALiteral;
6898   }
6899 
6900   default:
6901     return SLCT_NotALiteral;
6902   }
6903 }
6904 
6905 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
6906   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
6907       .Case("scanf", FST_Scanf)
6908       .Cases("printf", "printf0", FST_Printf)
6909       .Cases("NSString", "CFString", FST_NSString)
6910       .Case("strftime", FST_Strftime)
6911       .Case("strfmon", FST_Strfmon)
6912       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
6913       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
6914       .Case("os_trace", FST_OSLog)
6915       .Case("os_log", FST_OSLog)
6916       .Default(FST_Unknown);
6917 }
6918 
6919 /// CheckFormatArguments - Check calls to printf and scanf (and similar
6920 /// functions) for correct use of format strings.
6921 /// Returns true if a format string has been fully checked.
6922 bool Sema::CheckFormatArguments(const FormatAttr *Format,
6923                                 ArrayRef<const Expr *> Args,
6924                                 bool IsCXXMember,
6925                                 VariadicCallType CallType,
6926                                 SourceLocation Loc, SourceRange Range,
6927                                 llvm::SmallBitVector &CheckedVarArgs) {
6928   FormatStringInfo FSI;
6929   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
6930     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
6931                                 FSI.FirstDataArg, GetFormatStringType(Format),
6932                                 CallType, Loc, Range, CheckedVarArgs);
6933   return false;
6934 }
6935 
6936 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
6937                                 bool HasVAListArg, unsigned format_idx,
6938                                 unsigned firstDataArg, FormatStringType Type,
6939                                 VariadicCallType CallType,
6940                                 SourceLocation Loc, SourceRange Range,
6941                                 llvm::SmallBitVector &CheckedVarArgs) {
6942   // CHECK: printf/scanf-like function is called with no format string.
6943   if (format_idx >= Args.size()) {
6944     Diag(Loc, diag::warn_missing_format_string) << Range;
6945     return false;
6946   }
6947 
6948   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
6949 
6950   // CHECK: format string is not a string literal.
6951   //
6952   // Dynamically generated format strings are difficult to
6953   // automatically vet at compile time.  Requiring that format strings
6954   // are string literals: (1) permits the checking of format strings by
6955   // the compiler and thereby (2) can practically remove the source of
6956   // many format string exploits.
6957 
6958   // Format string can be either ObjC string (e.g. @"%d") or
6959   // C string (e.g. "%d")
6960   // ObjC string uses the same format specifiers as C string, so we can use
6961   // the same format string checking logic for both ObjC and C strings.
6962   UncoveredArgHandler UncoveredArg;
6963   StringLiteralCheckType CT =
6964       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
6965                             format_idx, firstDataArg, Type, CallType,
6966                             /*IsFunctionCall*/ true, CheckedVarArgs,
6967                             UncoveredArg,
6968                             /*no string offset*/ llvm::APSInt(64, false) = 0);
6969 
6970   // Generate a diagnostic where an uncovered argument is detected.
6971   if (UncoveredArg.hasUncoveredArg()) {
6972     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
6973     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
6974     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
6975   }
6976 
6977   if (CT != SLCT_NotALiteral)
6978     // Literal format string found, check done!
6979     return CT == SLCT_CheckedLiteral;
6980 
6981   // Strftime is particular as it always uses a single 'time' argument,
6982   // so it is safe to pass a non-literal string.
6983   if (Type == FST_Strftime)
6984     return false;
6985 
6986   // Do not emit diag when the string param is a macro expansion and the
6987   // format is either NSString or CFString. This is a hack to prevent
6988   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
6989   // which are usually used in place of NS and CF string literals.
6990   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
6991   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
6992     return false;
6993 
6994   // If there are no arguments specified, warn with -Wformat-security, otherwise
6995   // warn only with -Wformat-nonliteral.
6996   if (Args.size() == firstDataArg) {
6997     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
6998       << OrigFormatExpr->getSourceRange();
6999     switch (Type) {
7000     default:
7001       break;
7002     case FST_Kprintf:
7003     case FST_FreeBSDKPrintf:
7004     case FST_Printf:
7005       Diag(FormatLoc, diag::note_format_security_fixit)
7006         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
7007       break;
7008     case FST_NSString:
7009       Diag(FormatLoc, diag::note_format_security_fixit)
7010         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
7011       break;
7012     }
7013   } else {
7014     Diag(FormatLoc, diag::warn_format_nonliteral)
7015       << OrigFormatExpr->getSourceRange();
7016   }
7017   return false;
7018 }
7019 
7020 namespace {
7021 
7022 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
7023 protected:
7024   Sema &S;
7025   const FormatStringLiteral *FExpr;
7026   const Expr *OrigFormatExpr;
7027   const Sema::FormatStringType FSType;
7028   const unsigned FirstDataArg;
7029   const unsigned NumDataArgs;
7030   const char *Beg; // Start of format string.
7031   const bool HasVAListArg;
7032   ArrayRef<const Expr *> Args;
7033   unsigned FormatIdx;
7034   llvm::SmallBitVector CoveredArgs;
7035   bool usesPositionalArgs = false;
7036   bool atFirstArg = true;
7037   bool inFunctionCall;
7038   Sema::VariadicCallType CallType;
7039   llvm::SmallBitVector &CheckedVarArgs;
7040   UncoveredArgHandler &UncoveredArg;
7041 
7042 public:
7043   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
7044                      const Expr *origFormatExpr,
7045                      const Sema::FormatStringType type, unsigned firstDataArg,
7046                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
7047                      ArrayRef<const Expr *> Args, unsigned formatIdx,
7048                      bool inFunctionCall, Sema::VariadicCallType callType,
7049                      llvm::SmallBitVector &CheckedVarArgs,
7050                      UncoveredArgHandler &UncoveredArg)
7051       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
7052         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
7053         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
7054         inFunctionCall(inFunctionCall), CallType(callType),
7055         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
7056     CoveredArgs.resize(numDataArgs);
7057     CoveredArgs.reset();
7058   }
7059 
7060   void DoneProcessing();
7061 
7062   void HandleIncompleteSpecifier(const char *startSpecifier,
7063                                  unsigned specifierLen) override;
7064 
7065   void HandleInvalidLengthModifier(
7066                            const analyze_format_string::FormatSpecifier &FS,
7067                            const analyze_format_string::ConversionSpecifier &CS,
7068                            const char *startSpecifier, unsigned specifierLen,
7069                            unsigned DiagID);
7070 
7071   void HandleNonStandardLengthModifier(
7072                     const analyze_format_string::FormatSpecifier &FS,
7073                     const char *startSpecifier, unsigned specifierLen);
7074 
7075   void HandleNonStandardConversionSpecifier(
7076                     const analyze_format_string::ConversionSpecifier &CS,
7077                     const char *startSpecifier, unsigned specifierLen);
7078 
7079   void HandlePosition(const char *startPos, unsigned posLen) override;
7080 
7081   void HandleInvalidPosition(const char *startSpecifier,
7082                              unsigned specifierLen,
7083                              analyze_format_string::PositionContext p) override;
7084 
7085   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
7086 
7087   void HandleNullChar(const char *nullCharacter) override;
7088 
7089   template <typename Range>
7090   static void
7091   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
7092                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
7093                        bool IsStringLocation, Range StringRange,
7094                        ArrayRef<FixItHint> Fixit = None);
7095 
7096 protected:
7097   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
7098                                         const char *startSpec,
7099                                         unsigned specifierLen,
7100                                         const char *csStart, unsigned csLen);
7101 
7102   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
7103                                          const char *startSpec,
7104                                          unsigned specifierLen);
7105 
7106   SourceRange getFormatStringRange();
7107   CharSourceRange getSpecifierRange(const char *startSpecifier,
7108                                     unsigned specifierLen);
7109   SourceLocation getLocationOfByte(const char *x);
7110 
7111   const Expr *getDataArg(unsigned i) const;
7112 
7113   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
7114                     const analyze_format_string::ConversionSpecifier &CS,
7115                     const char *startSpecifier, unsigned specifierLen,
7116                     unsigned argIndex);
7117 
7118   template <typename Range>
7119   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
7120                             bool IsStringLocation, Range StringRange,
7121                             ArrayRef<FixItHint> Fixit = None);
7122 };
7123 
7124 } // namespace
7125 
7126 SourceRange CheckFormatHandler::getFormatStringRange() {
7127   return OrigFormatExpr->getSourceRange();
7128 }
7129 
7130 CharSourceRange CheckFormatHandler::
7131 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
7132   SourceLocation Start = getLocationOfByte(startSpecifier);
7133   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
7134 
7135   // Advance the end SourceLocation by one due to half-open ranges.
7136   End = End.getLocWithOffset(1);
7137 
7138   return CharSourceRange::getCharRange(Start, End);
7139 }
7140 
7141 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
7142   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
7143                                   S.getLangOpts(), S.Context.getTargetInfo());
7144 }
7145 
7146 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
7147                                                    unsigned specifierLen){
7148   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
7149                        getLocationOfByte(startSpecifier),
7150                        /*IsStringLocation*/true,
7151                        getSpecifierRange(startSpecifier, specifierLen));
7152 }
7153 
7154 void CheckFormatHandler::HandleInvalidLengthModifier(
7155     const analyze_format_string::FormatSpecifier &FS,
7156     const analyze_format_string::ConversionSpecifier &CS,
7157     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
7158   using namespace analyze_format_string;
7159 
7160   const LengthModifier &LM = FS.getLengthModifier();
7161   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7162 
7163   // See if we know how to fix this length modifier.
7164   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7165   if (FixedLM) {
7166     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7167                          getLocationOfByte(LM.getStart()),
7168                          /*IsStringLocation*/true,
7169                          getSpecifierRange(startSpecifier, specifierLen));
7170 
7171     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7172       << FixedLM->toString()
7173       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7174 
7175   } else {
7176     FixItHint Hint;
7177     if (DiagID == diag::warn_format_nonsensical_length)
7178       Hint = FixItHint::CreateRemoval(LMRange);
7179 
7180     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7181                          getLocationOfByte(LM.getStart()),
7182                          /*IsStringLocation*/true,
7183                          getSpecifierRange(startSpecifier, specifierLen),
7184                          Hint);
7185   }
7186 }
7187 
7188 void CheckFormatHandler::HandleNonStandardLengthModifier(
7189     const analyze_format_string::FormatSpecifier &FS,
7190     const char *startSpecifier, unsigned specifierLen) {
7191   using namespace analyze_format_string;
7192 
7193   const LengthModifier &LM = FS.getLengthModifier();
7194   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7195 
7196   // See if we know how to fix this length modifier.
7197   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7198   if (FixedLM) {
7199     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7200                            << LM.toString() << 0,
7201                          getLocationOfByte(LM.getStart()),
7202                          /*IsStringLocation*/true,
7203                          getSpecifierRange(startSpecifier, specifierLen));
7204 
7205     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7206       << FixedLM->toString()
7207       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7208 
7209   } else {
7210     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7211                            << LM.toString() << 0,
7212                          getLocationOfByte(LM.getStart()),
7213                          /*IsStringLocation*/true,
7214                          getSpecifierRange(startSpecifier, specifierLen));
7215   }
7216 }
7217 
7218 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
7219     const analyze_format_string::ConversionSpecifier &CS,
7220     const char *startSpecifier, unsigned specifierLen) {
7221   using namespace analyze_format_string;
7222 
7223   // See if we know how to fix this conversion specifier.
7224   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
7225   if (FixedCS) {
7226     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7227                           << CS.toString() << /*conversion specifier*/1,
7228                          getLocationOfByte(CS.getStart()),
7229                          /*IsStringLocation*/true,
7230                          getSpecifierRange(startSpecifier, specifierLen));
7231 
7232     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
7233     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
7234       << FixedCS->toString()
7235       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
7236   } else {
7237     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7238                           << CS.toString() << /*conversion specifier*/1,
7239                          getLocationOfByte(CS.getStart()),
7240                          /*IsStringLocation*/true,
7241                          getSpecifierRange(startSpecifier, specifierLen));
7242   }
7243 }
7244 
7245 void CheckFormatHandler::HandlePosition(const char *startPos,
7246                                         unsigned posLen) {
7247   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
7248                                getLocationOfByte(startPos),
7249                                /*IsStringLocation*/true,
7250                                getSpecifierRange(startPos, posLen));
7251 }
7252 
7253 void
7254 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
7255                                      analyze_format_string::PositionContext p) {
7256   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
7257                          << (unsigned) p,
7258                        getLocationOfByte(startPos), /*IsStringLocation*/true,
7259                        getSpecifierRange(startPos, posLen));
7260 }
7261 
7262 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
7263                                             unsigned posLen) {
7264   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
7265                                getLocationOfByte(startPos),
7266                                /*IsStringLocation*/true,
7267                                getSpecifierRange(startPos, posLen));
7268 }
7269 
7270 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
7271   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
7272     // The presence of a null character is likely an error.
7273     EmitFormatDiagnostic(
7274       S.PDiag(diag::warn_printf_format_string_contains_null_char),
7275       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
7276       getFormatStringRange());
7277   }
7278 }
7279 
7280 // Note that this may return NULL if there was an error parsing or building
7281 // one of the argument expressions.
7282 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
7283   return Args[FirstDataArg + i];
7284 }
7285 
7286 void CheckFormatHandler::DoneProcessing() {
7287   // Does the number of data arguments exceed the number of
7288   // format conversions in the format string?
7289   if (!HasVAListArg) {
7290       // Find any arguments that weren't covered.
7291     CoveredArgs.flip();
7292     signed notCoveredArg = CoveredArgs.find_first();
7293     if (notCoveredArg >= 0) {
7294       assert((unsigned)notCoveredArg < NumDataArgs);
7295       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
7296     } else {
7297       UncoveredArg.setAllCovered();
7298     }
7299   }
7300 }
7301 
7302 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
7303                                    const Expr *ArgExpr) {
7304   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
7305          "Invalid state");
7306 
7307   if (!ArgExpr)
7308     return;
7309 
7310   SourceLocation Loc = ArgExpr->getBeginLoc();
7311 
7312   if (S.getSourceManager().isInSystemMacro(Loc))
7313     return;
7314 
7315   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
7316   for (auto E : DiagnosticExprs)
7317     PDiag << E->getSourceRange();
7318 
7319   CheckFormatHandler::EmitFormatDiagnostic(
7320                                   S, IsFunctionCall, DiagnosticExprs[0],
7321                                   PDiag, Loc, /*IsStringLocation*/false,
7322                                   DiagnosticExprs[0]->getSourceRange());
7323 }
7324 
7325 bool
7326 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
7327                                                      SourceLocation Loc,
7328                                                      const char *startSpec,
7329                                                      unsigned specifierLen,
7330                                                      const char *csStart,
7331                                                      unsigned csLen) {
7332   bool keepGoing = true;
7333   if (argIndex < NumDataArgs) {
7334     // Consider the argument coverered, even though the specifier doesn't
7335     // make sense.
7336     CoveredArgs.set(argIndex);
7337   }
7338   else {
7339     // If argIndex exceeds the number of data arguments we
7340     // don't issue a warning because that is just a cascade of warnings (and
7341     // they may have intended '%%' anyway). We don't want to continue processing
7342     // the format string after this point, however, as we will like just get
7343     // gibberish when trying to match arguments.
7344     keepGoing = false;
7345   }
7346 
7347   StringRef Specifier(csStart, csLen);
7348 
7349   // If the specifier in non-printable, it could be the first byte of a UTF-8
7350   // sequence. In that case, print the UTF-8 code point. If not, print the byte
7351   // hex value.
7352   std::string CodePointStr;
7353   if (!llvm::sys::locale::isPrint(*csStart)) {
7354     llvm::UTF32 CodePoint;
7355     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
7356     const llvm::UTF8 *E =
7357         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
7358     llvm::ConversionResult Result =
7359         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
7360 
7361     if (Result != llvm::conversionOK) {
7362       unsigned char FirstChar = *csStart;
7363       CodePoint = (llvm::UTF32)FirstChar;
7364     }
7365 
7366     llvm::raw_string_ostream OS(CodePointStr);
7367     if (CodePoint < 256)
7368       OS << "\\x" << llvm::format("%02x", CodePoint);
7369     else if (CodePoint <= 0xFFFF)
7370       OS << "\\u" << llvm::format("%04x", CodePoint);
7371     else
7372       OS << "\\U" << llvm::format("%08x", CodePoint);
7373     OS.flush();
7374     Specifier = CodePointStr;
7375   }
7376 
7377   EmitFormatDiagnostic(
7378       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
7379       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
7380 
7381   return keepGoing;
7382 }
7383 
7384 void
7385 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
7386                                                       const char *startSpec,
7387                                                       unsigned specifierLen) {
7388   EmitFormatDiagnostic(
7389     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
7390     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
7391 }
7392 
7393 bool
7394 CheckFormatHandler::CheckNumArgs(
7395   const analyze_format_string::FormatSpecifier &FS,
7396   const analyze_format_string::ConversionSpecifier &CS,
7397   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
7398 
7399   if (argIndex >= NumDataArgs) {
7400     PartialDiagnostic PDiag = FS.usesPositionalArg()
7401       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
7402            << (argIndex+1) << NumDataArgs)
7403       : S.PDiag(diag::warn_printf_insufficient_data_args);
7404     EmitFormatDiagnostic(
7405       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
7406       getSpecifierRange(startSpecifier, specifierLen));
7407 
7408     // Since more arguments than conversion tokens are given, by extension
7409     // all arguments are covered, so mark this as so.
7410     UncoveredArg.setAllCovered();
7411     return false;
7412   }
7413   return true;
7414 }
7415 
7416 template<typename Range>
7417 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
7418                                               SourceLocation Loc,
7419                                               bool IsStringLocation,
7420                                               Range StringRange,
7421                                               ArrayRef<FixItHint> FixIt) {
7422   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
7423                        Loc, IsStringLocation, StringRange, FixIt);
7424 }
7425 
7426 /// If the format string is not within the function call, emit a note
7427 /// so that the function call and string are in diagnostic messages.
7428 ///
7429 /// \param InFunctionCall if true, the format string is within the function
7430 /// call and only one diagnostic message will be produced.  Otherwise, an
7431 /// extra note will be emitted pointing to location of the format string.
7432 ///
7433 /// \param ArgumentExpr the expression that is passed as the format string
7434 /// argument in the function call.  Used for getting locations when two
7435 /// diagnostics are emitted.
7436 ///
7437 /// \param PDiag the callee should already have provided any strings for the
7438 /// diagnostic message.  This function only adds locations and fixits
7439 /// to diagnostics.
7440 ///
7441 /// \param Loc primary location for diagnostic.  If two diagnostics are
7442 /// required, one will be at Loc and a new SourceLocation will be created for
7443 /// the other one.
7444 ///
7445 /// \param IsStringLocation if true, Loc points to the format string should be
7446 /// used for the note.  Otherwise, Loc points to the argument list and will
7447 /// be used with PDiag.
7448 ///
7449 /// \param StringRange some or all of the string to highlight.  This is
7450 /// templated so it can accept either a CharSourceRange or a SourceRange.
7451 ///
7452 /// \param FixIt optional fix it hint for the format string.
7453 template <typename Range>
7454 void CheckFormatHandler::EmitFormatDiagnostic(
7455     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
7456     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
7457     Range StringRange, ArrayRef<FixItHint> FixIt) {
7458   if (InFunctionCall) {
7459     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
7460     D << StringRange;
7461     D << FixIt;
7462   } else {
7463     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
7464       << ArgumentExpr->getSourceRange();
7465 
7466     const Sema::SemaDiagnosticBuilder &Note =
7467       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
7468              diag::note_format_string_defined);
7469 
7470     Note << StringRange;
7471     Note << FixIt;
7472   }
7473 }
7474 
7475 //===--- CHECK: Printf format string checking ------------------------------===//
7476 
7477 namespace {
7478 
7479 class CheckPrintfHandler : public CheckFormatHandler {
7480 public:
7481   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
7482                      const Expr *origFormatExpr,
7483                      const Sema::FormatStringType type, unsigned firstDataArg,
7484                      unsigned numDataArgs, bool isObjC, const char *beg,
7485                      bool hasVAListArg, ArrayRef<const Expr *> Args,
7486                      unsigned formatIdx, bool inFunctionCall,
7487                      Sema::VariadicCallType CallType,
7488                      llvm::SmallBitVector &CheckedVarArgs,
7489                      UncoveredArgHandler &UncoveredArg)
7490       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7491                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
7492                            inFunctionCall, CallType, CheckedVarArgs,
7493                            UncoveredArg) {}
7494 
7495   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
7496 
7497   /// Returns true if '%@' specifiers are allowed in the format string.
7498   bool allowsObjCArg() const {
7499     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
7500            FSType == Sema::FST_OSTrace;
7501   }
7502 
7503   bool HandleInvalidPrintfConversionSpecifier(
7504                                       const analyze_printf::PrintfSpecifier &FS,
7505                                       const char *startSpecifier,
7506                                       unsigned specifierLen) override;
7507 
7508   void handleInvalidMaskType(StringRef MaskType) override;
7509 
7510   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
7511                              const char *startSpecifier,
7512                              unsigned specifierLen) override;
7513   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7514                        const char *StartSpecifier,
7515                        unsigned SpecifierLen,
7516                        const Expr *E);
7517 
7518   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
7519                     const char *startSpecifier, unsigned specifierLen);
7520   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
7521                            const analyze_printf::OptionalAmount &Amt,
7522                            unsigned type,
7523                            const char *startSpecifier, unsigned specifierLen);
7524   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7525                   const analyze_printf::OptionalFlag &flag,
7526                   const char *startSpecifier, unsigned specifierLen);
7527   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
7528                          const analyze_printf::OptionalFlag &ignoredFlag,
7529                          const analyze_printf::OptionalFlag &flag,
7530                          const char *startSpecifier, unsigned specifierLen);
7531   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
7532                            const Expr *E);
7533 
7534   void HandleEmptyObjCModifierFlag(const char *startFlag,
7535                                    unsigned flagLen) override;
7536 
7537   void HandleInvalidObjCModifierFlag(const char *startFlag,
7538                                             unsigned flagLen) override;
7539 
7540   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
7541                                            const char *flagsEnd,
7542                                            const char *conversionPosition)
7543                                              override;
7544 };
7545 
7546 } // namespace
7547 
7548 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
7549                                       const analyze_printf::PrintfSpecifier &FS,
7550                                       const char *startSpecifier,
7551                                       unsigned specifierLen) {
7552   const analyze_printf::PrintfConversionSpecifier &CS =
7553     FS.getConversionSpecifier();
7554 
7555   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
7556                                           getLocationOfByte(CS.getStart()),
7557                                           startSpecifier, specifierLen,
7558                                           CS.getStart(), CS.getLength());
7559 }
7560 
7561 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
7562   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
7563 }
7564 
7565 bool CheckPrintfHandler::HandleAmount(
7566                                const analyze_format_string::OptionalAmount &Amt,
7567                                unsigned k, const char *startSpecifier,
7568                                unsigned specifierLen) {
7569   if (Amt.hasDataArgument()) {
7570     if (!HasVAListArg) {
7571       unsigned argIndex = Amt.getArgIndex();
7572       if (argIndex >= NumDataArgs) {
7573         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
7574                                << k,
7575                              getLocationOfByte(Amt.getStart()),
7576                              /*IsStringLocation*/true,
7577                              getSpecifierRange(startSpecifier, specifierLen));
7578         // Don't do any more checking.  We will just emit
7579         // spurious errors.
7580         return false;
7581       }
7582 
7583       // Type check the data argument.  It should be an 'int'.
7584       // Although not in conformance with C99, we also allow the argument to be
7585       // an 'unsigned int' as that is a reasonably safe case.  GCC also
7586       // doesn't emit a warning for that case.
7587       CoveredArgs.set(argIndex);
7588       const Expr *Arg = getDataArg(argIndex);
7589       if (!Arg)
7590         return false;
7591 
7592       QualType T = Arg->getType();
7593 
7594       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
7595       assert(AT.isValid());
7596 
7597       if (!AT.matchesType(S.Context, T)) {
7598         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
7599                                << k << AT.getRepresentativeTypeName(S.Context)
7600                                << T << Arg->getSourceRange(),
7601                              getLocationOfByte(Amt.getStart()),
7602                              /*IsStringLocation*/true,
7603                              getSpecifierRange(startSpecifier, specifierLen));
7604         // Don't do any more checking.  We will just emit
7605         // spurious errors.
7606         return false;
7607       }
7608     }
7609   }
7610   return true;
7611 }
7612 
7613 void CheckPrintfHandler::HandleInvalidAmount(
7614                                       const analyze_printf::PrintfSpecifier &FS,
7615                                       const analyze_printf::OptionalAmount &Amt,
7616                                       unsigned type,
7617                                       const char *startSpecifier,
7618                                       unsigned specifierLen) {
7619   const analyze_printf::PrintfConversionSpecifier &CS =
7620     FS.getConversionSpecifier();
7621 
7622   FixItHint fixit =
7623     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
7624       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
7625                                  Amt.getConstantLength()))
7626       : FixItHint();
7627 
7628   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
7629                          << type << CS.toString(),
7630                        getLocationOfByte(Amt.getStart()),
7631                        /*IsStringLocation*/true,
7632                        getSpecifierRange(startSpecifier, specifierLen),
7633                        fixit);
7634 }
7635 
7636 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7637                                     const analyze_printf::OptionalFlag &flag,
7638                                     const char *startSpecifier,
7639                                     unsigned specifierLen) {
7640   // Warn about pointless flag with a fixit removal.
7641   const analyze_printf::PrintfConversionSpecifier &CS =
7642     FS.getConversionSpecifier();
7643   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
7644                          << flag.toString() << CS.toString(),
7645                        getLocationOfByte(flag.getPosition()),
7646                        /*IsStringLocation*/true,
7647                        getSpecifierRange(startSpecifier, specifierLen),
7648                        FixItHint::CreateRemoval(
7649                          getSpecifierRange(flag.getPosition(), 1)));
7650 }
7651 
7652 void CheckPrintfHandler::HandleIgnoredFlag(
7653                                 const analyze_printf::PrintfSpecifier &FS,
7654                                 const analyze_printf::OptionalFlag &ignoredFlag,
7655                                 const analyze_printf::OptionalFlag &flag,
7656                                 const char *startSpecifier,
7657                                 unsigned specifierLen) {
7658   // Warn about ignored flag with a fixit removal.
7659   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
7660                          << ignoredFlag.toString() << flag.toString(),
7661                        getLocationOfByte(ignoredFlag.getPosition()),
7662                        /*IsStringLocation*/true,
7663                        getSpecifierRange(startSpecifier, specifierLen),
7664                        FixItHint::CreateRemoval(
7665                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
7666 }
7667 
7668 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
7669                                                      unsigned flagLen) {
7670   // Warn about an empty flag.
7671   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
7672                        getLocationOfByte(startFlag),
7673                        /*IsStringLocation*/true,
7674                        getSpecifierRange(startFlag, flagLen));
7675 }
7676 
7677 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
7678                                                        unsigned flagLen) {
7679   // Warn about an invalid flag.
7680   auto Range = getSpecifierRange(startFlag, flagLen);
7681   StringRef flag(startFlag, flagLen);
7682   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
7683                       getLocationOfByte(startFlag),
7684                       /*IsStringLocation*/true,
7685                       Range, FixItHint::CreateRemoval(Range));
7686 }
7687 
7688 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
7689     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
7690     // Warn about using '[...]' without a '@' conversion.
7691     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
7692     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
7693     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
7694                          getLocationOfByte(conversionPosition),
7695                          /*IsStringLocation*/true,
7696                          Range, FixItHint::CreateRemoval(Range));
7697 }
7698 
7699 // Determines if the specified is a C++ class or struct containing
7700 // a member with the specified name and kind (e.g. a CXXMethodDecl named
7701 // "c_str()").
7702 template<typename MemberKind>
7703 static llvm::SmallPtrSet<MemberKind*, 1>
7704 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
7705   const RecordType *RT = Ty->getAs<RecordType>();
7706   llvm::SmallPtrSet<MemberKind*, 1> Results;
7707 
7708   if (!RT)
7709     return Results;
7710   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
7711   if (!RD || !RD->getDefinition())
7712     return Results;
7713 
7714   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
7715                  Sema::LookupMemberName);
7716   R.suppressDiagnostics();
7717 
7718   // We just need to include all members of the right kind turned up by the
7719   // filter, at this point.
7720   if (S.LookupQualifiedName(R, RT->getDecl()))
7721     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7722       NamedDecl *decl = (*I)->getUnderlyingDecl();
7723       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
7724         Results.insert(FK);
7725     }
7726   return Results;
7727 }
7728 
7729 /// Check if we could call '.c_str()' on an object.
7730 ///
7731 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
7732 /// allow the call, or if it would be ambiguous).
7733 bool Sema::hasCStrMethod(const Expr *E) {
7734   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7735 
7736   MethodSet Results =
7737       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
7738   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7739        MI != ME; ++MI)
7740     if ((*MI)->getMinRequiredArguments() == 0)
7741       return true;
7742   return false;
7743 }
7744 
7745 // Check if a (w)string was passed when a (w)char* was needed, and offer a
7746 // better diagnostic if so. AT is assumed to be valid.
7747 // Returns true when a c_str() conversion method is found.
7748 bool CheckPrintfHandler::checkForCStrMembers(
7749     const analyze_printf::ArgType &AT, const Expr *E) {
7750   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7751 
7752   MethodSet Results =
7753       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
7754 
7755   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7756        MI != ME; ++MI) {
7757     const CXXMethodDecl *Method = *MI;
7758     if (Method->getMinRequiredArguments() == 0 &&
7759         AT.matchesType(S.Context, Method->getReturnType())) {
7760       // FIXME: Suggest parens if the expression needs them.
7761       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
7762       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
7763           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
7764       return true;
7765     }
7766   }
7767 
7768   return false;
7769 }
7770 
7771 bool
7772 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
7773                                             &FS,
7774                                           const char *startSpecifier,
7775                                           unsigned specifierLen) {
7776   using namespace analyze_format_string;
7777   using namespace analyze_printf;
7778 
7779   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
7780 
7781   if (FS.consumesDataArgument()) {
7782     if (atFirstArg) {
7783         atFirstArg = false;
7784         usesPositionalArgs = FS.usesPositionalArg();
7785     }
7786     else if (usesPositionalArgs != FS.usesPositionalArg()) {
7787       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
7788                                         startSpecifier, specifierLen);
7789       return false;
7790     }
7791   }
7792 
7793   // First check if the field width, precision, and conversion specifier
7794   // have matching data arguments.
7795   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
7796                     startSpecifier, specifierLen)) {
7797     return false;
7798   }
7799 
7800   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
7801                     startSpecifier, specifierLen)) {
7802     return false;
7803   }
7804 
7805   if (!CS.consumesDataArgument()) {
7806     // FIXME: Technically specifying a precision or field width here
7807     // makes no sense.  Worth issuing a warning at some point.
7808     return true;
7809   }
7810 
7811   // Consume the argument.
7812   unsigned argIndex = FS.getArgIndex();
7813   if (argIndex < NumDataArgs) {
7814     // The check to see if the argIndex is valid will come later.
7815     // We set the bit here because we may exit early from this
7816     // function if we encounter some other error.
7817     CoveredArgs.set(argIndex);
7818   }
7819 
7820   // FreeBSD kernel extensions.
7821   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
7822       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
7823     // We need at least two arguments.
7824     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
7825       return false;
7826 
7827     // Claim the second argument.
7828     CoveredArgs.set(argIndex + 1);
7829 
7830     // Type check the first argument (int for %b, pointer for %D)
7831     const Expr *Ex = getDataArg(argIndex);
7832     const analyze_printf::ArgType &AT =
7833       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
7834         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
7835     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
7836       EmitFormatDiagnostic(
7837           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7838               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
7839               << false << Ex->getSourceRange(),
7840           Ex->getBeginLoc(), /*IsStringLocation*/ false,
7841           getSpecifierRange(startSpecifier, specifierLen));
7842 
7843     // Type check the second argument (char * for both %b and %D)
7844     Ex = getDataArg(argIndex + 1);
7845     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
7846     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
7847       EmitFormatDiagnostic(
7848           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7849               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
7850               << false << Ex->getSourceRange(),
7851           Ex->getBeginLoc(), /*IsStringLocation*/ false,
7852           getSpecifierRange(startSpecifier, specifierLen));
7853 
7854      return true;
7855   }
7856 
7857   // Check for using an Objective-C specific conversion specifier
7858   // in a non-ObjC literal.
7859   if (!allowsObjCArg() && CS.isObjCArg()) {
7860     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7861                                                   specifierLen);
7862   }
7863 
7864   // %P can only be used with os_log.
7865   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
7866     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7867                                                   specifierLen);
7868   }
7869 
7870   // %n is not allowed with os_log.
7871   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
7872     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
7873                          getLocationOfByte(CS.getStart()),
7874                          /*IsStringLocation*/ false,
7875                          getSpecifierRange(startSpecifier, specifierLen));
7876 
7877     return true;
7878   }
7879 
7880   // Only scalars are allowed for os_trace.
7881   if (FSType == Sema::FST_OSTrace &&
7882       (CS.getKind() == ConversionSpecifier::PArg ||
7883        CS.getKind() == ConversionSpecifier::sArg ||
7884        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
7885     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7886                                                   specifierLen);
7887   }
7888 
7889   // Check for use of public/private annotation outside of os_log().
7890   if (FSType != Sema::FST_OSLog) {
7891     if (FS.isPublic().isSet()) {
7892       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
7893                                << "public",
7894                            getLocationOfByte(FS.isPublic().getPosition()),
7895                            /*IsStringLocation*/ false,
7896                            getSpecifierRange(startSpecifier, specifierLen));
7897     }
7898     if (FS.isPrivate().isSet()) {
7899       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
7900                                << "private",
7901                            getLocationOfByte(FS.isPrivate().getPosition()),
7902                            /*IsStringLocation*/ false,
7903                            getSpecifierRange(startSpecifier, specifierLen));
7904     }
7905   }
7906 
7907   // Check for invalid use of field width
7908   if (!FS.hasValidFieldWidth()) {
7909     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
7910         startSpecifier, specifierLen);
7911   }
7912 
7913   // Check for invalid use of precision
7914   if (!FS.hasValidPrecision()) {
7915     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
7916         startSpecifier, specifierLen);
7917   }
7918 
7919   // Precision is mandatory for %P specifier.
7920   if (CS.getKind() == ConversionSpecifier::PArg &&
7921       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
7922     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
7923                          getLocationOfByte(startSpecifier),
7924                          /*IsStringLocation*/ false,
7925                          getSpecifierRange(startSpecifier, specifierLen));
7926   }
7927 
7928   // Check each flag does not conflict with any other component.
7929   if (!FS.hasValidThousandsGroupingPrefix())
7930     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
7931   if (!FS.hasValidLeadingZeros())
7932     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
7933   if (!FS.hasValidPlusPrefix())
7934     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
7935   if (!FS.hasValidSpacePrefix())
7936     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
7937   if (!FS.hasValidAlternativeForm())
7938     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
7939   if (!FS.hasValidLeftJustified())
7940     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
7941 
7942   // Check that flags are not ignored by another flag
7943   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
7944     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
7945         startSpecifier, specifierLen);
7946   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
7947     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
7948             startSpecifier, specifierLen);
7949 
7950   // Check the length modifier is valid with the given conversion specifier.
7951   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
7952                                  S.getLangOpts()))
7953     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7954                                 diag::warn_format_nonsensical_length);
7955   else if (!FS.hasStandardLengthModifier())
7956     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
7957   else if (!FS.hasStandardLengthConversionCombination())
7958     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7959                                 diag::warn_format_non_standard_conversion_spec);
7960 
7961   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
7962     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
7963 
7964   // The remaining checks depend on the data arguments.
7965   if (HasVAListArg)
7966     return true;
7967 
7968   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
7969     return false;
7970 
7971   const Expr *Arg = getDataArg(argIndex);
7972   if (!Arg)
7973     return true;
7974 
7975   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
7976 }
7977 
7978 static bool requiresParensToAddCast(const Expr *E) {
7979   // FIXME: We should have a general way to reason about operator
7980   // precedence and whether parens are actually needed here.
7981   // Take care of a few common cases where they aren't.
7982   const Expr *Inside = E->IgnoreImpCasts();
7983   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
7984     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
7985 
7986   switch (Inside->getStmtClass()) {
7987   case Stmt::ArraySubscriptExprClass:
7988   case Stmt::CallExprClass:
7989   case Stmt::CharacterLiteralClass:
7990   case Stmt::CXXBoolLiteralExprClass:
7991   case Stmt::DeclRefExprClass:
7992   case Stmt::FloatingLiteralClass:
7993   case Stmt::IntegerLiteralClass:
7994   case Stmt::MemberExprClass:
7995   case Stmt::ObjCArrayLiteralClass:
7996   case Stmt::ObjCBoolLiteralExprClass:
7997   case Stmt::ObjCBoxedExprClass:
7998   case Stmt::ObjCDictionaryLiteralClass:
7999   case Stmt::ObjCEncodeExprClass:
8000   case Stmt::ObjCIvarRefExprClass:
8001   case Stmt::ObjCMessageExprClass:
8002   case Stmt::ObjCPropertyRefExprClass:
8003   case Stmt::ObjCStringLiteralClass:
8004   case Stmt::ObjCSubscriptRefExprClass:
8005   case Stmt::ParenExprClass:
8006   case Stmt::StringLiteralClass:
8007   case Stmt::UnaryOperatorClass:
8008     return false;
8009   default:
8010     return true;
8011   }
8012 }
8013 
8014 static std::pair<QualType, StringRef>
8015 shouldNotPrintDirectly(const ASTContext &Context,
8016                        QualType IntendedTy,
8017                        const Expr *E) {
8018   // Use a 'while' to peel off layers of typedefs.
8019   QualType TyTy = IntendedTy;
8020   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
8021     StringRef Name = UserTy->getDecl()->getName();
8022     QualType CastTy = llvm::StringSwitch<QualType>(Name)
8023       .Case("CFIndex", Context.getNSIntegerType())
8024       .Case("NSInteger", Context.getNSIntegerType())
8025       .Case("NSUInteger", Context.getNSUIntegerType())
8026       .Case("SInt32", Context.IntTy)
8027       .Case("UInt32", Context.UnsignedIntTy)
8028       .Default(QualType());
8029 
8030     if (!CastTy.isNull())
8031       return std::make_pair(CastTy, Name);
8032 
8033     TyTy = UserTy->desugar();
8034   }
8035 
8036   // Strip parens if necessary.
8037   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
8038     return shouldNotPrintDirectly(Context,
8039                                   PE->getSubExpr()->getType(),
8040                                   PE->getSubExpr());
8041 
8042   // If this is a conditional expression, then its result type is constructed
8043   // via usual arithmetic conversions and thus there might be no necessary
8044   // typedef sugar there.  Recurse to operands to check for NSInteger &
8045   // Co. usage condition.
8046   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8047     QualType TrueTy, FalseTy;
8048     StringRef TrueName, FalseName;
8049 
8050     std::tie(TrueTy, TrueName) =
8051       shouldNotPrintDirectly(Context,
8052                              CO->getTrueExpr()->getType(),
8053                              CO->getTrueExpr());
8054     std::tie(FalseTy, FalseName) =
8055       shouldNotPrintDirectly(Context,
8056                              CO->getFalseExpr()->getType(),
8057                              CO->getFalseExpr());
8058 
8059     if (TrueTy == FalseTy)
8060       return std::make_pair(TrueTy, TrueName);
8061     else if (TrueTy.isNull())
8062       return std::make_pair(FalseTy, FalseName);
8063     else if (FalseTy.isNull())
8064       return std::make_pair(TrueTy, TrueName);
8065   }
8066 
8067   return std::make_pair(QualType(), StringRef());
8068 }
8069 
8070 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
8071 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
8072 /// type do not count.
8073 static bool
8074 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
8075   QualType From = ICE->getSubExpr()->getType();
8076   QualType To = ICE->getType();
8077   // It's an integer promotion if the destination type is the promoted
8078   // source type.
8079   if (ICE->getCastKind() == CK_IntegralCast &&
8080       From->isPromotableIntegerType() &&
8081       S.Context.getPromotedIntegerType(From) == To)
8082     return true;
8083   // Look through vector types, since we do default argument promotion for
8084   // those in OpenCL.
8085   if (const auto *VecTy = From->getAs<ExtVectorType>())
8086     From = VecTy->getElementType();
8087   if (const auto *VecTy = To->getAs<ExtVectorType>())
8088     To = VecTy->getElementType();
8089   // It's a floating promotion if the source type is a lower rank.
8090   return ICE->getCastKind() == CK_FloatingCast &&
8091          S.Context.getFloatingTypeOrder(From, To) < 0;
8092 }
8093 
8094 bool
8095 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8096                                     const char *StartSpecifier,
8097                                     unsigned SpecifierLen,
8098                                     const Expr *E) {
8099   using namespace analyze_format_string;
8100   using namespace analyze_printf;
8101 
8102   // Now type check the data expression that matches the
8103   // format specifier.
8104   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
8105   if (!AT.isValid())
8106     return true;
8107 
8108   QualType ExprTy = E->getType();
8109   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
8110     ExprTy = TET->getUnderlyingExpr()->getType();
8111   }
8112 
8113   // Diagnose attempts to print a boolean value as a character. Unlike other
8114   // -Wformat diagnostics, this is fine from a type perspective, but it still
8115   // doesn't make sense.
8116   if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
8117       E->isKnownToHaveBooleanValue()) {
8118     const CharSourceRange &CSR =
8119         getSpecifierRange(StartSpecifier, SpecifierLen);
8120     SmallString<4> FSString;
8121     llvm::raw_svector_ostream os(FSString);
8122     FS.toString(os);
8123     EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
8124                              << FSString,
8125                          E->getExprLoc(), false, CSR);
8126     return true;
8127   }
8128 
8129   analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
8130   if (Match == analyze_printf::ArgType::Match)
8131     return true;
8132 
8133   // Look through argument promotions for our error message's reported type.
8134   // This includes the integral and floating promotions, but excludes array
8135   // and function pointer decay (seeing that an argument intended to be a
8136   // string has type 'char [6]' is probably more confusing than 'char *') and
8137   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
8138   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8139     if (isArithmeticArgumentPromotion(S, ICE)) {
8140       E = ICE->getSubExpr();
8141       ExprTy = E->getType();
8142 
8143       // Check if we didn't match because of an implicit cast from a 'char'
8144       // or 'short' to an 'int'.  This is done because printf is a varargs
8145       // function.
8146       if (ICE->getType() == S.Context.IntTy ||
8147           ICE->getType() == S.Context.UnsignedIntTy) {
8148         // All further checking is done on the subexpression
8149         const analyze_printf::ArgType::MatchKind ImplicitMatch =
8150             AT.matchesType(S.Context, ExprTy);
8151         if (ImplicitMatch == analyze_printf::ArgType::Match)
8152           return true;
8153         if (ImplicitMatch == ArgType::NoMatchPedantic ||
8154             ImplicitMatch == ArgType::NoMatchTypeConfusion)
8155           Match = ImplicitMatch;
8156       }
8157     }
8158   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
8159     // Special case for 'a', which has type 'int' in C.
8160     // Note, however, that we do /not/ want to treat multibyte constants like
8161     // 'MooV' as characters! This form is deprecated but still exists.
8162     if (ExprTy == S.Context.IntTy)
8163       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
8164         ExprTy = S.Context.CharTy;
8165   }
8166 
8167   // Look through enums to their underlying type.
8168   bool IsEnum = false;
8169   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
8170     ExprTy = EnumTy->getDecl()->getIntegerType();
8171     IsEnum = true;
8172   }
8173 
8174   // %C in an Objective-C context prints a unichar, not a wchar_t.
8175   // If the argument is an integer of some kind, believe the %C and suggest
8176   // a cast instead of changing the conversion specifier.
8177   QualType IntendedTy = ExprTy;
8178   if (isObjCContext() &&
8179       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
8180     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
8181         !ExprTy->isCharType()) {
8182       // 'unichar' is defined as a typedef of unsigned short, but we should
8183       // prefer using the typedef if it is visible.
8184       IntendedTy = S.Context.UnsignedShortTy;
8185 
8186       // While we are here, check if the value is an IntegerLiteral that happens
8187       // to be within the valid range.
8188       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
8189         const llvm::APInt &V = IL->getValue();
8190         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
8191           return true;
8192       }
8193 
8194       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
8195                           Sema::LookupOrdinaryName);
8196       if (S.LookupName(Result, S.getCurScope())) {
8197         NamedDecl *ND = Result.getFoundDecl();
8198         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
8199           if (TD->getUnderlyingType() == IntendedTy)
8200             IntendedTy = S.Context.getTypedefType(TD);
8201       }
8202     }
8203   }
8204 
8205   // Special-case some of Darwin's platform-independence types by suggesting
8206   // casts to primitive types that are known to be large enough.
8207   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
8208   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
8209     QualType CastTy;
8210     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
8211     if (!CastTy.isNull()) {
8212       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
8213       // (long in ASTContext). Only complain to pedants.
8214       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
8215           (AT.isSizeT() || AT.isPtrdiffT()) &&
8216           AT.matchesType(S.Context, CastTy))
8217         Match = ArgType::NoMatchPedantic;
8218       IntendedTy = CastTy;
8219       ShouldNotPrintDirectly = true;
8220     }
8221   }
8222 
8223   // We may be able to offer a FixItHint if it is a supported type.
8224   PrintfSpecifier fixedFS = FS;
8225   bool Success =
8226       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
8227 
8228   if (Success) {
8229     // Get the fix string from the fixed format specifier
8230     SmallString<16> buf;
8231     llvm::raw_svector_ostream os(buf);
8232     fixedFS.toString(os);
8233 
8234     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
8235 
8236     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
8237       unsigned Diag;
8238       switch (Match) {
8239       case ArgType::Match: llvm_unreachable("expected non-matching");
8240       case ArgType::NoMatchPedantic:
8241         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8242         break;
8243       case ArgType::NoMatchTypeConfusion:
8244         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8245         break;
8246       case ArgType::NoMatch:
8247         Diag = diag::warn_format_conversion_argument_type_mismatch;
8248         break;
8249       }
8250 
8251       // In this case, the specifier is wrong and should be changed to match
8252       // the argument.
8253       EmitFormatDiagnostic(S.PDiag(Diag)
8254                                << AT.getRepresentativeTypeName(S.Context)
8255                                << IntendedTy << IsEnum << E->getSourceRange(),
8256                            E->getBeginLoc(),
8257                            /*IsStringLocation*/ false, SpecRange,
8258                            FixItHint::CreateReplacement(SpecRange, os.str()));
8259     } else {
8260       // The canonical type for formatting this value is different from the
8261       // actual type of the expression. (This occurs, for example, with Darwin's
8262       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
8263       // should be printed as 'long' for 64-bit compatibility.)
8264       // Rather than emitting a normal format/argument mismatch, we want to
8265       // add a cast to the recommended type (and correct the format string
8266       // if necessary).
8267       SmallString<16> CastBuf;
8268       llvm::raw_svector_ostream CastFix(CastBuf);
8269       CastFix << "(";
8270       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
8271       CastFix << ")";
8272 
8273       SmallVector<FixItHint,4> Hints;
8274       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
8275         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
8276 
8277       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
8278         // If there's already a cast present, just replace it.
8279         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
8280         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
8281 
8282       } else if (!requiresParensToAddCast(E)) {
8283         // If the expression has high enough precedence,
8284         // just write the C-style cast.
8285         Hints.push_back(
8286             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8287       } else {
8288         // Otherwise, add parens around the expression as well as the cast.
8289         CastFix << "(";
8290         Hints.push_back(
8291             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8292 
8293         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
8294         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
8295       }
8296 
8297       if (ShouldNotPrintDirectly) {
8298         // The expression has a type that should not be printed directly.
8299         // We extract the name from the typedef because we don't want to show
8300         // the underlying type in the diagnostic.
8301         StringRef Name;
8302         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
8303           Name = TypedefTy->getDecl()->getName();
8304         else
8305           Name = CastTyName;
8306         unsigned Diag = Match == ArgType::NoMatchPedantic
8307                             ? diag::warn_format_argument_needs_cast_pedantic
8308                             : diag::warn_format_argument_needs_cast;
8309         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
8310                                            << E->getSourceRange(),
8311                              E->getBeginLoc(), /*IsStringLocation=*/false,
8312                              SpecRange, Hints);
8313       } else {
8314         // In this case, the expression could be printed using a different
8315         // specifier, but we've decided that the specifier is probably correct
8316         // and we should cast instead. Just use the normal warning message.
8317         EmitFormatDiagnostic(
8318             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8319                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
8320                 << E->getSourceRange(),
8321             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
8322       }
8323     }
8324   } else {
8325     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
8326                                                    SpecifierLen);
8327     // Since the warning for passing non-POD types to variadic functions
8328     // was deferred until now, we emit a warning for non-POD
8329     // arguments here.
8330     switch (S.isValidVarArgType(ExprTy)) {
8331     case Sema::VAK_Valid:
8332     case Sema::VAK_ValidInCXX11: {
8333       unsigned Diag;
8334       switch (Match) {
8335       case ArgType::Match: llvm_unreachable("expected non-matching");
8336       case ArgType::NoMatchPedantic:
8337         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8338         break;
8339       case ArgType::NoMatchTypeConfusion:
8340         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8341         break;
8342       case ArgType::NoMatch:
8343         Diag = diag::warn_format_conversion_argument_type_mismatch;
8344         break;
8345       }
8346 
8347       EmitFormatDiagnostic(
8348           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
8349                         << IsEnum << CSR << E->getSourceRange(),
8350           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8351       break;
8352     }
8353     case Sema::VAK_Undefined:
8354     case Sema::VAK_MSVCUndefined:
8355       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
8356                                << S.getLangOpts().CPlusPlus11 << ExprTy
8357                                << CallType
8358                                << AT.getRepresentativeTypeName(S.Context) << CSR
8359                                << E->getSourceRange(),
8360                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8361       checkForCStrMembers(AT, E);
8362       break;
8363 
8364     case Sema::VAK_Invalid:
8365       if (ExprTy->isObjCObjectType())
8366         EmitFormatDiagnostic(
8367             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
8368                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
8369                 << AT.getRepresentativeTypeName(S.Context) << CSR
8370                 << E->getSourceRange(),
8371             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8372       else
8373         // FIXME: If this is an initializer list, suggest removing the braces
8374         // or inserting a cast to the target type.
8375         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
8376             << isa<InitListExpr>(E) << ExprTy << CallType
8377             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
8378       break;
8379     }
8380 
8381     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
8382            "format string specifier index out of range");
8383     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
8384   }
8385 
8386   return true;
8387 }
8388 
8389 //===--- CHECK: Scanf format string checking ------------------------------===//
8390 
8391 namespace {
8392 
8393 class CheckScanfHandler : public CheckFormatHandler {
8394 public:
8395   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
8396                     const Expr *origFormatExpr, Sema::FormatStringType type,
8397                     unsigned firstDataArg, unsigned numDataArgs,
8398                     const char *beg, bool hasVAListArg,
8399                     ArrayRef<const Expr *> Args, unsigned formatIdx,
8400                     bool inFunctionCall, Sema::VariadicCallType CallType,
8401                     llvm::SmallBitVector &CheckedVarArgs,
8402                     UncoveredArgHandler &UncoveredArg)
8403       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8404                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
8405                            inFunctionCall, CallType, CheckedVarArgs,
8406                            UncoveredArg) {}
8407 
8408   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
8409                             const char *startSpecifier,
8410                             unsigned specifierLen) override;
8411 
8412   bool HandleInvalidScanfConversionSpecifier(
8413           const analyze_scanf::ScanfSpecifier &FS,
8414           const char *startSpecifier,
8415           unsigned specifierLen) override;
8416 
8417   void HandleIncompleteScanList(const char *start, const char *end) override;
8418 };
8419 
8420 } // namespace
8421 
8422 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
8423                                                  const char *end) {
8424   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
8425                        getLocationOfByte(end), /*IsStringLocation*/true,
8426                        getSpecifierRange(start, end - start));
8427 }
8428 
8429 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
8430                                         const analyze_scanf::ScanfSpecifier &FS,
8431                                         const char *startSpecifier,
8432                                         unsigned specifierLen) {
8433   const analyze_scanf::ScanfConversionSpecifier &CS =
8434     FS.getConversionSpecifier();
8435 
8436   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8437                                           getLocationOfByte(CS.getStart()),
8438                                           startSpecifier, specifierLen,
8439                                           CS.getStart(), CS.getLength());
8440 }
8441 
8442 bool CheckScanfHandler::HandleScanfSpecifier(
8443                                        const analyze_scanf::ScanfSpecifier &FS,
8444                                        const char *startSpecifier,
8445                                        unsigned specifierLen) {
8446   using namespace analyze_scanf;
8447   using namespace analyze_format_string;
8448 
8449   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
8450 
8451   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
8452   // be used to decide if we are using positional arguments consistently.
8453   if (FS.consumesDataArgument()) {
8454     if (atFirstArg) {
8455       atFirstArg = false;
8456       usesPositionalArgs = FS.usesPositionalArg();
8457     }
8458     else if (usesPositionalArgs != FS.usesPositionalArg()) {
8459       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8460                                         startSpecifier, specifierLen);
8461       return false;
8462     }
8463   }
8464 
8465   // Check if the field with is non-zero.
8466   const OptionalAmount &Amt = FS.getFieldWidth();
8467   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
8468     if (Amt.getConstantAmount() == 0) {
8469       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
8470                                                    Amt.getConstantLength());
8471       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
8472                            getLocationOfByte(Amt.getStart()),
8473                            /*IsStringLocation*/true, R,
8474                            FixItHint::CreateRemoval(R));
8475     }
8476   }
8477 
8478   if (!FS.consumesDataArgument()) {
8479     // FIXME: Technically specifying a precision or field width here
8480     // makes no sense.  Worth issuing a warning at some point.
8481     return true;
8482   }
8483 
8484   // Consume the argument.
8485   unsigned argIndex = FS.getArgIndex();
8486   if (argIndex < NumDataArgs) {
8487       // The check to see if the argIndex is valid will come later.
8488       // We set the bit here because we may exit early from this
8489       // function if we encounter some other error.
8490     CoveredArgs.set(argIndex);
8491   }
8492 
8493   // Check the length modifier is valid with the given conversion specifier.
8494   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8495                                  S.getLangOpts()))
8496     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8497                                 diag::warn_format_nonsensical_length);
8498   else if (!FS.hasStandardLengthModifier())
8499     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8500   else if (!FS.hasStandardLengthConversionCombination())
8501     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8502                                 diag::warn_format_non_standard_conversion_spec);
8503 
8504   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8505     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8506 
8507   // The remaining checks depend on the data arguments.
8508   if (HasVAListArg)
8509     return true;
8510 
8511   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8512     return false;
8513 
8514   // Check that the argument type matches the format specifier.
8515   const Expr *Ex = getDataArg(argIndex);
8516   if (!Ex)
8517     return true;
8518 
8519   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
8520 
8521   if (!AT.isValid()) {
8522     return true;
8523   }
8524 
8525   analyze_format_string::ArgType::MatchKind Match =
8526       AT.matchesType(S.Context, Ex->getType());
8527   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
8528   if (Match == analyze_format_string::ArgType::Match)
8529     return true;
8530 
8531   ScanfSpecifier fixedFS = FS;
8532   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
8533                                  S.getLangOpts(), S.Context);
8534 
8535   unsigned Diag =
8536       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
8537                : diag::warn_format_conversion_argument_type_mismatch;
8538 
8539   if (Success) {
8540     // Get the fix string from the fixed format specifier.
8541     SmallString<128> buf;
8542     llvm::raw_svector_ostream os(buf);
8543     fixedFS.toString(os);
8544 
8545     EmitFormatDiagnostic(
8546         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
8547                       << Ex->getType() << false << Ex->getSourceRange(),
8548         Ex->getBeginLoc(),
8549         /*IsStringLocation*/ false,
8550         getSpecifierRange(startSpecifier, specifierLen),
8551         FixItHint::CreateReplacement(
8552             getSpecifierRange(startSpecifier, specifierLen), os.str()));
8553   } else {
8554     EmitFormatDiagnostic(S.PDiag(Diag)
8555                              << AT.getRepresentativeTypeName(S.Context)
8556                              << Ex->getType() << false << Ex->getSourceRange(),
8557                          Ex->getBeginLoc(),
8558                          /*IsStringLocation*/ false,
8559                          getSpecifierRange(startSpecifier, specifierLen));
8560   }
8561 
8562   return true;
8563 }
8564 
8565 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
8566                               const Expr *OrigFormatExpr,
8567                               ArrayRef<const Expr *> Args,
8568                               bool HasVAListArg, unsigned format_idx,
8569                               unsigned firstDataArg,
8570                               Sema::FormatStringType Type,
8571                               bool inFunctionCall,
8572                               Sema::VariadicCallType CallType,
8573                               llvm::SmallBitVector &CheckedVarArgs,
8574                               UncoveredArgHandler &UncoveredArg,
8575                               bool IgnoreStringsWithoutSpecifiers) {
8576   // CHECK: is the format string a wide literal?
8577   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
8578     CheckFormatHandler::EmitFormatDiagnostic(
8579         S, inFunctionCall, Args[format_idx],
8580         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
8581         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8582     return;
8583   }
8584 
8585   // Str - The format string.  NOTE: this is NOT null-terminated!
8586   StringRef StrRef = FExpr->getString();
8587   const char *Str = StrRef.data();
8588   // Account for cases where the string literal is truncated in a declaration.
8589   const ConstantArrayType *T =
8590     S.Context.getAsConstantArrayType(FExpr->getType());
8591   assert(T && "String literal not of constant array type!");
8592   size_t TypeSize = T->getSize().getZExtValue();
8593   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8594   const unsigned numDataArgs = Args.size() - firstDataArg;
8595 
8596   if (IgnoreStringsWithoutSpecifiers &&
8597       !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
8598           Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
8599     return;
8600 
8601   // Emit a warning if the string literal is truncated and does not contain an
8602   // embedded null character.
8603   if (TypeSize <= StrRef.size() &&
8604       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
8605     CheckFormatHandler::EmitFormatDiagnostic(
8606         S, inFunctionCall, Args[format_idx],
8607         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
8608         FExpr->getBeginLoc(),
8609         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
8610     return;
8611   }
8612 
8613   // CHECK: empty format string?
8614   if (StrLen == 0 && numDataArgs > 0) {
8615     CheckFormatHandler::EmitFormatDiagnostic(
8616         S, inFunctionCall, Args[format_idx],
8617         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
8618         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8619     return;
8620   }
8621 
8622   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
8623       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
8624       Type == Sema::FST_OSTrace) {
8625     CheckPrintfHandler H(
8626         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
8627         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
8628         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
8629         CheckedVarArgs, UncoveredArg);
8630 
8631     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
8632                                                   S.getLangOpts(),
8633                                                   S.Context.getTargetInfo(),
8634                                             Type == Sema::FST_FreeBSDKPrintf))
8635       H.DoneProcessing();
8636   } else if (Type == Sema::FST_Scanf) {
8637     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
8638                         numDataArgs, Str, HasVAListArg, Args, format_idx,
8639                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
8640 
8641     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
8642                                                  S.getLangOpts(),
8643                                                  S.Context.getTargetInfo()))
8644       H.DoneProcessing();
8645   } // TODO: handle other formats
8646 }
8647 
8648 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
8649   // Str - The format string.  NOTE: this is NOT null-terminated!
8650   StringRef StrRef = FExpr->getString();
8651   const char *Str = StrRef.data();
8652   // Account for cases where the string literal is truncated in a declaration.
8653   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
8654   assert(T && "String literal not of constant array type!");
8655   size_t TypeSize = T->getSize().getZExtValue();
8656   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8657   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
8658                                                          getLangOpts(),
8659                                                          Context.getTargetInfo());
8660 }
8661 
8662 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
8663 
8664 // Returns the related absolute value function that is larger, of 0 if one
8665 // does not exist.
8666 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
8667   switch (AbsFunction) {
8668   default:
8669     return 0;
8670 
8671   case Builtin::BI__builtin_abs:
8672     return Builtin::BI__builtin_labs;
8673   case Builtin::BI__builtin_labs:
8674     return Builtin::BI__builtin_llabs;
8675   case Builtin::BI__builtin_llabs:
8676     return 0;
8677 
8678   case Builtin::BI__builtin_fabsf:
8679     return Builtin::BI__builtin_fabs;
8680   case Builtin::BI__builtin_fabs:
8681     return Builtin::BI__builtin_fabsl;
8682   case Builtin::BI__builtin_fabsl:
8683     return 0;
8684 
8685   case Builtin::BI__builtin_cabsf:
8686     return Builtin::BI__builtin_cabs;
8687   case Builtin::BI__builtin_cabs:
8688     return Builtin::BI__builtin_cabsl;
8689   case Builtin::BI__builtin_cabsl:
8690     return 0;
8691 
8692   case Builtin::BIabs:
8693     return Builtin::BIlabs;
8694   case Builtin::BIlabs:
8695     return Builtin::BIllabs;
8696   case Builtin::BIllabs:
8697     return 0;
8698 
8699   case Builtin::BIfabsf:
8700     return Builtin::BIfabs;
8701   case Builtin::BIfabs:
8702     return Builtin::BIfabsl;
8703   case Builtin::BIfabsl:
8704     return 0;
8705 
8706   case Builtin::BIcabsf:
8707    return Builtin::BIcabs;
8708   case Builtin::BIcabs:
8709     return Builtin::BIcabsl;
8710   case Builtin::BIcabsl:
8711     return 0;
8712   }
8713 }
8714 
8715 // Returns the argument type of the absolute value function.
8716 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
8717                                              unsigned AbsType) {
8718   if (AbsType == 0)
8719     return QualType();
8720 
8721   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
8722   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
8723   if (Error != ASTContext::GE_None)
8724     return QualType();
8725 
8726   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
8727   if (!FT)
8728     return QualType();
8729 
8730   if (FT->getNumParams() != 1)
8731     return QualType();
8732 
8733   return FT->getParamType(0);
8734 }
8735 
8736 // Returns the best absolute value function, or zero, based on type and
8737 // current absolute value function.
8738 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
8739                                    unsigned AbsFunctionKind) {
8740   unsigned BestKind = 0;
8741   uint64_t ArgSize = Context.getTypeSize(ArgType);
8742   for (unsigned Kind = AbsFunctionKind; Kind != 0;
8743        Kind = getLargerAbsoluteValueFunction(Kind)) {
8744     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
8745     if (Context.getTypeSize(ParamType) >= ArgSize) {
8746       if (BestKind == 0)
8747         BestKind = Kind;
8748       else if (Context.hasSameType(ParamType, ArgType)) {
8749         BestKind = Kind;
8750         break;
8751       }
8752     }
8753   }
8754   return BestKind;
8755 }
8756 
8757 enum AbsoluteValueKind {
8758   AVK_Integer,
8759   AVK_Floating,
8760   AVK_Complex
8761 };
8762 
8763 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
8764   if (T->isIntegralOrEnumerationType())
8765     return AVK_Integer;
8766   if (T->isRealFloatingType())
8767     return AVK_Floating;
8768   if (T->isAnyComplexType())
8769     return AVK_Complex;
8770 
8771   llvm_unreachable("Type not integer, floating, or complex");
8772 }
8773 
8774 // Changes the absolute value function to a different type.  Preserves whether
8775 // the function is a builtin.
8776 static unsigned changeAbsFunction(unsigned AbsKind,
8777                                   AbsoluteValueKind ValueKind) {
8778   switch (ValueKind) {
8779   case AVK_Integer:
8780     switch (AbsKind) {
8781     default:
8782       return 0;
8783     case Builtin::BI__builtin_fabsf:
8784     case Builtin::BI__builtin_fabs:
8785     case Builtin::BI__builtin_fabsl:
8786     case Builtin::BI__builtin_cabsf:
8787     case Builtin::BI__builtin_cabs:
8788     case Builtin::BI__builtin_cabsl:
8789       return Builtin::BI__builtin_abs;
8790     case Builtin::BIfabsf:
8791     case Builtin::BIfabs:
8792     case Builtin::BIfabsl:
8793     case Builtin::BIcabsf:
8794     case Builtin::BIcabs:
8795     case Builtin::BIcabsl:
8796       return Builtin::BIabs;
8797     }
8798   case AVK_Floating:
8799     switch (AbsKind) {
8800     default:
8801       return 0;
8802     case Builtin::BI__builtin_abs:
8803     case Builtin::BI__builtin_labs:
8804     case Builtin::BI__builtin_llabs:
8805     case Builtin::BI__builtin_cabsf:
8806     case Builtin::BI__builtin_cabs:
8807     case Builtin::BI__builtin_cabsl:
8808       return Builtin::BI__builtin_fabsf;
8809     case Builtin::BIabs:
8810     case Builtin::BIlabs:
8811     case Builtin::BIllabs:
8812     case Builtin::BIcabsf:
8813     case Builtin::BIcabs:
8814     case Builtin::BIcabsl:
8815       return Builtin::BIfabsf;
8816     }
8817   case AVK_Complex:
8818     switch (AbsKind) {
8819     default:
8820       return 0;
8821     case Builtin::BI__builtin_abs:
8822     case Builtin::BI__builtin_labs:
8823     case Builtin::BI__builtin_llabs:
8824     case Builtin::BI__builtin_fabsf:
8825     case Builtin::BI__builtin_fabs:
8826     case Builtin::BI__builtin_fabsl:
8827       return Builtin::BI__builtin_cabsf;
8828     case Builtin::BIabs:
8829     case Builtin::BIlabs:
8830     case Builtin::BIllabs:
8831     case Builtin::BIfabsf:
8832     case Builtin::BIfabs:
8833     case Builtin::BIfabsl:
8834       return Builtin::BIcabsf;
8835     }
8836   }
8837   llvm_unreachable("Unable to convert function");
8838 }
8839 
8840 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
8841   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
8842   if (!FnInfo)
8843     return 0;
8844 
8845   switch (FDecl->getBuiltinID()) {
8846   default:
8847     return 0;
8848   case Builtin::BI__builtin_abs:
8849   case Builtin::BI__builtin_fabs:
8850   case Builtin::BI__builtin_fabsf:
8851   case Builtin::BI__builtin_fabsl:
8852   case Builtin::BI__builtin_labs:
8853   case Builtin::BI__builtin_llabs:
8854   case Builtin::BI__builtin_cabs:
8855   case Builtin::BI__builtin_cabsf:
8856   case Builtin::BI__builtin_cabsl:
8857   case Builtin::BIabs:
8858   case Builtin::BIlabs:
8859   case Builtin::BIllabs:
8860   case Builtin::BIfabs:
8861   case Builtin::BIfabsf:
8862   case Builtin::BIfabsl:
8863   case Builtin::BIcabs:
8864   case Builtin::BIcabsf:
8865   case Builtin::BIcabsl:
8866     return FDecl->getBuiltinID();
8867   }
8868   llvm_unreachable("Unknown Builtin type");
8869 }
8870 
8871 // If the replacement is valid, emit a note with replacement function.
8872 // Additionally, suggest including the proper header if not already included.
8873 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
8874                             unsigned AbsKind, QualType ArgType) {
8875   bool EmitHeaderHint = true;
8876   const char *HeaderName = nullptr;
8877   const char *FunctionName = nullptr;
8878   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
8879     FunctionName = "std::abs";
8880     if (ArgType->isIntegralOrEnumerationType()) {
8881       HeaderName = "cstdlib";
8882     } else if (ArgType->isRealFloatingType()) {
8883       HeaderName = "cmath";
8884     } else {
8885       llvm_unreachable("Invalid Type");
8886     }
8887 
8888     // Lookup all std::abs
8889     if (NamespaceDecl *Std = S.getStdNamespace()) {
8890       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
8891       R.suppressDiagnostics();
8892       S.LookupQualifiedName(R, Std);
8893 
8894       for (const auto *I : R) {
8895         const FunctionDecl *FDecl = nullptr;
8896         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
8897           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
8898         } else {
8899           FDecl = dyn_cast<FunctionDecl>(I);
8900         }
8901         if (!FDecl)
8902           continue;
8903 
8904         // Found std::abs(), check that they are the right ones.
8905         if (FDecl->getNumParams() != 1)
8906           continue;
8907 
8908         // Check that the parameter type can handle the argument.
8909         QualType ParamType = FDecl->getParamDecl(0)->getType();
8910         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
8911             S.Context.getTypeSize(ArgType) <=
8912                 S.Context.getTypeSize(ParamType)) {
8913           // Found a function, don't need the header hint.
8914           EmitHeaderHint = false;
8915           break;
8916         }
8917       }
8918     }
8919   } else {
8920     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
8921     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
8922 
8923     if (HeaderName) {
8924       DeclarationName DN(&S.Context.Idents.get(FunctionName));
8925       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
8926       R.suppressDiagnostics();
8927       S.LookupName(R, S.getCurScope());
8928 
8929       if (R.isSingleResult()) {
8930         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
8931         if (FD && FD->getBuiltinID() == AbsKind) {
8932           EmitHeaderHint = false;
8933         } else {
8934           return;
8935         }
8936       } else if (!R.empty()) {
8937         return;
8938       }
8939     }
8940   }
8941 
8942   S.Diag(Loc, diag::note_replace_abs_function)
8943       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
8944 
8945   if (!HeaderName)
8946     return;
8947 
8948   if (!EmitHeaderHint)
8949     return;
8950 
8951   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
8952                                                     << FunctionName;
8953 }
8954 
8955 template <std::size_t StrLen>
8956 static bool IsStdFunction(const FunctionDecl *FDecl,
8957                           const char (&Str)[StrLen]) {
8958   if (!FDecl)
8959     return false;
8960   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
8961     return false;
8962   if (!FDecl->isInStdNamespace())
8963     return false;
8964 
8965   return true;
8966 }
8967 
8968 // Warn when using the wrong abs() function.
8969 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
8970                                       const FunctionDecl *FDecl) {
8971   if (Call->getNumArgs() != 1)
8972     return;
8973 
8974   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
8975   bool IsStdAbs = IsStdFunction(FDecl, "abs");
8976   if (AbsKind == 0 && !IsStdAbs)
8977     return;
8978 
8979   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
8980   QualType ParamType = Call->getArg(0)->getType();
8981 
8982   // Unsigned types cannot be negative.  Suggest removing the absolute value
8983   // function call.
8984   if (ArgType->isUnsignedIntegerType()) {
8985     const char *FunctionName =
8986         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
8987     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
8988     Diag(Call->getExprLoc(), diag::note_remove_abs)
8989         << FunctionName
8990         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
8991     return;
8992   }
8993 
8994   // Taking the absolute value of a pointer is very suspicious, they probably
8995   // wanted to index into an array, dereference a pointer, call a function, etc.
8996   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
8997     unsigned DiagType = 0;
8998     if (ArgType->isFunctionType())
8999       DiagType = 1;
9000     else if (ArgType->isArrayType())
9001       DiagType = 2;
9002 
9003     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
9004     return;
9005   }
9006 
9007   // std::abs has overloads which prevent most of the absolute value problems
9008   // from occurring.
9009   if (IsStdAbs)
9010     return;
9011 
9012   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
9013   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
9014 
9015   // The argument and parameter are the same kind.  Check if they are the right
9016   // size.
9017   if (ArgValueKind == ParamValueKind) {
9018     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
9019       return;
9020 
9021     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
9022     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
9023         << FDecl << ArgType << ParamType;
9024 
9025     if (NewAbsKind == 0)
9026       return;
9027 
9028     emitReplacement(*this, Call->getExprLoc(),
9029                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9030     return;
9031   }
9032 
9033   // ArgValueKind != ParamValueKind
9034   // The wrong type of absolute value function was used.  Attempt to find the
9035   // proper one.
9036   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
9037   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
9038   if (NewAbsKind == 0)
9039     return;
9040 
9041   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
9042       << FDecl << ParamValueKind << ArgValueKind;
9043 
9044   emitReplacement(*this, Call->getExprLoc(),
9045                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9046 }
9047 
9048 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
9049 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
9050                                 const FunctionDecl *FDecl) {
9051   if (!Call || !FDecl) return;
9052 
9053   // Ignore template specializations and macros.
9054   if (inTemplateInstantiation()) return;
9055   if (Call->getExprLoc().isMacroID()) return;
9056 
9057   // Only care about the one template argument, two function parameter std::max
9058   if (Call->getNumArgs() != 2) return;
9059   if (!IsStdFunction(FDecl, "max")) return;
9060   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
9061   if (!ArgList) return;
9062   if (ArgList->size() != 1) return;
9063 
9064   // Check that template type argument is unsigned integer.
9065   const auto& TA = ArgList->get(0);
9066   if (TA.getKind() != TemplateArgument::Type) return;
9067   QualType ArgType = TA.getAsType();
9068   if (!ArgType->isUnsignedIntegerType()) return;
9069 
9070   // See if either argument is a literal zero.
9071   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
9072     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
9073     if (!MTE) return false;
9074     const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
9075     if (!Num) return false;
9076     if (Num->getValue() != 0) return false;
9077     return true;
9078   };
9079 
9080   const Expr *FirstArg = Call->getArg(0);
9081   const Expr *SecondArg = Call->getArg(1);
9082   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
9083   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
9084 
9085   // Only warn when exactly one argument is zero.
9086   if (IsFirstArgZero == IsSecondArgZero) return;
9087 
9088   SourceRange FirstRange = FirstArg->getSourceRange();
9089   SourceRange SecondRange = SecondArg->getSourceRange();
9090 
9091   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
9092 
9093   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
9094       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
9095 
9096   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
9097   SourceRange RemovalRange;
9098   if (IsFirstArgZero) {
9099     RemovalRange = SourceRange(FirstRange.getBegin(),
9100                                SecondRange.getBegin().getLocWithOffset(-1));
9101   } else {
9102     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
9103                                SecondRange.getEnd());
9104   }
9105 
9106   Diag(Call->getExprLoc(), diag::note_remove_max_call)
9107         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
9108         << FixItHint::CreateRemoval(RemovalRange);
9109 }
9110 
9111 //===--- CHECK: Standard memory functions ---------------------------------===//
9112 
9113 /// Takes the expression passed to the size_t parameter of functions
9114 /// such as memcmp, strncat, etc and warns if it's a comparison.
9115 ///
9116 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
9117 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
9118                                            IdentifierInfo *FnName,
9119                                            SourceLocation FnLoc,
9120                                            SourceLocation RParenLoc) {
9121   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
9122   if (!Size)
9123     return false;
9124 
9125   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
9126   if (!Size->isComparisonOp() && !Size->isLogicalOp())
9127     return false;
9128 
9129   SourceRange SizeRange = Size->getSourceRange();
9130   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
9131       << SizeRange << FnName;
9132   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
9133       << FnName
9134       << FixItHint::CreateInsertion(
9135              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
9136       << FixItHint::CreateRemoval(RParenLoc);
9137   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
9138       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
9139       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
9140                                     ")");
9141 
9142   return true;
9143 }
9144 
9145 /// Determine whether the given type is or contains a dynamic class type
9146 /// (e.g., whether it has a vtable).
9147 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
9148                                                      bool &IsContained) {
9149   // Look through array types while ignoring qualifiers.
9150   const Type *Ty = T->getBaseElementTypeUnsafe();
9151   IsContained = false;
9152 
9153   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
9154   RD = RD ? RD->getDefinition() : nullptr;
9155   if (!RD || RD->isInvalidDecl())
9156     return nullptr;
9157 
9158   if (RD->isDynamicClass())
9159     return RD;
9160 
9161   // Check all the fields.  If any bases were dynamic, the class is dynamic.
9162   // It's impossible for a class to transitively contain itself by value, so
9163   // infinite recursion is impossible.
9164   for (auto *FD : RD->fields()) {
9165     bool SubContained;
9166     if (const CXXRecordDecl *ContainedRD =
9167             getContainedDynamicClass(FD->getType(), SubContained)) {
9168       IsContained = true;
9169       return ContainedRD;
9170     }
9171   }
9172 
9173   return nullptr;
9174 }
9175 
9176 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
9177   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
9178     if (Unary->getKind() == UETT_SizeOf)
9179       return Unary;
9180   return nullptr;
9181 }
9182 
9183 /// If E is a sizeof expression, returns its argument expression,
9184 /// otherwise returns NULL.
9185 static const Expr *getSizeOfExprArg(const Expr *E) {
9186   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9187     if (!SizeOf->isArgumentType())
9188       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
9189   return nullptr;
9190 }
9191 
9192 /// If E is a sizeof expression, returns its argument type.
9193 static QualType getSizeOfArgType(const Expr *E) {
9194   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9195     return SizeOf->getTypeOfArgument();
9196   return QualType();
9197 }
9198 
9199 namespace {
9200 
9201 struct SearchNonTrivialToInitializeField
9202     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
9203   using Super =
9204       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
9205 
9206   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
9207 
9208   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
9209                      SourceLocation SL) {
9210     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9211       asDerived().visitArray(PDIK, AT, SL);
9212       return;
9213     }
9214 
9215     Super::visitWithKind(PDIK, FT, SL);
9216   }
9217 
9218   void visitARCStrong(QualType FT, SourceLocation SL) {
9219     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9220   }
9221   void visitARCWeak(QualType FT, SourceLocation SL) {
9222     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9223   }
9224   void visitStruct(QualType FT, SourceLocation SL) {
9225     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9226       visit(FD->getType(), FD->getLocation());
9227   }
9228   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
9229                   const ArrayType *AT, SourceLocation SL) {
9230     visit(getContext().getBaseElementType(AT), SL);
9231   }
9232   void visitTrivial(QualType FT, SourceLocation SL) {}
9233 
9234   static void diag(QualType RT, const Expr *E, Sema &S) {
9235     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
9236   }
9237 
9238   ASTContext &getContext() { return S.getASTContext(); }
9239 
9240   const Expr *E;
9241   Sema &S;
9242 };
9243 
9244 struct SearchNonTrivialToCopyField
9245     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
9246   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
9247 
9248   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
9249 
9250   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
9251                      SourceLocation SL) {
9252     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9253       asDerived().visitArray(PCK, AT, SL);
9254       return;
9255     }
9256 
9257     Super::visitWithKind(PCK, FT, SL);
9258   }
9259 
9260   void visitARCStrong(QualType FT, SourceLocation SL) {
9261     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9262   }
9263   void visitARCWeak(QualType FT, SourceLocation SL) {
9264     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9265   }
9266   void visitStruct(QualType FT, SourceLocation SL) {
9267     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9268       visit(FD->getType(), FD->getLocation());
9269   }
9270   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
9271                   SourceLocation SL) {
9272     visit(getContext().getBaseElementType(AT), SL);
9273   }
9274   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
9275                 SourceLocation SL) {}
9276   void visitTrivial(QualType FT, SourceLocation SL) {}
9277   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
9278 
9279   static void diag(QualType RT, const Expr *E, Sema &S) {
9280     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
9281   }
9282 
9283   ASTContext &getContext() { return S.getASTContext(); }
9284 
9285   const Expr *E;
9286   Sema &S;
9287 };
9288 
9289 }
9290 
9291 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
9292 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
9293   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
9294 
9295   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
9296     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
9297       return false;
9298 
9299     return doesExprLikelyComputeSize(BO->getLHS()) ||
9300            doesExprLikelyComputeSize(BO->getRHS());
9301   }
9302 
9303   return getAsSizeOfExpr(SizeofExpr) != nullptr;
9304 }
9305 
9306 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
9307 ///
9308 /// \code
9309 ///   #define MACRO 0
9310 ///   foo(MACRO);
9311 ///   foo(0);
9312 /// \endcode
9313 ///
9314 /// This should return true for the first call to foo, but not for the second
9315 /// (regardless of whether foo is a macro or function).
9316 static bool isArgumentExpandedFromMacro(SourceManager &SM,
9317                                         SourceLocation CallLoc,
9318                                         SourceLocation ArgLoc) {
9319   if (!CallLoc.isMacroID())
9320     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
9321 
9322   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
9323          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
9324 }
9325 
9326 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
9327 /// last two arguments transposed.
9328 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
9329   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
9330     return;
9331 
9332   const Expr *SizeArg =
9333     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
9334 
9335   auto isLiteralZero = [](const Expr *E) {
9336     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
9337   };
9338 
9339   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
9340   SourceLocation CallLoc = Call->getRParenLoc();
9341   SourceManager &SM = S.getSourceManager();
9342   if (isLiteralZero(SizeArg) &&
9343       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
9344 
9345     SourceLocation DiagLoc = SizeArg->getExprLoc();
9346 
9347     // Some platforms #define bzero to __builtin_memset. See if this is the
9348     // case, and if so, emit a better diagnostic.
9349     if (BId == Builtin::BIbzero ||
9350         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
9351                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
9352       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
9353       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
9354     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
9355       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
9356       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
9357     }
9358     return;
9359   }
9360 
9361   // If the second argument to a memset is a sizeof expression and the third
9362   // isn't, this is also likely an error. This should catch
9363   // 'memset(buf, sizeof(buf), 0xff)'.
9364   if (BId == Builtin::BImemset &&
9365       doesExprLikelyComputeSize(Call->getArg(1)) &&
9366       !doesExprLikelyComputeSize(Call->getArg(2))) {
9367     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
9368     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
9369     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
9370     return;
9371   }
9372 }
9373 
9374 /// Check for dangerous or invalid arguments to memset().
9375 ///
9376 /// This issues warnings on known problematic, dangerous or unspecified
9377 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
9378 /// function calls.
9379 ///
9380 /// \param Call The call expression to diagnose.
9381 void Sema::CheckMemaccessArguments(const CallExpr *Call,
9382                                    unsigned BId,
9383                                    IdentifierInfo *FnName) {
9384   assert(BId != 0);
9385 
9386   // It is possible to have a non-standard definition of memset.  Validate
9387   // we have enough arguments, and if not, abort further checking.
9388   unsigned ExpectedNumArgs =
9389       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
9390   if (Call->getNumArgs() < ExpectedNumArgs)
9391     return;
9392 
9393   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
9394                       BId == Builtin::BIstrndup ? 1 : 2);
9395   unsigned LenArg =
9396       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
9397   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
9398 
9399   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
9400                                      Call->getBeginLoc(), Call->getRParenLoc()))
9401     return;
9402 
9403   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
9404   CheckMemaccessSize(*this, BId, Call);
9405 
9406   // We have special checking when the length is a sizeof expression.
9407   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
9408   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
9409   llvm::FoldingSetNodeID SizeOfArgID;
9410 
9411   // Although widely used, 'bzero' is not a standard function. Be more strict
9412   // with the argument types before allowing diagnostics and only allow the
9413   // form bzero(ptr, sizeof(...)).
9414   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9415   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
9416     return;
9417 
9418   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
9419     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
9420     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
9421 
9422     QualType DestTy = Dest->getType();
9423     QualType PointeeTy;
9424     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
9425       PointeeTy = DestPtrTy->getPointeeType();
9426 
9427       // Never warn about void type pointers. This can be used to suppress
9428       // false positives.
9429       if (PointeeTy->isVoidType())
9430         continue;
9431 
9432       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
9433       // actually comparing the expressions for equality. Because computing the
9434       // expression IDs can be expensive, we only do this if the diagnostic is
9435       // enabled.
9436       if (SizeOfArg &&
9437           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
9438                            SizeOfArg->getExprLoc())) {
9439         // We only compute IDs for expressions if the warning is enabled, and
9440         // cache the sizeof arg's ID.
9441         if (SizeOfArgID == llvm::FoldingSetNodeID())
9442           SizeOfArg->Profile(SizeOfArgID, Context, true);
9443         llvm::FoldingSetNodeID DestID;
9444         Dest->Profile(DestID, Context, true);
9445         if (DestID == SizeOfArgID) {
9446           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
9447           //       over sizeof(src) as well.
9448           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
9449           StringRef ReadableName = FnName->getName();
9450 
9451           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
9452             if (UnaryOp->getOpcode() == UO_AddrOf)
9453               ActionIdx = 1; // If its an address-of operator, just remove it.
9454           if (!PointeeTy->isIncompleteType() &&
9455               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
9456             ActionIdx = 2; // If the pointee's size is sizeof(char),
9457                            // suggest an explicit length.
9458 
9459           // If the function is defined as a builtin macro, do not show macro
9460           // expansion.
9461           SourceLocation SL = SizeOfArg->getExprLoc();
9462           SourceRange DSR = Dest->getSourceRange();
9463           SourceRange SSR = SizeOfArg->getSourceRange();
9464           SourceManager &SM = getSourceManager();
9465 
9466           if (SM.isMacroArgExpansion(SL)) {
9467             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
9468             SL = SM.getSpellingLoc(SL);
9469             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
9470                              SM.getSpellingLoc(DSR.getEnd()));
9471             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
9472                              SM.getSpellingLoc(SSR.getEnd()));
9473           }
9474 
9475           DiagRuntimeBehavior(SL, SizeOfArg,
9476                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
9477                                 << ReadableName
9478                                 << PointeeTy
9479                                 << DestTy
9480                                 << DSR
9481                                 << SSR);
9482           DiagRuntimeBehavior(SL, SizeOfArg,
9483                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
9484                                 << ActionIdx
9485                                 << SSR);
9486 
9487           break;
9488         }
9489       }
9490 
9491       // Also check for cases where the sizeof argument is the exact same
9492       // type as the memory argument, and where it points to a user-defined
9493       // record type.
9494       if (SizeOfArgTy != QualType()) {
9495         if (PointeeTy->isRecordType() &&
9496             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
9497           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
9498                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
9499                                 << FnName << SizeOfArgTy << ArgIdx
9500                                 << PointeeTy << Dest->getSourceRange()
9501                                 << LenExpr->getSourceRange());
9502           break;
9503         }
9504       }
9505     } else if (DestTy->isArrayType()) {
9506       PointeeTy = DestTy;
9507     }
9508 
9509     if (PointeeTy == QualType())
9510       continue;
9511 
9512     // Always complain about dynamic classes.
9513     bool IsContained;
9514     if (const CXXRecordDecl *ContainedRD =
9515             getContainedDynamicClass(PointeeTy, IsContained)) {
9516 
9517       unsigned OperationType = 0;
9518       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
9519       // "overwritten" if we're warning about the destination for any call
9520       // but memcmp; otherwise a verb appropriate to the call.
9521       if (ArgIdx != 0 || IsCmp) {
9522         if (BId == Builtin::BImemcpy)
9523           OperationType = 1;
9524         else if(BId == Builtin::BImemmove)
9525           OperationType = 2;
9526         else if (IsCmp)
9527           OperationType = 3;
9528       }
9529 
9530       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9531                           PDiag(diag::warn_dyn_class_memaccess)
9532                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
9533                               << IsContained << ContainedRD << OperationType
9534                               << Call->getCallee()->getSourceRange());
9535     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
9536              BId != Builtin::BImemset)
9537       DiagRuntimeBehavior(
9538         Dest->getExprLoc(), Dest,
9539         PDiag(diag::warn_arc_object_memaccess)
9540           << ArgIdx << FnName << PointeeTy
9541           << Call->getCallee()->getSourceRange());
9542     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
9543       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
9544           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
9545         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9546                             PDiag(diag::warn_cstruct_memaccess)
9547                                 << ArgIdx << FnName << PointeeTy << 0);
9548         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
9549       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
9550                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
9551         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9552                             PDiag(diag::warn_cstruct_memaccess)
9553                                 << ArgIdx << FnName << PointeeTy << 1);
9554         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
9555       } else {
9556         continue;
9557       }
9558     } else
9559       continue;
9560 
9561     DiagRuntimeBehavior(
9562       Dest->getExprLoc(), Dest,
9563       PDiag(diag::note_bad_memaccess_silence)
9564         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
9565     break;
9566   }
9567 }
9568 
9569 // A little helper routine: ignore addition and subtraction of integer literals.
9570 // This intentionally does not ignore all integer constant expressions because
9571 // we don't want to remove sizeof().
9572 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
9573   Ex = Ex->IgnoreParenCasts();
9574 
9575   while (true) {
9576     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
9577     if (!BO || !BO->isAdditiveOp())
9578       break;
9579 
9580     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
9581     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
9582 
9583     if (isa<IntegerLiteral>(RHS))
9584       Ex = LHS;
9585     else if (isa<IntegerLiteral>(LHS))
9586       Ex = RHS;
9587     else
9588       break;
9589   }
9590 
9591   return Ex;
9592 }
9593 
9594 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
9595                                                       ASTContext &Context) {
9596   // Only handle constant-sized or VLAs, but not flexible members.
9597   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
9598     // Only issue the FIXIT for arrays of size > 1.
9599     if (CAT->getSize().getSExtValue() <= 1)
9600       return false;
9601   } else if (!Ty->isVariableArrayType()) {
9602     return false;
9603   }
9604   return true;
9605 }
9606 
9607 // Warn if the user has made the 'size' argument to strlcpy or strlcat
9608 // be the size of the source, instead of the destination.
9609 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
9610                                     IdentifierInfo *FnName) {
9611 
9612   // Don't crash if the user has the wrong number of arguments
9613   unsigned NumArgs = Call->getNumArgs();
9614   if ((NumArgs != 3) && (NumArgs != 4))
9615     return;
9616 
9617   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
9618   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
9619   const Expr *CompareWithSrc = nullptr;
9620 
9621   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
9622                                      Call->getBeginLoc(), Call->getRParenLoc()))
9623     return;
9624 
9625   // Look for 'strlcpy(dst, x, sizeof(x))'
9626   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
9627     CompareWithSrc = Ex;
9628   else {
9629     // Look for 'strlcpy(dst, x, strlen(x))'
9630     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
9631       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
9632           SizeCall->getNumArgs() == 1)
9633         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
9634     }
9635   }
9636 
9637   if (!CompareWithSrc)
9638     return;
9639 
9640   // Determine if the argument to sizeof/strlen is equal to the source
9641   // argument.  In principle there's all kinds of things you could do
9642   // here, for instance creating an == expression and evaluating it with
9643   // EvaluateAsBooleanCondition, but this uses a more direct technique:
9644   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
9645   if (!SrcArgDRE)
9646     return;
9647 
9648   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
9649   if (!CompareWithSrcDRE ||
9650       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
9651     return;
9652 
9653   const Expr *OriginalSizeArg = Call->getArg(2);
9654   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
9655       << OriginalSizeArg->getSourceRange() << FnName;
9656 
9657   // Output a FIXIT hint if the destination is an array (rather than a
9658   // pointer to an array).  This could be enhanced to handle some
9659   // pointers if we know the actual size, like if DstArg is 'array+2'
9660   // we could say 'sizeof(array)-2'.
9661   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
9662   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
9663     return;
9664 
9665   SmallString<128> sizeString;
9666   llvm::raw_svector_ostream OS(sizeString);
9667   OS << "sizeof(";
9668   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9669   OS << ")";
9670 
9671   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
9672       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
9673                                       OS.str());
9674 }
9675 
9676 /// Check if two expressions refer to the same declaration.
9677 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
9678   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
9679     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
9680       return D1->getDecl() == D2->getDecl();
9681   return false;
9682 }
9683 
9684 static const Expr *getStrlenExprArg(const Expr *E) {
9685   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
9686     const FunctionDecl *FD = CE->getDirectCallee();
9687     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
9688       return nullptr;
9689     return CE->getArg(0)->IgnoreParenCasts();
9690   }
9691   return nullptr;
9692 }
9693 
9694 // Warn on anti-patterns as the 'size' argument to strncat.
9695 // The correct size argument should look like following:
9696 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
9697 void Sema::CheckStrncatArguments(const CallExpr *CE,
9698                                  IdentifierInfo *FnName) {
9699   // Don't crash if the user has the wrong number of arguments.
9700   if (CE->getNumArgs() < 3)
9701     return;
9702   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
9703   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
9704   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
9705 
9706   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
9707                                      CE->getRParenLoc()))
9708     return;
9709 
9710   // Identify common expressions, which are wrongly used as the size argument
9711   // to strncat and may lead to buffer overflows.
9712   unsigned PatternType = 0;
9713   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
9714     // - sizeof(dst)
9715     if (referToTheSameDecl(SizeOfArg, DstArg))
9716       PatternType = 1;
9717     // - sizeof(src)
9718     else if (referToTheSameDecl(SizeOfArg, SrcArg))
9719       PatternType = 2;
9720   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
9721     if (BE->getOpcode() == BO_Sub) {
9722       const Expr *L = BE->getLHS()->IgnoreParenCasts();
9723       const Expr *R = BE->getRHS()->IgnoreParenCasts();
9724       // - sizeof(dst) - strlen(dst)
9725       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
9726           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
9727         PatternType = 1;
9728       // - sizeof(src) - (anything)
9729       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
9730         PatternType = 2;
9731     }
9732   }
9733 
9734   if (PatternType == 0)
9735     return;
9736 
9737   // Generate the diagnostic.
9738   SourceLocation SL = LenArg->getBeginLoc();
9739   SourceRange SR = LenArg->getSourceRange();
9740   SourceManager &SM = getSourceManager();
9741 
9742   // If the function is defined as a builtin macro, do not show macro expansion.
9743   if (SM.isMacroArgExpansion(SL)) {
9744     SL = SM.getSpellingLoc(SL);
9745     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
9746                      SM.getSpellingLoc(SR.getEnd()));
9747   }
9748 
9749   // Check if the destination is an array (rather than a pointer to an array).
9750   QualType DstTy = DstArg->getType();
9751   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
9752                                                                     Context);
9753   if (!isKnownSizeArray) {
9754     if (PatternType == 1)
9755       Diag(SL, diag::warn_strncat_wrong_size) << SR;
9756     else
9757       Diag(SL, diag::warn_strncat_src_size) << SR;
9758     return;
9759   }
9760 
9761   if (PatternType == 1)
9762     Diag(SL, diag::warn_strncat_large_size) << SR;
9763   else
9764     Diag(SL, diag::warn_strncat_src_size) << SR;
9765 
9766   SmallString<128> sizeString;
9767   llvm::raw_svector_ostream OS(sizeString);
9768   OS << "sizeof(";
9769   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9770   OS << ") - ";
9771   OS << "strlen(";
9772   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9773   OS << ") - 1";
9774 
9775   Diag(SL, diag::note_strncat_wrong_size)
9776     << FixItHint::CreateReplacement(SR, OS.str());
9777 }
9778 
9779 void
9780 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
9781                          SourceLocation ReturnLoc,
9782                          bool isObjCMethod,
9783                          const AttrVec *Attrs,
9784                          const FunctionDecl *FD) {
9785   // Check if the return value is null but should not be.
9786   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
9787        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
9788       CheckNonNullExpr(*this, RetValExp))
9789     Diag(ReturnLoc, diag::warn_null_ret)
9790       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
9791 
9792   // C++11 [basic.stc.dynamic.allocation]p4:
9793   //   If an allocation function declared with a non-throwing
9794   //   exception-specification fails to allocate storage, it shall return
9795   //   a null pointer. Any other allocation function that fails to allocate
9796   //   storage shall indicate failure only by throwing an exception [...]
9797   if (FD) {
9798     OverloadedOperatorKind Op = FD->getOverloadedOperator();
9799     if (Op == OO_New || Op == OO_Array_New) {
9800       const FunctionProtoType *Proto
9801         = FD->getType()->castAs<FunctionProtoType>();
9802       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
9803           CheckNonNullExpr(*this, RetValExp))
9804         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
9805           << FD << getLangOpts().CPlusPlus11;
9806     }
9807   }
9808 }
9809 
9810 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
9811 
9812 /// Check for comparisons of floating point operands using != and ==.
9813 /// Issue a warning if these are no self-comparisons, as they are not likely
9814 /// to do what the programmer intended.
9815 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
9816   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
9817   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
9818 
9819   // Special case: check for x == x (which is OK).
9820   // Do not emit warnings for such cases.
9821   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
9822     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
9823       if (DRL->getDecl() == DRR->getDecl())
9824         return;
9825 
9826   // Special case: check for comparisons against literals that can be exactly
9827   //  represented by APFloat.  In such cases, do not emit a warning.  This
9828   //  is a heuristic: often comparison against such literals are used to
9829   //  detect if a value in a variable has not changed.  This clearly can
9830   //  lead to false negatives.
9831   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
9832     if (FLL->isExact())
9833       return;
9834   } else
9835     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
9836       if (FLR->isExact())
9837         return;
9838 
9839   // Check for comparisons with builtin types.
9840   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
9841     if (CL->getBuiltinCallee())
9842       return;
9843 
9844   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
9845     if (CR->getBuiltinCallee())
9846       return;
9847 
9848   // Emit the diagnostic.
9849   Diag(Loc, diag::warn_floatingpoint_eq)
9850     << LHS->getSourceRange() << RHS->getSourceRange();
9851 }
9852 
9853 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
9854 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
9855 
9856 namespace {
9857 
9858 /// Structure recording the 'active' range of an integer-valued
9859 /// expression.
9860 struct IntRange {
9861   /// The number of bits active in the int.
9862   unsigned Width;
9863 
9864   /// True if the int is known not to have negative values.
9865   bool NonNegative;
9866 
9867   IntRange(unsigned Width, bool NonNegative)
9868       : Width(Width), NonNegative(NonNegative) {}
9869 
9870   /// Returns the range of the bool type.
9871   static IntRange forBoolType() {
9872     return IntRange(1, true);
9873   }
9874 
9875   /// Returns the range of an opaque value of the given integral type.
9876   static IntRange forValueOfType(ASTContext &C, QualType T) {
9877     return forValueOfCanonicalType(C,
9878                           T->getCanonicalTypeInternal().getTypePtr());
9879   }
9880 
9881   /// Returns the range of an opaque value of a canonical integral type.
9882   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
9883     assert(T->isCanonicalUnqualified());
9884 
9885     if (const VectorType *VT = dyn_cast<VectorType>(T))
9886       T = VT->getElementType().getTypePtr();
9887     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
9888       T = CT->getElementType().getTypePtr();
9889     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
9890       T = AT->getValueType().getTypePtr();
9891 
9892     if (!C.getLangOpts().CPlusPlus) {
9893       // For enum types in C code, use the underlying datatype.
9894       if (const EnumType *ET = dyn_cast<EnumType>(T))
9895         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
9896     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
9897       // For enum types in C++, use the known bit width of the enumerators.
9898       EnumDecl *Enum = ET->getDecl();
9899       // In C++11, enums can have a fixed underlying type. Use this type to
9900       // compute the range.
9901       if (Enum->isFixed()) {
9902         return IntRange(C.getIntWidth(QualType(T, 0)),
9903                         !ET->isSignedIntegerOrEnumerationType());
9904       }
9905 
9906       unsigned NumPositive = Enum->getNumPositiveBits();
9907       unsigned NumNegative = Enum->getNumNegativeBits();
9908 
9909       if (NumNegative == 0)
9910         return IntRange(NumPositive, true/*NonNegative*/);
9911       else
9912         return IntRange(std::max(NumPositive + 1, NumNegative),
9913                         false/*NonNegative*/);
9914     }
9915 
9916     if (const auto *EIT = dyn_cast<ExtIntType>(T))
9917       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
9918 
9919     const BuiltinType *BT = cast<BuiltinType>(T);
9920     assert(BT->isInteger());
9921 
9922     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
9923   }
9924 
9925   /// Returns the "target" range of a canonical integral type, i.e.
9926   /// the range of values expressible in the type.
9927   ///
9928   /// This matches forValueOfCanonicalType except that enums have the
9929   /// full range of their type, not the range of their enumerators.
9930   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
9931     assert(T->isCanonicalUnqualified());
9932 
9933     if (const VectorType *VT = dyn_cast<VectorType>(T))
9934       T = VT->getElementType().getTypePtr();
9935     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
9936       T = CT->getElementType().getTypePtr();
9937     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
9938       T = AT->getValueType().getTypePtr();
9939     if (const EnumType *ET = dyn_cast<EnumType>(T))
9940       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
9941 
9942     if (const auto *EIT = dyn_cast<ExtIntType>(T))
9943       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
9944 
9945     const BuiltinType *BT = cast<BuiltinType>(T);
9946     assert(BT->isInteger());
9947 
9948     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
9949   }
9950 
9951   /// Returns the supremum of two ranges: i.e. their conservative merge.
9952   static IntRange join(IntRange L, IntRange R) {
9953     return IntRange(std::max(L.Width, R.Width),
9954                     L.NonNegative && R.NonNegative);
9955   }
9956 
9957   /// Returns the infinum of two ranges: i.e. their aggressive merge.
9958   static IntRange meet(IntRange L, IntRange R) {
9959     return IntRange(std::min(L.Width, R.Width),
9960                     L.NonNegative || R.NonNegative);
9961   }
9962 };
9963 
9964 } // namespace
9965 
9966 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
9967                               unsigned MaxWidth) {
9968   if (value.isSigned() && value.isNegative())
9969     return IntRange(value.getMinSignedBits(), false);
9970 
9971   if (value.getBitWidth() > MaxWidth)
9972     value = value.trunc(MaxWidth);
9973 
9974   // isNonNegative() just checks the sign bit without considering
9975   // signedness.
9976   return IntRange(value.getActiveBits(), true);
9977 }
9978 
9979 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
9980                               unsigned MaxWidth) {
9981   if (result.isInt())
9982     return GetValueRange(C, result.getInt(), MaxWidth);
9983 
9984   if (result.isVector()) {
9985     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
9986     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
9987       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
9988       R = IntRange::join(R, El);
9989     }
9990     return R;
9991   }
9992 
9993   if (result.isComplexInt()) {
9994     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
9995     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
9996     return IntRange::join(R, I);
9997   }
9998 
9999   // This can happen with lossless casts to intptr_t of "based" lvalues.
10000   // Assume it might use arbitrary bits.
10001   // FIXME: The only reason we need to pass the type in here is to get
10002   // the sign right on this one case.  It would be nice if APValue
10003   // preserved this.
10004   assert(result.isLValue() || result.isAddrLabelDiff());
10005   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
10006 }
10007 
10008 static QualType GetExprType(const Expr *E) {
10009   QualType Ty = E->getType();
10010   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
10011     Ty = AtomicRHS->getValueType();
10012   return Ty;
10013 }
10014 
10015 /// Pseudo-evaluate the given integer expression, estimating the
10016 /// range of values it might take.
10017 ///
10018 /// \param MaxWidth - the width to which the value will be truncated
10019 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
10020                              bool InConstantContext) {
10021   E = E->IgnoreParens();
10022 
10023   // Try a full evaluation first.
10024   Expr::EvalResult result;
10025   if (E->EvaluateAsRValue(result, C, InConstantContext))
10026     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
10027 
10028   // I think we only want to look through implicit casts here; if the
10029   // user has an explicit widening cast, we should treat the value as
10030   // being of the new, wider type.
10031   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
10032     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
10033       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext);
10034 
10035     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
10036 
10037     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
10038                          CE->getCastKind() == CK_BooleanToSignedIntegral;
10039 
10040     // Assume that non-integer casts can span the full range of the type.
10041     if (!isIntegerCast)
10042       return OutputTypeRange;
10043 
10044     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
10045                                      std::min(MaxWidth, OutputTypeRange.Width),
10046                                      InConstantContext);
10047 
10048     // Bail out if the subexpr's range is as wide as the cast type.
10049     if (SubRange.Width >= OutputTypeRange.Width)
10050       return OutputTypeRange;
10051 
10052     // Otherwise, we take the smaller width, and we're non-negative if
10053     // either the output type or the subexpr is.
10054     return IntRange(SubRange.Width,
10055                     SubRange.NonNegative || OutputTypeRange.NonNegative);
10056   }
10057 
10058   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
10059     // If we can fold the condition, just take that operand.
10060     bool CondResult;
10061     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
10062       return GetExprRange(C,
10063                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
10064                           MaxWidth, InConstantContext);
10065 
10066     // Otherwise, conservatively merge.
10067     IntRange L =
10068         GetExprRange(C, CO->getTrueExpr(), MaxWidth, InConstantContext);
10069     IntRange R =
10070         GetExprRange(C, CO->getFalseExpr(), MaxWidth, InConstantContext);
10071     return IntRange::join(L, R);
10072   }
10073 
10074   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
10075     switch (BO->getOpcode()) {
10076     case BO_Cmp:
10077       llvm_unreachable("builtin <=> should have class type");
10078 
10079     // Boolean-valued operations are single-bit and positive.
10080     case BO_LAnd:
10081     case BO_LOr:
10082     case BO_LT:
10083     case BO_GT:
10084     case BO_LE:
10085     case BO_GE:
10086     case BO_EQ:
10087     case BO_NE:
10088       return IntRange::forBoolType();
10089 
10090     // The type of the assignments is the type of the LHS, so the RHS
10091     // is not necessarily the same type.
10092     case BO_MulAssign:
10093     case BO_DivAssign:
10094     case BO_RemAssign:
10095     case BO_AddAssign:
10096     case BO_SubAssign:
10097     case BO_XorAssign:
10098     case BO_OrAssign:
10099       // TODO: bitfields?
10100       return IntRange::forValueOfType(C, GetExprType(E));
10101 
10102     // Simple assignments just pass through the RHS, which will have
10103     // been coerced to the LHS type.
10104     case BO_Assign:
10105       // TODO: bitfields?
10106       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
10107 
10108     // Operations with opaque sources are black-listed.
10109     case BO_PtrMemD:
10110     case BO_PtrMemI:
10111       return IntRange::forValueOfType(C, GetExprType(E));
10112 
10113     // Bitwise-and uses the *infinum* of the two source ranges.
10114     case BO_And:
10115     case BO_AndAssign:
10116       return IntRange::meet(
10117           GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext),
10118           GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext));
10119 
10120     // Left shift gets black-listed based on a judgement call.
10121     case BO_Shl:
10122       // ...except that we want to treat '1 << (blah)' as logically
10123       // positive.  It's an important idiom.
10124       if (IntegerLiteral *I
10125             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
10126         if (I->getValue() == 1) {
10127           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
10128           return IntRange(R.Width, /*NonNegative*/ true);
10129         }
10130       }
10131       LLVM_FALLTHROUGH;
10132 
10133     case BO_ShlAssign:
10134       return IntRange::forValueOfType(C, GetExprType(E));
10135 
10136     // Right shift by a constant can narrow its left argument.
10137     case BO_Shr:
10138     case BO_ShrAssign: {
10139       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext);
10140 
10141       // If the shift amount is a positive constant, drop the width by
10142       // that much.
10143       llvm::APSInt shift;
10144       if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
10145           shift.isNonNegative()) {
10146         unsigned zext = shift.getZExtValue();
10147         if (zext >= L.Width)
10148           L.Width = (L.NonNegative ? 0 : 1);
10149         else
10150           L.Width -= zext;
10151       }
10152 
10153       return L;
10154     }
10155 
10156     // Comma acts as its right operand.
10157     case BO_Comma:
10158       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
10159 
10160     // Black-list pointer subtractions.
10161     case BO_Sub:
10162       if (BO->getLHS()->getType()->isPointerType())
10163         return IntRange::forValueOfType(C, GetExprType(E));
10164       break;
10165 
10166     // The width of a division result is mostly determined by the size
10167     // of the LHS.
10168     case BO_Div: {
10169       // Don't 'pre-truncate' the operands.
10170       unsigned opWidth = C.getIntWidth(GetExprType(E));
10171       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext);
10172 
10173       // If the divisor is constant, use that.
10174       llvm::APSInt divisor;
10175       if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
10176         unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
10177         if (log2 >= L.Width)
10178           L.Width = (L.NonNegative ? 0 : 1);
10179         else
10180           L.Width = std::min(L.Width - log2, MaxWidth);
10181         return L;
10182       }
10183 
10184       // Otherwise, just use the LHS's width.
10185       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext);
10186       return IntRange(L.Width, L.NonNegative && R.NonNegative);
10187     }
10188 
10189     // The result of a remainder can't be larger than the result of
10190     // either side.
10191     case BO_Rem: {
10192       // Don't 'pre-truncate' the operands.
10193       unsigned opWidth = C.getIntWidth(GetExprType(E));
10194       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext);
10195       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext);
10196 
10197       IntRange meet = IntRange::meet(L, R);
10198       meet.Width = std::min(meet.Width, MaxWidth);
10199       return meet;
10200     }
10201 
10202     // The default behavior is okay for these.
10203     case BO_Mul:
10204     case BO_Add:
10205     case BO_Xor:
10206     case BO_Or:
10207       break;
10208     }
10209 
10210     // The default case is to treat the operation as if it were closed
10211     // on the narrowest type that encompasses both operands.
10212     IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext);
10213     IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
10214     return IntRange::join(L, R);
10215   }
10216 
10217   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
10218     switch (UO->getOpcode()) {
10219     // Boolean-valued operations are white-listed.
10220     case UO_LNot:
10221       return IntRange::forBoolType();
10222 
10223     // Operations with opaque sources are black-listed.
10224     case UO_Deref:
10225     case UO_AddrOf: // should be impossible
10226       return IntRange::forValueOfType(C, GetExprType(E));
10227 
10228     default:
10229       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext);
10230     }
10231   }
10232 
10233   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
10234     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext);
10235 
10236   if (const auto *BitField = E->getSourceBitField())
10237     return IntRange(BitField->getBitWidthValue(C),
10238                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
10239 
10240   return IntRange::forValueOfType(C, GetExprType(E));
10241 }
10242 
10243 static IntRange GetExprRange(ASTContext &C, const Expr *E,
10244                              bool InConstantContext) {
10245   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext);
10246 }
10247 
10248 /// Checks whether the given value, which currently has the given
10249 /// source semantics, has the same value when coerced through the
10250 /// target semantics.
10251 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
10252                                  const llvm::fltSemantics &Src,
10253                                  const llvm::fltSemantics &Tgt) {
10254   llvm::APFloat truncated = value;
10255 
10256   bool ignored;
10257   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
10258   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
10259 
10260   return truncated.bitwiseIsEqual(value);
10261 }
10262 
10263 /// Checks whether the given value, which currently has the given
10264 /// source semantics, has the same value when coerced through the
10265 /// target semantics.
10266 ///
10267 /// The value might be a vector of floats (or a complex number).
10268 static bool IsSameFloatAfterCast(const APValue &value,
10269                                  const llvm::fltSemantics &Src,
10270                                  const llvm::fltSemantics &Tgt) {
10271   if (value.isFloat())
10272     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
10273 
10274   if (value.isVector()) {
10275     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
10276       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
10277         return false;
10278     return true;
10279   }
10280 
10281   assert(value.isComplexFloat());
10282   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
10283           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
10284 }
10285 
10286 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
10287                                        bool IsListInit = false);
10288 
10289 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
10290   // Suppress cases where we are comparing against an enum constant.
10291   if (const DeclRefExpr *DR =
10292       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
10293     if (isa<EnumConstantDecl>(DR->getDecl()))
10294       return true;
10295 
10296   // Suppress cases where the value is expanded from a macro, unless that macro
10297   // is how a language represents a boolean literal. This is the case in both C
10298   // and Objective-C.
10299   SourceLocation BeginLoc = E->getBeginLoc();
10300   if (BeginLoc.isMacroID()) {
10301     StringRef MacroName = Lexer::getImmediateMacroName(
10302         BeginLoc, S.getSourceManager(), S.getLangOpts());
10303     return MacroName != "YES" && MacroName != "NO" &&
10304            MacroName != "true" && MacroName != "false";
10305   }
10306 
10307   return false;
10308 }
10309 
10310 static bool isKnownToHaveUnsignedValue(Expr *E) {
10311   return E->getType()->isIntegerType() &&
10312          (!E->getType()->isSignedIntegerType() ||
10313           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
10314 }
10315 
10316 namespace {
10317 /// The promoted range of values of a type. In general this has the
10318 /// following structure:
10319 ///
10320 ///     |-----------| . . . |-----------|
10321 ///     ^           ^       ^           ^
10322 ///    Min       HoleMin  HoleMax      Max
10323 ///
10324 /// ... where there is only a hole if a signed type is promoted to unsigned
10325 /// (in which case Min and Max are the smallest and largest representable
10326 /// values).
10327 struct PromotedRange {
10328   // Min, or HoleMax if there is a hole.
10329   llvm::APSInt PromotedMin;
10330   // Max, or HoleMin if there is a hole.
10331   llvm::APSInt PromotedMax;
10332 
10333   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
10334     if (R.Width == 0)
10335       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
10336     else if (R.Width >= BitWidth && !Unsigned) {
10337       // Promotion made the type *narrower*. This happens when promoting
10338       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
10339       // Treat all values of 'signed int' as being in range for now.
10340       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
10341       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
10342     } else {
10343       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
10344                         .extOrTrunc(BitWidth);
10345       PromotedMin.setIsUnsigned(Unsigned);
10346 
10347       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
10348                         .extOrTrunc(BitWidth);
10349       PromotedMax.setIsUnsigned(Unsigned);
10350     }
10351   }
10352 
10353   // Determine whether this range is contiguous (has no hole).
10354   bool isContiguous() const { return PromotedMin <= PromotedMax; }
10355 
10356   // Where a constant value is within the range.
10357   enum ComparisonResult {
10358     LT = 0x1,
10359     LE = 0x2,
10360     GT = 0x4,
10361     GE = 0x8,
10362     EQ = 0x10,
10363     NE = 0x20,
10364     InRangeFlag = 0x40,
10365 
10366     Less = LE | LT | NE,
10367     Min = LE | InRangeFlag,
10368     InRange = InRangeFlag,
10369     Max = GE | InRangeFlag,
10370     Greater = GE | GT | NE,
10371 
10372     OnlyValue = LE | GE | EQ | InRangeFlag,
10373     InHole = NE
10374   };
10375 
10376   ComparisonResult compare(const llvm::APSInt &Value) const {
10377     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
10378            Value.isUnsigned() == PromotedMin.isUnsigned());
10379     if (!isContiguous()) {
10380       assert(Value.isUnsigned() && "discontiguous range for signed compare");
10381       if (Value.isMinValue()) return Min;
10382       if (Value.isMaxValue()) return Max;
10383       if (Value >= PromotedMin) return InRange;
10384       if (Value <= PromotedMax) return InRange;
10385       return InHole;
10386     }
10387 
10388     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
10389     case -1: return Less;
10390     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
10391     case 1:
10392       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
10393       case -1: return InRange;
10394       case 0: return Max;
10395       case 1: return Greater;
10396       }
10397     }
10398 
10399     llvm_unreachable("impossible compare result");
10400   }
10401 
10402   static llvm::Optional<StringRef>
10403   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
10404     if (Op == BO_Cmp) {
10405       ComparisonResult LTFlag = LT, GTFlag = GT;
10406       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
10407 
10408       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
10409       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
10410       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
10411       return llvm::None;
10412     }
10413 
10414     ComparisonResult TrueFlag, FalseFlag;
10415     if (Op == BO_EQ) {
10416       TrueFlag = EQ;
10417       FalseFlag = NE;
10418     } else if (Op == BO_NE) {
10419       TrueFlag = NE;
10420       FalseFlag = EQ;
10421     } else {
10422       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
10423         TrueFlag = LT;
10424         FalseFlag = GE;
10425       } else {
10426         TrueFlag = GT;
10427         FalseFlag = LE;
10428       }
10429       if (Op == BO_GE || Op == BO_LE)
10430         std::swap(TrueFlag, FalseFlag);
10431     }
10432     if (R & TrueFlag)
10433       return StringRef("true");
10434     if (R & FalseFlag)
10435       return StringRef("false");
10436     return llvm::None;
10437   }
10438 };
10439 }
10440 
10441 static bool HasEnumType(Expr *E) {
10442   // Strip off implicit integral promotions.
10443   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
10444     if (ICE->getCastKind() != CK_IntegralCast &&
10445         ICE->getCastKind() != CK_NoOp)
10446       break;
10447     E = ICE->getSubExpr();
10448   }
10449 
10450   return E->getType()->isEnumeralType();
10451 }
10452 
10453 static int classifyConstantValue(Expr *Constant) {
10454   // The values of this enumeration are used in the diagnostics
10455   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
10456   enum ConstantValueKind {
10457     Miscellaneous = 0,
10458     LiteralTrue,
10459     LiteralFalse
10460   };
10461   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
10462     return BL->getValue() ? ConstantValueKind::LiteralTrue
10463                           : ConstantValueKind::LiteralFalse;
10464   return ConstantValueKind::Miscellaneous;
10465 }
10466 
10467 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
10468                                         Expr *Constant, Expr *Other,
10469                                         const llvm::APSInt &Value,
10470                                         bool RhsConstant) {
10471   if (S.inTemplateInstantiation())
10472     return false;
10473 
10474   Expr *OriginalOther = Other;
10475 
10476   Constant = Constant->IgnoreParenImpCasts();
10477   Other = Other->IgnoreParenImpCasts();
10478 
10479   // Suppress warnings on tautological comparisons between values of the same
10480   // enumeration type. There are only two ways we could warn on this:
10481   //  - If the constant is outside the range of representable values of
10482   //    the enumeration. In such a case, we should warn about the cast
10483   //    to enumeration type, not about the comparison.
10484   //  - If the constant is the maximum / minimum in-range value. For an
10485   //    enumeratin type, such comparisons can be meaningful and useful.
10486   if (Constant->getType()->isEnumeralType() &&
10487       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
10488     return false;
10489 
10490   // TODO: Investigate using GetExprRange() to get tighter bounds
10491   // on the bit ranges.
10492   QualType OtherT = Other->getType();
10493   if (const auto *AT = OtherT->getAs<AtomicType>())
10494     OtherT = AT->getValueType();
10495   IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
10496 
10497   // Special case for ObjC BOOL on targets where its a typedef for a signed char
10498   // (Namely, macOS).
10499   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
10500                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
10501                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
10502 
10503   // Whether we're treating Other as being a bool because of the form of
10504   // expression despite it having another type (typically 'int' in C).
10505   bool OtherIsBooleanDespiteType =
10506       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
10507   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
10508     OtherRange = IntRange::forBoolType();
10509 
10510   // Determine the promoted range of the other type and see if a comparison of
10511   // the constant against that range is tautological.
10512   PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
10513                                    Value.isUnsigned());
10514   auto Cmp = OtherPromotedRange.compare(Value);
10515   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
10516   if (!Result)
10517     return false;
10518 
10519   // Suppress the diagnostic for an in-range comparison if the constant comes
10520   // from a macro or enumerator. We don't want to diagnose
10521   //
10522   //   some_long_value <= INT_MAX
10523   //
10524   // when sizeof(int) == sizeof(long).
10525   bool InRange = Cmp & PromotedRange::InRangeFlag;
10526   if (InRange && IsEnumConstOrFromMacro(S, Constant))
10527     return false;
10528 
10529   // If this is a comparison to an enum constant, include that
10530   // constant in the diagnostic.
10531   const EnumConstantDecl *ED = nullptr;
10532   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
10533     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
10534 
10535   // Should be enough for uint128 (39 decimal digits)
10536   SmallString<64> PrettySourceValue;
10537   llvm::raw_svector_ostream OS(PrettySourceValue);
10538   if (ED) {
10539     OS << '\'' << *ED << "' (" << Value << ")";
10540   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
10541                Constant->IgnoreParenImpCasts())) {
10542     OS << (BL->getValue() ? "YES" : "NO");
10543   } else {
10544     OS << Value;
10545   }
10546 
10547   if (IsObjCSignedCharBool) {
10548     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
10549                           S.PDiag(diag::warn_tautological_compare_objc_bool)
10550                               << OS.str() << *Result);
10551     return true;
10552   }
10553 
10554   // FIXME: We use a somewhat different formatting for the in-range cases and
10555   // cases involving boolean values for historical reasons. We should pick a
10556   // consistent way of presenting these diagnostics.
10557   if (!InRange || Other->isKnownToHaveBooleanValue()) {
10558 
10559     S.DiagRuntimeBehavior(
10560         E->getOperatorLoc(), E,
10561         S.PDiag(!InRange ? diag::warn_out_of_range_compare
10562                          : diag::warn_tautological_bool_compare)
10563             << OS.str() << classifyConstantValue(Constant) << OtherT
10564             << OtherIsBooleanDespiteType << *Result
10565             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
10566   } else {
10567     unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
10568                         ? (HasEnumType(OriginalOther)
10569                                ? diag::warn_unsigned_enum_always_true_comparison
10570                                : diag::warn_unsigned_always_true_comparison)
10571                         : diag::warn_tautological_constant_compare;
10572 
10573     S.Diag(E->getOperatorLoc(), Diag)
10574         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
10575         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
10576   }
10577 
10578   return true;
10579 }
10580 
10581 /// Analyze the operands of the given comparison.  Implements the
10582 /// fallback case from AnalyzeComparison.
10583 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
10584   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10585   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10586 }
10587 
10588 /// Implements -Wsign-compare.
10589 ///
10590 /// \param E the binary operator to check for warnings
10591 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
10592   // The type the comparison is being performed in.
10593   QualType T = E->getLHS()->getType();
10594 
10595   // Only analyze comparison operators where both sides have been converted to
10596   // the same type.
10597   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
10598     return AnalyzeImpConvsInComparison(S, E);
10599 
10600   // Don't analyze value-dependent comparisons directly.
10601   if (E->isValueDependent())
10602     return AnalyzeImpConvsInComparison(S, E);
10603 
10604   Expr *LHS = E->getLHS();
10605   Expr *RHS = E->getRHS();
10606 
10607   if (T->isIntegralType(S.Context)) {
10608     llvm::APSInt RHSValue;
10609     llvm::APSInt LHSValue;
10610 
10611     bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
10612     bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
10613 
10614     // We don't care about expressions whose result is a constant.
10615     if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
10616       return AnalyzeImpConvsInComparison(S, E);
10617 
10618     // We only care about expressions where just one side is literal
10619     if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
10620       // Is the constant on the RHS or LHS?
10621       const bool RhsConstant = IsRHSIntegralLiteral;
10622       Expr *Const = RhsConstant ? RHS : LHS;
10623       Expr *Other = RhsConstant ? LHS : RHS;
10624       const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
10625 
10626       // Check whether an integer constant comparison results in a value
10627       // of 'true' or 'false'.
10628       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
10629         return AnalyzeImpConvsInComparison(S, E);
10630     }
10631   }
10632 
10633   if (!T->hasUnsignedIntegerRepresentation()) {
10634     // We don't do anything special if this isn't an unsigned integral
10635     // comparison:  we're only interested in integral comparisons, and
10636     // signed comparisons only happen in cases we don't care to warn about.
10637     return AnalyzeImpConvsInComparison(S, E);
10638   }
10639 
10640   LHS = LHS->IgnoreParenImpCasts();
10641   RHS = RHS->IgnoreParenImpCasts();
10642 
10643   if (!S.getLangOpts().CPlusPlus) {
10644     // Avoid warning about comparison of integers with different signs when
10645     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
10646     // the type of `E`.
10647     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
10648       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10649     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
10650       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10651   }
10652 
10653   // Check to see if one of the (unmodified) operands is of different
10654   // signedness.
10655   Expr *signedOperand, *unsignedOperand;
10656   if (LHS->getType()->hasSignedIntegerRepresentation()) {
10657     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
10658            "unsigned comparison between two signed integer expressions?");
10659     signedOperand = LHS;
10660     unsignedOperand = RHS;
10661   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
10662     signedOperand = RHS;
10663     unsignedOperand = LHS;
10664   } else {
10665     return AnalyzeImpConvsInComparison(S, E);
10666   }
10667 
10668   // Otherwise, calculate the effective range of the signed operand.
10669   IntRange signedRange =
10670       GetExprRange(S.Context, signedOperand, S.isConstantEvaluated());
10671 
10672   // Go ahead and analyze implicit conversions in the operands.  Note
10673   // that we skip the implicit conversions on both sides.
10674   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
10675   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
10676 
10677   // If the signed range is non-negative, -Wsign-compare won't fire.
10678   if (signedRange.NonNegative)
10679     return;
10680 
10681   // For (in)equality comparisons, if the unsigned operand is a
10682   // constant which cannot collide with a overflowed signed operand,
10683   // then reinterpreting the signed operand as unsigned will not
10684   // change the result of the comparison.
10685   if (E->isEqualityOp()) {
10686     unsigned comparisonWidth = S.Context.getIntWidth(T);
10687     IntRange unsignedRange =
10688         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated());
10689 
10690     // We should never be unable to prove that the unsigned operand is
10691     // non-negative.
10692     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
10693 
10694     if (unsignedRange.Width < comparisonWidth)
10695       return;
10696   }
10697 
10698   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
10699                         S.PDiag(diag::warn_mixed_sign_comparison)
10700                             << LHS->getType() << RHS->getType()
10701                             << LHS->getSourceRange() << RHS->getSourceRange());
10702 }
10703 
10704 /// Analyzes an attempt to assign the given value to a bitfield.
10705 ///
10706 /// Returns true if there was something fishy about the attempt.
10707 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
10708                                       SourceLocation InitLoc) {
10709   assert(Bitfield->isBitField());
10710   if (Bitfield->isInvalidDecl())
10711     return false;
10712 
10713   // White-list bool bitfields.
10714   QualType BitfieldType = Bitfield->getType();
10715   if (BitfieldType->isBooleanType())
10716      return false;
10717 
10718   if (BitfieldType->isEnumeralType()) {
10719     EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
10720     // If the underlying enum type was not explicitly specified as an unsigned
10721     // type and the enum contain only positive values, MSVC++ will cause an
10722     // inconsistency by storing this as a signed type.
10723     if (S.getLangOpts().CPlusPlus11 &&
10724         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
10725         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
10726         BitfieldEnumDecl->getNumNegativeBits() == 0) {
10727       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
10728         << BitfieldEnumDecl->getNameAsString();
10729     }
10730   }
10731 
10732   if (Bitfield->getType()->isBooleanType())
10733     return false;
10734 
10735   // Ignore value- or type-dependent expressions.
10736   if (Bitfield->getBitWidth()->isValueDependent() ||
10737       Bitfield->getBitWidth()->isTypeDependent() ||
10738       Init->isValueDependent() ||
10739       Init->isTypeDependent())
10740     return false;
10741 
10742   Expr *OriginalInit = Init->IgnoreParenImpCasts();
10743   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
10744 
10745   Expr::EvalResult Result;
10746   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
10747                                    Expr::SE_AllowSideEffects)) {
10748     // The RHS is not constant.  If the RHS has an enum type, make sure the
10749     // bitfield is wide enough to hold all the values of the enum without
10750     // truncation.
10751     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
10752       EnumDecl *ED = EnumTy->getDecl();
10753       bool SignedBitfield = BitfieldType->isSignedIntegerType();
10754 
10755       // Enum types are implicitly signed on Windows, so check if there are any
10756       // negative enumerators to see if the enum was intended to be signed or
10757       // not.
10758       bool SignedEnum = ED->getNumNegativeBits() > 0;
10759 
10760       // Check for surprising sign changes when assigning enum values to a
10761       // bitfield of different signedness.  If the bitfield is signed and we
10762       // have exactly the right number of bits to store this unsigned enum,
10763       // suggest changing the enum to an unsigned type. This typically happens
10764       // on Windows where unfixed enums always use an underlying type of 'int'.
10765       unsigned DiagID = 0;
10766       if (SignedEnum && !SignedBitfield) {
10767         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
10768       } else if (SignedBitfield && !SignedEnum &&
10769                  ED->getNumPositiveBits() == FieldWidth) {
10770         DiagID = diag::warn_signed_bitfield_enum_conversion;
10771       }
10772 
10773       if (DiagID) {
10774         S.Diag(InitLoc, DiagID) << Bitfield << ED;
10775         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
10776         SourceRange TypeRange =
10777             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
10778         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
10779             << SignedEnum << TypeRange;
10780       }
10781 
10782       // Compute the required bitwidth. If the enum has negative values, we need
10783       // one more bit than the normal number of positive bits to represent the
10784       // sign bit.
10785       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
10786                                                   ED->getNumNegativeBits())
10787                                        : ED->getNumPositiveBits();
10788 
10789       // Check the bitwidth.
10790       if (BitsNeeded > FieldWidth) {
10791         Expr *WidthExpr = Bitfield->getBitWidth();
10792         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
10793             << Bitfield << ED;
10794         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
10795             << BitsNeeded << ED << WidthExpr->getSourceRange();
10796       }
10797     }
10798 
10799     return false;
10800   }
10801 
10802   llvm::APSInt Value = Result.Val.getInt();
10803 
10804   unsigned OriginalWidth = Value.getBitWidth();
10805 
10806   if (!Value.isSigned() || Value.isNegative())
10807     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
10808       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
10809         OriginalWidth = Value.getMinSignedBits();
10810 
10811   if (OriginalWidth <= FieldWidth)
10812     return false;
10813 
10814   // Compute the value which the bitfield will contain.
10815   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
10816   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
10817 
10818   // Check whether the stored value is equal to the original value.
10819   TruncatedValue = TruncatedValue.extend(OriginalWidth);
10820   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
10821     return false;
10822 
10823   // Special-case bitfields of width 1: booleans are naturally 0/1, and
10824   // therefore don't strictly fit into a signed bitfield of width 1.
10825   if (FieldWidth == 1 && Value == 1)
10826     return false;
10827 
10828   std::string PrettyValue = Value.toString(10);
10829   std::string PrettyTrunc = TruncatedValue.toString(10);
10830 
10831   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
10832     << PrettyValue << PrettyTrunc << OriginalInit->getType()
10833     << Init->getSourceRange();
10834 
10835   return true;
10836 }
10837 
10838 /// Analyze the given simple or compound assignment for warning-worthy
10839 /// operations.
10840 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
10841   // Just recurse on the LHS.
10842   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10843 
10844   // We want to recurse on the RHS as normal unless we're assigning to
10845   // a bitfield.
10846   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
10847     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
10848                                   E->getOperatorLoc())) {
10849       // Recurse, ignoring any implicit conversions on the RHS.
10850       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
10851                                         E->getOperatorLoc());
10852     }
10853   }
10854 
10855   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10856 
10857   // Diagnose implicitly sequentially-consistent atomic assignment.
10858   if (E->getLHS()->getType()->isAtomicType())
10859     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
10860 }
10861 
10862 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
10863 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
10864                             SourceLocation CContext, unsigned diag,
10865                             bool pruneControlFlow = false) {
10866   if (pruneControlFlow) {
10867     S.DiagRuntimeBehavior(E->getExprLoc(), E,
10868                           S.PDiag(diag)
10869                               << SourceType << T << E->getSourceRange()
10870                               << SourceRange(CContext));
10871     return;
10872   }
10873   S.Diag(E->getExprLoc(), diag)
10874     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
10875 }
10876 
10877 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
10878 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
10879                             SourceLocation CContext,
10880                             unsigned diag, bool pruneControlFlow = false) {
10881   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
10882 }
10883 
10884 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
10885   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
10886       S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
10887 }
10888 
10889 static void adornObjCBoolConversionDiagWithTernaryFixit(
10890     Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
10891   Expr *Ignored = SourceExpr->IgnoreImplicit();
10892   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
10893     Ignored = OVE->getSourceExpr();
10894   bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
10895                      isa<BinaryOperator>(Ignored) ||
10896                      isa<CXXOperatorCallExpr>(Ignored);
10897   SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
10898   if (NeedsParens)
10899     Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
10900             << FixItHint::CreateInsertion(EndLoc, ")");
10901   Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
10902 }
10903 
10904 /// Diagnose an implicit cast from a floating point value to an integer value.
10905 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
10906                                     SourceLocation CContext) {
10907   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
10908   const bool PruneWarnings = S.inTemplateInstantiation();
10909 
10910   Expr *InnerE = E->IgnoreParenImpCasts();
10911   // We also want to warn on, e.g., "int i = -1.234"
10912   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
10913     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
10914       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
10915 
10916   const bool IsLiteral =
10917       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
10918 
10919   llvm::APFloat Value(0.0);
10920   bool IsConstant =
10921     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
10922   if (!IsConstant) {
10923     if (isObjCSignedCharBool(S, T)) {
10924       return adornObjCBoolConversionDiagWithTernaryFixit(
10925           S, E,
10926           S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
10927               << E->getType());
10928     }
10929 
10930     return DiagnoseImpCast(S, E, T, CContext,
10931                            diag::warn_impcast_float_integer, PruneWarnings);
10932   }
10933 
10934   bool isExact = false;
10935 
10936   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
10937                             T->hasUnsignedIntegerRepresentation());
10938   llvm::APFloat::opStatus Result = Value.convertToInteger(
10939       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
10940 
10941   // FIXME: Force the precision of the source value down so we don't print
10942   // digits which are usually useless (we don't really care here if we
10943   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
10944   // would automatically print the shortest representation, but it's a bit
10945   // tricky to implement.
10946   SmallString<16> PrettySourceValue;
10947   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
10948   precision = (precision * 59 + 195) / 196;
10949   Value.toString(PrettySourceValue, precision);
10950 
10951   if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
10952     return adornObjCBoolConversionDiagWithTernaryFixit(
10953         S, E,
10954         S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
10955             << PrettySourceValue);
10956   }
10957 
10958   if (Result == llvm::APFloat::opOK && isExact) {
10959     if (IsLiteral) return;
10960     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
10961                            PruneWarnings);
10962   }
10963 
10964   // Conversion of a floating-point value to a non-bool integer where the
10965   // integral part cannot be represented by the integer type is undefined.
10966   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
10967     return DiagnoseImpCast(
10968         S, E, T, CContext,
10969         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
10970                   : diag::warn_impcast_float_to_integer_out_of_range,
10971         PruneWarnings);
10972 
10973   unsigned DiagID = 0;
10974   if (IsLiteral) {
10975     // Warn on floating point literal to integer.
10976     DiagID = diag::warn_impcast_literal_float_to_integer;
10977   } else if (IntegerValue == 0) {
10978     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
10979       return DiagnoseImpCast(S, E, T, CContext,
10980                              diag::warn_impcast_float_integer, PruneWarnings);
10981     }
10982     // Warn on non-zero to zero conversion.
10983     DiagID = diag::warn_impcast_float_to_integer_zero;
10984   } else {
10985     if (IntegerValue.isUnsigned()) {
10986       if (!IntegerValue.isMaxValue()) {
10987         return DiagnoseImpCast(S, E, T, CContext,
10988                                diag::warn_impcast_float_integer, PruneWarnings);
10989       }
10990     } else {  // IntegerValue.isSigned()
10991       if (!IntegerValue.isMaxSignedValue() &&
10992           !IntegerValue.isMinSignedValue()) {
10993         return DiagnoseImpCast(S, E, T, CContext,
10994                                diag::warn_impcast_float_integer, PruneWarnings);
10995       }
10996     }
10997     // Warn on evaluatable floating point expression to integer conversion.
10998     DiagID = diag::warn_impcast_float_to_integer;
10999   }
11000 
11001   SmallString<16> PrettyTargetValue;
11002   if (IsBool)
11003     PrettyTargetValue = Value.isZero() ? "false" : "true";
11004   else
11005     IntegerValue.toString(PrettyTargetValue);
11006 
11007   if (PruneWarnings) {
11008     S.DiagRuntimeBehavior(E->getExprLoc(), E,
11009                           S.PDiag(DiagID)
11010                               << E->getType() << T.getUnqualifiedType()
11011                               << PrettySourceValue << PrettyTargetValue
11012                               << E->getSourceRange() << SourceRange(CContext));
11013   } else {
11014     S.Diag(E->getExprLoc(), DiagID)
11015         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
11016         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
11017   }
11018 }
11019 
11020 /// Analyze the given compound assignment for the possible losing of
11021 /// floating-point precision.
11022 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
11023   assert(isa<CompoundAssignOperator>(E) &&
11024          "Must be compound assignment operation");
11025   // Recurse on the LHS and RHS in here
11026   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11027   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11028 
11029   if (E->getLHS()->getType()->isAtomicType())
11030     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
11031 
11032   // Now check the outermost expression
11033   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
11034   const auto *RBT = cast<CompoundAssignOperator>(E)
11035                         ->getComputationResultType()
11036                         ->getAs<BuiltinType>();
11037 
11038   // The below checks assume source is floating point.
11039   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
11040 
11041   // If source is floating point but target is an integer.
11042   if (ResultBT->isInteger())
11043     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
11044                            E->getExprLoc(), diag::warn_impcast_float_integer);
11045 
11046   if (!ResultBT->isFloatingPoint())
11047     return;
11048 
11049   // If both source and target are floating points, warn about losing precision.
11050   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
11051       QualType(ResultBT, 0), QualType(RBT, 0));
11052   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
11053     // warn about dropping FP rank.
11054     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
11055                     diag::warn_impcast_float_result_precision);
11056 }
11057 
11058 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
11059                                       IntRange Range) {
11060   if (!Range.Width) return "0";
11061 
11062   llvm::APSInt ValueInRange = Value;
11063   ValueInRange.setIsSigned(!Range.NonNegative);
11064   ValueInRange = ValueInRange.trunc(Range.Width);
11065   return ValueInRange.toString(10);
11066 }
11067 
11068 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
11069   if (!isa<ImplicitCastExpr>(Ex))
11070     return false;
11071 
11072   Expr *InnerE = Ex->IgnoreParenImpCasts();
11073   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
11074   const Type *Source =
11075     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
11076   if (Target->isDependentType())
11077     return false;
11078 
11079   const BuiltinType *FloatCandidateBT =
11080     dyn_cast<BuiltinType>(ToBool ? Source : Target);
11081   const Type *BoolCandidateType = ToBool ? Target : Source;
11082 
11083   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
11084           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
11085 }
11086 
11087 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
11088                                              SourceLocation CC) {
11089   unsigned NumArgs = TheCall->getNumArgs();
11090   for (unsigned i = 0; i < NumArgs; ++i) {
11091     Expr *CurrA = TheCall->getArg(i);
11092     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
11093       continue;
11094 
11095     bool IsSwapped = ((i > 0) &&
11096         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
11097     IsSwapped |= ((i < (NumArgs - 1)) &&
11098         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
11099     if (IsSwapped) {
11100       // Warn on this floating-point to bool conversion.
11101       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
11102                       CurrA->getType(), CC,
11103                       diag::warn_impcast_floating_point_to_bool);
11104     }
11105   }
11106 }
11107 
11108 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
11109                                    SourceLocation CC) {
11110   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
11111                         E->getExprLoc()))
11112     return;
11113 
11114   // Don't warn on functions which have return type nullptr_t.
11115   if (isa<CallExpr>(E))
11116     return;
11117 
11118   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
11119   const Expr::NullPointerConstantKind NullKind =
11120       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
11121   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
11122     return;
11123 
11124   // Return if target type is a safe conversion.
11125   if (T->isAnyPointerType() || T->isBlockPointerType() ||
11126       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
11127     return;
11128 
11129   SourceLocation Loc = E->getSourceRange().getBegin();
11130 
11131   // Venture through the macro stacks to get to the source of macro arguments.
11132   // The new location is a better location than the complete location that was
11133   // passed in.
11134   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
11135   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
11136 
11137   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
11138   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
11139     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
11140         Loc, S.SourceMgr, S.getLangOpts());
11141     if (MacroName == "NULL")
11142       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
11143   }
11144 
11145   // Only warn if the null and context location are in the same macro expansion.
11146   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
11147     return;
11148 
11149   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
11150       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
11151       << FixItHint::CreateReplacement(Loc,
11152                                       S.getFixItZeroLiteralForType(T, Loc));
11153 }
11154 
11155 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
11156                                   ObjCArrayLiteral *ArrayLiteral);
11157 
11158 static void
11159 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
11160                            ObjCDictionaryLiteral *DictionaryLiteral);
11161 
11162 /// Check a single element within a collection literal against the
11163 /// target element type.
11164 static void checkObjCCollectionLiteralElement(Sema &S,
11165                                               QualType TargetElementType,
11166                                               Expr *Element,
11167                                               unsigned ElementKind) {
11168   // Skip a bitcast to 'id' or qualified 'id'.
11169   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
11170     if (ICE->getCastKind() == CK_BitCast &&
11171         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
11172       Element = ICE->getSubExpr();
11173   }
11174 
11175   QualType ElementType = Element->getType();
11176   ExprResult ElementResult(Element);
11177   if (ElementType->getAs<ObjCObjectPointerType>() &&
11178       S.CheckSingleAssignmentConstraints(TargetElementType,
11179                                          ElementResult,
11180                                          false, false)
11181         != Sema::Compatible) {
11182     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
11183         << ElementType << ElementKind << TargetElementType
11184         << Element->getSourceRange();
11185   }
11186 
11187   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
11188     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
11189   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
11190     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
11191 }
11192 
11193 /// Check an Objective-C array literal being converted to the given
11194 /// target type.
11195 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
11196                                   ObjCArrayLiteral *ArrayLiteral) {
11197   if (!S.NSArrayDecl)
11198     return;
11199 
11200   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
11201   if (!TargetObjCPtr)
11202     return;
11203 
11204   if (TargetObjCPtr->isUnspecialized() ||
11205       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
11206         != S.NSArrayDecl->getCanonicalDecl())
11207     return;
11208 
11209   auto TypeArgs = TargetObjCPtr->getTypeArgs();
11210   if (TypeArgs.size() != 1)
11211     return;
11212 
11213   QualType TargetElementType = TypeArgs[0];
11214   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
11215     checkObjCCollectionLiteralElement(S, TargetElementType,
11216                                       ArrayLiteral->getElement(I),
11217                                       0);
11218   }
11219 }
11220 
11221 /// Check an Objective-C dictionary literal being converted to the given
11222 /// target type.
11223 static void
11224 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
11225                            ObjCDictionaryLiteral *DictionaryLiteral) {
11226   if (!S.NSDictionaryDecl)
11227     return;
11228 
11229   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
11230   if (!TargetObjCPtr)
11231     return;
11232 
11233   if (TargetObjCPtr->isUnspecialized() ||
11234       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
11235         != S.NSDictionaryDecl->getCanonicalDecl())
11236     return;
11237 
11238   auto TypeArgs = TargetObjCPtr->getTypeArgs();
11239   if (TypeArgs.size() != 2)
11240     return;
11241 
11242   QualType TargetKeyType = TypeArgs[0];
11243   QualType TargetObjectType = TypeArgs[1];
11244   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
11245     auto Element = DictionaryLiteral->getKeyValueElement(I);
11246     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
11247     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
11248   }
11249 }
11250 
11251 // Helper function to filter out cases for constant width constant conversion.
11252 // Don't warn on char array initialization or for non-decimal values.
11253 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
11254                                           SourceLocation CC) {
11255   // If initializing from a constant, and the constant starts with '0',
11256   // then it is a binary, octal, or hexadecimal.  Allow these constants
11257   // to fill all the bits, even if there is a sign change.
11258   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
11259     const char FirstLiteralCharacter =
11260         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
11261     if (FirstLiteralCharacter == '0')
11262       return false;
11263   }
11264 
11265   // If the CC location points to a '{', and the type is char, then assume
11266   // assume it is an array initialization.
11267   if (CC.isValid() && T->isCharType()) {
11268     const char FirstContextCharacter =
11269         S.getSourceManager().getCharacterData(CC)[0];
11270     if (FirstContextCharacter == '{')
11271       return false;
11272   }
11273 
11274   return true;
11275 }
11276 
11277 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
11278   const auto *IL = dyn_cast<IntegerLiteral>(E);
11279   if (!IL) {
11280     if (auto *UO = dyn_cast<UnaryOperator>(E)) {
11281       if (UO->getOpcode() == UO_Minus)
11282         return dyn_cast<IntegerLiteral>(UO->getSubExpr());
11283     }
11284   }
11285 
11286   return IL;
11287 }
11288 
11289 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
11290   E = E->IgnoreParenImpCasts();
11291   SourceLocation ExprLoc = E->getExprLoc();
11292 
11293   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11294     BinaryOperator::Opcode Opc = BO->getOpcode();
11295     Expr::EvalResult Result;
11296     // Do not diagnose unsigned shifts.
11297     if (Opc == BO_Shl) {
11298       const auto *LHS = getIntegerLiteral(BO->getLHS());
11299       const auto *RHS = getIntegerLiteral(BO->getRHS());
11300       if (LHS && LHS->getValue() == 0)
11301         S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
11302       else if (!E->isValueDependent() && LHS && RHS &&
11303                RHS->getValue().isNonNegative() &&
11304                E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
11305         S.Diag(ExprLoc, diag::warn_left_shift_always)
11306             << (Result.Val.getInt() != 0);
11307       else if (E->getType()->isSignedIntegerType())
11308         S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
11309     }
11310   }
11311 
11312   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11313     const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
11314     const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
11315     if (!LHS || !RHS)
11316       return;
11317     if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
11318         (RHS->getValue() == 0 || RHS->getValue() == 1))
11319       // Do not diagnose common idioms.
11320       return;
11321     if (LHS->getValue() != 0 && RHS->getValue() != 0)
11322       S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
11323   }
11324 }
11325 
11326 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
11327                                     SourceLocation CC,
11328                                     bool *ICContext = nullptr,
11329                                     bool IsListInit = false) {
11330   if (E->isTypeDependent() || E->isValueDependent()) return;
11331 
11332   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
11333   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
11334   if (Source == Target) return;
11335   if (Target->isDependentType()) return;
11336 
11337   // If the conversion context location is invalid don't complain. We also
11338   // don't want to emit a warning if the issue occurs from the expansion of
11339   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
11340   // delay this check as long as possible. Once we detect we are in that
11341   // scenario, we just return.
11342   if (CC.isInvalid())
11343     return;
11344 
11345   if (Source->isAtomicType())
11346     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
11347 
11348   // Diagnose implicit casts to bool.
11349   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
11350     if (isa<StringLiteral>(E))
11351       // Warn on string literal to bool.  Checks for string literals in logical
11352       // and expressions, for instance, assert(0 && "error here"), are
11353       // prevented by a check in AnalyzeImplicitConversions().
11354       return DiagnoseImpCast(S, E, T, CC,
11355                              diag::warn_impcast_string_literal_to_bool);
11356     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
11357         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
11358       // This covers the literal expressions that evaluate to Objective-C
11359       // objects.
11360       return DiagnoseImpCast(S, E, T, CC,
11361                              diag::warn_impcast_objective_c_literal_to_bool);
11362     }
11363     if (Source->isPointerType() || Source->canDecayToPointerType()) {
11364       // Warn on pointer to bool conversion that is always true.
11365       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
11366                                      SourceRange(CC));
11367     }
11368   }
11369 
11370   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
11371   // is a typedef for signed char (macOS), then that constant value has to be 1
11372   // or 0.
11373   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
11374     Expr::EvalResult Result;
11375     if (E->EvaluateAsInt(Result, S.getASTContext(),
11376                          Expr::SE_AllowSideEffects)) {
11377       if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
11378         adornObjCBoolConversionDiagWithTernaryFixit(
11379             S, E,
11380             S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
11381                 << Result.Val.getInt().toString(10));
11382       }
11383       return;
11384     }
11385   }
11386 
11387   // Check implicit casts from Objective-C collection literals to specialized
11388   // collection types, e.g., NSArray<NSString *> *.
11389   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
11390     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
11391   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
11392     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
11393 
11394   // Strip vector types.
11395   if (isa<VectorType>(Source)) {
11396     if (!isa<VectorType>(Target)) {
11397       if (S.SourceMgr.isInSystemMacro(CC))
11398         return;
11399       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
11400     }
11401 
11402     // If the vector cast is cast between two vectors of the same size, it is
11403     // a bitcast, not a conversion.
11404     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
11405       return;
11406 
11407     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
11408     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
11409   }
11410   if (auto VecTy = dyn_cast<VectorType>(Target))
11411     Target = VecTy->getElementType().getTypePtr();
11412 
11413   // Strip complex types.
11414   if (isa<ComplexType>(Source)) {
11415     if (!isa<ComplexType>(Target)) {
11416       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
11417         return;
11418 
11419       return DiagnoseImpCast(S, E, T, CC,
11420                              S.getLangOpts().CPlusPlus
11421                                  ? diag::err_impcast_complex_scalar
11422                                  : diag::warn_impcast_complex_scalar);
11423     }
11424 
11425     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
11426     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
11427   }
11428 
11429   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
11430   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
11431 
11432   // If the source is floating point...
11433   if (SourceBT && SourceBT->isFloatingPoint()) {
11434     // ...and the target is floating point...
11435     if (TargetBT && TargetBT->isFloatingPoint()) {
11436       // ...then warn if we're dropping FP rank.
11437 
11438       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
11439           QualType(SourceBT, 0), QualType(TargetBT, 0));
11440       if (Order > 0) {
11441         // Don't warn about float constants that are precisely
11442         // representable in the target type.
11443         Expr::EvalResult result;
11444         if (E->EvaluateAsRValue(result, S.Context)) {
11445           // Value might be a float, a float vector, or a float complex.
11446           if (IsSameFloatAfterCast(result.Val,
11447                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
11448                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
11449             return;
11450         }
11451 
11452         if (S.SourceMgr.isInSystemMacro(CC))
11453           return;
11454 
11455         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
11456       }
11457       // ... or possibly if we're increasing rank, too
11458       else if (Order < 0) {
11459         if (S.SourceMgr.isInSystemMacro(CC))
11460           return;
11461 
11462         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
11463       }
11464       return;
11465     }
11466 
11467     // If the target is integral, always warn.
11468     if (TargetBT && TargetBT->isInteger()) {
11469       if (S.SourceMgr.isInSystemMacro(CC))
11470         return;
11471 
11472       DiagnoseFloatingImpCast(S, E, T, CC);
11473     }
11474 
11475     // Detect the case where a call result is converted from floating-point to
11476     // to bool, and the final argument to the call is converted from bool, to
11477     // discover this typo:
11478     //
11479     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
11480     //
11481     // FIXME: This is an incredibly special case; is there some more general
11482     // way to detect this class of misplaced-parentheses bug?
11483     if (Target->isBooleanType() && isa<CallExpr>(E)) {
11484       // Check last argument of function call to see if it is an
11485       // implicit cast from a type matching the type the result
11486       // is being cast to.
11487       CallExpr *CEx = cast<CallExpr>(E);
11488       if (unsigned NumArgs = CEx->getNumArgs()) {
11489         Expr *LastA = CEx->getArg(NumArgs - 1);
11490         Expr *InnerE = LastA->IgnoreParenImpCasts();
11491         if (isa<ImplicitCastExpr>(LastA) &&
11492             InnerE->getType()->isBooleanType()) {
11493           // Warn on this floating-point to bool conversion
11494           DiagnoseImpCast(S, E, T, CC,
11495                           diag::warn_impcast_floating_point_to_bool);
11496         }
11497       }
11498     }
11499     return;
11500   }
11501 
11502   // Valid casts involving fixed point types should be accounted for here.
11503   if (Source->isFixedPointType()) {
11504     if (Target->isUnsaturatedFixedPointType()) {
11505       Expr::EvalResult Result;
11506       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
11507                                   S.isConstantEvaluated())) {
11508         APFixedPoint Value = Result.Val.getFixedPoint();
11509         APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
11510         APFixedPoint MinVal = S.Context.getFixedPointMin(T);
11511         if (Value > MaxVal || Value < MinVal) {
11512           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11513                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11514                                     << Value.toString() << T
11515                                     << E->getSourceRange()
11516                                     << clang::SourceRange(CC));
11517           return;
11518         }
11519       }
11520     } else if (Target->isIntegerType()) {
11521       Expr::EvalResult Result;
11522       if (!S.isConstantEvaluated() &&
11523           E->EvaluateAsFixedPoint(Result, S.Context,
11524                                   Expr::SE_AllowSideEffects)) {
11525         APFixedPoint FXResult = Result.Val.getFixedPoint();
11526 
11527         bool Overflowed;
11528         llvm::APSInt IntResult = FXResult.convertToInt(
11529             S.Context.getIntWidth(T),
11530             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
11531 
11532         if (Overflowed) {
11533           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11534                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11535                                     << FXResult.toString() << T
11536                                     << E->getSourceRange()
11537                                     << clang::SourceRange(CC));
11538           return;
11539         }
11540       }
11541     }
11542   } else if (Target->isUnsaturatedFixedPointType()) {
11543     if (Source->isIntegerType()) {
11544       Expr::EvalResult Result;
11545       if (!S.isConstantEvaluated() &&
11546           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
11547         llvm::APSInt Value = Result.Val.getInt();
11548 
11549         bool Overflowed;
11550         APFixedPoint IntResult = APFixedPoint::getFromIntValue(
11551             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
11552 
11553         if (Overflowed) {
11554           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11555                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11556                                     << Value.toString(/*Radix=*/10) << T
11557                                     << E->getSourceRange()
11558                                     << clang::SourceRange(CC));
11559           return;
11560         }
11561       }
11562     }
11563   }
11564 
11565   // If we are casting an integer type to a floating point type without
11566   // initialization-list syntax, we might lose accuracy if the floating
11567   // point type has a narrower significand than the integer type.
11568   if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
11569       TargetBT->isFloatingType() && !IsListInit) {
11570     // Determine the number of precision bits in the source integer type.
11571     IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated());
11572     unsigned int SourcePrecision = SourceRange.Width;
11573 
11574     // Determine the number of precision bits in the
11575     // target floating point type.
11576     unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
11577         S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
11578 
11579     if (SourcePrecision > 0 && TargetPrecision > 0 &&
11580         SourcePrecision > TargetPrecision) {
11581 
11582       llvm::APSInt SourceInt;
11583       if (E->isIntegerConstantExpr(SourceInt, S.Context)) {
11584         // If the source integer is a constant, convert it to the target
11585         // floating point type. Issue a warning if the value changes
11586         // during the whole conversion.
11587         llvm::APFloat TargetFloatValue(
11588             S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
11589         llvm::APFloat::opStatus ConversionStatus =
11590             TargetFloatValue.convertFromAPInt(
11591                 SourceInt, SourceBT->isSignedInteger(),
11592                 llvm::APFloat::rmNearestTiesToEven);
11593 
11594         if (ConversionStatus != llvm::APFloat::opOK) {
11595           std::string PrettySourceValue = SourceInt.toString(10);
11596           SmallString<32> PrettyTargetValue;
11597           TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
11598 
11599           S.DiagRuntimeBehavior(
11600               E->getExprLoc(), E,
11601               S.PDiag(diag::warn_impcast_integer_float_precision_constant)
11602                   << PrettySourceValue << PrettyTargetValue << E->getType() << T
11603                   << E->getSourceRange() << clang::SourceRange(CC));
11604         }
11605       } else {
11606         // Otherwise, the implicit conversion may lose precision.
11607         DiagnoseImpCast(S, E, T, CC,
11608                         diag::warn_impcast_integer_float_precision);
11609       }
11610     }
11611   }
11612 
11613   DiagnoseNullConversion(S, E, T, CC);
11614 
11615   S.DiscardMisalignedMemberAddress(Target, E);
11616 
11617   if (Target->isBooleanType())
11618     DiagnoseIntInBoolContext(S, E);
11619 
11620   if (!Source->isIntegerType() || !Target->isIntegerType())
11621     return;
11622 
11623   // TODO: remove this early return once the false positives for constant->bool
11624   // in templates, macros, etc, are reduced or removed.
11625   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
11626     return;
11627 
11628   if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
11629       !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
11630     return adornObjCBoolConversionDiagWithTernaryFixit(
11631         S, E,
11632         S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
11633             << E->getType());
11634   }
11635 
11636   IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated());
11637   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
11638 
11639   if (SourceRange.Width > TargetRange.Width) {
11640     // If the source is a constant, use a default-on diagnostic.
11641     // TODO: this should happen for bitfield stores, too.
11642     Expr::EvalResult Result;
11643     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
11644                          S.isConstantEvaluated())) {
11645       llvm::APSInt Value(32);
11646       Value = Result.Val.getInt();
11647 
11648       if (S.SourceMgr.isInSystemMacro(CC))
11649         return;
11650 
11651       std::string PrettySourceValue = Value.toString(10);
11652       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
11653 
11654       S.DiagRuntimeBehavior(
11655           E->getExprLoc(), E,
11656           S.PDiag(diag::warn_impcast_integer_precision_constant)
11657               << PrettySourceValue << PrettyTargetValue << E->getType() << T
11658               << E->getSourceRange() << clang::SourceRange(CC));
11659       return;
11660     }
11661 
11662     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
11663     if (S.SourceMgr.isInSystemMacro(CC))
11664       return;
11665 
11666     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
11667       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
11668                              /* pruneControlFlow */ true);
11669     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
11670   }
11671 
11672   if (TargetRange.Width > SourceRange.Width) {
11673     if (auto *UO = dyn_cast<UnaryOperator>(E))
11674       if (UO->getOpcode() == UO_Minus)
11675         if (Source->isUnsignedIntegerType()) {
11676           if (Target->isUnsignedIntegerType())
11677             return DiagnoseImpCast(S, E, T, CC,
11678                                    diag::warn_impcast_high_order_zero_bits);
11679           if (Target->isSignedIntegerType())
11680             return DiagnoseImpCast(S, E, T, CC,
11681                                    diag::warn_impcast_nonnegative_result);
11682         }
11683   }
11684 
11685   if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
11686       SourceRange.NonNegative && Source->isSignedIntegerType()) {
11687     // Warn when doing a signed to signed conversion, warn if the positive
11688     // source value is exactly the width of the target type, which will
11689     // cause a negative value to be stored.
11690 
11691     Expr::EvalResult Result;
11692     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
11693         !S.SourceMgr.isInSystemMacro(CC)) {
11694       llvm::APSInt Value = Result.Val.getInt();
11695       if (isSameWidthConstantConversion(S, E, T, CC)) {
11696         std::string PrettySourceValue = Value.toString(10);
11697         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
11698 
11699         S.DiagRuntimeBehavior(
11700             E->getExprLoc(), E,
11701             S.PDiag(diag::warn_impcast_integer_precision_constant)
11702                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
11703                 << E->getSourceRange() << clang::SourceRange(CC));
11704         return;
11705       }
11706     }
11707 
11708     // Fall through for non-constants to give a sign conversion warning.
11709   }
11710 
11711   if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
11712       (!TargetRange.NonNegative && SourceRange.NonNegative &&
11713        SourceRange.Width == TargetRange.Width)) {
11714     if (S.SourceMgr.isInSystemMacro(CC))
11715       return;
11716 
11717     unsigned DiagID = diag::warn_impcast_integer_sign;
11718 
11719     // Traditionally, gcc has warned about this under -Wsign-compare.
11720     // We also want to warn about it in -Wconversion.
11721     // So if -Wconversion is off, use a completely identical diagnostic
11722     // in the sign-compare group.
11723     // The conditional-checking code will
11724     if (ICContext) {
11725       DiagID = diag::warn_impcast_integer_sign_conditional;
11726       *ICContext = true;
11727     }
11728 
11729     return DiagnoseImpCast(S, E, T, CC, DiagID);
11730   }
11731 
11732   // Diagnose conversions between different enumeration types.
11733   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
11734   // type, to give us better diagnostics.
11735   QualType SourceType = E->getType();
11736   if (!S.getLangOpts().CPlusPlus) {
11737     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11738       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
11739         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
11740         SourceType = S.Context.getTypeDeclType(Enum);
11741         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
11742       }
11743   }
11744 
11745   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
11746     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
11747       if (SourceEnum->getDecl()->hasNameForLinkage() &&
11748           TargetEnum->getDecl()->hasNameForLinkage() &&
11749           SourceEnum != TargetEnum) {
11750         if (S.SourceMgr.isInSystemMacro(CC))
11751           return;
11752 
11753         return DiagnoseImpCast(S, E, SourceType, T, CC,
11754                                diag::warn_impcast_different_enum_types);
11755       }
11756 }
11757 
11758 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
11759                                      SourceLocation CC, QualType T);
11760 
11761 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
11762                                     SourceLocation CC, bool &ICContext) {
11763   E = E->IgnoreParenImpCasts();
11764 
11765   if (isa<ConditionalOperator>(E))
11766     return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
11767 
11768   AnalyzeImplicitConversions(S, E, CC);
11769   if (E->getType() != T)
11770     return CheckImplicitConversion(S, E, T, CC, &ICContext);
11771 }
11772 
11773 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
11774                                      SourceLocation CC, QualType T) {
11775   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
11776 
11777   bool Suspicious = false;
11778   CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
11779   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
11780 
11781   if (T->isBooleanType())
11782     DiagnoseIntInBoolContext(S, E);
11783 
11784   // If -Wconversion would have warned about either of the candidates
11785   // for a signedness conversion to the context type...
11786   if (!Suspicious) return;
11787 
11788   // ...but it's currently ignored...
11789   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
11790     return;
11791 
11792   // ...then check whether it would have warned about either of the
11793   // candidates for a signedness conversion to the condition type.
11794   if (E->getType() == T) return;
11795 
11796   Suspicious = false;
11797   CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
11798                           E->getType(), CC, &Suspicious);
11799   if (!Suspicious)
11800     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
11801                             E->getType(), CC, &Suspicious);
11802 }
11803 
11804 /// Check conversion of given expression to boolean.
11805 /// Input argument E is a logical expression.
11806 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
11807   if (S.getLangOpts().Bool)
11808     return;
11809   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
11810     return;
11811   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
11812 }
11813 
11814 namespace {
11815 struct AnalyzeImplicitConversionsWorkItem {
11816   Expr *E;
11817   SourceLocation CC;
11818   bool IsListInit;
11819 };
11820 }
11821 
11822 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
11823 /// that should be visited are added to WorkList.
11824 static void AnalyzeImplicitConversions(
11825     Sema &S, AnalyzeImplicitConversionsWorkItem Item,
11826     llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
11827   Expr *OrigE = Item.E;
11828   SourceLocation CC = Item.CC;
11829 
11830   QualType T = OrigE->getType();
11831   Expr *E = OrigE->IgnoreParenImpCasts();
11832 
11833   // Propagate whether we are in a C++ list initialization expression.
11834   // If so, we do not issue warnings for implicit int-float conversion
11835   // precision loss, because C++11 narrowing already handles it.
11836   bool IsListInit = Item.IsListInit ||
11837                     (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
11838 
11839   if (E->isTypeDependent() || E->isValueDependent())
11840     return;
11841 
11842   Expr *SourceExpr = E;
11843   // Examine, but don't traverse into the source expression of an
11844   // OpaqueValueExpr, since it may have multiple parents and we don't want to
11845   // emit duplicate diagnostics. Its fine to examine the form or attempt to
11846   // evaluate it in the context of checking the specific conversion to T though.
11847   if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
11848     if (auto *Src = OVE->getSourceExpr())
11849       SourceExpr = Src;
11850 
11851   if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
11852     if (UO->getOpcode() == UO_Not &&
11853         UO->getSubExpr()->isKnownToHaveBooleanValue())
11854       S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
11855           << OrigE->getSourceRange() << T->isBooleanType()
11856           << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
11857 
11858   // For conditional operators, we analyze the arguments as if they
11859   // were being fed directly into the output.
11860   if (auto *CO = dyn_cast<ConditionalOperator>(SourceExpr)) {
11861     CheckConditionalOperator(S, CO, CC, T);
11862     return;
11863   }
11864 
11865   // Check implicit argument conversions for function calls.
11866   if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
11867     CheckImplicitArgumentConversions(S, Call, CC);
11868 
11869   // Go ahead and check any implicit conversions we might have skipped.
11870   // The non-canonical typecheck is just an optimization;
11871   // CheckImplicitConversion will filter out dead implicit conversions.
11872   if (SourceExpr->getType() != T)
11873     CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit);
11874 
11875   // Now continue drilling into this expression.
11876 
11877   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
11878     // The bound subexpressions in a PseudoObjectExpr are not reachable
11879     // as transitive children.
11880     // FIXME: Use a more uniform representation for this.
11881     for (auto *SE : POE->semantics())
11882       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
11883         WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
11884   }
11885 
11886   // Skip past explicit casts.
11887   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
11888     E = CE->getSubExpr()->IgnoreParenImpCasts();
11889     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
11890       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
11891     WorkList.push_back({E, CC, IsListInit});
11892     return;
11893   }
11894 
11895   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11896     // Do a somewhat different check with comparison operators.
11897     if (BO->isComparisonOp())
11898       return AnalyzeComparison(S, BO);
11899 
11900     // And with simple assignments.
11901     if (BO->getOpcode() == BO_Assign)
11902       return AnalyzeAssignment(S, BO);
11903     // And with compound assignments.
11904     if (BO->isAssignmentOp())
11905       return AnalyzeCompoundAssignment(S, BO);
11906   }
11907 
11908   // These break the otherwise-useful invariant below.  Fortunately,
11909   // we don't really need to recurse into them, because any internal
11910   // expressions should have been analyzed already when they were
11911   // built into statements.
11912   if (isa<StmtExpr>(E)) return;
11913 
11914   // Don't descend into unevaluated contexts.
11915   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
11916 
11917   // Now just recurse over the expression's children.
11918   CC = E->getExprLoc();
11919   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
11920   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
11921   for (Stmt *SubStmt : E->children()) {
11922     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
11923     if (!ChildExpr)
11924       continue;
11925 
11926     if (IsLogicalAndOperator &&
11927         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
11928       // Ignore checking string literals that are in logical and operators.
11929       // This is a common pattern for asserts.
11930       continue;
11931     WorkList.push_back({ChildExpr, CC, IsListInit});
11932   }
11933 
11934   if (BO && BO->isLogicalOp()) {
11935     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
11936     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
11937       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
11938 
11939     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
11940     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
11941       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
11942   }
11943 
11944   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
11945     if (U->getOpcode() == UO_LNot) {
11946       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
11947     } else if (U->getOpcode() != UO_AddrOf) {
11948       if (U->getSubExpr()->getType()->isAtomicType())
11949         S.Diag(U->getSubExpr()->getBeginLoc(),
11950                diag::warn_atomic_implicit_seq_cst);
11951     }
11952   }
11953 }
11954 
11955 /// AnalyzeImplicitConversions - Find and report any interesting
11956 /// implicit conversions in the given expression.  There are a couple
11957 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
11958 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
11959                                        bool IsListInit/*= false*/) {
11960   llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
11961   WorkList.push_back({OrigE, CC, IsListInit});
11962   while (!WorkList.empty())
11963     AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
11964 }
11965 
11966 /// Diagnose integer type and any valid implicit conversion to it.
11967 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
11968   // Taking into account implicit conversions,
11969   // allow any integer.
11970   if (!E->getType()->isIntegerType()) {
11971     S.Diag(E->getBeginLoc(),
11972            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
11973     return true;
11974   }
11975   // Potentially emit standard warnings for implicit conversions if enabled
11976   // using -Wconversion.
11977   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
11978   return false;
11979 }
11980 
11981 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
11982 // Returns true when emitting a warning about taking the address of a reference.
11983 static bool CheckForReference(Sema &SemaRef, const Expr *E,
11984                               const PartialDiagnostic &PD) {
11985   E = E->IgnoreParenImpCasts();
11986 
11987   const FunctionDecl *FD = nullptr;
11988 
11989   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11990     if (!DRE->getDecl()->getType()->isReferenceType())
11991       return false;
11992   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
11993     if (!M->getMemberDecl()->getType()->isReferenceType())
11994       return false;
11995   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
11996     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
11997       return false;
11998     FD = Call->getDirectCallee();
11999   } else {
12000     return false;
12001   }
12002 
12003   SemaRef.Diag(E->getExprLoc(), PD);
12004 
12005   // If possible, point to location of function.
12006   if (FD) {
12007     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
12008   }
12009 
12010   return true;
12011 }
12012 
12013 // Returns true if the SourceLocation is expanded from any macro body.
12014 // Returns false if the SourceLocation is invalid, is from not in a macro
12015 // expansion, or is from expanded from a top-level macro argument.
12016 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
12017   if (Loc.isInvalid())
12018     return false;
12019 
12020   while (Loc.isMacroID()) {
12021     if (SM.isMacroBodyExpansion(Loc))
12022       return true;
12023     Loc = SM.getImmediateMacroCallerLoc(Loc);
12024   }
12025 
12026   return false;
12027 }
12028 
12029 /// Diagnose pointers that are always non-null.
12030 /// \param E the expression containing the pointer
12031 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
12032 /// compared to a null pointer
12033 /// \param IsEqual True when the comparison is equal to a null pointer
12034 /// \param Range Extra SourceRange to highlight in the diagnostic
12035 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
12036                                         Expr::NullPointerConstantKind NullKind,
12037                                         bool IsEqual, SourceRange Range) {
12038   if (!E)
12039     return;
12040 
12041   // Don't warn inside macros.
12042   if (E->getExprLoc().isMacroID()) {
12043     const SourceManager &SM = getSourceManager();
12044     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
12045         IsInAnyMacroBody(SM, Range.getBegin()))
12046       return;
12047   }
12048   E = E->IgnoreImpCasts();
12049 
12050   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
12051 
12052   if (isa<CXXThisExpr>(E)) {
12053     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
12054                                 : diag::warn_this_bool_conversion;
12055     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
12056     return;
12057   }
12058 
12059   bool IsAddressOf = false;
12060 
12061   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
12062     if (UO->getOpcode() != UO_AddrOf)
12063       return;
12064     IsAddressOf = true;
12065     E = UO->getSubExpr();
12066   }
12067 
12068   if (IsAddressOf) {
12069     unsigned DiagID = IsCompare
12070                           ? diag::warn_address_of_reference_null_compare
12071                           : diag::warn_address_of_reference_bool_conversion;
12072     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
12073                                          << IsEqual;
12074     if (CheckForReference(*this, E, PD)) {
12075       return;
12076     }
12077   }
12078 
12079   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
12080     bool IsParam = isa<NonNullAttr>(NonnullAttr);
12081     std::string Str;
12082     llvm::raw_string_ostream S(Str);
12083     E->printPretty(S, nullptr, getPrintingPolicy());
12084     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
12085                                 : diag::warn_cast_nonnull_to_bool;
12086     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
12087       << E->getSourceRange() << Range << IsEqual;
12088     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
12089   };
12090 
12091   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
12092   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
12093     if (auto *Callee = Call->getDirectCallee()) {
12094       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
12095         ComplainAboutNonnullParamOrCall(A);
12096         return;
12097       }
12098     }
12099   }
12100 
12101   // Expect to find a single Decl.  Skip anything more complicated.
12102   ValueDecl *D = nullptr;
12103   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
12104     D = R->getDecl();
12105   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
12106     D = M->getMemberDecl();
12107   }
12108 
12109   // Weak Decls can be null.
12110   if (!D || D->isWeak())
12111     return;
12112 
12113   // Check for parameter decl with nonnull attribute
12114   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
12115     if (getCurFunction() &&
12116         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
12117       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
12118         ComplainAboutNonnullParamOrCall(A);
12119         return;
12120       }
12121 
12122       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
12123         // Skip function template not specialized yet.
12124         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
12125           return;
12126         auto ParamIter = llvm::find(FD->parameters(), PV);
12127         assert(ParamIter != FD->param_end());
12128         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
12129 
12130         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
12131           if (!NonNull->args_size()) {
12132               ComplainAboutNonnullParamOrCall(NonNull);
12133               return;
12134           }
12135 
12136           for (const ParamIdx &ArgNo : NonNull->args()) {
12137             if (ArgNo.getASTIndex() == ParamNo) {
12138               ComplainAboutNonnullParamOrCall(NonNull);
12139               return;
12140             }
12141           }
12142         }
12143       }
12144     }
12145   }
12146 
12147   QualType T = D->getType();
12148   const bool IsArray = T->isArrayType();
12149   const bool IsFunction = T->isFunctionType();
12150 
12151   // Address of function is used to silence the function warning.
12152   if (IsAddressOf && IsFunction) {
12153     return;
12154   }
12155 
12156   // Found nothing.
12157   if (!IsAddressOf && !IsFunction && !IsArray)
12158     return;
12159 
12160   // Pretty print the expression for the diagnostic.
12161   std::string Str;
12162   llvm::raw_string_ostream S(Str);
12163   E->printPretty(S, nullptr, getPrintingPolicy());
12164 
12165   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
12166                               : diag::warn_impcast_pointer_to_bool;
12167   enum {
12168     AddressOf,
12169     FunctionPointer,
12170     ArrayPointer
12171   } DiagType;
12172   if (IsAddressOf)
12173     DiagType = AddressOf;
12174   else if (IsFunction)
12175     DiagType = FunctionPointer;
12176   else if (IsArray)
12177     DiagType = ArrayPointer;
12178   else
12179     llvm_unreachable("Could not determine diagnostic.");
12180   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
12181                                 << Range << IsEqual;
12182 
12183   if (!IsFunction)
12184     return;
12185 
12186   // Suggest '&' to silence the function warning.
12187   Diag(E->getExprLoc(), diag::note_function_warning_silence)
12188       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
12189 
12190   // Check to see if '()' fixit should be emitted.
12191   QualType ReturnType;
12192   UnresolvedSet<4> NonTemplateOverloads;
12193   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
12194   if (ReturnType.isNull())
12195     return;
12196 
12197   if (IsCompare) {
12198     // There are two cases here.  If there is null constant, the only suggest
12199     // for a pointer return type.  If the null is 0, then suggest if the return
12200     // type is a pointer or an integer type.
12201     if (!ReturnType->isPointerType()) {
12202       if (NullKind == Expr::NPCK_ZeroExpression ||
12203           NullKind == Expr::NPCK_ZeroLiteral) {
12204         if (!ReturnType->isIntegerType())
12205           return;
12206       } else {
12207         return;
12208       }
12209     }
12210   } else { // !IsCompare
12211     // For function to bool, only suggest if the function pointer has bool
12212     // return type.
12213     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
12214       return;
12215   }
12216   Diag(E->getExprLoc(), diag::note_function_to_function_call)
12217       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
12218 }
12219 
12220 /// Diagnoses "dangerous" implicit conversions within the given
12221 /// expression (which is a full expression).  Implements -Wconversion
12222 /// and -Wsign-compare.
12223 ///
12224 /// \param CC the "context" location of the implicit conversion, i.e.
12225 ///   the most location of the syntactic entity requiring the implicit
12226 ///   conversion
12227 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
12228   // Don't diagnose in unevaluated contexts.
12229   if (isUnevaluatedContext())
12230     return;
12231 
12232   // Don't diagnose for value- or type-dependent expressions.
12233   if (E->isTypeDependent() || E->isValueDependent())
12234     return;
12235 
12236   // Check for array bounds violations in cases where the check isn't triggered
12237   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
12238   // ArraySubscriptExpr is on the RHS of a variable initialization.
12239   CheckArrayAccess(E);
12240 
12241   // This is not the right CC for (e.g.) a variable initialization.
12242   AnalyzeImplicitConversions(*this, E, CC);
12243 }
12244 
12245 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
12246 /// Input argument E is a logical expression.
12247 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
12248   ::CheckBoolLikeConversion(*this, E, CC);
12249 }
12250 
12251 /// Diagnose when expression is an integer constant expression and its evaluation
12252 /// results in integer overflow
12253 void Sema::CheckForIntOverflow (Expr *E) {
12254   // Use a work list to deal with nested struct initializers.
12255   SmallVector<Expr *, 2> Exprs(1, E);
12256 
12257   do {
12258     Expr *OriginalE = Exprs.pop_back_val();
12259     Expr *E = OriginalE->IgnoreParenCasts();
12260 
12261     if (isa<BinaryOperator>(E)) {
12262       E->EvaluateForOverflow(Context);
12263       continue;
12264     }
12265 
12266     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
12267       Exprs.append(InitList->inits().begin(), InitList->inits().end());
12268     else if (isa<ObjCBoxedExpr>(OriginalE))
12269       E->EvaluateForOverflow(Context);
12270     else if (auto Call = dyn_cast<CallExpr>(E))
12271       Exprs.append(Call->arg_begin(), Call->arg_end());
12272     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
12273       Exprs.append(Message->arg_begin(), Message->arg_end());
12274   } while (!Exprs.empty());
12275 }
12276 
12277 namespace {
12278 
12279 /// Visitor for expressions which looks for unsequenced operations on the
12280 /// same object.
12281 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
12282   using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
12283 
12284   /// A tree of sequenced regions within an expression. Two regions are
12285   /// unsequenced if one is an ancestor or a descendent of the other. When we
12286   /// finish processing an expression with sequencing, such as a comma
12287   /// expression, we fold its tree nodes into its parent, since they are
12288   /// unsequenced with respect to nodes we will visit later.
12289   class SequenceTree {
12290     struct Value {
12291       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
12292       unsigned Parent : 31;
12293       unsigned Merged : 1;
12294     };
12295     SmallVector<Value, 8> Values;
12296 
12297   public:
12298     /// A region within an expression which may be sequenced with respect
12299     /// to some other region.
12300     class Seq {
12301       friend class SequenceTree;
12302 
12303       unsigned Index;
12304 
12305       explicit Seq(unsigned N) : Index(N) {}
12306 
12307     public:
12308       Seq() : Index(0) {}
12309     };
12310 
12311     SequenceTree() { Values.push_back(Value(0)); }
12312     Seq root() const { return Seq(0); }
12313 
12314     /// Create a new sequence of operations, which is an unsequenced
12315     /// subset of \p Parent. This sequence of operations is sequenced with
12316     /// respect to other children of \p Parent.
12317     Seq allocate(Seq Parent) {
12318       Values.push_back(Value(Parent.Index));
12319       return Seq(Values.size() - 1);
12320     }
12321 
12322     /// Merge a sequence of operations into its parent.
12323     void merge(Seq S) {
12324       Values[S.Index].Merged = true;
12325     }
12326 
12327     /// Determine whether two operations are unsequenced. This operation
12328     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
12329     /// should have been merged into its parent as appropriate.
12330     bool isUnsequenced(Seq Cur, Seq Old) {
12331       unsigned C = representative(Cur.Index);
12332       unsigned Target = representative(Old.Index);
12333       while (C >= Target) {
12334         if (C == Target)
12335           return true;
12336         C = Values[C].Parent;
12337       }
12338       return false;
12339     }
12340 
12341   private:
12342     /// Pick a representative for a sequence.
12343     unsigned representative(unsigned K) {
12344       if (Values[K].Merged)
12345         // Perform path compression as we go.
12346         return Values[K].Parent = representative(Values[K].Parent);
12347       return K;
12348     }
12349   };
12350 
12351   /// An object for which we can track unsequenced uses.
12352   using Object = const NamedDecl *;
12353 
12354   /// Different flavors of object usage which we track. We only track the
12355   /// least-sequenced usage of each kind.
12356   enum UsageKind {
12357     /// A read of an object. Multiple unsequenced reads are OK.
12358     UK_Use,
12359 
12360     /// A modification of an object which is sequenced before the value
12361     /// computation of the expression, such as ++n in C++.
12362     UK_ModAsValue,
12363 
12364     /// A modification of an object which is not sequenced before the value
12365     /// computation of the expression, such as n++.
12366     UK_ModAsSideEffect,
12367 
12368     UK_Count = UK_ModAsSideEffect + 1
12369   };
12370 
12371   /// Bundle together a sequencing region and the expression corresponding
12372   /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
12373   struct Usage {
12374     const Expr *UsageExpr;
12375     SequenceTree::Seq Seq;
12376 
12377     Usage() : UsageExpr(nullptr), Seq() {}
12378   };
12379 
12380   struct UsageInfo {
12381     Usage Uses[UK_Count];
12382 
12383     /// Have we issued a diagnostic for this object already?
12384     bool Diagnosed;
12385 
12386     UsageInfo() : Uses(), Diagnosed(false) {}
12387   };
12388   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
12389 
12390   Sema &SemaRef;
12391 
12392   /// Sequenced regions within the expression.
12393   SequenceTree Tree;
12394 
12395   /// Declaration modifications and references which we have seen.
12396   UsageInfoMap UsageMap;
12397 
12398   /// The region we are currently within.
12399   SequenceTree::Seq Region;
12400 
12401   /// Filled in with declarations which were modified as a side-effect
12402   /// (that is, post-increment operations).
12403   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
12404 
12405   /// Expressions to check later. We defer checking these to reduce
12406   /// stack usage.
12407   SmallVectorImpl<const Expr *> &WorkList;
12408 
12409   /// RAII object wrapping the visitation of a sequenced subexpression of an
12410   /// expression. At the end of this process, the side-effects of the evaluation
12411   /// become sequenced with respect to the value computation of the result, so
12412   /// we downgrade any UK_ModAsSideEffect within the evaluation to
12413   /// UK_ModAsValue.
12414   struct SequencedSubexpression {
12415     SequencedSubexpression(SequenceChecker &Self)
12416       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
12417       Self.ModAsSideEffect = &ModAsSideEffect;
12418     }
12419 
12420     ~SequencedSubexpression() {
12421       for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
12422         // Add a new usage with usage kind UK_ModAsValue, and then restore
12423         // the previous usage with UK_ModAsSideEffect (thus clearing it if
12424         // the previous one was empty).
12425         UsageInfo &UI = Self.UsageMap[M.first];
12426         auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
12427         Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
12428         SideEffectUsage = M.second;
12429       }
12430       Self.ModAsSideEffect = OldModAsSideEffect;
12431     }
12432 
12433     SequenceChecker &Self;
12434     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
12435     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
12436   };
12437 
12438   /// RAII object wrapping the visitation of a subexpression which we might
12439   /// choose to evaluate as a constant. If any subexpression is evaluated and
12440   /// found to be non-constant, this allows us to suppress the evaluation of
12441   /// the outer expression.
12442   class EvaluationTracker {
12443   public:
12444     EvaluationTracker(SequenceChecker &Self)
12445         : Self(Self), Prev(Self.EvalTracker) {
12446       Self.EvalTracker = this;
12447     }
12448 
12449     ~EvaluationTracker() {
12450       Self.EvalTracker = Prev;
12451       if (Prev)
12452         Prev->EvalOK &= EvalOK;
12453     }
12454 
12455     bool evaluate(const Expr *E, bool &Result) {
12456       if (!EvalOK || E->isValueDependent())
12457         return false;
12458       EvalOK = E->EvaluateAsBooleanCondition(
12459           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
12460       return EvalOK;
12461     }
12462 
12463   private:
12464     SequenceChecker &Self;
12465     EvaluationTracker *Prev;
12466     bool EvalOK = true;
12467   } *EvalTracker = nullptr;
12468 
12469   /// Find the object which is produced by the specified expression,
12470   /// if any.
12471   Object getObject(const Expr *E, bool Mod) const {
12472     E = E->IgnoreParenCasts();
12473     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
12474       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
12475         return getObject(UO->getSubExpr(), Mod);
12476     } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12477       if (BO->getOpcode() == BO_Comma)
12478         return getObject(BO->getRHS(), Mod);
12479       if (Mod && BO->isAssignmentOp())
12480         return getObject(BO->getLHS(), Mod);
12481     } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
12482       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
12483       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
12484         return ME->getMemberDecl();
12485     } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12486       // FIXME: If this is a reference, map through to its value.
12487       return DRE->getDecl();
12488     return nullptr;
12489   }
12490 
12491   /// Note that an object \p O was modified or used by an expression
12492   /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
12493   /// the object \p O as obtained via the \p UsageMap.
12494   void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
12495     // Get the old usage for the given object and usage kind.
12496     Usage &U = UI.Uses[UK];
12497     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
12498       // If we have a modification as side effect and are in a sequenced
12499       // subexpression, save the old Usage so that we can restore it later
12500       // in SequencedSubexpression::~SequencedSubexpression.
12501       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
12502         ModAsSideEffect->push_back(std::make_pair(O, U));
12503       // Then record the new usage with the current sequencing region.
12504       U.UsageExpr = UsageExpr;
12505       U.Seq = Region;
12506     }
12507   }
12508 
12509   /// Check whether a modification or use of an object \p O in an expression
12510   /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
12511   /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
12512   /// \p IsModMod is true when we are checking for a mod-mod unsequenced
12513   /// usage and false we are checking for a mod-use unsequenced usage.
12514   void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
12515                   UsageKind OtherKind, bool IsModMod) {
12516     if (UI.Diagnosed)
12517       return;
12518 
12519     const Usage &U = UI.Uses[OtherKind];
12520     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
12521       return;
12522 
12523     const Expr *Mod = U.UsageExpr;
12524     const Expr *ModOrUse = UsageExpr;
12525     if (OtherKind == UK_Use)
12526       std::swap(Mod, ModOrUse);
12527 
12528     SemaRef.DiagRuntimeBehavior(
12529         Mod->getExprLoc(), {Mod, ModOrUse},
12530         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
12531                                : diag::warn_unsequenced_mod_use)
12532             << O << SourceRange(ModOrUse->getExprLoc()));
12533     UI.Diagnosed = true;
12534   }
12535 
12536   // A note on note{Pre, Post}{Use, Mod}:
12537   //
12538   // (It helps to follow the algorithm with an expression such as
12539   //  "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
12540   //  operations before C++17 and both are well-defined in C++17).
12541   //
12542   // When visiting a node which uses/modify an object we first call notePreUse
12543   // or notePreMod before visiting its sub-expression(s). At this point the
12544   // children of the current node have not yet been visited and so the eventual
12545   // uses/modifications resulting from the children of the current node have not
12546   // been recorded yet.
12547   //
12548   // We then visit the children of the current node. After that notePostUse or
12549   // notePostMod is called. These will 1) detect an unsequenced modification
12550   // as side effect (as in "k++ + k") and 2) add a new usage with the
12551   // appropriate usage kind.
12552   //
12553   // We also have to be careful that some operation sequences modification as
12554   // side effect as well (for example: || or ,). To account for this we wrap
12555   // the visitation of such a sub-expression (for example: the LHS of || or ,)
12556   // with SequencedSubexpression. SequencedSubexpression is an RAII object
12557   // which record usages which are modifications as side effect, and then
12558   // downgrade them (or more accurately restore the previous usage which was a
12559   // modification as side effect) when exiting the scope of the sequenced
12560   // subexpression.
12561 
12562   void notePreUse(Object O, const Expr *UseExpr) {
12563     UsageInfo &UI = UsageMap[O];
12564     // Uses conflict with other modifications.
12565     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
12566   }
12567 
12568   void notePostUse(Object O, const Expr *UseExpr) {
12569     UsageInfo &UI = UsageMap[O];
12570     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
12571                /*IsModMod=*/false);
12572     addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
12573   }
12574 
12575   void notePreMod(Object O, const Expr *ModExpr) {
12576     UsageInfo &UI = UsageMap[O];
12577     // Modifications conflict with other modifications and with uses.
12578     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
12579     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
12580   }
12581 
12582   void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
12583     UsageInfo &UI = UsageMap[O];
12584     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
12585                /*IsModMod=*/true);
12586     addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
12587   }
12588 
12589 public:
12590   SequenceChecker(Sema &S, const Expr *E,
12591                   SmallVectorImpl<const Expr *> &WorkList)
12592       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
12593     Visit(E);
12594     // Silence a -Wunused-private-field since WorkList is now unused.
12595     // TODO: Evaluate if it can be used, and if not remove it.
12596     (void)this->WorkList;
12597   }
12598 
12599   void VisitStmt(const Stmt *S) {
12600     // Skip all statements which aren't expressions for now.
12601   }
12602 
12603   void VisitExpr(const Expr *E) {
12604     // By default, just recurse to evaluated subexpressions.
12605     Base::VisitStmt(E);
12606   }
12607 
12608   void VisitCastExpr(const CastExpr *E) {
12609     Object O = Object();
12610     if (E->getCastKind() == CK_LValueToRValue)
12611       O = getObject(E->getSubExpr(), false);
12612 
12613     if (O)
12614       notePreUse(O, E);
12615     VisitExpr(E);
12616     if (O)
12617       notePostUse(O, E);
12618   }
12619 
12620   void VisitSequencedExpressions(const Expr *SequencedBefore,
12621                                  const Expr *SequencedAfter) {
12622     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
12623     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
12624     SequenceTree::Seq OldRegion = Region;
12625 
12626     {
12627       SequencedSubexpression SeqBefore(*this);
12628       Region = BeforeRegion;
12629       Visit(SequencedBefore);
12630     }
12631 
12632     Region = AfterRegion;
12633     Visit(SequencedAfter);
12634 
12635     Region = OldRegion;
12636 
12637     Tree.merge(BeforeRegion);
12638     Tree.merge(AfterRegion);
12639   }
12640 
12641   void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
12642     // C++17 [expr.sub]p1:
12643     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
12644     //   expression E1 is sequenced before the expression E2.
12645     if (SemaRef.getLangOpts().CPlusPlus17)
12646       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
12647     else {
12648       Visit(ASE->getLHS());
12649       Visit(ASE->getRHS());
12650     }
12651   }
12652 
12653   void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
12654   void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
12655   void VisitBinPtrMem(const BinaryOperator *BO) {
12656     // C++17 [expr.mptr.oper]p4:
12657     //  Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
12658     //  the expression E1 is sequenced before the expression E2.
12659     if (SemaRef.getLangOpts().CPlusPlus17)
12660       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12661     else {
12662       Visit(BO->getLHS());
12663       Visit(BO->getRHS());
12664     }
12665   }
12666 
12667   void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
12668   void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
12669   void VisitBinShlShr(const BinaryOperator *BO) {
12670     // C++17 [expr.shift]p4:
12671     //  The expression E1 is sequenced before the expression E2.
12672     if (SemaRef.getLangOpts().CPlusPlus17)
12673       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12674     else {
12675       Visit(BO->getLHS());
12676       Visit(BO->getRHS());
12677     }
12678   }
12679 
12680   void VisitBinComma(const BinaryOperator *BO) {
12681     // C++11 [expr.comma]p1:
12682     //   Every value computation and side effect associated with the left
12683     //   expression is sequenced before every value computation and side
12684     //   effect associated with the right expression.
12685     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12686   }
12687 
12688   void VisitBinAssign(const BinaryOperator *BO) {
12689     SequenceTree::Seq RHSRegion;
12690     SequenceTree::Seq LHSRegion;
12691     if (SemaRef.getLangOpts().CPlusPlus17) {
12692       RHSRegion = Tree.allocate(Region);
12693       LHSRegion = Tree.allocate(Region);
12694     } else {
12695       RHSRegion = Region;
12696       LHSRegion = Region;
12697     }
12698     SequenceTree::Seq OldRegion = Region;
12699 
12700     // C++11 [expr.ass]p1:
12701     //  [...] the assignment is sequenced after the value computation
12702     //  of the right and left operands, [...]
12703     //
12704     // so check it before inspecting the operands and update the
12705     // map afterwards.
12706     Object O = getObject(BO->getLHS(), /*Mod=*/true);
12707     if (O)
12708       notePreMod(O, BO);
12709 
12710     if (SemaRef.getLangOpts().CPlusPlus17) {
12711       // C++17 [expr.ass]p1:
12712       //  [...] The right operand is sequenced before the left operand. [...]
12713       {
12714         SequencedSubexpression SeqBefore(*this);
12715         Region = RHSRegion;
12716         Visit(BO->getRHS());
12717       }
12718 
12719       Region = LHSRegion;
12720       Visit(BO->getLHS());
12721 
12722       if (O && isa<CompoundAssignOperator>(BO))
12723         notePostUse(O, BO);
12724 
12725     } else {
12726       // C++11 does not specify any sequencing between the LHS and RHS.
12727       Region = LHSRegion;
12728       Visit(BO->getLHS());
12729 
12730       if (O && isa<CompoundAssignOperator>(BO))
12731         notePostUse(O, BO);
12732 
12733       Region = RHSRegion;
12734       Visit(BO->getRHS());
12735     }
12736 
12737     // C++11 [expr.ass]p1:
12738     //  the assignment is sequenced [...] before the value computation of the
12739     //  assignment expression.
12740     // C11 6.5.16/3 has no such rule.
12741     Region = OldRegion;
12742     if (O)
12743       notePostMod(O, BO,
12744                   SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12745                                                   : UK_ModAsSideEffect);
12746     if (SemaRef.getLangOpts().CPlusPlus17) {
12747       Tree.merge(RHSRegion);
12748       Tree.merge(LHSRegion);
12749     }
12750   }
12751 
12752   void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
12753     VisitBinAssign(CAO);
12754   }
12755 
12756   void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12757   void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12758   void VisitUnaryPreIncDec(const UnaryOperator *UO) {
12759     Object O = getObject(UO->getSubExpr(), true);
12760     if (!O)
12761       return VisitExpr(UO);
12762 
12763     notePreMod(O, UO);
12764     Visit(UO->getSubExpr());
12765     // C++11 [expr.pre.incr]p1:
12766     //   the expression ++x is equivalent to x+=1
12767     notePostMod(O, UO,
12768                 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12769                                                 : UK_ModAsSideEffect);
12770   }
12771 
12772   void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12773   void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12774   void VisitUnaryPostIncDec(const UnaryOperator *UO) {
12775     Object O = getObject(UO->getSubExpr(), true);
12776     if (!O)
12777       return VisitExpr(UO);
12778 
12779     notePreMod(O, UO);
12780     Visit(UO->getSubExpr());
12781     notePostMod(O, UO, UK_ModAsSideEffect);
12782   }
12783 
12784   void VisitBinLOr(const BinaryOperator *BO) {
12785     // C++11 [expr.log.or]p2:
12786     //  If the second expression is evaluated, every value computation and
12787     //  side effect associated with the first expression is sequenced before
12788     //  every value computation and side effect associated with the
12789     //  second expression.
12790     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
12791     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
12792     SequenceTree::Seq OldRegion = Region;
12793 
12794     EvaluationTracker Eval(*this);
12795     {
12796       SequencedSubexpression Sequenced(*this);
12797       Region = LHSRegion;
12798       Visit(BO->getLHS());
12799     }
12800 
12801     // C++11 [expr.log.or]p1:
12802     //  [...] the second operand is not evaluated if the first operand
12803     //  evaluates to true.
12804     bool EvalResult = false;
12805     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
12806     bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
12807     if (ShouldVisitRHS) {
12808       Region = RHSRegion;
12809       Visit(BO->getRHS());
12810     }
12811 
12812     Region = OldRegion;
12813     Tree.merge(LHSRegion);
12814     Tree.merge(RHSRegion);
12815   }
12816 
12817   void VisitBinLAnd(const BinaryOperator *BO) {
12818     // C++11 [expr.log.and]p2:
12819     //  If the second expression is evaluated, every value computation and
12820     //  side effect associated with the first expression is sequenced before
12821     //  every value computation and side effect associated with the
12822     //  second expression.
12823     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
12824     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
12825     SequenceTree::Seq OldRegion = Region;
12826 
12827     EvaluationTracker Eval(*this);
12828     {
12829       SequencedSubexpression Sequenced(*this);
12830       Region = LHSRegion;
12831       Visit(BO->getLHS());
12832     }
12833 
12834     // C++11 [expr.log.and]p1:
12835     //  [...] the second operand is not evaluated if the first operand is false.
12836     bool EvalResult = false;
12837     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
12838     bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
12839     if (ShouldVisitRHS) {
12840       Region = RHSRegion;
12841       Visit(BO->getRHS());
12842     }
12843 
12844     Region = OldRegion;
12845     Tree.merge(LHSRegion);
12846     Tree.merge(RHSRegion);
12847   }
12848 
12849   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
12850     // C++11 [expr.cond]p1:
12851     //  [...] Every value computation and side effect associated with the first
12852     //  expression is sequenced before every value computation and side effect
12853     //  associated with the second or third expression.
12854     SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
12855 
12856     // No sequencing is specified between the true and false expression.
12857     // However since exactly one of both is going to be evaluated we can
12858     // consider them to be sequenced. This is needed to avoid warning on
12859     // something like "x ? y+= 1 : y += 2;" in the case where we will visit
12860     // both the true and false expressions because we can't evaluate x.
12861     // This will still allow us to detect an expression like (pre C++17)
12862     // "(x ? y += 1 : y += 2) = y".
12863     //
12864     // We don't wrap the visitation of the true and false expression with
12865     // SequencedSubexpression because we don't want to downgrade modifications
12866     // as side effect in the true and false expressions after the visition
12867     // is done. (for example in the expression "(x ? y++ : y++) + y" we should
12868     // not warn between the two "y++", but we should warn between the "y++"
12869     // and the "y".
12870     SequenceTree::Seq TrueRegion = Tree.allocate(Region);
12871     SequenceTree::Seq FalseRegion = Tree.allocate(Region);
12872     SequenceTree::Seq OldRegion = Region;
12873 
12874     EvaluationTracker Eval(*this);
12875     {
12876       SequencedSubexpression Sequenced(*this);
12877       Region = ConditionRegion;
12878       Visit(CO->getCond());
12879     }
12880 
12881     // C++11 [expr.cond]p1:
12882     // [...] The first expression is contextually converted to bool (Clause 4).
12883     // It is evaluated and if it is true, the result of the conditional
12884     // expression is the value of the second expression, otherwise that of the
12885     // third expression. Only one of the second and third expressions is
12886     // evaluated. [...]
12887     bool EvalResult = false;
12888     bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
12889     bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
12890     bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
12891     if (ShouldVisitTrueExpr) {
12892       Region = TrueRegion;
12893       Visit(CO->getTrueExpr());
12894     }
12895     if (ShouldVisitFalseExpr) {
12896       Region = FalseRegion;
12897       Visit(CO->getFalseExpr());
12898     }
12899 
12900     Region = OldRegion;
12901     Tree.merge(ConditionRegion);
12902     Tree.merge(TrueRegion);
12903     Tree.merge(FalseRegion);
12904   }
12905 
12906   void VisitCallExpr(const CallExpr *CE) {
12907     // C++11 [intro.execution]p15:
12908     //   When calling a function [...], every value computation and side effect
12909     //   associated with any argument expression, or with the postfix expression
12910     //   designating the called function, is sequenced before execution of every
12911     //   expression or statement in the body of the function [and thus before
12912     //   the value computation of its result].
12913     SequencedSubexpression Sequenced(*this);
12914     SemaRef.runWithSufficientStackSpace(CE->getExprLoc(),
12915                                         [&] { Base::VisitCallExpr(CE); });
12916 
12917     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
12918   }
12919 
12920   void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
12921     // This is a call, so all subexpressions are sequenced before the result.
12922     SequencedSubexpression Sequenced(*this);
12923 
12924     if (!CCE->isListInitialization())
12925       return VisitExpr(CCE);
12926 
12927     // In C++11, list initializations are sequenced.
12928     SmallVector<SequenceTree::Seq, 32> Elts;
12929     SequenceTree::Seq Parent = Region;
12930     for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
12931                                               E = CCE->arg_end();
12932          I != E; ++I) {
12933       Region = Tree.allocate(Parent);
12934       Elts.push_back(Region);
12935       Visit(*I);
12936     }
12937 
12938     // Forget that the initializers are sequenced.
12939     Region = Parent;
12940     for (unsigned I = 0; I < Elts.size(); ++I)
12941       Tree.merge(Elts[I]);
12942   }
12943 
12944   void VisitInitListExpr(const InitListExpr *ILE) {
12945     if (!SemaRef.getLangOpts().CPlusPlus11)
12946       return VisitExpr(ILE);
12947 
12948     // In C++11, list initializations are sequenced.
12949     SmallVector<SequenceTree::Seq, 32> Elts;
12950     SequenceTree::Seq Parent = Region;
12951     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
12952       const Expr *E = ILE->getInit(I);
12953       if (!E)
12954         continue;
12955       Region = Tree.allocate(Parent);
12956       Elts.push_back(Region);
12957       Visit(E);
12958     }
12959 
12960     // Forget that the initializers are sequenced.
12961     Region = Parent;
12962     for (unsigned I = 0; I < Elts.size(); ++I)
12963       Tree.merge(Elts[I]);
12964   }
12965 };
12966 
12967 } // namespace
12968 
12969 void Sema::CheckUnsequencedOperations(const Expr *E) {
12970   SmallVector<const Expr *, 8> WorkList;
12971   WorkList.push_back(E);
12972   while (!WorkList.empty()) {
12973     const Expr *Item = WorkList.pop_back_val();
12974     SequenceChecker(*this, Item, WorkList);
12975   }
12976 }
12977 
12978 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
12979                               bool IsConstexpr) {
12980   llvm::SaveAndRestore<bool> ConstantContext(
12981       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
12982   CheckImplicitConversions(E, CheckLoc);
12983   if (!E->isInstantiationDependent())
12984     CheckUnsequencedOperations(E);
12985   if (!IsConstexpr && !E->isValueDependent())
12986     CheckForIntOverflow(E);
12987   DiagnoseMisalignedMembers();
12988 }
12989 
12990 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
12991                                        FieldDecl *BitField,
12992                                        Expr *Init) {
12993   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
12994 }
12995 
12996 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
12997                                          SourceLocation Loc) {
12998   if (!PType->isVariablyModifiedType())
12999     return;
13000   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
13001     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
13002     return;
13003   }
13004   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
13005     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
13006     return;
13007   }
13008   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
13009     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
13010     return;
13011   }
13012 
13013   const ArrayType *AT = S.Context.getAsArrayType(PType);
13014   if (!AT)
13015     return;
13016 
13017   if (AT->getSizeModifier() != ArrayType::Star) {
13018     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
13019     return;
13020   }
13021 
13022   S.Diag(Loc, diag::err_array_star_in_function_definition);
13023 }
13024 
13025 /// CheckParmsForFunctionDef - Check that the parameters of the given
13026 /// function are appropriate for the definition of a function. This
13027 /// takes care of any checks that cannot be performed on the
13028 /// declaration itself, e.g., that the types of each of the function
13029 /// parameters are complete.
13030 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
13031                                     bool CheckParameterNames) {
13032   bool HasInvalidParm = false;
13033   for (ParmVarDecl *Param : Parameters) {
13034     // C99 6.7.5.3p4: the parameters in a parameter type list in a
13035     // function declarator that is part of a function definition of
13036     // that function shall not have incomplete type.
13037     //
13038     // This is also C++ [dcl.fct]p6.
13039     if (!Param->isInvalidDecl() &&
13040         RequireCompleteType(Param->getLocation(), Param->getType(),
13041                             diag::err_typecheck_decl_incomplete_type)) {
13042       Param->setInvalidDecl();
13043       HasInvalidParm = true;
13044     }
13045 
13046     // C99 6.9.1p5: If the declarator includes a parameter type list, the
13047     // declaration of each parameter shall include an identifier.
13048     if (CheckParameterNames && Param->getIdentifier() == nullptr &&
13049         !Param->isImplicit() && !getLangOpts().CPlusPlus) {
13050       // Diagnose this as an extension in C17 and earlier.
13051       if (!getLangOpts().C2x)
13052         Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
13053     }
13054 
13055     // C99 6.7.5.3p12:
13056     //   If the function declarator is not part of a definition of that
13057     //   function, parameters may have incomplete type and may use the [*]
13058     //   notation in their sequences of declarator specifiers to specify
13059     //   variable length array types.
13060     QualType PType = Param->getOriginalType();
13061     // FIXME: This diagnostic should point the '[*]' if source-location
13062     // information is added for it.
13063     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
13064 
13065     // If the parameter is a c++ class type and it has to be destructed in the
13066     // callee function, declare the destructor so that it can be called by the
13067     // callee function. Do not perform any direct access check on the dtor here.
13068     if (!Param->isInvalidDecl()) {
13069       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
13070         if (!ClassDecl->isInvalidDecl() &&
13071             !ClassDecl->hasIrrelevantDestructor() &&
13072             !ClassDecl->isDependentContext() &&
13073             ClassDecl->isParamDestroyedInCallee()) {
13074           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
13075           MarkFunctionReferenced(Param->getLocation(), Destructor);
13076           DiagnoseUseOfDecl(Destructor, Param->getLocation());
13077         }
13078       }
13079     }
13080 
13081     // Parameters with the pass_object_size attribute only need to be marked
13082     // constant at function definitions. Because we lack information about
13083     // whether we're on a declaration or definition when we're instantiating the
13084     // attribute, we need to check for constness here.
13085     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
13086       if (!Param->getType().isConstQualified())
13087         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
13088             << Attr->getSpelling() << 1;
13089 
13090     // Check for parameter names shadowing fields from the class.
13091     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
13092       // The owning context for the parameter should be the function, but we
13093       // want to see if this function's declaration context is a record.
13094       DeclContext *DC = Param->getDeclContext();
13095       if (DC && DC->isFunctionOrMethod()) {
13096         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
13097           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
13098                                      RD, /*DeclIsField*/ false);
13099       }
13100     }
13101   }
13102 
13103   return HasInvalidParm;
13104 }
13105 
13106 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr
13107 /// or MemberExpr.
13108 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
13109                               ASTContext &Context) {
13110   if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
13111     return Context.getDeclAlign(DRE->getDecl());
13112 
13113   if (const auto *ME = dyn_cast<MemberExpr>(E))
13114     return Context.getDeclAlign(ME->getMemberDecl());
13115 
13116   return TypeAlign;
13117 }
13118 
13119 /// CheckCastAlign - Implements -Wcast-align, which warns when a
13120 /// pointer cast increases the alignment requirements.
13121 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
13122   // This is actually a lot of work to potentially be doing on every
13123   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
13124   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
13125     return;
13126 
13127   // Ignore dependent types.
13128   if (T->isDependentType() || Op->getType()->isDependentType())
13129     return;
13130 
13131   // Require that the destination be a pointer type.
13132   const PointerType *DestPtr = T->getAs<PointerType>();
13133   if (!DestPtr) return;
13134 
13135   // If the destination has alignment 1, we're done.
13136   QualType DestPointee = DestPtr->getPointeeType();
13137   if (DestPointee->isIncompleteType()) return;
13138   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
13139   if (DestAlign.isOne()) return;
13140 
13141   // Require that the source be a pointer type.
13142   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
13143   if (!SrcPtr) return;
13144   QualType SrcPointee = SrcPtr->getPointeeType();
13145 
13146   // Whitelist casts from cv void*.  We already implicitly
13147   // whitelisted casts to cv void*, since they have alignment 1.
13148   // Also whitelist casts involving incomplete types, which implicitly
13149   // includes 'void'.
13150   if (SrcPointee->isIncompleteType()) return;
13151 
13152   CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
13153 
13154   if (auto *CE = dyn_cast<CastExpr>(Op)) {
13155     if (CE->getCastKind() == CK_ArrayToPointerDecay)
13156       SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
13157   } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
13158     if (UO->getOpcode() == UO_AddrOf)
13159       SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
13160   }
13161 
13162   if (SrcAlign >= DestAlign) return;
13163 
13164   Diag(TRange.getBegin(), diag::warn_cast_align)
13165     << Op->getType() << T
13166     << static_cast<unsigned>(SrcAlign.getQuantity())
13167     << static_cast<unsigned>(DestAlign.getQuantity())
13168     << TRange << Op->getSourceRange();
13169 }
13170 
13171 /// Check whether this array fits the idiom of a size-one tail padded
13172 /// array member of a struct.
13173 ///
13174 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
13175 /// commonly used to emulate flexible arrays in C89 code.
13176 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
13177                                     const NamedDecl *ND) {
13178   if (Size != 1 || !ND) return false;
13179 
13180   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
13181   if (!FD) return false;
13182 
13183   // Don't consider sizes resulting from macro expansions or template argument
13184   // substitution to form C89 tail-padded arrays.
13185 
13186   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
13187   while (TInfo) {
13188     TypeLoc TL = TInfo->getTypeLoc();
13189     // Look through typedefs.
13190     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
13191       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
13192       TInfo = TDL->getTypeSourceInfo();
13193       continue;
13194     }
13195     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
13196       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
13197       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
13198         return false;
13199     }
13200     break;
13201   }
13202 
13203   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
13204   if (!RD) return false;
13205   if (RD->isUnion()) return false;
13206   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
13207     if (!CRD->isStandardLayout()) return false;
13208   }
13209 
13210   // See if this is the last field decl in the record.
13211   const Decl *D = FD;
13212   while ((D = D->getNextDeclInContext()))
13213     if (isa<FieldDecl>(D))
13214       return false;
13215   return true;
13216 }
13217 
13218 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
13219                             const ArraySubscriptExpr *ASE,
13220                             bool AllowOnePastEnd, bool IndexNegated) {
13221   // Already diagnosed by the constant evaluator.
13222   if (isConstantEvaluated())
13223     return;
13224 
13225   IndexExpr = IndexExpr->IgnoreParenImpCasts();
13226   if (IndexExpr->isValueDependent())
13227     return;
13228 
13229   const Type *EffectiveType =
13230       BaseExpr->getType()->getPointeeOrArrayElementType();
13231   BaseExpr = BaseExpr->IgnoreParenCasts();
13232   const ConstantArrayType *ArrayTy =
13233       Context.getAsConstantArrayType(BaseExpr->getType());
13234 
13235   if (!ArrayTy)
13236     return;
13237 
13238   const Type *BaseType = ArrayTy->getElementType().getTypePtr();
13239   if (EffectiveType->isDependentType() || BaseType->isDependentType())
13240     return;
13241 
13242   Expr::EvalResult Result;
13243   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
13244     return;
13245 
13246   llvm::APSInt index = Result.Val.getInt();
13247   if (IndexNegated)
13248     index = -index;
13249 
13250   const NamedDecl *ND = nullptr;
13251   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
13252     ND = DRE->getDecl();
13253   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
13254     ND = ME->getMemberDecl();
13255 
13256   if (index.isUnsigned() || !index.isNegative()) {
13257     // It is possible that the type of the base expression after
13258     // IgnoreParenCasts is incomplete, even though the type of the base
13259     // expression before IgnoreParenCasts is complete (see PR39746 for an
13260     // example). In this case we have no information about whether the array
13261     // access exceeds the array bounds. However we can still diagnose an array
13262     // access which precedes the array bounds.
13263     if (BaseType->isIncompleteType())
13264       return;
13265 
13266     llvm::APInt size = ArrayTy->getSize();
13267     if (!size.isStrictlyPositive())
13268       return;
13269 
13270     if (BaseType != EffectiveType) {
13271       // Make sure we're comparing apples to apples when comparing index to size
13272       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
13273       uint64_t array_typesize = Context.getTypeSize(BaseType);
13274       // Handle ptrarith_typesize being zero, such as when casting to void*
13275       if (!ptrarith_typesize) ptrarith_typesize = 1;
13276       if (ptrarith_typesize != array_typesize) {
13277         // There's a cast to a different size type involved
13278         uint64_t ratio = array_typesize / ptrarith_typesize;
13279         // TODO: Be smarter about handling cases where array_typesize is not a
13280         // multiple of ptrarith_typesize
13281         if (ptrarith_typesize * ratio == array_typesize)
13282           size *= llvm::APInt(size.getBitWidth(), ratio);
13283       }
13284     }
13285 
13286     if (size.getBitWidth() > index.getBitWidth())
13287       index = index.zext(size.getBitWidth());
13288     else if (size.getBitWidth() < index.getBitWidth())
13289       size = size.zext(index.getBitWidth());
13290 
13291     // For array subscripting the index must be less than size, but for pointer
13292     // arithmetic also allow the index (offset) to be equal to size since
13293     // computing the next address after the end of the array is legal and
13294     // commonly done e.g. in C++ iterators and range-based for loops.
13295     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
13296       return;
13297 
13298     // Also don't warn for arrays of size 1 which are members of some
13299     // structure. These are often used to approximate flexible arrays in C89
13300     // code.
13301     if (IsTailPaddedMemberArray(*this, size, ND))
13302       return;
13303 
13304     // Suppress the warning if the subscript expression (as identified by the
13305     // ']' location) and the index expression are both from macro expansions
13306     // within a system header.
13307     if (ASE) {
13308       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
13309           ASE->getRBracketLoc());
13310       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
13311         SourceLocation IndexLoc =
13312             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
13313         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
13314           return;
13315       }
13316     }
13317 
13318     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
13319     if (ASE)
13320       DiagID = diag::warn_array_index_exceeds_bounds;
13321 
13322     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
13323                         PDiag(DiagID) << index.toString(10, true)
13324                                       << size.toString(10, true)
13325                                       << (unsigned)size.getLimitedValue(~0U)
13326                                       << IndexExpr->getSourceRange());
13327   } else {
13328     unsigned DiagID = diag::warn_array_index_precedes_bounds;
13329     if (!ASE) {
13330       DiagID = diag::warn_ptr_arith_precedes_bounds;
13331       if (index.isNegative()) index = -index;
13332     }
13333 
13334     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
13335                         PDiag(DiagID) << index.toString(10, true)
13336                                       << IndexExpr->getSourceRange());
13337   }
13338 
13339   if (!ND) {
13340     // Try harder to find a NamedDecl to point at in the note.
13341     while (const ArraySubscriptExpr *ASE =
13342            dyn_cast<ArraySubscriptExpr>(BaseExpr))
13343       BaseExpr = ASE->getBase()->IgnoreParenCasts();
13344     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
13345       ND = DRE->getDecl();
13346     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
13347       ND = ME->getMemberDecl();
13348   }
13349 
13350   if (ND)
13351     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
13352                         PDiag(diag::note_array_declared_here)
13353                             << ND->getDeclName());
13354 }
13355 
13356 void Sema::CheckArrayAccess(const Expr *expr) {
13357   int AllowOnePastEnd = 0;
13358   while (expr) {
13359     expr = expr->IgnoreParenImpCasts();
13360     switch (expr->getStmtClass()) {
13361       case Stmt::ArraySubscriptExprClass: {
13362         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
13363         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
13364                          AllowOnePastEnd > 0);
13365         expr = ASE->getBase();
13366         break;
13367       }
13368       case Stmt::MemberExprClass: {
13369         expr = cast<MemberExpr>(expr)->getBase();
13370         break;
13371       }
13372       case Stmt::OMPArraySectionExprClass: {
13373         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
13374         if (ASE->getLowerBound())
13375           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
13376                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
13377         return;
13378       }
13379       case Stmt::UnaryOperatorClass: {
13380         // Only unwrap the * and & unary operators
13381         const UnaryOperator *UO = cast<UnaryOperator>(expr);
13382         expr = UO->getSubExpr();
13383         switch (UO->getOpcode()) {
13384           case UO_AddrOf:
13385             AllowOnePastEnd++;
13386             break;
13387           case UO_Deref:
13388             AllowOnePastEnd--;
13389             break;
13390           default:
13391             return;
13392         }
13393         break;
13394       }
13395       case Stmt::ConditionalOperatorClass: {
13396         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
13397         if (const Expr *lhs = cond->getLHS())
13398           CheckArrayAccess(lhs);
13399         if (const Expr *rhs = cond->getRHS())
13400           CheckArrayAccess(rhs);
13401         return;
13402       }
13403       case Stmt::CXXOperatorCallExprClass: {
13404         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
13405         for (const auto *Arg : OCE->arguments())
13406           CheckArrayAccess(Arg);
13407         return;
13408       }
13409       default:
13410         return;
13411     }
13412   }
13413 }
13414 
13415 //===--- CHECK: Objective-C retain cycles ----------------------------------//
13416 
13417 namespace {
13418 
13419 struct RetainCycleOwner {
13420   VarDecl *Variable = nullptr;
13421   SourceRange Range;
13422   SourceLocation Loc;
13423   bool Indirect = false;
13424 
13425   RetainCycleOwner() = default;
13426 
13427   void setLocsFrom(Expr *e) {
13428     Loc = e->getExprLoc();
13429     Range = e->getSourceRange();
13430   }
13431 };
13432 
13433 } // namespace
13434 
13435 /// Consider whether capturing the given variable can possibly lead to
13436 /// a retain cycle.
13437 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
13438   // In ARC, it's captured strongly iff the variable has __strong
13439   // lifetime.  In MRR, it's captured strongly if the variable is
13440   // __block and has an appropriate type.
13441   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
13442     return false;
13443 
13444   owner.Variable = var;
13445   if (ref)
13446     owner.setLocsFrom(ref);
13447   return true;
13448 }
13449 
13450 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
13451   while (true) {
13452     e = e->IgnoreParens();
13453     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
13454       switch (cast->getCastKind()) {
13455       case CK_BitCast:
13456       case CK_LValueBitCast:
13457       case CK_LValueToRValue:
13458       case CK_ARCReclaimReturnedObject:
13459         e = cast->getSubExpr();
13460         continue;
13461 
13462       default:
13463         return false;
13464       }
13465     }
13466 
13467     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
13468       ObjCIvarDecl *ivar = ref->getDecl();
13469       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
13470         return false;
13471 
13472       // Try to find a retain cycle in the base.
13473       if (!findRetainCycleOwner(S, ref->getBase(), owner))
13474         return false;
13475 
13476       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
13477       owner.Indirect = true;
13478       return true;
13479     }
13480 
13481     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
13482       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
13483       if (!var) return false;
13484       return considerVariable(var, ref, owner);
13485     }
13486 
13487     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
13488       if (member->isArrow()) return false;
13489 
13490       // Don't count this as an indirect ownership.
13491       e = member->getBase();
13492       continue;
13493     }
13494 
13495     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
13496       // Only pay attention to pseudo-objects on property references.
13497       ObjCPropertyRefExpr *pre
13498         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
13499                                               ->IgnoreParens());
13500       if (!pre) return false;
13501       if (pre->isImplicitProperty()) return false;
13502       ObjCPropertyDecl *property = pre->getExplicitProperty();
13503       if (!property->isRetaining() &&
13504           !(property->getPropertyIvarDecl() &&
13505             property->getPropertyIvarDecl()->getType()
13506               .getObjCLifetime() == Qualifiers::OCL_Strong))
13507           return false;
13508 
13509       owner.Indirect = true;
13510       if (pre->isSuperReceiver()) {
13511         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
13512         if (!owner.Variable)
13513           return false;
13514         owner.Loc = pre->getLocation();
13515         owner.Range = pre->getSourceRange();
13516         return true;
13517       }
13518       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
13519                               ->getSourceExpr());
13520       continue;
13521     }
13522 
13523     // Array ivars?
13524 
13525     return false;
13526   }
13527 }
13528 
13529 namespace {
13530 
13531   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
13532     ASTContext &Context;
13533     VarDecl *Variable;
13534     Expr *Capturer = nullptr;
13535     bool VarWillBeReased = false;
13536 
13537     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
13538         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
13539           Context(Context), Variable(variable) {}
13540 
13541     void VisitDeclRefExpr(DeclRefExpr *ref) {
13542       if (ref->getDecl() == Variable && !Capturer)
13543         Capturer = ref;
13544     }
13545 
13546     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
13547       if (Capturer) return;
13548       Visit(ref->getBase());
13549       if (Capturer && ref->isFreeIvar())
13550         Capturer = ref;
13551     }
13552 
13553     void VisitBlockExpr(BlockExpr *block) {
13554       // Look inside nested blocks
13555       if (block->getBlockDecl()->capturesVariable(Variable))
13556         Visit(block->getBlockDecl()->getBody());
13557     }
13558 
13559     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
13560       if (Capturer) return;
13561       if (OVE->getSourceExpr())
13562         Visit(OVE->getSourceExpr());
13563     }
13564 
13565     void VisitBinaryOperator(BinaryOperator *BinOp) {
13566       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
13567         return;
13568       Expr *LHS = BinOp->getLHS();
13569       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
13570         if (DRE->getDecl() != Variable)
13571           return;
13572         if (Expr *RHS = BinOp->getRHS()) {
13573           RHS = RHS->IgnoreParenCasts();
13574           llvm::APSInt Value;
13575           VarWillBeReased =
13576             (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
13577         }
13578       }
13579     }
13580   };
13581 
13582 } // namespace
13583 
13584 /// Check whether the given argument is a block which captures a
13585 /// variable.
13586 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
13587   assert(owner.Variable && owner.Loc.isValid());
13588 
13589   e = e->IgnoreParenCasts();
13590 
13591   // Look through [^{...} copy] and Block_copy(^{...}).
13592   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
13593     Selector Cmd = ME->getSelector();
13594     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
13595       e = ME->getInstanceReceiver();
13596       if (!e)
13597         return nullptr;
13598       e = e->IgnoreParenCasts();
13599     }
13600   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
13601     if (CE->getNumArgs() == 1) {
13602       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
13603       if (Fn) {
13604         const IdentifierInfo *FnI = Fn->getIdentifier();
13605         if (FnI && FnI->isStr("_Block_copy")) {
13606           e = CE->getArg(0)->IgnoreParenCasts();
13607         }
13608       }
13609     }
13610   }
13611 
13612   BlockExpr *block = dyn_cast<BlockExpr>(e);
13613   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
13614     return nullptr;
13615 
13616   FindCaptureVisitor visitor(S.Context, owner.Variable);
13617   visitor.Visit(block->getBlockDecl()->getBody());
13618   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
13619 }
13620 
13621 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
13622                                 RetainCycleOwner &owner) {
13623   assert(capturer);
13624   assert(owner.Variable && owner.Loc.isValid());
13625 
13626   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
13627     << owner.Variable << capturer->getSourceRange();
13628   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
13629     << owner.Indirect << owner.Range;
13630 }
13631 
13632 /// Check for a keyword selector that starts with the word 'add' or
13633 /// 'set'.
13634 static bool isSetterLikeSelector(Selector sel) {
13635   if (sel.isUnarySelector()) return false;
13636 
13637   StringRef str = sel.getNameForSlot(0);
13638   while (!str.empty() && str.front() == '_') str = str.substr(1);
13639   if (str.startswith("set"))
13640     str = str.substr(3);
13641   else if (str.startswith("add")) {
13642     // Specially whitelist 'addOperationWithBlock:'.
13643     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
13644       return false;
13645     str = str.substr(3);
13646   }
13647   else
13648     return false;
13649 
13650   if (str.empty()) return true;
13651   return !isLowercase(str.front());
13652 }
13653 
13654 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
13655                                                     ObjCMessageExpr *Message) {
13656   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
13657                                                 Message->getReceiverInterface(),
13658                                                 NSAPI::ClassId_NSMutableArray);
13659   if (!IsMutableArray) {
13660     return None;
13661   }
13662 
13663   Selector Sel = Message->getSelector();
13664 
13665   Optional<NSAPI::NSArrayMethodKind> MKOpt =
13666     S.NSAPIObj->getNSArrayMethodKind(Sel);
13667   if (!MKOpt) {
13668     return None;
13669   }
13670 
13671   NSAPI::NSArrayMethodKind MK = *MKOpt;
13672 
13673   switch (MK) {
13674     case NSAPI::NSMutableArr_addObject:
13675     case NSAPI::NSMutableArr_insertObjectAtIndex:
13676     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
13677       return 0;
13678     case NSAPI::NSMutableArr_replaceObjectAtIndex:
13679       return 1;
13680 
13681     default:
13682       return None;
13683   }
13684 
13685   return None;
13686 }
13687 
13688 static
13689 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
13690                                                   ObjCMessageExpr *Message) {
13691   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
13692                                             Message->getReceiverInterface(),
13693                                             NSAPI::ClassId_NSMutableDictionary);
13694   if (!IsMutableDictionary) {
13695     return None;
13696   }
13697 
13698   Selector Sel = Message->getSelector();
13699 
13700   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
13701     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
13702   if (!MKOpt) {
13703     return None;
13704   }
13705 
13706   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
13707 
13708   switch (MK) {
13709     case NSAPI::NSMutableDict_setObjectForKey:
13710     case NSAPI::NSMutableDict_setValueForKey:
13711     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
13712       return 0;
13713 
13714     default:
13715       return None;
13716   }
13717 
13718   return None;
13719 }
13720 
13721 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
13722   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
13723                                                 Message->getReceiverInterface(),
13724                                                 NSAPI::ClassId_NSMutableSet);
13725 
13726   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
13727                                             Message->getReceiverInterface(),
13728                                             NSAPI::ClassId_NSMutableOrderedSet);
13729   if (!IsMutableSet && !IsMutableOrderedSet) {
13730     return None;
13731   }
13732 
13733   Selector Sel = Message->getSelector();
13734 
13735   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
13736   if (!MKOpt) {
13737     return None;
13738   }
13739 
13740   NSAPI::NSSetMethodKind MK = *MKOpt;
13741 
13742   switch (MK) {
13743     case NSAPI::NSMutableSet_addObject:
13744     case NSAPI::NSOrderedSet_setObjectAtIndex:
13745     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
13746     case NSAPI::NSOrderedSet_insertObjectAtIndex:
13747       return 0;
13748     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
13749       return 1;
13750   }
13751 
13752   return None;
13753 }
13754 
13755 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
13756   if (!Message->isInstanceMessage()) {
13757     return;
13758   }
13759 
13760   Optional<int> ArgOpt;
13761 
13762   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
13763       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
13764       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
13765     return;
13766   }
13767 
13768   int ArgIndex = *ArgOpt;
13769 
13770   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
13771   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
13772     Arg = OE->getSourceExpr()->IgnoreImpCasts();
13773   }
13774 
13775   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
13776     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
13777       if (ArgRE->isObjCSelfExpr()) {
13778         Diag(Message->getSourceRange().getBegin(),
13779              diag::warn_objc_circular_container)
13780           << ArgRE->getDecl() << StringRef("'super'");
13781       }
13782     }
13783   } else {
13784     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
13785 
13786     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
13787       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
13788     }
13789 
13790     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
13791       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
13792         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
13793           ValueDecl *Decl = ReceiverRE->getDecl();
13794           Diag(Message->getSourceRange().getBegin(),
13795                diag::warn_objc_circular_container)
13796             << Decl << Decl;
13797           if (!ArgRE->isObjCSelfExpr()) {
13798             Diag(Decl->getLocation(),
13799                  diag::note_objc_circular_container_declared_here)
13800               << Decl;
13801           }
13802         }
13803       }
13804     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
13805       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
13806         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
13807           ObjCIvarDecl *Decl = IvarRE->getDecl();
13808           Diag(Message->getSourceRange().getBegin(),
13809                diag::warn_objc_circular_container)
13810             << Decl << Decl;
13811           Diag(Decl->getLocation(),
13812                diag::note_objc_circular_container_declared_here)
13813             << Decl;
13814         }
13815       }
13816     }
13817   }
13818 }
13819 
13820 /// Check a message send to see if it's likely to cause a retain cycle.
13821 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
13822   // Only check instance methods whose selector looks like a setter.
13823   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
13824     return;
13825 
13826   // Try to find a variable that the receiver is strongly owned by.
13827   RetainCycleOwner owner;
13828   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
13829     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
13830       return;
13831   } else {
13832     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
13833     owner.Variable = getCurMethodDecl()->getSelfDecl();
13834     owner.Loc = msg->getSuperLoc();
13835     owner.Range = msg->getSuperLoc();
13836   }
13837 
13838   // Check whether the receiver is captured by any of the arguments.
13839   const ObjCMethodDecl *MD = msg->getMethodDecl();
13840   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
13841     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
13842       // noescape blocks should not be retained by the method.
13843       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
13844         continue;
13845       return diagnoseRetainCycle(*this, capturer, owner);
13846     }
13847   }
13848 }
13849 
13850 /// Check a property assign to see if it's likely to cause a retain cycle.
13851 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
13852   RetainCycleOwner owner;
13853   if (!findRetainCycleOwner(*this, receiver, owner))
13854     return;
13855 
13856   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
13857     diagnoseRetainCycle(*this, capturer, owner);
13858 }
13859 
13860 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
13861   RetainCycleOwner Owner;
13862   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
13863     return;
13864 
13865   // Because we don't have an expression for the variable, we have to set the
13866   // location explicitly here.
13867   Owner.Loc = Var->getLocation();
13868   Owner.Range = Var->getSourceRange();
13869 
13870   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
13871     diagnoseRetainCycle(*this, Capturer, Owner);
13872 }
13873 
13874 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
13875                                      Expr *RHS, bool isProperty) {
13876   // Check if RHS is an Objective-C object literal, which also can get
13877   // immediately zapped in a weak reference.  Note that we explicitly
13878   // allow ObjCStringLiterals, since those are designed to never really die.
13879   RHS = RHS->IgnoreParenImpCasts();
13880 
13881   // This enum needs to match with the 'select' in
13882   // warn_objc_arc_literal_assign (off-by-1).
13883   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
13884   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
13885     return false;
13886 
13887   S.Diag(Loc, diag::warn_arc_literal_assign)
13888     << (unsigned) Kind
13889     << (isProperty ? 0 : 1)
13890     << RHS->getSourceRange();
13891 
13892   return true;
13893 }
13894 
13895 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
13896                                     Qualifiers::ObjCLifetime LT,
13897                                     Expr *RHS, bool isProperty) {
13898   // Strip off any implicit cast added to get to the one ARC-specific.
13899   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
13900     if (cast->getCastKind() == CK_ARCConsumeObject) {
13901       S.Diag(Loc, diag::warn_arc_retained_assign)
13902         << (LT == Qualifiers::OCL_ExplicitNone)
13903         << (isProperty ? 0 : 1)
13904         << RHS->getSourceRange();
13905       return true;
13906     }
13907     RHS = cast->getSubExpr();
13908   }
13909 
13910   if (LT == Qualifiers::OCL_Weak &&
13911       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
13912     return true;
13913 
13914   return false;
13915 }
13916 
13917 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
13918                               QualType LHS, Expr *RHS) {
13919   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
13920 
13921   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
13922     return false;
13923 
13924   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
13925     return true;
13926 
13927   return false;
13928 }
13929 
13930 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
13931                               Expr *LHS, Expr *RHS) {
13932   QualType LHSType;
13933   // PropertyRef on LHS type need be directly obtained from
13934   // its declaration as it has a PseudoType.
13935   ObjCPropertyRefExpr *PRE
13936     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
13937   if (PRE && !PRE->isImplicitProperty()) {
13938     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
13939     if (PD)
13940       LHSType = PD->getType();
13941   }
13942 
13943   if (LHSType.isNull())
13944     LHSType = LHS->getType();
13945 
13946   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
13947 
13948   if (LT == Qualifiers::OCL_Weak) {
13949     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
13950       getCurFunction()->markSafeWeakUse(LHS);
13951   }
13952 
13953   if (checkUnsafeAssigns(Loc, LHSType, RHS))
13954     return;
13955 
13956   // FIXME. Check for other life times.
13957   if (LT != Qualifiers::OCL_None)
13958     return;
13959 
13960   if (PRE) {
13961     if (PRE->isImplicitProperty())
13962       return;
13963     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
13964     if (!PD)
13965       return;
13966 
13967     unsigned Attributes = PD->getPropertyAttributes();
13968     if (Attributes & ObjCPropertyAttribute::kind_assign) {
13969       // when 'assign' attribute was not explicitly specified
13970       // by user, ignore it and rely on property type itself
13971       // for lifetime info.
13972       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
13973       if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
13974           LHSType->isObjCRetainableType())
13975         return;
13976 
13977       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
13978         if (cast->getCastKind() == CK_ARCConsumeObject) {
13979           Diag(Loc, diag::warn_arc_retained_property_assign)
13980           << RHS->getSourceRange();
13981           return;
13982         }
13983         RHS = cast->getSubExpr();
13984       }
13985     } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
13986       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
13987         return;
13988     }
13989   }
13990 }
13991 
13992 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
13993 
13994 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
13995                                         SourceLocation StmtLoc,
13996                                         const NullStmt *Body) {
13997   // Do not warn if the body is a macro that expands to nothing, e.g:
13998   //
13999   // #define CALL(x)
14000   // if (condition)
14001   //   CALL(0);
14002   if (Body->hasLeadingEmptyMacro())
14003     return false;
14004 
14005   // Get line numbers of statement and body.
14006   bool StmtLineInvalid;
14007   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
14008                                                       &StmtLineInvalid);
14009   if (StmtLineInvalid)
14010     return false;
14011 
14012   bool BodyLineInvalid;
14013   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
14014                                                       &BodyLineInvalid);
14015   if (BodyLineInvalid)
14016     return false;
14017 
14018   // Warn if null statement and body are on the same line.
14019   if (StmtLine != BodyLine)
14020     return false;
14021 
14022   return true;
14023 }
14024 
14025 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
14026                                  const Stmt *Body,
14027                                  unsigned DiagID) {
14028   // Since this is a syntactic check, don't emit diagnostic for template
14029   // instantiations, this just adds noise.
14030   if (CurrentInstantiationScope)
14031     return;
14032 
14033   // The body should be a null statement.
14034   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
14035   if (!NBody)
14036     return;
14037 
14038   // Do the usual checks.
14039   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
14040     return;
14041 
14042   Diag(NBody->getSemiLoc(), DiagID);
14043   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
14044 }
14045 
14046 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
14047                                  const Stmt *PossibleBody) {
14048   assert(!CurrentInstantiationScope); // Ensured by caller
14049 
14050   SourceLocation StmtLoc;
14051   const Stmt *Body;
14052   unsigned DiagID;
14053   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
14054     StmtLoc = FS->getRParenLoc();
14055     Body = FS->getBody();
14056     DiagID = diag::warn_empty_for_body;
14057   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
14058     StmtLoc = WS->getCond()->getSourceRange().getEnd();
14059     Body = WS->getBody();
14060     DiagID = diag::warn_empty_while_body;
14061   } else
14062     return; // Neither `for' nor `while'.
14063 
14064   // The body should be a null statement.
14065   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
14066   if (!NBody)
14067     return;
14068 
14069   // Skip expensive checks if diagnostic is disabled.
14070   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
14071     return;
14072 
14073   // Do the usual checks.
14074   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
14075     return;
14076 
14077   // `for(...);' and `while(...);' are popular idioms, so in order to keep
14078   // noise level low, emit diagnostics only if for/while is followed by a
14079   // CompoundStmt, e.g.:
14080   //    for (int i = 0; i < n; i++);
14081   //    {
14082   //      a(i);
14083   //    }
14084   // or if for/while is followed by a statement with more indentation
14085   // than for/while itself:
14086   //    for (int i = 0; i < n; i++);
14087   //      a(i);
14088   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
14089   if (!ProbableTypo) {
14090     bool BodyColInvalid;
14091     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
14092         PossibleBody->getBeginLoc(), &BodyColInvalid);
14093     if (BodyColInvalid)
14094       return;
14095 
14096     bool StmtColInvalid;
14097     unsigned StmtCol =
14098         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
14099     if (StmtColInvalid)
14100       return;
14101 
14102     if (BodyCol > StmtCol)
14103       ProbableTypo = true;
14104   }
14105 
14106   if (ProbableTypo) {
14107     Diag(NBody->getSemiLoc(), DiagID);
14108     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
14109   }
14110 }
14111 
14112 //===--- CHECK: Warn on self move with std::move. -------------------------===//
14113 
14114 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
14115 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
14116                              SourceLocation OpLoc) {
14117   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
14118     return;
14119 
14120   if (inTemplateInstantiation())
14121     return;
14122 
14123   // Strip parens and casts away.
14124   LHSExpr = LHSExpr->IgnoreParenImpCasts();
14125   RHSExpr = RHSExpr->IgnoreParenImpCasts();
14126 
14127   // Check for a call expression
14128   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
14129   if (!CE || CE->getNumArgs() != 1)
14130     return;
14131 
14132   // Check for a call to std::move
14133   if (!CE->isCallToStdMove())
14134     return;
14135 
14136   // Get argument from std::move
14137   RHSExpr = CE->getArg(0);
14138 
14139   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
14140   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
14141 
14142   // Two DeclRefExpr's, check that the decls are the same.
14143   if (LHSDeclRef && RHSDeclRef) {
14144     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
14145       return;
14146     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
14147         RHSDeclRef->getDecl()->getCanonicalDecl())
14148       return;
14149 
14150     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
14151                                         << LHSExpr->getSourceRange()
14152                                         << RHSExpr->getSourceRange();
14153     return;
14154   }
14155 
14156   // Member variables require a different approach to check for self moves.
14157   // MemberExpr's are the same if every nested MemberExpr refers to the same
14158   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
14159   // the base Expr's are CXXThisExpr's.
14160   const Expr *LHSBase = LHSExpr;
14161   const Expr *RHSBase = RHSExpr;
14162   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
14163   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
14164   if (!LHSME || !RHSME)
14165     return;
14166 
14167   while (LHSME && RHSME) {
14168     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
14169         RHSME->getMemberDecl()->getCanonicalDecl())
14170       return;
14171 
14172     LHSBase = LHSME->getBase();
14173     RHSBase = RHSME->getBase();
14174     LHSME = dyn_cast<MemberExpr>(LHSBase);
14175     RHSME = dyn_cast<MemberExpr>(RHSBase);
14176   }
14177 
14178   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
14179   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
14180   if (LHSDeclRef && RHSDeclRef) {
14181     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
14182       return;
14183     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
14184         RHSDeclRef->getDecl()->getCanonicalDecl())
14185       return;
14186 
14187     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
14188                                         << LHSExpr->getSourceRange()
14189                                         << RHSExpr->getSourceRange();
14190     return;
14191   }
14192 
14193   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
14194     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
14195                                         << LHSExpr->getSourceRange()
14196                                         << RHSExpr->getSourceRange();
14197 }
14198 
14199 //===--- Layout compatibility ----------------------------------------------//
14200 
14201 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
14202 
14203 /// Check if two enumeration types are layout-compatible.
14204 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
14205   // C++11 [dcl.enum] p8:
14206   // Two enumeration types are layout-compatible if they have the same
14207   // underlying type.
14208   return ED1->isComplete() && ED2->isComplete() &&
14209          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
14210 }
14211 
14212 /// Check if two fields are layout-compatible.
14213 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
14214                                FieldDecl *Field2) {
14215   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
14216     return false;
14217 
14218   if (Field1->isBitField() != Field2->isBitField())
14219     return false;
14220 
14221   if (Field1->isBitField()) {
14222     // Make sure that the bit-fields are the same length.
14223     unsigned Bits1 = Field1->getBitWidthValue(C);
14224     unsigned Bits2 = Field2->getBitWidthValue(C);
14225 
14226     if (Bits1 != Bits2)
14227       return false;
14228   }
14229 
14230   return true;
14231 }
14232 
14233 /// Check if two standard-layout structs are layout-compatible.
14234 /// (C++11 [class.mem] p17)
14235 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
14236                                      RecordDecl *RD2) {
14237   // If both records are C++ classes, check that base classes match.
14238   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
14239     // If one of records is a CXXRecordDecl we are in C++ mode,
14240     // thus the other one is a CXXRecordDecl, too.
14241     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
14242     // Check number of base classes.
14243     if (D1CXX->getNumBases() != D2CXX->getNumBases())
14244       return false;
14245 
14246     // Check the base classes.
14247     for (CXXRecordDecl::base_class_const_iterator
14248                Base1 = D1CXX->bases_begin(),
14249            BaseEnd1 = D1CXX->bases_end(),
14250               Base2 = D2CXX->bases_begin();
14251          Base1 != BaseEnd1;
14252          ++Base1, ++Base2) {
14253       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
14254         return false;
14255     }
14256   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
14257     // If only RD2 is a C++ class, it should have zero base classes.
14258     if (D2CXX->getNumBases() > 0)
14259       return false;
14260   }
14261 
14262   // Check the fields.
14263   RecordDecl::field_iterator Field2 = RD2->field_begin(),
14264                              Field2End = RD2->field_end(),
14265                              Field1 = RD1->field_begin(),
14266                              Field1End = RD1->field_end();
14267   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
14268     if (!isLayoutCompatible(C, *Field1, *Field2))
14269       return false;
14270   }
14271   if (Field1 != Field1End || Field2 != Field2End)
14272     return false;
14273 
14274   return true;
14275 }
14276 
14277 /// Check if two standard-layout unions are layout-compatible.
14278 /// (C++11 [class.mem] p18)
14279 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
14280                                     RecordDecl *RD2) {
14281   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
14282   for (auto *Field2 : RD2->fields())
14283     UnmatchedFields.insert(Field2);
14284 
14285   for (auto *Field1 : RD1->fields()) {
14286     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
14287         I = UnmatchedFields.begin(),
14288         E = UnmatchedFields.end();
14289 
14290     for ( ; I != E; ++I) {
14291       if (isLayoutCompatible(C, Field1, *I)) {
14292         bool Result = UnmatchedFields.erase(*I);
14293         (void) Result;
14294         assert(Result);
14295         break;
14296       }
14297     }
14298     if (I == E)
14299       return false;
14300   }
14301 
14302   return UnmatchedFields.empty();
14303 }
14304 
14305 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
14306                                RecordDecl *RD2) {
14307   if (RD1->isUnion() != RD2->isUnion())
14308     return false;
14309 
14310   if (RD1->isUnion())
14311     return isLayoutCompatibleUnion(C, RD1, RD2);
14312   else
14313     return isLayoutCompatibleStruct(C, RD1, RD2);
14314 }
14315 
14316 /// Check if two types are layout-compatible in C++11 sense.
14317 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
14318   if (T1.isNull() || T2.isNull())
14319     return false;
14320 
14321   // C++11 [basic.types] p11:
14322   // If two types T1 and T2 are the same type, then T1 and T2 are
14323   // layout-compatible types.
14324   if (C.hasSameType(T1, T2))
14325     return true;
14326 
14327   T1 = T1.getCanonicalType().getUnqualifiedType();
14328   T2 = T2.getCanonicalType().getUnqualifiedType();
14329 
14330   const Type::TypeClass TC1 = T1->getTypeClass();
14331   const Type::TypeClass TC2 = T2->getTypeClass();
14332 
14333   if (TC1 != TC2)
14334     return false;
14335 
14336   if (TC1 == Type::Enum) {
14337     return isLayoutCompatible(C,
14338                               cast<EnumType>(T1)->getDecl(),
14339                               cast<EnumType>(T2)->getDecl());
14340   } else if (TC1 == Type::Record) {
14341     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
14342       return false;
14343 
14344     return isLayoutCompatible(C,
14345                               cast<RecordType>(T1)->getDecl(),
14346                               cast<RecordType>(T2)->getDecl());
14347   }
14348 
14349   return false;
14350 }
14351 
14352 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
14353 
14354 /// Given a type tag expression find the type tag itself.
14355 ///
14356 /// \param TypeExpr Type tag expression, as it appears in user's code.
14357 ///
14358 /// \param VD Declaration of an identifier that appears in a type tag.
14359 ///
14360 /// \param MagicValue Type tag magic value.
14361 ///
14362 /// \param isConstantEvaluated wether the evalaution should be performed in
14363 
14364 /// constant context.
14365 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
14366                             const ValueDecl **VD, uint64_t *MagicValue,
14367                             bool isConstantEvaluated) {
14368   while(true) {
14369     if (!TypeExpr)
14370       return false;
14371 
14372     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
14373 
14374     switch (TypeExpr->getStmtClass()) {
14375     case Stmt::UnaryOperatorClass: {
14376       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
14377       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
14378         TypeExpr = UO->getSubExpr();
14379         continue;
14380       }
14381       return false;
14382     }
14383 
14384     case Stmt::DeclRefExprClass: {
14385       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
14386       *VD = DRE->getDecl();
14387       return true;
14388     }
14389 
14390     case Stmt::IntegerLiteralClass: {
14391       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
14392       llvm::APInt MagicValueAPInt = IL->getValue();
14393       if (MagicValueAPInt.getActiveBits() <= 64) {
14394         *MagicValue = MagicValueAPInt.getZExtValue();
14395         return true;
14396       } else
14397         return false;
14398     }
14399 
14400     case Stmt::BinaryConditionalOperatorClass:
14401     case Stmt::ConditionalOperatorClass: {
14402       const AbstractConditionalOperator *ACO =
14403           cast<AbstractConditionalOperator>(TypeExpr);
14404       bool Result;
14405       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
14406                                                      isConstantEvaluated)) {
14407         if (Result)
14408           TypeExpr = ACO->getTrueExpr();
14409         else
14410           TypeExpr = ACO->getFalseExpr();
14411         continue;
14412       }
14413       return false;
14414     }
14415 
14416     case Stmt::BinaryOperatorClass: {
14417       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
14418       if (BO->getOpcode() == BO_Comma) {
14419         TypeExpr = BO->getRHS();
14420         continue;
14421       }
14422       return false;
14423     }
14424 
14425     default:
14426       return false;
14427     }
14428   }
14429 }
14430 
14431 /// Retrieve the C type corresponding to type tag TypeExpr.
14432 ///
14433 /// \param TypeExpr Expression that specifies a type tag.
14434 ///
14435 /// \param MagicValues Registered magic values.
14436 ///
14437 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
14438 ///        kind.
14439 ///
14440 /// \param TypeInfo Information about the corresponding C type.
14441 ///
14442 /// \param isConstantEvaluated wether the evalaution should be performed in
14443 /// constant context.
14444 ///
14445 /// \returns true if the corresponding C type was found.
14446 static bool GetMatchingCType(
14447     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
14448     const ASTContext &Ctx,
14449     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
14450         *MagicValues,
14451     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
14452     bool isConstantEvaluated) {
14453   FoundWrongKind = false;
14454 
14455   // Variable declaration that has type_tag_for_datatype attribute.
14456   const ValueDecl *VD = nullptr;
14457 
14458   uint64_t MagicValue;
14459 
14460   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
14461     return false;
14462 
14463   if (VD) {
14464     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
14465       if (I->getArgumentKind() != ArgumentKind) {
14466         FoundWrongKind = true;
14467         return false;
14468       }
14469       TypeInfo.Type = I->getMatchingCType();
14470       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
14471       TypeInfo.MustBeNull = I->getMustBeNull();
14472       return true;
14473     }
14474     return false;
14475   }
14476 
14477   if (!MagicValues)
14478     return false;
14479 
14480   llvm::DenseMap<Sema::TypeTagMagicValue,
14481                  Sema::TypeTagData>::const_iterator I =
14482       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
14483   if (I == MagicValues->end())
14484     return false;
14485 
14486   TypeInfo = I->second;
14487   return true;
14488 }
14489 
14490 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
14491                                       uint64_t MagicValue, QualType Type,
14492                                       bool LayoutCompatible,
14493                                       bool MustBeNull) {
14494   if (!TypeTagForDatatypeMagicValues)
14495     TypeTagForDatatypeMagicValues.reset(
14496         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
14497 
14498   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
14499   (*TypeTagForDatatypeMagicValues)[Magic] =
14500       TypeTagData(Type, LayoutCompatible, MustBeNull);
14501 }
14502 
14503 static bool IsSameCharType(QualType T1, QualType T2) {
14504   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
14505   if (!BT1)
14506     return false;
14507 
14508   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
14509   if (!BT2)
14510     return false;
14511 
14512   BuiltinType::Kind T1Kind = BT1->getKind();
14513   BuiltinType::Kind T2Kind = BT2->getKind();
14514 
14515   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
14516          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
14517          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
14518          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
14519 }
14520 
14521 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
14522                                     const ArrayRef<const Expr *> ExprArgs,
14523                                     SourceLocation CallSiteLoc) {
14524   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
14525   bool IsPointerAttr = Attr->getIsPointer();
14526 
14527   // Retrieve the argument representing the 'type_tag'.
14528   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
14529   if (TypeTagIdxAST >= ExprArgs.size()) {
14530     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
14531         << 0 << Attr->getTypeTagIdx().getSourceIndex();
14532     return;
14533   }
14534   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
14535   bool FoundWrongKind;
14536   TypeTagData TypeInfo;
14537   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
14538                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
14539                         TypeInfo, isConstantEvaluated())) {
14540     if (FoundWrongKind)
14541       Diag(TypeTagExpr->getExprLoc(),
14542            diag::warn_type_tag_for_datatype_wrong_kind)
14543         << TypeTagExpr->getSourceRange();
14544     return;
14545   }
14546 
14547   // Retrieve the argument representing the 'arg_idx'.
14548   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
14549   if (ArgumentIdxAST >= ExprArgs.size()) {
14550     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
14551         << 1 << Attr->getArgumentIdx().getSourceIndex();
14552     return;
14553   }
14554   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
14555   if (IsPointerAttr) {
14556     // Skip implicit cast of pointer to `void *' (as a function argument).
14557     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
14558       if (ICE->getType()->isVoidPointerType() &&
14559           ICE->getCastKind() == CK_BitCast)
14560         ArgumentExpr = ICE->getSubExpr();
14561   }
14562   QualType ArgumentType = ArgumentExpr->getType();
14563 
14564   // Passing a `void*' pointer shouldn't trigger a warning.
14565   if (IsPointerAttr && ArgumentType->isVoidPointerType())
14566     return;
14567 
14568   if (TypeInfo.MustBeNull) {
14569     // Type tag with matching void type requires a null pointer.
14570     if (!ArgumentExpr->isNullPointerConstant(Context,
14571                                              Expr::NPC_ValueDependentIsNotNull)) {
14572       Diag(ArgumentExpr->getExprLoc(),
14573            diag::warn_type_safety_null_pointer_required)
14574           << ArgumentKind->getName()
14575           << ArgumentExpr->getSourceRange()
14576           << TypeTagExpr->getSourceRange();
14577     }
14578     return;
14579   }
14580 
14581   QualType RequiredType = TypeInfo.Type;
14582   if (IsPointerAttr)
14583     RequiredType = Context.getPointerType(RequiredType);
14584 
14585   bool mismatch = false;
14586   if (!TypeInfo.LayoutCompatible) {
14587     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
14588 
14589     // C++11 [basic.fundamental] p1:
14590     // Plain char, signed char, and unsigned char are three distinct types.
14591     //
14592     // But we treat plain `char' as equivalent to `signed char' or `unsigned
14593     // char' depending on the current char signedness mode.
14594     if (mismatch)
14595       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
14596                                            RequiredType->getPointeeType())) ||
14597           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
14598         mismatch = false;
14599   } else
14600     if (IsPointerAttr)
14601       mismatch = !isLayoutCompatible(Context,
14602                                      ArgumentType->getPointeeType(),
14603                                      RequiredType->getPointeeType());
14604     else
14605       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
14606 
14607   if (mismatch)
14608     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
14609         << ArgumentType << ArgumentKind
14610         << TypeInfo.LayoutCompatible << RequiredType
14611         << ArgumentExpr->getSourceRange()
14612         << TypeTagExpr->getSourceRange();
14613 }
14614 
14615 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
14616                                          CharUnits Alignment) {
14617   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
14618 }
14619 
14620 void Sema::DiagnoseMisalignedMembers() {
14621   for (MisalignedMember &m : MisalignedMembers) {
14622     const NamedDecl *ND = m.RD;
14623     if (ND->getName().empty()) {
14624       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
14625         ND = TD;
14626     }
14627     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
14628         << m.MD << ND << m.E->getSourceRange();
14629   }
14630   MisalignedMembers.clear();
14631 }
14632 
14633 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
14634   E = E->IgnoreParens();
14635   if (!T->isPointerType() && !T->isIntegerType())
14636     return;
14637   if (isa<UnaryOperator>(E) &&
14638       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
14639     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
14640     if (isa<MemberExpr>(Op)) {
14641       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
14642       if (MA != MisalignedMembers.end() &&
14643           (T->isIntegerType() ||
14644            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
14645                                    Context.getTypeAlignInChars(
14646                                        T->getPointeeType()) <= MA->Alignment))))
14647         MisalignedMembers.erase(MA);
14648     }
14649   }
14650 }
14651 
14652 void Sema::RefersToMemberWithReducedAlignment(
14653     Expr *E,
14654     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
14655         Action) {
14656   const auto *ME = dyn_cast<MemberExpr>(E);
14657   if (!ME)
14658     return;
14659 
14660   // No need to check expressions with an __unaligned-qualified type.
14661   if (E->getType().getQualifiers().hasUnaligned())
14662     return;
14663 
14664   // For a chain of MemberExpr like "a.b.c.d" this list
14665   // will keep FieldDecl's like [d, c, b].
14666   SmallVector<FieldDecl *, 4> ReverseMemberChain;
14667   const MemberExpr *TopME = nullptr;
14668   bool AnyIsPacked = false;
14669   do {
14670     QualType BaseType = ME->getBase()->getType();
14671     if (BaseType->isDependentType())
14672       return;
14673     if (ME->isArrow())
14674       BaseType = BaseType->getPointeeType();
14675     RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
14676     if (RD->isInvalidDecl())
14677       return;
14678 
14679     ValueDecl *MD = ME->getMemberDecl();
14680     auto *FD = dyn_cast<FieldDecl>(MD);
14681     // We do not care about non-data members.
14682     if (!FD || FD->isInvalidDecl())
14683       return;
14684 
14685     AnyIsPacked =
14686         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
14687     ReverseMemberChain.push_back(FD);
14688 
14689     TopME = ME;
14690     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
14691   } while (ME);
14692   assert(TopME && "We did not compute a topmost MemberExpr!");
14693 
14694   // Not the scope of this diagnostic.
14695   if (!AnyIsPacked)
14696     return;
14697 
14698   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
14699   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
14700   // TODO: The innermost base of the member expression may be too complicated.
14701   // For now, just disregard these cases. This is left for future
14702   // improvement.
14703   if (!DRE && !isa<CXXThisExpr>(TopBase))
14704       return;
14705 
14706   // Alignment expected by the whole expression.
14707   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
14708 
14709   // No need to do anything else with this case.
14710   if (ExpectedAlignment.isOne())
14711     return;
14712 
14713   // Synthesize offset of the whole access.
14714   CharUnits Offset;
14715   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
14716        I++) {
14717     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
14718   }
14719 
14720   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
14721   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
14722       ReverseMemberChain.back()->getParent()->getTypeForDecl());
14723 
14724   // The base expression of the innermost MemberExpr may give
14725   // stronger guarantees than the class containing the member.
14726   if (DRE && !TopME->isArrow()) {
14727     const ValueDecl *VD = DRE->getDecl();
14728     if (!VD->getType()->isReferenceType())
14729       CompleteObjectAlignment =
14730           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
14731   }
14732 
14733   // Check if the synthesized offset fulfills the alignment.
14734   if (Offset % ExpectedAlignment != 0 ||
14735       // It may fulfill the offset it but the effective alignment may still be
14736       // lower than the expected expression alignment.
14737       CompleteObjectAlignment < ExpectedAlignment) {
14738     // If this happens, we want to determine a sensible culprit of this.
14739     // Intuitively, watching the chain of member expressions from right to
14740     // left, we start with the required alignment (as required by the field
14741     // type) but some packed attribute in that chain has reduced the alignment.
14742     // It may happen that another packed structure increases it again. But if
14743     // we are here such increase has not been enough. So pointing the first
14744     // FieldDecl that either is packed or else its RecordDecl is,
14745     // seems reasonable.
14746     FieldDecl *FD = nullptr;
14747     CharUnits Alignment;
14748     for (FieldDecl *FDI : ReverseMemberChain) {
14749       if (FDI->hasAttr<PackedAttr>() ||
14750           FDI->getParent()->hasAttr<PackedAttr>()) {
14751         FD = FDI;
14752         Alignment = std::min(
14753             Context.getTypeAlignInChars(FD->getType()),
14754             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
14755         break;
14756       }
14757     }
14758     assert(FD && "We did not find a packed FieldDecl!");
14759     Action(E, FD->getParent(), FD, Alignment);
14760   }
14761 }
14762 
14763 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
14764   using namespace std::placeholders;
14765 
14766   RefersToMemberWithReducedAlignment(
14767       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
14768                      _2, _3, _4));
14769 }
14770