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     // __builtin_memcpy_inline size argument is a constant by definition.
1653     if (TheCall->getArg(2)->EvaluateKnownConstInt(Context).isNullValue())
1654       break;
1655     CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
1656     CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
1657     break;
1658   }
1659 #define BUILTIN(ID, TYPE, ATTRS)
1660 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1661   case Builtin::BI##ID: \
1662     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1663 #include "clang/Basic/Builtins.def"
1664   case Builtin::BI__annotation:
1665     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1666       return ExprError();
1667     break;
1668   case Builtin::BI__builtin_annotation:
1669     if (SemaBuiltinAnnotation(*this, TheCall))
1670       return ExprError();
1671     break;
1672   case Builtin::BI__builtin_addressof:
1673     if (SemaBuiltinAddressof(*this, TheCall))
1674       return ExprError();
1675     break;
1676   case Builtin::BI__builtin_is_aligned:
1677   case Builtin::BI__builtin_align_up:
1678   case Builtin::BI__builtin_align_down:
1679     if (SemaBuiltinAlignment(*this, TheCall, BuiltinID))
1680       return ExprError();
1681     break;
1682   case Builtin::BI__builtin_add_overflow:
1683   case Builtin::BI__builtin_sub_overflow:
1684   case Builtin::BI__builtin_mul_overflow:
1685     if (SemaBuiltinOverflow(*this, TheCall))
1686       return ExprError();
1687     break;
1688   case Builtin::BI__builtin_operator_new:
1689   case Builtin::BI__builtin_operator_delete: {
1690     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1691     ExprResult Res =
1692         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1693     if (Res.isInvalid())
1694       CorrectDelayedTyposInExpr(TheCallResult.get());
1695     return Res;
1696   }
1697   case Builtin::BI__builtin_dump_struct: {
1698     // We first want to ensure we are called with 2 arguments
1699     if (checkArgCount(*this, TheCall, 2))
1700       return ExprError();
1701     // Ensure that the first argument is of type 'struct XX *'
1702     const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1703     const QualType PtrArgType = PtrArg->getType();
1704     if (!PtrArgType->isPointerType() ||
1705         !PtrArgType->getPointeeType()->isRecordType()) {
1706       Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1707           << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1708           << "structure pointer";
1709       return ExprError();
1710     }
1711 
1712     // Ensure that the second argument is of type 'FunctionType'
1713     const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1714     const QualType FnPtrArgType = FnPtrArg->getType();
1715     if (!FnPtrArgType->isPointerType()) {
1716       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1717           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1718           << FnPtrArgType << "'int (*)(const char *, ...)'";
1719       return ExprError();
1720     }
1721 
1722     const auto *FuncType =
1723         FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1724 
1725     if (!FuncType) {
1726       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1727           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1728           << FnPtrArgType << "'int (*)(const char *, ...)'";
1729       return ExprError();
1730     }
1731 
1732     if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1733       if (!FT->getNumParams()) {
1734         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1735             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1736             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1737         return ExprError();
1738       }
1739       QualType PT = FT->getParamType(0);
1740       if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1741           !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1742           !PT->getPointeeType().isConstQualified()) {
1743         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1744             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1745             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1746         return ExprError();
1747       }
1748     }
1749 
1750     TheCall->setType(Context.IntTy);
1751     break;
1752   }
1753   case Builtin::BI__builtin_preserve_access_index:
1754     if (SemaBuiltinPreserveAI(*this, TheCall))
1755       return ExprError();
1756     break;
1757   case Builtin::BI__builtin_call_with_static_chain:
1758     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1759       return ExprError();
1760     break;
1761   case Builtin::BI__exception_code:
1762   case Builtin::BI_exception_code:
1763     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1764                                  diag::err_seh___except_block))
1765       return ExprError();
1766     break;
1767   case Builtin::BI__exception_info:
1768   case Builtin::BI_exception_info:
1769     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1770                                  diag::err_seh___except_filter))
1771       return ExprError();
1772     break;
1773   case Builtin::BI__GetExceptionInfo:
1774     if (checkArgCount(*this, TheCall, 1))
1775       return ExprError();
1776 
1777     if (CheckCXXThrowOperand(
1778             TheCall->getBeginLoc(),
1779             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1780             TheCall))
1781       return ExprError();
1782 
1783     TheCall->setType(Context.VoidPtrTy);
1784     break;
1785   // OpenCL v2.0, s6.13.16 - Pipe functions
1786   case Builtin::BIread_pipe:
1787   case Builtin::BIwrite_pipe:
1788     // Since those two functions are declared with var args, we need a semantic
1789     // check for the argument.
1790     if (SemaBuiltinRWPipe(*this, TheCall))
1791       return ExprError();
1792     break;
1793   case Builtin::BIreserve_read_pipe:
1794   case Builtin::BIreserve_write_pipe:
1795   case Builtin::BIwork_group_reserve_read_pipe:
1796   case Builtin::BIwork_group_reserve_write_pipe:
1797     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1798       return ExprError();
1799     break;
1800   case Builtin::BIsub_group_reserve_read_pipe:
1801   case Builtin::BIsub_group_reserve_write_pipe:
1802     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1803         SemaBuiltinReserveRWPipe(*this, TheCall))
1804       return ExprError();
1805     break;
1806   case Builtin::BIcommit_read_pipe:
1807   case Builtin::BIcommit_write_pipe:
1808   case Builtin::BIwork_group_commit_read_pipe:
1809   case Builtin::BIwork_group_commit_write_pipe:
1810     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1811       return ExprError();
1812     break;
1813   case Builtin::BIsub_group_commit_read_pipe:
1814   case Builtin::BIsub_group_commit_write_pipe:
1815     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1816         SemaBuiltinCommitRWPipe(*this, TheCall))
1817       return ExprError();
1818     break;
1819   case Builtin::BIget_pipe_num_packets:
1820   case Builtin::BIget_pipe_max_packets:
1821     if (SemaBuiltinPipePackets(*this, TheCall))
1822       return ExprError();
1823     break;
1824   case Builtin::BIto_global:
1825   case Builtin::BIto_local:
1826   case Builtin::BIto_private:
1827     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1828       return ExprError();
1829     break;
1830   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1831   case Builtin::BIenqueue_kernel:
1832     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1833       return ExprError();
1834     break;
1835   case Builtin::BIget_kernel_work_group_size:
1836   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1837     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1838       return ExprError();
1839     break;
1840   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1841   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1842     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1843       return ExprError();
1844     break;
1845   case Builtin::BI__builtin_os_log_format:
1846   case Builtin::BI__builtin_os_log_format_buffer_size:
1847     if (SemaBuiltinOSLogFormat(TheCall))
1848       return ExprError();
1849     break;
1850   }
1851 
1852   // Since the target specific builtins for each arch overlap, only check those
1853   // of the arch we are compiling for.
1854   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1855     switch (Context.getTargetInfo().getTriple().getArch()) {
1856       case llvm::Triple::arm:
1857       case llvm::Triple::armeb:
1858       case llvm::Triple::thumb:
1859       case llvm::Triple::thumbeb:
1860         if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1861           return ExprError();
1862         break;
1863       case llvm::Triple::aarch64:
1864       case llvm::Triple::aarch64_32:
1865       case llvm::Triple::aarch64_be:
1866         if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
1867           return ExprError();
1868         break;
1869       case llvm::Triple::bpfeb:
1870       case llvm::Triple::bpfel:
1871         if (CheckBPFBuiltinFunctionCall(BuiltinID, TheCall))
1872           return ExprError();
1873         break;
1874       case llvm::Triple::hexagon:
1875         if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall))
1876           return ExprError();
1877         break;
1878       case llvm::Triple::mips:
1879       case llvm::Triple::mipsel:
1880       case llvm::Triple::mips64:
1881       case llvm::Triple::mips64el:
1882         if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1883           return ExprError();
1884         break;
1885       case llvm::Triple::systemz:
1886         if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1887           return ExprError();
1888         break;
1889       case llvm::Triple::x86:
1890       case llvm::Triple::x86_64:
1891         if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1892           return ExprError();
1893         break;
1894       case llvm::Triple::ppc:
1895       case llvm::Triple::ppc64:
1896       case llvm::Triple::ppc64le:
1897         if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1898           return ExprError();
1899         break;
1900       default:
1901         break;
1902     }
1903   }
1904 
1905   return TheCallResult;
1906 }
1907 
1908 // Get the valid immediate range for the specified NEON type code.
1909 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1910   NeonTypeFlags Type(t);
1911   int IsQuad = ForceQuad ? true : Type.isQuad();
1912   switch (Type.getEltType()) {
1913   case NeonTypeFlags::Int8:
1914   case NeonTypeFlags::Poly8:
1915     return shift ? 7 : (8 << IsQuad) - 1;
1916   case NeonTypeFlags::Int16:
1917   case NeonTypeFlags::Poly16:
1918     return shift ? 15 : (4 << IsQuad) - 1;
1919   case NeonTypeFlags::Int32:
1920     return shift ? 31 : (2 << IsQuad) - 1;
1921   case NeonTypeFlags::Int64:
1922   case NeonTypeFlags::Poly64:
1923     return shift ? 63 : (1 << IsQuad) - 1;
1924   case NeonTypeFlags::Poly128:
1925     return shift ? 127 : (1 << IsQuad) - 1;
1926   case NeonTypeFlags::Float16:
1927     assert(!shift && "cannot shift float types!");
1928     return (4 << IsQuad) - 1;
1929   case NeonTypeFlags::Float32:
1930     assert(!shift && "cannot shift float types!");
1931     return (2 << IsQuad) - 1;
1932   case NeonTypeFlags::Float64:
1933     assert(!shift && "cannot shift float types!");
1934     return (1 << IsQuad) - 1;
1935   }
1936   llvm_unreachable("Invalid NeonTypeFlag!");
1937 }
1938 
1939 /// getNeonEltType - Return the QualType corresponding to the elements of
1940 /// the vector type specified by the NeonTypeFlags.  This is used to check
1941 /// the pointer arguments for Neon load/store intrinsics.
1942 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
1943                                bool IsPolyUnsigned, bool IsInt64Long) {
1944   switch (Flags.getEltType()) {
1945   case NeonTypeFlags::Int8:
1946     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1947   case NeonTypeFlags::Int16:
1948     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1949   case NeonTypeFlags::Int32:
1950     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1951   case NeonTypeFlags::Int64:
1952     if (IsInt64Long)
1953       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1954     else
1955       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1956                                 : Context.LongLongTy;
1957   case NeonTypeFlags::Poly8:
1958     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
1959   case NeonTypeFlags::Poly16:
1960     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
1961   case NeonTypeFlags::Poly64:
1962     if (IsInt64Long)
1963       return Context.UnsignedLongTy;
1964     else
1965       return Context.UnsignedLongLongTy;
1966   case NeonTypeFlags::Poly128:
1967     break;
1968   case NeonTypeFlags::Float16:
1969     return Context.HalfTy;
1970   case NeonTypeFlags::Float32:
1971     return Context.FloatTy;
1972   case NeonTypeFlags::Float64:
1973     return Context.DoubleTy;
1974   }
1975   llvm_unreachable("Invalid NeonTypeFlag!");
1976 }
1977 
1978 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1979   llvm::APSInt Result;
1980   uint64_t mask = 0;
1981   unsigned TV = 0;
1982   int PtrArgNum = -1;
1983   bool HasConstPtr = false;
1984   switch (BuiltinID) {
1985 #define GET_NEON_OVERLOAD_CHECK
1986 #include "clang/Basic/arm_neon.inc"
1987 #include "clang/Basic/arm_fp16.inc"
1988 #undef GET_NEON_OVERLOAD_CHECK
1989   }
1990 
1991   // For NEON intrinsics which are overloaded on vector element type, validate
1992   // the immediate which specifies which variant to emit.
1993   unsigned ImmArg = TheCall->getNumArgs()-1;
1994   if (mask) {
1995     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1996       return true;
1997 
1998     TV = Result.getLimitedValue(64);
1999     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
2000       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
2001              << TheCall->getArg(ImmArg)->getSourceRange();
2002   }
2003 
2004   if (PtrArgNum >= 0) {
2005     // Check that pointer arguments have the specified type.
2006     Expr *Arg = TheCall->getArg(PtrArgNum);
2007     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
2008       Arg = ICE->getSubExpr();
2009     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
2010     QualType RHSTy = RHS.get()->getType();
2011 
2012     llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
2013     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
2014                           Arch == llvm::Triple::aarch64_32 ||
2015                           Arch == llvm::Triple::aarch64_be;
2016     bool IsInt64Long =
2017         Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
2018     QualType EltTy =
2019         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
2020     if (HasConstPtr)
2021       EltTy = EltTy.withConst();
2022     QualType LHSTy = Context.getPointerType(EltTy);
2023     AssignConvertType ConvTy;
2024     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
2025     if (RHS.isInvalid())
2026       return true;
2027     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
2028                                  RHS.get(), AA_Assigning))
2029       return true;
2030   }
2031 
2032   // For NEON intrinsics which take an immediate value as part of the
2033   // instruction, range check them here.
2034   unsigned i = 0, l = 0, u = 0;
2035   switch (BuiltinID) {
2036   default:
2037     return false;
2038   #define GET_NEON_IMMEDIATE_CHECK
2039   #include "clang/Basic/arm_neon.inc"
2040   #include "clang/Basic/arm_fp16.inc"
2041   #undef GET_NEON_IMMEDIATE_CHECK
2042   }
2043 
2044   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2045 }
2046 
2047 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2048   switch (BuiltinID) {
2049   default:
2050     return false;
2051   #include "clang/Basic/arm_mve_builtin_sema.inc"
2052   }
2053 }
2054 
2055 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
2056                                         unsigned MaxWidth) {
2057   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
2058           BuiltinID == ARM::BI__builtin_arm_ldaex ||
2059           BuiltinID == ARM::BI__builtin_arm_strex ||
2060           BuiltinID == ARM::BI__builtin_arm_stlex ||
2061           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2062           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2063           BuiltinID == AArch64::BI__builtin_arm_strex ||
2064           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
2065          "unexpected ARM builtin");
2066   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
2067                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
2068                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2069                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
2070 
2071   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2072 
2073   // Ensure that we have the proper number of arguments.
2074   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
2075     return true;
2076 
2077   // Inspect the pointer argument of the atomic builtin.  This should always be
2078   // a pointer type, whose element is an integral scalar or pointer type.
2079   // Because it is a pointer type, we don't have to worry about any implicit
2080   // casts here.
2081   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
2082   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
2083   if (PointerArgRes.isInvalid())
2084     return true;
2085   PointerArg = PointerArgRes.get();
2086 
2087   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2088   if (!pointerType) {
2089     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
2090         << PointerArg->getType() << PointerArg->getSourceRange();
2091     return true;
2092   }
2093 
2094   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
2095   // task is to insert the appropriate casts into the AST. First work out just
2096   // what the appropriate type is.
2097   QualType ValType = pointerType->getPointeeType();
2098   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
2099   if (IsLdrex)
2100     AddrType.addConst();
2101 
2102   // Issue a warning if the cast is dodgy.
2103   CastKind CastNeeded = CK_NoOp;
2104   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
2105     CastNeeded = CK_BitCast;
2106     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
2107         << PointerArg->getType() << Context.getPointerType(AddrType)
2108         << AA_Passing << PointerArg->getSourceRange();
2109   }
2110 
2111   // Finally, do the cast and replace the argument with the corrected version.
2112   AddrType = Context.getPointerType(AddrType);
2113   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
2114   if (PointerArgRes.isInvalid())
2115     return true;
2116   PointerArg = PointerArgRes.get();
2117 
2118   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
2119 
2120   // In general, we allow ints, floats and pointers to be loaded and stored.
2121   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2122       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
2123     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
2124         << PointerArg->getType() << PointerArg->getSourceRange();
2125     return true;
2126   }
2127 
2128   // But ARM doesn't have instructions to deal with 128-bit versions.
2129   if (Context.getTypeSize(ValType) > MaxWidth) {
2130     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
2131     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
2132         << PointerArg->getType() << PointerArg->getSourceRange();
2133     return true;
2134   }
2135 
2136   switch (ValType.getObjCLifetime()) {
2137   case Qualifiers::OCL_None:
2138   case Qualifiers::OCL_ExplicitNone:
2139     // okay
2140     break;
2141 
2142   case Qualifiers::OCL_Weak:
2143   case Qualifiers::OCL_Strong:
2144   case Qualifiers::OCL_Autoreleasing:
2145     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
2146         << ValType << PointerArg->getSourceRange();
2147     return true;
2148   }
2149 
2150   if (IsLdrex) {
2151     TheCall->setType(ValType);
2152     return false;
2153   }
2154 
2155   // Initialize the argument to be stored.
2156   ExprResult ValArg = TheCall->getArg(0);
2157   InitializedEntity Entity = InitializedEntity::InitializeParameter(
2158       Context, ValType, /*consume*/ false);
2159   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2160   if (ValArg.isInvalid())
2161     return true;
2162   TheCall->setArg(0, ValArg.get());
2163 
2164   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
2165   // but the custom checker bypasses all default analysis.
2166   TheCall->setType(Context.IntTy);
2167   return false;
2168 }
2169 
2170 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2171   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
2172       BuiltinID == ARM::BI__builtin_arm_ldaex ||
2173       BuiltinID == ARM::BI__builtin_arm_strex ||
2174       BuiltinID == ARM::BI__builtin_arm_stlex) {
2175     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
2176   }
2177 
2178   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
2179     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2180       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
2181   }
2182 
2183   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2184       BuiltinID == ARM::BI__builtin_arm_wsr64)
2185     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
2186 
2187   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
2188       BuiltinID == ARM::BI__builtin_arm_rsrp ||
2189       BuiltinID == ARM::BI__builtin_arm_wsr ||
2190       BuiltinID == ARM::BI__builtin_arm_wsrp)
2191     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2192 
2193   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
2194     return true;
2195   if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
2196     return true;
2197 
2198   // For intrinsics which take an immediate value as part of the instruction,
2199   // range check them here.
2200   // FIXME: VFP Intrinsics should error if VFP not present.
2201   switch (BuiltinID) {
2202   default: return false;
2203   case ARM::BI__builtin_arm_ssat:
2204     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
2205   case ARM::BI__builtin_arm_usat:
2206     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
2207   case ARM::BI__builtin_arm_ssat16:
2208     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
2209   case ARM::BI__builtin_arm_usat16:
2210     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2211   case ARM::BI__builtin_arm_vcvtr_f:
2212   case ARM::BI__builtin_arm_vcvtr_d:
2213     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
2214   case ARM::BI__builtin_arm_dmb:
2215   case ARM::BI__builtin_arm_dsb:
2216   case ARM::BI__builtin_arm_isb:
2217   case ARM::BI__builtin_arm_dbg:
2218     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
2219   }
2220 }
2221 
2222 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
2223                                          CallExpr *TheCall) {
2224   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2225       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2226       BuiltinID == AArch64::BI__builtin_arm_strex ||
2227       BuiltinID == AArch64::BI__builtin_arm_stlex) {
2228     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
2229   }
2230 
2231   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
2232     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2233       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
2234       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
2235       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
2236   }
2237 
2238   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2239       BuiltinID == AArch64::BI__builtin_arm_wsr64)
2240     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2241 
2242   // Memory Tagging Extensions (MTE) Intrinsics
2243   if (BuiltinID == AArch64::BI__builtin_arm_irg ||
2244       BuiltinID == AArch64::BI__builtin_arm_addg ||
2245       BuiltinID == AArch64::BI__builtin_arm_gmi ||
2246       BuiltinID == AArch64::BI__builtin_arm_ldg ||
2247       BuiltinID == AArch64::BI__builtin_arm_stg ||
2248       BuiltinID == AArch64::BI__builtin_arm_subp) {
2249     return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
2250   }
2251 
2252   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
2253       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2254       BuiltinID == AArch64::BI__builtin_arm_wsr ||
2255       BuiltinID == AArch64::BI__builtin_arm_wsrp)
2256     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2257 
2258   // Only check the valid encoding range. Any constant in this range would be
2259   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
2260   // an exception for incorrect registers. This matches MSVC behavior.
2261   if (BuiltinID == AArch64::BI_ReadStatusReg ||
2262       BuiltinID == AArch64::BI_WriteStatusReg)
2263     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
2264 
2265   if (BuiltinID == AArch64::BI__getReg)
2266     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
2267 
2268   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
2269     return true;
2270 
2271   // For intrinsics which take an immediate value as part of the instruction,
2272   // range check them here.
2273   unsigned i = 0, l = 0, u = 0;
2274   switch (BuiltinID) {
2275   default: return false;
2276   case AArch64::BI__builtin_arm_dmb:
2277   case AArch64::BI__builtin_arm_dsb:
2278   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
2279   case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
2280   }
2281 
2282   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2283 }
2284 
2285 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
2286                                        CallExpr *TheCall) {
2287   assert(BuiltinID == BPF::BI__builtin_preserve_field_info &&
2288          "unexpected ARM builtin");
2289 
2290   if (checkArgCount(*this, TheCall, 2))
2291     return true;
2292 
2293   // The first argument needs to be a record field access.
2294   // If it is an array element access, we delay decision
2295   // to BPF backend to check whether the access is a
2296   // field access or not.
2297   Expr *Arg = TheCall->getArg(0);
2298   if (Arg->getType()->getAsPlaceholderType() ||
2299       (Arg->IgnoreParens()->getObjectKind() != OK_BitField &&
2300        !dyn_cast<MemberExpr>(Arg->IgnoreParens()) &&
2301        !dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens()))) {
2302     Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_field)
2303         << 1 << Arg->getSourceRange();
2304     return true;
2305   }
2306 
2307   // The second argument needs to be a constant int
2308   llvm::APSInt Value;
2309   if (!TheCall->getArg(1)->isIntegerConstantExpr(Value, Context)) {
2310     Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_const)
2311         << 2 << Arg->getSourceRange();
2312     return true;
2313   }
2314 
2315   TheCall->setType(Context.UnsignedIntTy);
2316   return false;
2317 }
2318 
2319 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2320   struct ArgInfo {
2321     uint8_t OpNum;
2322     bool IsSigned;
2323     uint8_t BitWidth;
2324     uint8_t Align;
2325   };
2326   struct BuiltinInfo {
2327     unsigned BuiltinID;
2328     ArgInfo Infos[2];
2329   };
2330 
2331   static BuiltinInfo Infos[] = {
2332     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
2333     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
2334     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
2335     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  1 }} },
2336     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
2337     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
2338     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
2339     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
2340     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
2341     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
2342     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
2343 
2344     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
2345     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
2346     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
2347     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
2348     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
2349     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
2350     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
2351     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
2352     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
2353     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
2354     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
2355 
2356     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
2357     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
2358     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
2359     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
2360     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
2361     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
2362     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
2363     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
2364     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
2365     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
2366     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
2367     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
2368     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
2369     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
2370     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
2371     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
2372     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
2373     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
2374     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
2375     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
2376     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
2377     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
2378     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
2379     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
2380     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
2381     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
2382     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
2383     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
2384     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
2385     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
2386     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
2387     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
2388     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
2389     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
2390     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
2391     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
2392     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
2393     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
2394     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
2395     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
2396     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
2397     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
2398     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
2399     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
2400     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
2401     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
2402     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
2403     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
2404     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
2405     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
2406     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
2407     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
2408                                                       {{ 1, false, 6,  0 }} },
2409     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
2410     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
2411     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
2412     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
2413     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
2414     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
2415     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
2416                                                       {{ 1, false, 5,  0 }} },
2417     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
2418     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
2419     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
2420     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
2421     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
2422     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
2423                                                        { 2, false, 5,  0 }} },
2424     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
2425                                                        { 2, false, 6,  0 }} },
2426     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
2427                                                        { 3, false, 5,  0 }} },
2428     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
2429                                                        { 3, false, 6,  0 }} },
2430     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
2431     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
2432     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
2433     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
2434     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
2435     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
2436     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
2437     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
2438     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
2439     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
2440     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
2441     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
2442     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
2443     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
2444     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
2445     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
2446                                                       {{ 2, false, 4,  0 },
2447                                                        { 3, false, 5,  0 }} },
2448     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
2449                                                       {{ 2, false, 4,  0 },
2450                                                        { 3, false, 5,  0 }} },
2451     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
2452                                                       {{ 2, false, 4,  0 },
2453                                                        { 3, false, 5,  0 }} },
2454     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
2455                                                       {{ 2, false, 4,  0 },
2456                                                        { 3, false, 5,  0 }} },
2457     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
2458     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
2459     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
2460     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
2461     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
2462     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
2463     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
2464     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
2465     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
2466     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
2467     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
2468                                                        { 2, false, 5,  0 }} },
2469     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
2470                                                        { 2, false, 6,  0 }} },
2471     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
2472     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
2473     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
2474     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
2475     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
2476     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
2477     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
2478     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
2479     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
2480                                                       {{ 1, false, 4,  0 }} },
2481     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
2482     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
2483                                                       {{ 1, false, 4,  0 }} },
2484     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
2485     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
2486     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
2487     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
2488     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
2489     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
2490     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
2491     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
2492     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
2493     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
2494     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
2495     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
2496     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
2497     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
2498     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
2499     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
2500     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
2501     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
2502     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
2503     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
2504                                                       {{ 3, false, 1,  0 }} },
2505     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
2506     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
2507     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
2508     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
2509                                                       {{ 3, false, 1,  0 }} },
2510     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
2511     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
2512     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
2513     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
2514                                                       {{ 3, false, 1,  0 }} },
2515   };
2516 
2517   // Use a dynamically initialized static to sort the table exactly once on
2518   // first run.
2519   static const bool SortOnce =
2520       (llvm::sort(Infos,
2521                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
2522                    return LHS.BuiltinID < RHS.BuiltinID;
2523                  }),
2524        true);
2525   (void)SortOnce;
2526 
2527   const BuiltinInfo *F = llvm::partition_point(
2528       Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
2529   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
2530     return false;
2531 
2532   bool Error = false;
2533 
2534   for (const ArgInfo &A : F->Infos) {
2535     // Ignore empty ArgInfo elements.
2536     if (A.BitWidth == 0)
2537       continue;
2538 
2539     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
2540     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
2541     if (!A.Align) {
2542       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
2543     } else {
2544       unsigned M = 1 << A.Align;
2545       Min *= M;
2546       Max *= M;
2547       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
2548                SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
2549     }
2550   }
2551   return Error;
2552 }
2553 
2554 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
2555                                            CallExpr *TheCall) {
2556   return CheckHexagonBuiltinArgument(BuiltinID, TheCall);
2557 }
2558 
2559 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2560   return CheckMipsBuiltinCpu(BuiltinID, TheCall) ||
2561          CheckMipsBuiltinArgument(BuiltinID, TheCall);
2562 }
2563 
2564 bool Sema::CheckMipsBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) {
2565   const TargetInfo &TI = Context.getTargetInfo();
2566 
2567   if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
2568       BuiltinID <= Mips::BI__builtin_mips_lwx) {
2569     if (!TI.hasFeature("dsp"))
2570       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
2571   }
2572 
2573   if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
2574       BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
2575     if (!TI.hasFeature("dspr2"))
2576       return Diag(TheCall->getBeginLoc(),
2577                   diag::err_mips_builtin_requires_dspr2);
2578   }
2579 
2580   if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
2581       BuiltinID <= Mips::BI__builtin_msa_xori_b) {
2582     if (!TI.hasFeature("msa"))
2583       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
2584   }
2585 
2586   return false;
2587 }
2588 
2589 // CheckMipsBuiltinArgument - Checks the constant value passed to the
2590 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
2591 // ordering for DSP is unspecified. MSA is ordered by the data format used
2592 // by the underlying instruction i.e., df/m, df/n and then by size.
2593 //
2594 // FIXME: The size tests here should instead be tablegen'd along with the
2595 //        definitions from include/clang/Basic/BuiltinsMips.def.
2596 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
2597 //        be too.
2598 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2599   unsigned i = 0, l = 0, u = 0, m = 0;
2600   switch (BuiltinID) {
2601   default: return false;
2602   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
2603   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
2604   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
2605   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
2606   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
2607   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
2608   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
2609   // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
2610   // df/m field.
2611   // These intrinsics take an unsigned 3 bit immediate.
2612   case Mips::BI__builtin_msa_bclri_b:
2613   case Mips::BI__builtin_msa_bnegi_b:
2614   case Mips::BI__builtin_msa_bseti_b:
2615   case Mips::BI__builtin_msa_sat_s_b:
2616   case Mips::BI__builtin_msa_sat_u_b:
2617   case Mips::BI__builtin_msa_slli_b:
2618   case Mips::BI__builtin_msa_srai_b:
2619   case Mips::BI__builtin_msa_srari_b:
2620   case Mips::BI__builtin_msa_srli_b:
2621   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
2622   case Mips::BI__builtin_msa_binsli_b:
2623   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
2624   // These intrinsics take an unsigned 4 bit immediate.
2625   case Mips::BI__builtin_msa_bclri_h:
2626   case Mips::BI__builtin_msa_bnegi_h:
2627   case Mips::BI__builtin_msa_bseti_h:
2628   case Mips::BI__builtin_msa_sat_s_h:
2629   case Mips::BI__builtin_msa_sat_u_h:
2630   case Mips::BI__builtin_msa_slli_h:
2631   case Mips::BI__builtin_msa_srai_h:
2632   case Mips::BI__builtin_msa_srari_h:
2633   case Mips::BI__builtin_msa_srli_h:
2634   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
2635   case Mips::BI__builtin_msa_binsli_h:
2636   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
2637   // These intrinsics take an unsigned 5 bit immediate.
2638   // The first block of intrinsics actually have an unsigned 5 bit field,
2639   // not a df/n field.
2640   case Mips::BI__builtin_msa_cfcmsa:
2641   case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
2642   case Mips::BI__builtin_msa_clei_u_b:
2643   case Mips::BI__builtin_msa_clei_u_h:
2644   case Mips::BI__builtin_msa_clei_u_w:
2645   case Mips::BI__builtin_msa_clei_u_d:
2646   case Mips::BI__builtin_msa_clti_u_b:
2647   case Mips::BI__builtin_msa_clti_u_h:
2648   case Mips::BI__builtin_msa_clti_u_w:
2649   case Mips::BI__builtin_msa_clti_u_d:
2650   case Mips::BI__builtin_msa_maxi_u_b:
2651   case Mips::BI__builtin_msa_maxi_u_h:
2652   case Mips::BI__builtin_msa_maxi_u_w:
2653   case Mips::BI__builtin_msa_maxi_u_d:
2654   case Mips::BI__builtin_msa_mini_u_b:
2655   case Mips::BI__builtin_msa_mini_u_h:
2656   case Mips::BI__builtin_msa_mini_u_w:
2657   case Mips::BI__builtin_msa_mini_u_d:
2658   case Mips::BI__builtin_msa_addvi_b:
2659   case Mips::BI__builtin_msa_addvi_h:
2660   case Mips::BI__builtin_msa_addvi_w:
2661   case Mips::BI__builtin_msa_addvi_d:
2662   case Mips::BI__builtin_msa_bclri_w:
2663   case Mips::BI__builtin_msa_bnegi_w:
2664   case Mips::BI__builtin_msa_bseti_w:
2665   case Mips::BI__builtin_msa_sat_s_w:
2666   case Mips::BI__builtin_msa_sat_u_w:
2667   case Mips::BI__builtin_msa_slli_w:
2668   case Mips::BI__builtin_msa_srai_w:
2669   case Mips::BI__builtin_msa_srari_w:
2670   case Mips::BI__builtin_msa_srli_w:
2671   case Mips::BI__builtin_msa_srlri_w:
2672   case Mips::BI__builtin_msa_subvi_b:
2673   case Mips::BI__builtin_msa_subvi_h:
2674   case Mips::BI__builtin_msa_subvi_w:
2675   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
2676   case Mips::BI__builtin_msa_binsli_w:
2677   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
2678   // These intrinsics take an unsigned 6 bit immediate.
2679   case Mips::BI__builtin_msa_bclri_d:
2680   case Mips::BI__builtin_msa_bnegi_d:
2681   case Mips::BI__builtin_msa_bseti_d:
2682   case Mips::BI__builtin_msa_sat_s_d:
2683   case Mips::BI__builtin_msa_sat_u_d:
2684   case Mips::BI__builtin_msa_slli_d:
2685   case Mips::BI__builtin_msa_srai_d:
2686   case Mips::BI__builtin_msa_srari_d:
2687   case Mips::BI__builtin_msa_srli_d:
2688   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
2689   case Mips::BI__builtin_msa_binsli_d:
2690   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
2691   // These intrinsics take a signed 5 bit immediate.
2692   case Mips::BI__builtin_msa_ceqi_b:
2693   case Mips::BI__builtin_msa_ceqi_h:
2694   case Mips::BI__builtin_msa_ceqi_w:
2695   case Mips::BI__builtin_msa_ceqi_d:
2696   case Mips::BI__builtin_msa_clti_s_b:
2697   case Mips::BI__builtin_msa_clti_s_h:
2698   case Mips::BI__builtin_msa_clti_s_w:
2699   case Mips::BI__builtin_msa_clti_s_d:
2700   case Mips::BI__builtin_msa_clei_s_b:
2701   case Mips::BI__builtin_msa_clei_s_h:
2702   case Mips::BI__builtin_msa_clei_s_w:
2703   case Mips::BI__builtin_msa_clei_s_d:
2704   case Mips::BI__builtin_msa_maxi_s_b:
2705   case Mips::BI__builtin_msa_maxi_s_h:
2706   case Mips::BI__builtin_msa_maxi_s_w:
2707   case Mips::BI__builtin_msa_maxi_s_d:
2708   case Mips::BI__builtin_msa_mini_s_b:
2709   case Mips::BI__builtin_msa_mini_s_h:
2710   case Mips::BI__builtin_msa_mini_s_w:
2711   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
2712   // These intrinsics take an unsigned 8 bit immediate.
2713   case Mips::BI__builtin_msa_andi_b:
2714   case Mips::BI__builtin_msa_nori_b:
2715   case Mips::BI__builtin_msa_ori_b:
2716   case Mips::BI__builtin_msa_shf_b:
2717   case Mips::BI__builtin_msa_shf_h:
2718   case Mips::BI__builtin_msa_shf_w:
2719   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
2720   case Mips::BI__builtin_msa_bseli_b:
2721   case Mips::BI__builtin_msa_bmnzi_b:
2722   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
2723   // df/n format
2724   // These intrinsics take an unsigned 4 bit immediate.
2725   case Mips::BI__builtin_msa_copy_s_b:
2726   case Mips::BI__builtin_msa_copy_u_b:
2727   case Mips::BI__builtin_msa_insve_b:
2728   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
2729   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
2730   // These intrinsics take an unsigned 3 bit immediate.
2731   case Mips::BI__builtin_msa_copy_s_h:
2732   case Mips::BI__builtin_msa_copy_u_h:
2733   case Mips::BI__builtin_msa_insve_h:
2734   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
2735   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
2736   // These intrinsics take an unsigned 2 bit immediate.
2737   case Mips::BI__builtin_msa_copy_s_w:
2738   case Mips::BI__builtin_msa_copy_u_w:
2739   case Mips::BI__builtin_msa_insve_w:
2740   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
2741   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
2742   // These intrinsics take an unsigned 1 bit immediate.
2743   case Mips::BI__builtin_msa_copy_s_d:
2744   case Mips::BI__builtin_msa_copy_u_d:
2745   case Mips::BI__builtin_msa_insve_d:
2746   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
2747   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
2748   // Memory offsets and immediate loads.
2749   // These intrinsics take a signed 10 bit immediate.
2750   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
2751   case Mips::BI__builtin_msa_ldi_h:
2752   case Mips::BI__builtin_msa_ldi_w:
2753   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
2754   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
2755   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
2756   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
2757   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
2758   case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break;
2759   case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break;
2760   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
2761   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
2762   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
2763   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
2764   case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break;
2765   case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break;
2766   }
2767 
2768   if (!m)
2769     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2770 
2771   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
2772          SemaBuiltinConstantArgMultiple(TheCall, i, m);
2773 }
2774 
2775 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2776   unsigned i = 0, l = 0, u = 0;
2777   bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
2778                       BuiltinID == PPC::BI__builtin_divdeu ||
2779                       BuiltinID == PPC::BI__builtin_bpermd;
2780   bool IsTarget64Bit = Context.getTargetInfo()
2781                               .getTypeWidth(Context
2782                                             .getTargetInfo()
2783                                             .getIntPtrType()) == 64;
2784   bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
2785                        BuiltinID == PPC::BI__builtin_divweu ||
2786                        BuiltinID == PPC::BI__builtin_divde ||
2787                        BuiltinID == PPC::BI__builtin_divdeu;
2788 
2789   if (Is64BitBltin && !IsTarget64Bit)
2790     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
2791            << TheCall->getSourceRange();
2792 
2793   if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
2794       (BuiltinID == PPC::BI__builtin_bpermd &&
2795        !Context.getTargetInfo().hasFeature("bpermd")))
2796     return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
2797            << TheCall->getSourceRange();
2798 
2799   auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool {
2800     if (!Context.getTargetInfo().hasFeature("vsx"))
2801       return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
2802              << TheCall->getSourceRange();
2803     return false;
2804   };
2805 
2806   switch (BuiltinID) {
2807   default: return false;
2808   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
2809   case PPC::BI__builtin_altivec_crypto_vshasigmad:
2810     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2811            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
2812   case PPC::BI__builtin_altivec_dss:
2813     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
2814   case PPC::BI__builtin_tbegin:
2815   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
2816   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
2817   case PPC::BI__builtin_tabortwc:
2818   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
2819   case PPC::BI__builtin_tabortwci:
2820   case PPC::BI__builtin_tabortdci:
2821     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
2822            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
2823   case PPC::BI__builtin_altivec_dst:
2824   case PPC::BI__builtin_altivec_dstt:
2825   case PPC::BI__builtin_altivec_dstst:
2826   case PPC::BI__builtin_altivec_dststt:
2827     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
2828   case PPC::BI__builtin_vsx_xxpermdi:
2829   case PPC::BI__builtin_vsx_xxsldwi:
2830     return SemaBuiltinVSX(TheCall);
2831   case PPC::BI__builtin_unpack_vector_int128:
2832     return SemaVSXCheck(TheCall) ||
2833            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
2834   case PPC::BI__builtin_pack_vector_int128:
2835     return SemaVSXCheck(TheCall);
2836   }
2837   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2838 }
2839 
2840 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
2841                                            CallExpr *TheCall) {
2842   if (BuiltinID == SystemZ::BI__builtin_tabort) {
2843     Expr *Arg = TheCall->getArg(0);
2844     llvm::APSInt AbortCode(32);
2845     if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
2846         AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
2847       return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
2848              << Arg->getSourceRange();
2849   }
2850 
2851   // For intrinsics which take an immediate value as part of the instruction,
2852   // range check them here.
2853   unsigned i = 0, l = 0, u = 0;
2854   switch (BuiltinID) {
2855   default: return false;
2856   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
2857   case SystemZ::BI__builtin_s390_verimb:
2858   case SystemZ::BI__builtin_s390_verimh:
2859   case SystemZ::BI__builtin_s390_verimf:
2860   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
2861   case SystemZ::BI__builtin_s390_vfaeb:
2862   case SystemZ::BI__builtin_s390_vfaeh:
2863   case SystemZ::BI__builtin_s390_vfaef:
2864   case SystemZ::BI__builtin_s390_vfaebs:
2865   case SystemZ::BI__builtin_s390_vfaehs:
2866   case SystemZ::BI__builtin_s390_vfaefs:
2867   case SystemZ::BI__builtin_s390_vfaezb:
2868   case SystemZ::BI__builtin_s390_vfaezh:
2869   case SystemZ::BI__builtin_s390_vfaezf:
2870   case SystemZ::BI__builtin_s390_vfaezbs:
2871   case SystemZ::BI__builtin_s390_vfaezhs:
2872   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
2873   case SystemZ::BI__builtin_s390_vfisb:
2874   case SystemZ::BI__builtin_s390_vfidb:
2875     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
2876            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
2877   case SystemZ::BI__builtin_s390_vftcisb:
2878   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
2879   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
2880   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
2881   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
2882   case SystemZ::BI__builtin_s390_vstrcb:
2883   case SystemZ::BI__builtin_s390_vstrch:
2884   case SystemZ::BI__builtin_s390_vstrcf:
2885   case SystemZ::BI__builtin_s390_vstrczb:
2886   case SystemZ::BI__builtin_s390_vstrczh:
2887   case SystemZ::BI__builtin_s390_vstrczf:
2888   case SystemZ::BI__builtin_s390_vstrcbs:
2889   case SystemZ::BI__builtin_s390_vstrchs:
2890   case SystemZ::BI__builtin_s390_vstrcfs:
2891   case SystemZ::BI__builtin_s390_vstrczbs:
2892   case SystemZ::BI__builtin_s390_vstrczhs:
2893   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
2894   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
2895   case SystemZ::BI__builtin_s390_vfminsb:
2896   case SystemZ::BI__builtin_s390_vfmaxsb:
2897   case SystemZ::BI__builtin_s390_vfmindb:
2898   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
2899   case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
2900   case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
2901   }
2902   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2903 }
2904 
2905 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
2906 /// This checks that the target supports __builtin_cpu_supports and
2907 /// that the string argument is constant and valid.
2908 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
2909   Expr *Arg = TheCall->getArg(0);
2910 
2911   // Check if the argument is a string literal.
2912   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
2913     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
2914            << Arg->getSourceRange();
2915 
2916   // Check the contents of the string.
2917   StringRef Feature =
2918       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
2919   if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
2920     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
2921            << Arg->getSourceRange();
2922   return false;
2923 }
2924 
2925 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
2926 /// This checks that the target supports __builtin_cpu_is and
2927 /// that the string argument is constant and valid.
2928 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
2929   Expr *Arg = TheCall->getArg(0);
2930 
2931   // Check if the argument is a string literal.
2932   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
2933     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
2934            << Arg->getSourceRange();
2935 
2936   // Check the contents of the string.
2937   StringRef Feature =
2938       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
2939   if (!S.Context.getTargetInfo().validateCpuIs(Feature))
2940     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
2941            << Arg->getSourceRange();
2942   return false;
2943 }
2944 
2945 // Check if the rounding mode is legal.
2946 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
2947   // Indicates if this instruction has rounding control or just SAE.
2948   bool HasRC = false;
2949 
2950   unsigned ArgNum = 0;
2951   switch (BuiltinID) {
2952   default:
2953     return false;
2954   case X86::BI__builtin_ia32_vcvttsd2si32:
2955   case X86::BI__builtin_ia32_vcvttsd2si64:
2956   case X86::BI__builtin_ia32_vcvttsd2usi32:
2957   case X86::BI__builtin_ia32_vcvttsd2usi64:
2958   case X86::BI__builtin_ia32_vcvttss2si32:
2959   case X86::BI__builtin_ia32_vcvttss2si64:
2960   case X86::BI__builtin_ia32_vcvttss2usi32:
2961   case X86::BI__builtin_ia32_vcvttss2usi64:
2962     ArgNum = 1;
2963     break;
2964   case X86::BI__builtin_ia32_maxpd512:
2965   case X86::BI__builtin_ia32_maxps512:
2966   case X86::BI__builtin_ia32_minpd512:
2967   case X86::BI__builtin_ia32_minps512:
2968     ArgNum = 2;
2969     break;
2970   case X86::BI__builtin_ia32_cvtps2pd512_mask:
2971   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
2972   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
2973   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
2974   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
2975   case X86::BI__builtin_ia32_cvttps2dq512_mask:
2976   case X86::BI__builtin_ia32_cvttps2qq512_mask:
2977   case X86::BI__builtin_ia32_cvttps2udq512_mask:
2978   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
2979   case X86::BI__builtin_ia32_exp2pd_mask:
2980   case X86::BI__builtin_ia32_exp2ps_mask:
2981   case X86::BI__builtin_ia32_getexppd512_mask:
2982   case X86::BI__builtin_ia32_getexpps512_mask:
2983   case X86::BI__builtin_ia32_rcp28pd_mask:
2984   case X86::BI__builtin_ia32_rcp28ps_mask:
2985   case X86::BI__builtin_ia32_rsqrt28pd_mask:
2986   case X86::BI__builtin_ia32_rsqrt28ps_mask:
2987   case X86::BI__builtin_ia32_vcomisd:
2988   case X86::BI__builtin_ia32_vcomiss:
2989   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
2990     ArgNum = 3;
2991     break;
2992   case X86::BI__builtin_ia32_cmppd512_mask:
2993   case X86::BI__builtin_ia32_cmpps512_mask:
2994   case X86::BI__builtin_ia32_cmpsd_mask:
2995   case X86::BI__builtin_ia32_cmpss_mask:
2996   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
2997   case X86::BI__builtin_ia32_getexpsd128_round_mask:
2998   case X86::BI__builtin_ia32_getexpss128_round_mask:
2999   case X86::BI__builtin_ia32_getmantpd512_mask:
3000   case X86::BI__builtin_ia32_getmantps512_mask:
3001   case X86::BI__builtin_ia32_maxsd_round_mask:
3002   case X86::BI__builtin_ia32_maxss_round_mask:
3003   case X86::BI__builtin_ia32_minsd_round_mask:
3004   case X86::BI__builtin_ia32_minss_round_mask:
3005   case X86::BI__builtin_ia32_rcp28sd_round_mask:
3006   case X86::BI__builtin_ia32_rcp28ss_round_mask:
3007   case X86::BI__builtin_ia32_reducepd512_mask:
3008   case X86::BI__builtin_ia32_reduceps512_mask:
3009   case X86::BI__builtin_ia32_rndscalepd_mask:
3010   case X86::BI__builtin_ia32_rndscaleps_mask:
3011   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
3012   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
3013     ArgNum = 4;
3014     break;
3015   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3016   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3017   case X86::BI__builtin_ia32_fixupimmps512_mask:
3018   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3019   case X86::BI__builtin_ia32_fixupimmsd_mask:
3020   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3021   case X86::BI__builtin_ia32_fixupimmss_mask:
3022   case X86::BI__builtin_ia32_fixupimmss_maskz:
3023   case X86::BI__builtin_ia32_getmantsd_round_mask:
3024   case X86::BI__builtin_ia32_getmantss_round_mask:
3025   case X86::BI__builtin_ia32_rangepd512_mask:
3026   case X86::BI__builtin_ia32_rangeps512_mask:
3027   case X86::BI__builtin_ia32_rangesd128_round_mask:
3028   case X86::BI__builtin_ia32_rangess128_round_mask:
3029   case X86::BI__builtin_ia32_reducesd_mask:
3030   case X86::BI__builtin_ia32_reducess_mask:
3031   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3032   case X86::BI__builtin_ia32_rndscaless_round_mask:
3033     ArgNum = 5;
3034     break;
3035   case X86::BI__builtin_ia32_vcvtsd2si64:
3036   case X86::BI__builtin_ia32_vcvtsd2si32:
3037   case X86::BI__builtin_ia32_vcvtsd2usi32:
3038   case X86::BI__builtin_ia32_vcvtsd2usi64:
3039   case X86::BI__builtin_ia32_vcvtss2si32:
3040   case X86::BI__builtin_ia32_vcvtss2si64:
3041   case X86::BI__builtin_ia32_vcvtss2usi32:
3042   case X86::BI__builtin_ia32_vcvtss2usi64:
3043   case X86::BI__builtin_ia32_sqrtpd512:
3044   case X86::BI__builtin_ia32_sqrtps512:
3045     ArgNum = 1;
3046     HasRC = true;
3047     break;
3048   case X86::BI__builtin_ia32_addpd512:
3049   case X86::BI__builtin_ia32_addps512:
3050   case X86::BI__builtin_ia32_divpd512:
3051   case X86::BI__builtin_ia32_divps512:
3052   case X86::BI__builtin_ia32_mulpd512:
3053   case X86::BI__builtin_ia32_mulps512:
3054   case X86::BI__builtin_ia32_subpd512:
3055   case X86::BI__builtin_ia32_subps512:
3056   case X86::BI__builtin_ia32_cvtsi2sd64:
3057   case X86::BI__builtin_ia32_cvtsi2ss32:
3058   case X86::BI__builtin_ia32_cvtsi2ss64:
3059   case X86::BI__builtin_ia32_cvtusi2sd64:
3060   case X86::BI__builtin_ia32_cvtusi2ss32:
3061   case X86::BI__builtin_ia32_cvtusi2ss64:
3062     ArgNum = 2;
3063     HasRC = true;
3064     break;
3065   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
3066   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
3067   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
3068   case X86::BI__builtin_ia32_cvtpd2dq512_mask:
3069   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
3070   case X86::BI__builtin_ia32_cvtpd2udq512_mask:
3071   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
3072   case X86::BI__builtin_ia32_cvtps2dq512_mask:
3073   case X86::BI__builtin_ia32_cvtps2qq512_mask:
3074   case X86::BI__builtin_ia32_cvtps2udq512_mask:
3075   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
3076   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
3077   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
3078   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
3079   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
3080     ArgNum = 3;
3081     HasRC = true;
3082     break;
3083   case X86::BI__builtin_ia32_addss_round_mask:
3084   case X86::BI__builtin_ia32_addsd_round_mask:
3085   case X86::BI__builtin_ia32_divss_round_mask:
3086   case X86::BI__builtin_ia32_divsd_round_mask:
3087   case X86::BI__builtin_ia32_mulss_round_mask:
3088   case X86::BI__builtin_ia32_mulsd_round_mask:
3089   case X86::BI__builtin_ia32_subss_round_mask:
3090   case X86::BI__builtin_ia32_subsd_round_mask:
3091   case X86::BI__builtin_ia32_scalefpd512_mask:
3092   case X86::BI__builtin_ia32_scalefps512_mask:
3093   case X86::BI__builtin_ia32_scalefsd_round_mask:
3094   case X86::BI__builtin_ia32_scalefss_round_mask:
3095   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
3096   case X86::BI__builtin_ia32_sqrtsd_round_mask:
3097   case X86::BI__builtin_ia32_sqrtss_round_mask:
3098   case X86::BI__builtin_ia32_vfmaddsd3_mask:
3099   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
3100   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
3101   case X86::BI__builtin_ia32_vfmaddss3_mask:
3102   case X86::BI__builtin_ia32_vfmaddss3_maskz:
3103   case X86::BI__builtin_ia32_vfmaddss3_mask3:
3104   case X86::BI__builtin_ia32_vfmaddpd512_mask:
3105   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
3106   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
3107   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
3108   case X86::BI__builtin_ia32_vfmaddps512_mask:
3109   case X86::BI__builtin_ia32_vfmaddps512_maskz:
3110   case X86::BI__builtin_ia32_vfmaddps512_mask3:
3111   case X86::BI__builtin_ia32_vfmsubps512_mask3:
3112   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
3113   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
3114   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
3115   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
3116   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
3117   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
3118   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
3119   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
3120     ArgNum = 4;
3121     HasRC = true;
3122     break;
3123   }
3124 
3125   llvm::APSInt Result;
3126 
3127   // We can't check the value of a dependent argument.
3128   Expr *Arg = TheCall->getArg(ArgNum);
3129   if (Arg->isTypeDependent() || Arg->isValueDependent())
3130     return false;
3131 
3132   // Check constant-ness first.
3133   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3134     return true;
3135 
3136   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
3137   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
3138   // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
3139   // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
3140   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
3141       Result == 8/*ROUND_NO_EXC*/ ||
3142       (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
3143       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
3144     return false;
3145 
3146   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
3147          << Arg->getSourceRange();
3148 }
3149 
3150 // Check if the gather/scatter scale is legal.
3151 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
3152                                              CallExpr *TheCall) {
3153   unsigned ArgNum = 0;
3154   switch (BuiltinID) {
3155   default:
3156     return false;
3157   case X86::BI__builtin_ia32_gatherpfdpd:
3158   case X86::BI__builtin_ia32_gatherpfdps:
3159   case X86::BI__builtin_ia32_gatherpfqpd:
3160   case X86::BI__builtin_ia32_gatherpfqps:
3161   case X86::BI__builtin_ia32_scatterpfdpd:
3162   case X86::BI__builtin_ia32_scatterpfdps:
3163   case X86::BI__builtin_ia32_scatterpfqpd:
3164   case X86::BI__builtin_ia32_scatterpfqps:
3165     ArgNum = 3;
3166     break;
3167   case X86::BI__builtin_ia32_gatherd_pd:
3168   case X86::BI__builtin_ia32_gatherd_pd256:
3169   case X86::BI__builtin_ia32_gatherq_pd:
3170   case X86::BI__builtin_ia32_gatherq_pd256:
3171   case X86::BI__builtin_ia32_gatherd_ps:
3172   case X86::BI__builtin_ia32_gatherd_ps256:
3173   case X86::BI__builtin_ia32_gatherq_ps:
3174   case X86::BI__builtin_ia32_gatherq_ps256:
3175   case X86::BI__builtin_ia32_gatherd_q:
3176   case X86::BI__builtin_ia32_gatherd_q256:
3177   case X86::BI__builtin_ia32_gatherq_q:
3178   case X86::BI__builtin_ia32_gatherq_q256:
3179   case X86::BI__builtin_ia32_gatherd_d:
3180   case X86::BI__builtin_ia32_gatherd_d256:
3181   case X86::BI__builtin_ia32_gatherq_d:
3182   case X86::BI__builtin_ia32_gatherq_d256:
3183   case X86::BI__builtin_ia32_gather3div2df:
3184   case X86::BI__builtin_ia32_gather3div2di:
3185   case X86::BI__builtin_ia32_gather3div4df:
3186   case X86::BI__builtin_ia32_gather3div4di:
3187   case X86::BI__builtin_ia32_gather3div4sf:
3188   case X86::BI__builtin_ia32_gather3div4si:
3189   case X86::BI__builtin_ia32_gather3div8sf:
3190   case X86::BI__builtin_ia32_gather3div8si:
3191   case X86::BI__builtin_ia32_gather3siv2df:
3192   case X86::BI__builtin_ia32_gather3siv2di:
3193   case X86::BI__builtin_ia32_gather3siv4df:
3194   case X86::BI__builtin_ia32_gather3siv4di:
3195   case X86::BI__builtin_ia32_gather3siv4sf:
3196   case X86::BI__builtin_ia32_gather3siv4si:
3197   case X86::BI__builtin_ia32_gather3siv8sf:
3198   case X86::BI__builtin_ia32_gather3siv8si:
3199   case X86::BI__builtin_ia32_gathersiv8df:
3200   case X86::BI__builtin_ia32_gathersiv16sf:
3201   case X86::BI__builtin_ia32_gatherdiv8df:
3202   case X86::BI__builtin_ia32_gatherdiv16sf:
3203   case X86::BI__builtin_ia32_gathersiv8di:
3204   case X86::BI__builtin_ia32_gathersiv16si:
3205   case X86::BI__builtin_ia32_gatherdiv8di:
3206   case X86::BI__builtin_ia32_gatherdiv16si:
3207   case X86::BI__builtin_ia32_scatterdiv2df:
3208   case X86::BI__builtin_ia32_scatterdiv2di:
3209   case X86::BI__builtin_ia32_scatterdiv4df:
3210   case X86::BI__builtin_ia32_scatterdiv4di:
3211   case X86::BI__builtin_ia32_scatterdiv4sf:
3212   case X86::BI__builtin_ia32_scatterdiv4si:
3213   case X86::BI__builtin_ia32_scatterdiv8sf:
3214   case X86::BI__builtin_ia32_scatterdiv8si:
3215   case X86::BI__builtin_ia32_scattersiv2df:
3216   case X86::BI__builtin_ia32_scattersiv2di:
3217   case X86::BI__builtin_ia32_scattersiv4df:
3218   case X86::BI__builtin_ia32_scattersiv4di:
3219   case X86::BI__builtin_ia32_scattersiv4sf:
3220   case X86::BI__builtin_ia32_scattersiv4si:
3221   case X86::BI__builtin_ia32_scattersiv8sf:
3222   case X86::BI__builtin_ia32_scattersiv8si:
3223   case X86::BI__builtin_ia32_scattersiv8df:
3224   case X86::BI__builtin_ia32_scattersiv16sf:
3225   case X86::BI__builtin_ia32_scatterdiv8df:
3226   case X86::BI__builtin_ia32_scatterdiv16sf:
3227   case X86::BI__builtin_ia32_scattersiv8di:
3228   case X86::BI__builtin_ia32_scattersiv16si:
3229   case X86::BI__builtin_ia32_scatterdiv8di:
3230   case X86::BI__builtin_ia32_scatterdiv16si:
3231     ArgNum = 4;
3232     break;
3233   }
3234 
3235   llvm::APSInt Result;
3236 
3237   // We can't check the value of a dependent argument.
3238   Expr *Arg = TheCall->getArg(ArgNum);
3239   if (Arg->isTypeDependent() || Arg->isValueDependent())
3240     return false;
3241 
3242   // Check constant-ness first.
3243   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3244     return true;
3245 
3246   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
3247     return false;
3248 
3249   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
3250          << Arg->getSourceRange();
3251 }
3252 
3253 static bool isX86_32Builtin(unsigned BuiltinID) {
3254   // These builtins only work on x86-32 targets.
3255   switch (BuiltinID) {
3256   case X86::BI__builtin_ia32_readeflags_u32:
3257   case X86::BI__builtin_ia32_writeeflags_u32:
3258     return true;
3259   }
3260 
3261   return false;
3262 }
3263 
3264 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3265   if (BuiltinID == X86::BI__builtin_cpu_supports)
3266     return SemaBuiltinCpuSupports(*this, TheCall);
3267 
3268   if (BuiltinID == X86::BI__builtin_cpu_is)
3269     return SemaBuiltinCpuIs(*this, TheCall);
3270 
3271   // Check for 32-bit only builtins on a 64-bit target.
3272   const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3273   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
3274     return Diag(TheCall->getCallee()->getBeginLoc(),
3275                 diag::err_32_bit_builtin_64_bit_tgt);
3276 
3277   // If the intrinsic has rounding or SAE make sure its valid.
3278   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
3279     return true;
3280 
3281   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
3282   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
3283     return true;
3284 
3285   // For intrinsics which take an immediate value as part of the instruction,
3286   // range check them here.
3287   int i = 0, l = 0, u = 0;
3288   switch (BuiltinID) {
3289   default:
3290     return false;
3291   case X86::BI__builtin_ia32_vec_ext_v2si:
3292   case X86::BI__builtin_ia32_vec_ext_v2di:
3293   case X86::BI__builtin_ia32_vextractf128_pd256:
3294   case X86::BI__builtin_ia32_vextractf128_ps256:
3295   case X86::BI__builtin_ia32_vextractf128_si256:
3296   case X86::BI__builtin_ia32_extract128i256:
3297   case X86::BI__builtin_ia32_extractf64x4_mask:
3298   case X86::BI__builtin_ia32_extracti64x4_mask:
3299   case X86::BI__builtin_ia32_extractf32x8_mask:
3300   case X86::BI__builtin_ia32_extracti32x8_mask:
3301   case X86::BI__builtin_ia32_extractf64x2_256_mask:
3302   case X86::BI__builtin_ia32_extracti64x2_256_mask:
3303   case X86::BI__builtin_ia32_extractf32x4_256_mask:
3304   case X86::BI__builtin_ia32_extracti32x4_256_mask:
3305     i = 1; l = 0; u = 1;
3306     break;
3307   case X86::BI__builtin_ia32_vec_set_v2di:
3308   case X86::BI__builtin_ia32_vinsertf128_pd256:
3309   case X86::BI__builtin_ia32_vinsertf128_ps256:
3310   case X86::BI__builtin_ia32_vinsertf128_si256:
3311   case X86::BI__builtin_ia32_insert128i256:
3312   case X86::BI__builtin_ia32_insertf32x8:
3313   case X86::BI__builtin_ia32_inserti32x8:
3314   case X86::BI__builtin_ia32_insertf64x4:
3315   case X86::BI__builtin_ia32_inserti64x4:
3316   case X86::BI__builtin_ia32_insertf64x2_256:
3317   case X86::BI__builtin_ia32_inserti64x2_256:
3318   case X86::BI__builtin_ia32_insertf32x4_256:
3319   case X86::BI__builtin_ia32_inserti32x4_256:
3320     i = 2; l = 0; u = 1;
3321     break;
3322   case X86::BI__builtin_ia32_vpermilpd:
3323   case X86::BI__builtin_ia32_vec_ext_v4hi:
3324   case X86::BI__builtin_ia32_vec_ext_v4si:
3325   case X86::BI__builtin_ia32_vec_ext_v4sf:
3326   case X86::BI__builtin_ia32_vec_ext_v4di:
3327   case X86::BI__builtin_ia32_extractf32x4_mask:
3328   case X86::BI__builtin_ia32_extracti32x4_mask:
3329   case X86::BI__builtin_ia32_extractf64x2_512_mask:
3330   case X86::BI__builtin_ia32_extracti64x2_512_mask:
3331     i = 1; l = 0; u = 3;
3332     break;
3333   case X86::BI_mm_prefetch:
3334   case X86::BI__builtin_ia32_vec_ext_v8hi:
3335   case X86::BI__builtin_ia32_vec_ext_v8si:
3336     i = 1; l = 0; u = 7;
3337     break;
3338   case X86::BI__builtin_ia32_sha1rnds4:
3339   case X86::BI__builtin_ia32_blendpd:
3340   case X86::BI__builtin_ia32_shufpd:
3341   case X86::BI__builtin_ia32_vec_set_v4hi:
3342   case X86::BI__builtin_ia32_vec_set_v4si:
3343   case X86::BI__builtin_ia32_vec_set_v4di:
3344   case X86::BI__builtin_ia32_shuf_f32x4_256:
3345   case X86::BI__builtin_ia32_shuf_f64x2_256:
3346   case X86::BI__builtin_ia32_shuf_i32x4_256:
3347   case X86::BI__builtin_ia32_shuf_i64x2_256:
3348   case X86::BI__builtin_ia32_insertf64x2_512:
3349   case X86::BI__builtin_ia32_inserti64x2_512:
3350   case X86::BI__builtin_ia32_insertf32x4:
3351   case X86::BI__builtin_ia32_inserti32x4:
3352     i = 2; l = 0; u = 3;
3353     break;
3354   case X86::BI__builtin_ia32_vpermil2pd:
3355   case X86::BI__builtin_ia32_vpermil2pd256:
3356   case X86::BI__builtin_ia32_vpermil2ps:
3357   case X86::BI__builtin_ia32_vpermil2ps256:
3358     i = 3; l = 0; u = 3;
3359     break;
3360   case X86::BI__builtin_ia32_cmpb128_mask:
3361   case X86::BI__builtin_ia32_cmpw128_mask:
3362   case X86::BI__builtin_ia32_cmpd128_mask:
3363   case X86::BI__builtin_ia32_cmpq128_mask:
3364   case X86::BI__builtin_ia32_cmpb256_mask:
3365   case X86::BI__builtin_ia32_cmpw256_mask:
3366   case X86::BI__builtin_ia32_cmpd256_mask:
3367   case X86::BI__builtin_ia32_cmpq256_mask:
3368   case X86::BI__builtin_ia32_cmpb512_mask:
3369   case X86::BI__builtin_ia32_cmpw512_mask:
3370   case X86::BI__builtin_ia32_cmpd512_mask:
3371   case X86::BI__builtin_ia32_cmpq512_mask:
3372   case X86::BI__builtin_ia32_ucmpb128_mask:
3373   case X86::BI__builtin_ia32_ucmpw128_mask:
3374   case X86::BI__builtin_ia32_ucmpd128_mask:
3375   case X86::BI__builtin_ia32_ucmpq128_mask:
3376   case X86::BI__builtin_ia32_ucmpb256_mask:
3377   case X86::BI__builtin_ia32_ucmpw256_mask:
3378   case X86::BI__builtin_ia32_ucmpd256_mask:
3379   case X86::BI__builtin_ia32_ucmpq256_mask:
3380   case X86::BI__builtin_ia32_ucmpb512_mask:
3381   case X86::BI__builtin_ia32_ucmpw512_mask:
3382   case X86::BI__builtin_ia32_ucmpd512_mask:
3383   case X86::BI__builtin_ia32_ucmpq512_mask:
3384   case X86::BI__builtin_ia32_vpcomub:
3385   case X86::BI__builtin_ia32_vpcomuw:
3386   case X86::BI__builtin_ia32_vpcomud:
3387   case X86::BI__builtin_ia32_vpcomuq:
3388   case X86::BI__builtin_ia32_vpcomb:
3389   case X86::BI__builtin_ia32_vpcomw:
3390   case X86::BI__builtin_ia32_vpcomd:
3391   case X86::BI__builtin_ia32_vpcomq:
3392   case X86::BI__builtin_ia32_vec_set_v8hi:
3393   case X86::BI__builtin_ia32_vec_set_v8si:
3394     i = 2; l = 0; u = 7;
3395     break;
3396   case X86::BI__builtin_ia32_vpermilpd256:
3397   case X86::BI__builtin_ia32_roundps:
3398   case X86::BI__builtin_ia32_roundpd:
3399   case X86::BI__builtin_ia32_roundps256:
3400   case X86::BI__builtin_ia32_roundpd256:
3401   case X86::BI__builtin_ia32_getmantpd128_mask:
3402   case X86::BI__builtin_ia32_getmantpd256_mask:
3403   case X86::BI__builtin_ia32_getmantps128_mask:
3404   case X86::BI__builtin_ia32_getmantps256_mask:
3405   case X86::BI__builtin_ia32_getmantpd512_mask:
3406   case X86::BI__builtin_ia32_getmantps512_mask:
3407   case X86::BI__builtin_ia32_vec_ext_v16qi:
3408   case X86::BI__builtin_ia32_vec_ext_v16hi:
3409     i = 1; l = 0; u = 15;
3410     break;
3411   case X86::BI__builtin_ia32_pblendd128:
3412   case X86::BI__builtin_ia32_blendps:
3413   case X86::BI__builtin_ia32_blendpd256:
3414   case X86::BI__builtin_ia32_shufpd256:
3415   case X86::BI__builtin_ia32_roundss:
3416   case X86::BI__builtin_ia32_roundsd:
3417   case X86::BI__builtin_ia32_rangepd128_mask:
3418   case X86::BI__builtin_ia32_rangepd256_mask:
3419   case X86::BI__builtin_ia32_rangepd512_mask:
3420   case X86::BI__builtin_ia32_rangeps128_mask:
3421   case X86::BI__builtin_ia32_rangeps256_mask:
3422   case X86::BI__builtin_ia32_rangeps512_mask:
3423   case X86::BI__builtin_ia32_getmantsd_round_mask:
3424   case X86::BI__builtin_ia32_getmantss_round_mask:
3425   case X86::BI__builtin_ia32_vec_set_v16qi:
3426   case X86::BI__builtin_ia32_vec_set_v16hi:
3427     i = 2; l = 0; u = 15;
3428     break;
3429   case X86::BI__builtin_ia32_vec_ext_v32qi:
3430     i = 1; l = 0; u = 31;
3431     break;
3432   case X86::BI__builtin_ia32_cmpps:
3433   case X86::BI__builtin_ia32_cmpss:
3434   case X86::BI__builtin_ia32_cmppd:
3435   case X86::BI__builtin_ia32_cmpsd:
3436   case X86::BI__builtin_ia32_cmpps256:
3437   case X86::BI__builtin_ia32_cmppd256:
3438   case X86::BI__builtin_ia32_cmpps128_mask:
3439   case X86::BI__builtin_ia32_cmppd128_mask:
3440   case X86::BI__builtin_ia32_cmpps256_mask:
3441   case X86::BI__builtin_ia32_cmppd256_mask:
3442   case X86::BI__builtin_ia32_cmpps512_mask:
3443   case X86::BI__builtin_ia32_cmppd512_mask:
3444   case X86::BI__builtin_ia32_cmpsd_mask:
3445   case X86::BI__builtin_ia32_cmpss_mask:
3446   case X86::BI__builtin_ia32_vec_set_v32qi:
3447     i = 2; l = 0; u = 31;
3448     break;
3449   case X86::BI__builtin_ia32_permdf256:
3450   case X86::BI__builtin_ia32_permdi256:
3451   case X86::BI__builtin_ia32_permdf512:
3452   case X86::BI__builtin_ia32_permdi512:
3453   case X86::BI__builtin_ia32_vpermilps:
3454   case X86::BI__builtin_ia32_vpermilps256:
3455   case X86::BI__builtin_ia32_vpermilpd512:
3456   case X86::BI__builtin_ia32_vpermilps512:
3457   case X86::BI__builtin_ia32_pshufd:
3458   case X86::BI__builtin_ia32_pshufd256:
3459   case X86::BI__builtin_ia32_pshufd512:
3460   case X86::BI__builtin_ia32_pshufhw:
3461   case X86::BI__builtin_ia32_pshufhw256:
3462   case X86::BI__builtin_ia32_pshufhw512:
3463   case X86::BI__builtin_ia32_pshuflw:
3464   case X86::BI__builtin_ia32_pshuflw256:
3465   case X86::BI__builtin_ia32_pshuflw512:
3466   case X86::BI__builtin_ia32_vcvtps2ph:
3467   case X86::BI__builtin_ia32_vcvtps2ph_mask:
3468   case X86::BI__builtin_ia32_vcvtps2ph256:
3469   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
3470   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
3471   case X86::BI__builtin_ia32_rndscaleps_128_mask:
3472   case X86::BI__builtin_ia32_rndscalepd_128_mask:
3473   case X86::BI__builtin_ia32_rndscaleps_256_mask:
3474   case X86::BI__builtin_ia32_rndscalepd_256_mask:
3475   case X86::BI__builtin_ia32_rndscaleps_mask:
3476   case X86::BI__builtin_ia32_rndscalepd_mask:
3477   case X86::BI__builtin_ia32_reducepd128_mask:
3478   case X86::BI__builtin_ia32_reducepd256_mask:
3479   case X86::BI__builtin_ia32_reducepd512_mask:
3480   case X86::BI__builtin_ia32_reduceps128_mask:
3481   case X86::BI__builtin_ia32_reduceps256_mask:
3482   case X86::BI__builtin_ia32_reduceps512_mask:
3483   case X86::BI__builtin_ia32_prold512:
3484   case X86::BI__builtin_ia32_prolq512:
3485   case X86::BI__builtin_ia32_prold128:
3486   case X86::BI__builtin_ia32_prold256:
3487   case X86::BI__builtin_ia32_prolq128:
3488   case X86::BI__builtin_ia32_prolq256:
3489   case X86::BI__builtin_ia32_prord512:
3490   case X86::BI__builtin_ia32_prorq512:
3491   case X86::BI__builtin_ia32_prord128:
3492   case X86::BI__builtin_ia32_prord256:
3493   case X86::BI__builtin_ia32_prorq128:
3494   case X86::BI__builtin_ia32_prorq256:
3495   case X86::BI__builtin_ia32_fpclasspd128_mask:
3496   case X86::BI__builtin_ia32_fpclasspd256_mask:
3497   case X86::BI__builtin_ia32_fpclassps128_mask:
3498   case X86::BI__builtin_ia32_fpclassps256_mask:
3499   case X86::BI__builtin_ia32_fpclassps512_mask:
3500   case X86::BI__builtin_ia32_fpclasspd512_mask:
3501   case X86::BI__builtin_ia32_fpclasssd_mask:
3502   case X86::BI__builtin_ia32_fpclassss_mask:
3503   case X86::BI__builtin_ia32_pslldqi128_byteshift:
3504   case X86::BI__builtin_ia32_pslldqi256_byteshift:
3505   case X86::BI__builtin_ia32_pslldqi512_byteshift:
3506   case X86::BI__builtin_ia32_psrldqi128_byteshift:
3507   case X86::BI__builtin_ia32_psrldqi256_byteshift:
3508   case X86::BI__builtin_ia32_psrldqi512_byteshift:
3509   case X86::BI__builtin_ia32_kshiftliqi:
3510   case X86::BI__builtin_ia32_kshiftlihi:
3511   case X86::BI__builtin_ia32_kshiftlisi:
3512   case X86::BI__builtin_ia32_kshiftlidi:
3513   case X86::BI__builtin_ia32_kshiftriqi:
3514   case X86::BI__builtin_ia32_kshiftrihi:
3515   case X86::BI__builtin_ia32_kshiftrisi:
3516   case X86::BI__builtin_ia32_kshiftridi:
3517     i = 1; l = 0; u = 255;
3518     break;
3519   case X86::BI__builtin_ia32_vperm2f128_pd256:
3520   case X86::BI__builtin_ia32_vperm2f128_ps256:
3521   case X86::BI__builtin_ia32_vperm2f128_si256:
3522   case X86::BI__builtin_ia32_permti256:
3523   case X86::BI__builtin_ia32_pblendw128:
3524   case X86::BI__builtin_ia32_pblendw256:
3525   case X86::BI__builtin_ia32_blendps256:
3526   case X86::BI__builtin_ia32_pblendd256:
3527   case X86::BI__builtin_ia32_palignr128:
3528   case X86::BI__builtin_ia32_palignr256:
3529   case X86::BI__builtin_ia32_palignr512:
3530   case X86::BI__builtin_ia32_alignq512:
3531   case X86::BI__builtin_ia32_alignd512:
3532   case X86::BI__builtin_ia32_alignd128:
3533   case X86::BI__builtin_ia32_alignd256:
3534   case X86::BI__builtin_ia32_alignq128:
3535   case X86::BI__builtin_ia32_alignq256:
3536   case X86::BI__builtin_ia32_vcomisd:
3537   case X86::BI__builtin_ia32_vcomiss:
3538   case X86::BI__builtin_ia32_shuf_f32x4:
3539   case X86::BI__builtin_ia32_shuf_f64x2:
3540   case X86::BI__builtin_ia32_shuf_i32x4:
3541   case X86::BI__builtin_ia32_shuf_i64x2:
3542   case X86::BI__builtin_ia32_shufpd512:
3543   case X86::BI__builtin_ia32_shufps:
3544   case X86::BI__builtin_ia32_shufps256:
3545   case X86::BI__builtin_ia32_shufps512:
3546   case X86::BI__builtin_ia32_dbpsadbw128:
3547   case X86::BI__builtin_ia32_dbpsadbw256:
3548   case X86::BI__builtin_ia32_dbpsadbw512:
3549   case X86::BI__builtin_ia32_vpshldd128:
3550   case X86::BI__builtin_ia32_vpshldd256:
3551   case X86::BI__builtin_ia32_vpshldd512:
3552   case X86::BI__builtin_ia32_vpshldq128:
3553   case X86::BI__builtin_ia32_vpshldq256:
3554   case X86::BI__builtin_ia32_vpshldq512:
3555   case X86::BI__builtin_ia32_vpshldw128:
3556   case X86::BI__builtin_ia32_vpshldw256:
3557   case X86::BI__builtin_ia32_vpshldw512:
3558   case X86::BI__builtin_ia32_vpshrdd128:
3559   case X86::BI__builtin_ia32_vpshrdd256:
3560   case X86::BI__builtin_ia32_vpshrdd512:
3561   case X86::BI__builtin_ia32_vpshrdq128:
3562   case X86::BI__builtin_ia32_vpshrdq256:
3563   case X86::BI__builtin_ia32_vpshrdq512:
3564   case X86::BI__builtin_ia32_vpshrdw128:
3565   case X86::BI__builtin_ia32_vpshrdw256:
3566   case X86::BI__builtin_ia32_vpshrdw512:
3567     i = 2; l = 0; u = 255;
3568     break;
3569   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3570   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3571   case X86::BI__builtin_ia32_fixupimmps512_mask:
3572   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3573   case X86::BI__builtin_ia32_fixupimmsd_mask:
3574   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3575   case X86::BI__builtin_ia32_fixupimmss_mask:
3576   case X86::BI__builtin_ia32_fixupimmss_maskz:
3577   case X86::BI__builtin_ia32_fixupimmpd128_mask:
3578   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
3579   case X86::BI__builtin_ia32_fixupimmpd256_mask:
3580   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
3581   case X86::BI__builtin_ia32_fixupimmps128_mask:
3582   case X86::BI__builtin_ia32_fixupimmps128_maskz:
3583   case X86::BI__builtin_ia32_fixupimmps256_mask:
3584   case X86::BI__builtin_ia32_fixupimmps256_maskz:
3585   case X86::BI__builtin_ia32_pternlogd512_mask:
3586   case X86::BI__builtin_ia32_pternlogd512_maskz:
3587   case X86::BI__builtin_ia32_pternlogq512_mask:
3588   case X86::BI__builtin_ia32_pternlogq512_maskz:
3589   case X86::BI__builtin_ia32_pternlogd128_mask:
3590   case X86::BI__builtin_ia32_pternlogd128_maskz:
3591   case X86::BI__builtin_ia32_pternlogd256_mask:
3592   case X86::BI__builtin_ia32_pternlogd256_maskz:
3593   case X86::BI__builtin_ia32_pternlogq128_mask:
3594   case X86::BI__builtin_ia32_pternlogq128_maskz:
3595   case X86::BI__builtin_ia32_pternlogq256_mask:
3596   case X86::BI__builtin_ia32_pternlogq256_maskz:
3597     i = 3; l = 0; u = 255;
3598     break;
3599   case X86::BI__builtin_ia32_gatherpfdpd:
3600   case X86::BI__builtin_ia32_gatherpfdps:
3601   case X86::BI__builtin_ia32_gatherpfqpd:
3602   case X86::BI__builtin_ia32_gatherpfqps:
3603   case X86::BI__builtin_ia32_scatterpfdpd:
3604   case X86::BI__builtin_ia32_scatterpfdps:
3605   case X86::BI__builtin_ia32_scatterpfqpd:
3606   case X86::BI__builtin_ia32_scatterpfqps:
3607     i = 4; l = 2; u = 3;
3608     break;
3609   case X86::BI__builtin_ia32_reducesd_mask:
3610   case X86::BI__builtin_ia32_reducess_mask:
3611   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3612   case X86::BI__builtin_ia32_rndscaless_round_mask:
3613     i = 4; l = 0; u = 255;
3614     break;
3615   }
3616 
3617   // Note that we don't force a hard error on the range check here, allowing
3618   // template-generated or macro-generated dead code to potentially have out-of-
3619   // range values. These need to code generate, but don't need to necessarily
3620   // make any sense. We use a warning that defaults to an error.
3621   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
3622 }
3623 
3624 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
3625 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
3626 /// Returns true when the format fits the function and the FormatStringInfo has
3627 /// been populated.
3628 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
3629                                FormatStringInfo *FSI) {
3630   FSI->HasVAListArg = Format->getFirstArg() == 0;
3631   FSI->FormatIdx = Format->getFormatIdx() - 1;
3632   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
3633 
3634   // The way the format attribute works in GCC, the implicit this argument
3635   // of member functions is counted. However, it doesn't appear in our own
3636   // lists, so decrement format_idx in that case.
3637   if (IsCXXMember) {
3638     if(FSI->FormatIdx == 0)
3639       return false;
3640     --FSI->FormatIdx;
3641     if (FSI->FirstDataArg != 0)
3642       --FSI->FirstDataArg;
3643   }
3644   return true;
3645 }
3646 
3647 /// Checks if a the given expression evaluates to null.
3648 ///
3649 /// Returns true if the value evaluates to null.
3650 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
3651   // If the expression has non-null type, it doesn't evaluate to null.
3652   if (auto nullability
3653         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
3654     if (*nullability == NullabilityKind::NonNull)
3655       return false;
3656   }
3657 
3658   // As a special case, transparent unions initialized with zero are
3659   // considered null for the purposes of the nonnull attribute.
3660   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
3661     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
3662       if (const CompoundLiteralExpr *CLE =
3663           dyn_cast<CompoundLiteralExpr>(Expr))
3664         if (const InitListExpr *ILE =
3665             dyn_cast<InitListExpr>(CLE->getInitializer()))
3666           Expr = ILE->getInit(0);
3667   }
3668 
3669   bool Result;
3670   return (!Expr->isValueDependent() &&
3671           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
3672           !Result);
3673 }
3674 
3675 static void CheckNonNullArgument(Sema &S,
3676                                  const Expr *ArgExpr,
3677                                  SourceLocation CallSiteLoc) {
3678   if (CheckNonNullExpr(S, ArgExpr))
3679     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
3680                           S.PDiag(diag::warn_null_arg)
3681                               << ArgExpr->getSourceRange());
3682 }
3683 
3684 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
3685   FormatStringInfo FSI;
3686   if ((GetFormatStringType(Format) == FST_NSString) &&
3687       getFormatStringInfo(Format, false, &FSI)) {
3688     Idx = FSI.FormatIdx;
3689     return true;
3690   }
3691   return false;
3692 }
3693 
3694 /// Diagnose use of %s directive in an NSString which is being passed
3695 /// as formatting string to formatting method.
3696 static void
3697 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
3698                                         const NamedDecl *FDecl,
3699                                         Expr **Args,
3700                                         unsigned NumArgs) {
3701   unsigned Idx = 0;
3702   bool Format = false;
3703   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
3704   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
3705     Idx = 2;
3706     Format = true;
3707   }
3708   else
3709     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
3710       if (S.GetFormatNSStringIdx(I, Idx)) {
3711         Format = true;
3712         break;
3713       }
3714     }
3715   if (!Format || NumArgs <= Idx)
3716     return;
3717   const Expr *FormatExpr = Args[Idx];
3718   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
3719     FormatExpr = CSCE->getSubExpr();
3720   const StringLiteral *FormatString;
3721   if (const ObjCStringLiteral *OSL =
3722       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
3723     FormatString = OSL->getString();
3724   else
3725     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
3726   if (!FormatString)
3727     return;
3728   if (S.FormatStringHasSArg(FormatString)) {
3729     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
3730       << "%s" << 1 << 1;
3731     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
3732       << FDecl->getDeclName();
3733   }
3734 }
3735 
3736 /// Determine whether the given type has a non-null nullability annotation.
3737 static bool isNonNullType(ASTContext &ctx, QualType type) {
3738   if (auto nullability = type->getNullability(ctx))
3739     return *nullability == NullabilityKind::NonNull;
3740 
3741   return false;
3742 }
3743 
3744 static void CheckNonNullArguments(Sema &S,
3745                                   const NamedDecl *FDecl,
3746                                   const FunctionProtoType *Proto,
3747                                   ArrayRef<const Expr *> Args,
3748                                   SourceLocation CallSiteLoc) {
3749   assert((FDecl || Proto) && "Need a function declaration or prototype");
3750 
3751   // Already checked by by constant evaluator.
3752   if (S.isConstantEvaluated())
3753     return;
3754   // Check the attributes attached to the method/function itself.
3755   llvm::SmallBitVector NonNullArgs;
3756   if (FDecl) {
3757     // Handle the nonnull attribute on the function/method declaration itself.
3758     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
3759       if (!NonNull->args_size()) {
3760         // Easy case: all pointer arguments are nonnull.
3761         for (const auto *Arg : Args)
3762           if (S.isValidPointerAttrType(Arg->getType()))
3763             CheckNonNullArgument(S, Arg, CallSiteLoc);
3764         return;
3765       }
3766 
3767       for (const ParamIdx &Idx : NonNull->args()) {
3768         unsigned IdxAST = Idx.getASTIndex();
3769         if (IdxAST >= Args.size())
3770           continue;
3771         if (NonNullArgs.empty())
3772           NonNullArgs.resize(Args.size());
3773         NonNullArgs.set(IdxAST);
3774       }
3775     }
3776   }
3777 
3778   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
3779     // Handle the nonnull attribute on the parameters of the
3780     // function/method.
3781     ArrayRef<ParmVarDecl*> parms;
3782     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
3783       parms = FD->parameters();
3784     else
3785       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
3786 
3787     unsigned ParamIndex = 0;
3788     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
3789          I != E; ++I, ++ParamIndex) {
3790       const ParmVarDecl *PVD = *I;
3791       if (PVD->hasAttr<NonNullAttr>() ||
3792           isNonNullType(S.Context, PVD->getType())) {
3793         if (NonNullArgs.empty())
3794           NonNullArgs.resize(Args.size());
3795 
3796         NonNullArgs.set(ParamIndex);
3797       }
3798     }
3799   } else {
3800     // If we have a non-function, non-method declaration but no
3801     // function prototype, try to dig out the function prototype.
3802     if (!Proto) {
3803       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
3804         QualType type = VD->getType().getNonReferenceType();
3805         if (auto pointerType = type->getAs<PointerType>())
3806           type = pointerType->getPointeeType();
3807         else if (auto blockType = type->getAs<BlockPointerType>())
3808           type = blockType->getPointeeType();
3809         // FIXME: data member pointers?
3810 
3811         // Dig out the function prototype, if there is one.
3812         Proto = type->getAs<FunctionProtoType>();
3813       }
3814     }
3815 
3816     // Fill in non-null argument information from the nullability
3817     // information on the parameter types (if we have them).
3818     if (Proto) {
3819       unsigned Index = 0;
3820       for (auto paramType : Proto->getParamTypes()) {
3821         if (isNonNullType(S.Context, paramType)) {
3822           if (NonNullArgs.empty())
3823             NonNullArgs.resize(Args.size());
3824 
3825           NonNullArgs.set(Index);
3826         }
3827 
3828         ++Index;
3829       }
3830     }
3831   }
3832 
3833   // Check for non-null arguments.
3834   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
3835        ArgIndex != ArgIndexEnd; ++ArgIndex) {
3836     if (NonNullArgs[ArgIndex])
3837       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
3838   }
3839 }
3840 
3841 /// Handles the checks for format strings, non-POD arguments to vararg
3842 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
3843 /// attributes.
3844 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
3845                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
3846                      bool IsMemberFunction, SourceLocation Loc,
3847                      SourceRange Range, VariadicCallType CallType) {
3848   // FIXME: We should check as much as we can in the template definition.
3849   if (CurContext->isDependentContext())
3850     return;
3851 
3852   // Printf and scanf checking.
3853   llvm::SmallBitVector CheckedVarArgs;
3854   if (FDecl) {
3855     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
3856       // Only create vector if there are format attributes.
3857       CheckedVarArgs.resize(Args.size());
3858 
3859       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
3860                            CheckedVarArgs);
3861     }
3862   }
3863 
3864   // Refuse POD arguments that weren't caught by the format string
3865   // checks above.
3866   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
3867   if (CallType != VariadicDoesNotApply &&
3868       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
3869     unsigned NumParams = Proto ? Proto->getNumParams()
3870                        : FDecl && isa<FunctionDecl>(FDecl)
3871                            ? cast<FunctionDecl>(FDecl)->getNumParams()
3872                        : FDecl && isa<ObjCMethodDecl>(FDecl)
3873                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
3874                        : 0;
3875 
3876     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
3877       // Args[ArgIdx] can be null in malformed code.
3878       if (const Expr *Arg = Args[ArgIdx]) {
3879         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
3880           checkVariadicArgument(Arg, CallType);
3881       }
3882     }
3883   }
3884 
3885   if (FDecl || Proto) {
3886     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
3887 
3888     // Type safety checking.
3889     if (FDecl) {
3890       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
3891         CheckArgumentWithTypeTag(I, Args, Loc);
3892     }
3893   }
3894 
3895   if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
3896     auto *AA = FDecl->getAttr<AllocAlignAttr>();
3897     const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
3898     if (!Arg->isValueDependent()) {
3899       llvm::APSInt I(64);
3900       if (Arg->isIntegerConstantExpr(I, Context)) {
3901         if (!I.isPowerOf2()) {
3902           Diag(Arg->getExprLoc(), diag::err_alignment_not_power_of_two)
3903               << Arg->getSourceRange();
3904           return;
3905         }
3906 
3907         if (I > Sema::MaximumAlignment)
3908           Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
3909               << Arg->getSourceRange() << Sema::MaximumAlignment;
3910       }
3911     }
3912   }
3913 
3914   if (FD)
3915     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
3916 }
3917 
3918 /// CheckConstructorCall - Check a constructor call for correctness and safety
3919 /// properties not enforced by the C type system.
3920 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
3921                                 ArrayRef<const Expr *> Args,
3922                                 const FunctionProtoType *Proto,
3923                                 SourceLocation Loc) {
3924   VariadicCallType CallType =
3925     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
3926   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
3927             Loc, SourceRange(), CallType);
3928 }
3929 
3930 /// CheckFunctionCall - Check a direct function call for various correctness
3931 /// and safety properties not strictly enforced by the C type system.
3932 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
3933                              const FunctionProtoType *Proto) {
3934   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
3935                               isa<CXXMethodDecl>(FDecl);
3936   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
3937                           IsMemberOperatorCall;
3938   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
3939                                                   TheCall->getCallee());
3940   Expr** Args = TheCall->getArgs();
3941   unsigned NumArgs = TheCall->getNumArgs();
3942 
3943   Expr *ImplicitThis = nullptr;
3944   if (IsMemberOperatorCall) {
3945     // If this is a call to a member operator, hide the first argument
3946     // from checkCall.
3947     // FIXME: Our choice of AST representation here is less than ideal.
3948     ImplicitThis = Args[0];
3949     ++Args;
3950     --NumArgs;
3951   } else if (IsMemberFunction)
3952     ImplicitThis =
3953         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
3954 
3955   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
3956             IsMemberFunction, TheCall->getRParenLoc(),
3957             TheCall->getCallee()->getSourceRange(), CallType);
3958 
3959   IdentifierInfo *FnInfo = FDecl->getIdentifier();
3960   // None of the checks below are needed for functions that don't have
3961   // simple names (e.g., C++ conversion functions).
3962   if (!FnInfo)
3963     return false;
3964 
3965   CheckAbsoluteValueFunction(TheCall, FDecl);
3966   CheckMaxUnsignedZero(TheCall, FDecl);
3967 
3968   if (getLangOpts().ObjC)
3969     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
3970 
3971   unsigned CMId = FDecl->getMemoryFunctionKind();
3972   if (CMId == 0)
3973     return false;
3974 
3975   // Handle memory setting and copying functions.
3976   if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
3977     CheckStrlcpycatArguments(TheCall, FnInfo);
3978   else if (CMId == Builtin::BIstrncat)
3979     CheckStrncatArguments(TheCall, FnInfo);
3980   else
3981     CheckMemaccessArguments(TheCall, CMId, FnInfo);
3982 
3983   return false;
3984 }
3985 
3986 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
3987                                ArrayRef<const Expr *> Args) {
3988   VariadicCallType CallType =
3989       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
3990 
3991   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
3992             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
3993             CallType);
3994 
3995   return false;
3996 }
3997 
3998 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
3999                             const FunctionProtoType *Proto) {
4000   QualType Ty;
4001   if (const auto *V = dyn_cast<VarDecl>(NDecl))
4002     Ty = V->getType().getNonReferenceType();
4003   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4004     Ty = F->getType().getNonReferenceType();
4005   else
4006     return false;
4007 
4008   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4009       !Ty->isFunctionProtoType())
4010     return false;
4011 
4012   VariadicCallType CallType;
4013   if (!Proto || !Proto->isVariadic()) {
4014     CallType = VariadicDoesNotApply;
4015   } else if (Ty->isBlockPointerType()) {
4016     CallType = VariadicBlock;
4017   } else { // Ty->isFunctionPointerType()
4018     CallType = VariadicFunction;
4019   }
4020 
4021   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4022             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4023             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4024             TheCall->getCallee()->getSourceRange(), CallType);
4025 
4026   return false;
4027 }
4028 
4029 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
4030 /// such as function pointers returned from functions.
4031 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4032   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4033                                                   TheCall->getCallee());
4034   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4035             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4036             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4037             TheCall->getCallee()->getSourceRange(), CallType);
4038 
4039   return false;
4040 }
4041 
4042 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4043   if (!llvm::isValidAtomicOrderingCABI(Ordering))
4044     return false;
4045 
4046   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4047   switch (Op) {
4048   case AtomicExpr::AO__c11_atomic_init:
4049   case AtomicExpr::AO__opencl_atomic_init:
4050     llvm_unreachable("There is no ordering argument for an init");
4051 
4052   case AtomicExpr::AO__c11_atomic_load:
4053   case AtomicExpr::AO__opencl_atomic_load:
4054   case AtomicExpr::AO__atomic_load_n:
4055   case AtomicExpr::AO__atomic_load:
4056     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4057            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4058 
4059   case AtomicExpr::AO__c11_atomic_store:
4060   case AtomicExpr::AO__opencl_atomic_store:
4061   case AtomicExpr::AO__atomic_store:
4062   case AtomicExpr::AO__atomic_store_n:
4063     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4064            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4065            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4066 
4067   default:
4068     return true;
4069   }
4070 }
4071 
4072 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
4073                                          AtomicExpr::AtomicOp Op) {
4074   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4075   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4076   MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
4077   return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
4078                          DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
4079                          Op);
4080 }
4081 
4082 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
4083                                  SourceLocation RParenLoc, MultiExprArg Args,
4084                                  AtomicExpr::AtomicOp Op,
4085                                  AtomicArgumentOrder ArgOrder) {
4086   // All the non-OpenCL operations take one of the following forms.
4087   // The OpenCL operations take the __c11 forms with one extra argument for
4088   // synchronization scope.
4089   enum {
4090     // C    __c11_atomic_init(A *, C)
4091     Init,
4092 
4093     // C    __c11_atomic_load(A *, int)
4094     Load,
4095 
4096     // void __atomic_load(A *, CP, int)
4097     LoadCopy,
4098 
4099     // void __atomic_store(A *, CP, int)
4100     Copy,
4101 
4102     // C    __c11_atomic_add(A *, M, int)
4103     Arithmetic,
4104 
4105     // C    __atomic_exchange_n(A *, CP, int)
4106     Xchg,
4107 
4108     // void __atomic_exchange(A *, C *, CP, int)
4109     GNUXchg,
4110 
4111     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4112     C11CmpXchg,
4113 
4114     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4115     GNUCmpXchg
4116   } Form = Init;
4117 
4118   const unsigned NumForm = GNUCmpXchg + 1;
4119   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
4120   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
4121   // where:
4122   //   C is an appropriate type,
4123   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4124   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4125   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4126   //   the int parameters are for orderings.
4127 
4128   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4129       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4130       "need to update code for modified forms");
4131   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
4132                     AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
4133                         AtomicExpr::AO__atomic_load,
4134                 "need to update code for modified C11 atomics");
4135   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
4136                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
4137   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
4138                Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
4139                IsOpenCL;
4140   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4141              Op == AtomicExpr::AO__atomic_store_n ||
4142              Op == AtomicExpr::AO__atomic_exchange_n ||
4143              Op == AtomicExpr::AO__atomic_compare_exchange_n;
4144   bool IsAddSub = false;
4145 
4146   switch (Op) {
4147   case AtomicExpr::AO__c11_atomic_init:
4148   case AtomicExpr::AO__opencl_atomic_init:
4149     Form = Init;
4150     break;
4151 
4152   case AtomicExpr::AO__c11_atomic_load:
4153   case AtomicExpr::AO__opencl_atomic_load:
4154   case AtomicExpr::AO__atomic_load_n:
4155     Form = Load;
4156     break;
4157 
4158   case AtomicExpr::AO__atomic_load:
4159     Form = LoadCopy;
4160     break;
4161 
4162   case AtomicExpr::AO__c11_atomic_store:
4163   case AtomicExpr::AO__opencl_atomic_store:
4164   case AtomicExpr::AO__atomic_store:
4165   case AtomicExpr::AO__atomic_store_n:
4166     Form = Copy;
4167     break;
4168 
4169   case AtomicExpr::AO__c11_atomic_fetch_add:
4170   case AtomicExpr::AO__c11_atomic_fetch_sub:
4171   case AtomicExpr::AO__opencl_atomic_fetch_add:
4172   case AtomicExpr::AO__opencl_atomic_fetch_sub:
4173   case AtomicExpr::AO__atomic_fetch_add:
4174   case AtomicExpr::AO__atomic_fetch_sub:
4175   case AtomicExpr::AO__atomic_add_fetch:
4176   case AtomicExpr::AO__atomic_sub_fetch:
4177     IsAddSub = true;
4178     LLVM_FALLTHROUGH;
4179   case AtomicExpr::AO__c11_atomic_fetch_and:
4180   case AtomicExpr::AO__c11_atomic_fetch_or:
4181   case AtomicExpr::AO__c11_atomic_fetch_xor:
4182   case AtomicExpr::AO__opencl_atomic_fetch_and:
4183   case AtomicExpr::AO__opencl_atomic_fetch_or:
4184   case AtomicExpr::AO__opencl_atomic_fetch_xor:
4185   case AtomicExpr::AO__atomic_fetch_and:
4186   case AtomicExpr::AO__atomic_fetch_or:
4187   case AtomicExpr::AO__atomic_fetch_xor:
4188   case AtomicExpr::AO__atomic_fetch_nand:
4189   case AtomicExpr::AO__atomic_and_fetch:
4190   case AtomicExpr::AO__atomic_or_fetch:
4191   case AtomicExpr::AO__atomic_xor_fetch:
4192   case AtomicExpr::AO__atomic_nand_fetch:
4193   case AtomicExpr::AO__c11_atomic_fetch_min:
4194   case AtomicExpr::AO__c11_atomic_fetch_max:
4195   case AtomicExpr::AO__opencl_atomic_fetch_min:
4196   case AtomicExpr::AO__opencl_atomic_fetch_max:
4197   case AtomicExpr::AO__atomic_min_fetch:
4198   case AtomicExpr::AO__atomic_max_fetch:
4199   case AtomicExpr::AO__atomic_fetch_min:
4200   case AtomicExpr::AO__atomic_fetch_max:
4201     Form = Arithmetic;
4202     break;
4203 
4204   case AtomicExpr::AO__c11_atomic_exchange:
4205   case AtomicExpr::AO__opencl_atomic_exchange:
4206   case AtomicExpr::AO__atomic_exchange_n:
4207     Form = Xchg;
4208     break;
4209 
4210   case AtomicExpr::AO__atomic_exchange:
4211     Form = GNUXchg;
4212     break;
4213 
4214   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
4215   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
4216   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
4217   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
4218     Form = C11CmpXchg;
4219     break;
4220 
4221   case AtomicExpr::AO__atomic_compare_exchange:
4222   case AtomicExpr::AO__atomic_compare_exchange_n:
4223     Form = GNUCmpXchg;
4224     break;
4225   }
4226 
4227   unsigned AdjustedNumArgs = NumArgs[Form];
4228   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
4229     ++AdjustedNumArgs;
4230   // Check we have the right number of arguments.
4231   if (Args.size() < AdjustedNumArgs) {
4232     Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
4233         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4234         << ExprRange;
4235     return ExprError();
4236   } else if (Args.size() > AdjustedNumArgs) {
4237     Diag(Args[AdjustedNumArgs]->getBeginLoc(),
4238          diag::err_typecheck_call_too_many_args)
4239         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4240         << ExprRange;
4241     return ExprError();
4242   }
4243 
4244   // Inspect the first argument of the atomic operation.
4245   Expr *Ptr = Args[0];
4246   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
4247   if (ConvertedPtr.isInvalid())
4248     return ExprError();
4249 
4250   Ptr = ConvertedPtr.get();
4251   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
4252   if (!pointerType) {
4253     Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
4254         << Ptr->getType() << Ptr->getSourceRange();
4255     return ExprError();
4256   }
4257 
4258   // For a __c11 builtin, this should be a pointer to an _Atomic type.
4259   QualType AtomTy = pointerType->getPointeeType(); // 'A'
4260   QualType ValType = AtomTy; // 'C'
4261   if (IsC11) {
4262     if (!AtomTy->isAtomicType()) {
4263       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
4264           << Ptr->getType() << Ptr->getSourceRange();
4265       return ExprError();
4266     }
4267     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
4268         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
4269       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
4270           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
4271           << Ptr->getSourceRange();
4272       return ExprError();
4273     }
4274     ValType = AtomTy->castAs<AtomicType>()->getValueType();
4275   } else if (Form != Load && Form != LoadCopy) {
4276     if (ValType.isConstQualified()) {
4277       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
4278           << Ptr->getType() << Ptr->getSourceRange();
4279       return ExprError();
4280     }
4281   }
4282 
4283   // For an arithmetic operation, the implied arithmetic must be well-formed.
4284   if (Form == Arithmetic) {
4285     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
4286     if (IsAddSub && !ValType->isIntegerType()
4287         && !ValType->isPointerType()) {
4288       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4289           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4290       return ExprError();
4291     }
4292     if (!IsAddSub && !ValType->isIntegerType()) {
4293       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
4294           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4295       return ExprError();
4296     }
4297     if (IsC11 && ValType->isPointerType() &&
4298         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
4299                             diag::err_incomplete_type)) {
4300       return ExprError();
4301     }
4302   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
4303     // For __atomic_*_n operations, the value type must be a scalar integral or
4304     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
4305     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4306         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4307     return ExprError();
4308   }
4309 
4310   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
4311       !AtomTy->isScalarType()) {
4312     // For GNU atomics, require a trivially-copyable type. This is not part of
4313     // the GNU atomics specification, but we enforce it for sanity.
4314     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
4315         << Ptr->getType() << Ptr->getSourceRange();
4316     return ExprError();
4317   }
4318 
4319   switch (ValType.getObjCLifetime()) {
4320   case Qualifiers::OCL_None:
4321   case Qualifiers::OCL_ExplicitNone:
4322     // okay
4323     break;
4324 
4325   case Qualifiers::OCL_Weak:
4326   case Qualifiers::OCL_Strong:
4327   case Qualifiers::OCL_Autoreleasing:
4328     // FIXME: Can this happen? By this point, ValType should be known
4329     // to be trivially copyable.
4330     Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
4331         << ValType << Ptr->getSourceRange();
4332     return ExprError();
4333   }
4334 
4335   // All atomic operations have an overload which takes a pointer to a volatile
4336   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
4337   // into the result or the other operands. Similarly atomic_load takes a
4338   // pointer to a const 'A'.
4339   ValType.removeLocalVolatile();
4340   ValType.removeLocalConst();
4341   QualType ResultType = ValType;
4342   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
4343       Form == Init)
4344     ResultType = Context.VoidTy;
4345   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
4346     ResultType = Context.BoolTy;
4347 
4348   // The type of a parameter passed 'by value'. In the GNU atomics, such
4349   // arguments are actually passed as pointers.
4350   QualType ByValType = ValType; // 'CP'
4351   bool IsPassedByAddress = false;
4352   if (!IsC11 && !IsN) {
4353     ByValType = Ptr->getType();
4354     IsPassedByAddress = true;
4355   }
4356 
4357   SmallVector<Expr *, 5> APIOrderedArgs;
4358   if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
4359     APIOrderedArgs.push_back(Args[0]);
4360     switch (Form) {
4361     case Init:
4362     case Load:
4363       APIOrderedArgs.push_back(Args[1]); // Val1/Order
4364       break;
4365     case LoadCopy:
4366     case Copy:
4367     case Arithmetic:
4368     case Xchg:
4369       APIOrderedArgs.push_back(Args[2]); // Val1
4370       APIOrderedArgs.push_back(Args[1]); // Order
4371       break;
4372     case GNUXchg:
4373       APIOrderedArgs.push_back(Args[2]); // Val1
4374       APIOrderedArgs.push_back(Args[3]); // Val2
4375       APIOrderedArgs.push_back(Args[1]); // Order
4376       break;
4377     case C11CmpXchg:
4378       APIOrderedArgs.push_back(Args[2]); // Val1
4379       APIOrderedArgs.push_back(Args[4]); // Val2
4380       APIOrderedArgs.push_back(Args[1]); // Order
4381       APIOrderedArgs.push_back(Args[3]); // OrderFail
4382       break;
4383     case GNUCmpXchg:
4384       APIOrderedArgs.push_back(Args[2]); // Val1
4385       APIOrderedArgs.push_back(Args[4]); // Val2
4386       APIOrderedArgs.push_back(Args[5]); // Weak
4387       APIOrderedArgs.push_back(Args[1]); // Order
4388       APIOrderedArgs.push_back(Args[3]); // OrderFail
4389       break;
4390     }
4391   } else
4392     APIOrderedArgs.append(Args.begin(), Args.end());
4393 
4394   // The first argument's non-CV pointer type is used to deduce the type of
4395   // subsequent arguments, except for:
4396   //  - weak flag (always converted to bool)
4397   //  - memory order (always converted to int)
4398   //  - scope  (always converted to int)
4399   for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
4400     QualType Ty;
4401     if (i < NumVals[Form] + 1) {
4402       switch (i) {
4403       case 0:
4404         // The first argument is always a pointer. It has a fixed type.
4405         // It is always dereferenced, a nullptr is undefined.
4406         CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4407         // Nothing else to do: we already know all we want about this pointer.
4408         continue;
4409       case 1:
4410         // The second argument is the non-atomic operand. For arithmetic, this
4411         // is always passed by value, and for a compare_exchange it is always
4412         // passed by address. For the rest, GNU uses by-address and C11 uses
4413         // by-value.
4414         assert(Form != Load);
4415         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
4416           Ty = ValType;
4417         else if (Form == Copy || Form == Xchg) {
4418           if (IsPassedByAddress) {
4419             // The value pointer is always dereferenced, a nullptr is undefined.
4420             CheckNonNullArgument(*this, APIOrderedArgs[i],
4421                                  ExprRange.getBegin());
4422           }
4423           Ty = ByValType;
4424         } else if (Form == Arithmetic)
4425           Ty = Context.getPointerDiffType();
4426         else {
4427           Expr *ValArg = APIOrderedArgs[i];
4428           // The value pointer is always dereferenced, a nullptr is undefined.
4429           CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
4430           LangAS AS = LangAS::Default;
4431           // Keep address space of non-atomic pointer type.
4432           if (const PointerType *PtrTy =
4433                   ValArg->getType()->getAs<PointerType>()) {
4434             AS = PtrTy->getPointeeType().getAddressSpace();
4435           }
4436           Ty = Context.getPointerType(
4437               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
4438         }
4439         break;
4440       case 2:
4441         // The third argument to compare_exchange / GNU exchange is the desired
4442         // value, either by-value (for the C11 and *_n variant) or as a pointer.
4443         if (IsPassedByAddress)
4444           CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4445         Ty = ByValType;
4446         break;
4447       case 3:
4448         // The fourth argument to GNU compare_exchange is a 'weak' flag.
4449         Ty = Context.BoolTy;
4450         break;
4451       }
4452     } else {
4453       // The order(s) and scope are always converted to int.
4454       Ty = Context.IntTy;
4455     }
4456 
4457     InitializedEntity Entity =
4458         InitializedEntity::InitializeParameter(Context, Ty, false);
4459     ExprResult Arg = APIOrderedArgs[i];
4460     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4461     if (Arg.isInvalid())
4462       return true;
4463     APIOrderedArgs[i] = Arg.get();
4464   }
4465 
4466   // Permute the arguments into a 'consistent' order.
4467   SmallVector<Expr*, 5> SubExprs;
4468   SubExprs.push_back(Ptr);
4469   switch (Form) {
4470   case Init:
4471     // Note, AtomicExpr::getVal1() has a special case for this atomic.
4472     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4473     break;
4474   case Load:
4475     SubExprs.push_back(APIOrderedArgs[1]); // Order
4476     break;
4477   case LoadCopy:
4478   case Copy:
4479   case Arithmetic:
4480   case Xchg:
4481     SubExprs.push_back(APIOrderedArgs[2]); // Order
4482     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4483     break;
4484   case GNUXchg:
4485     // Note, AtomicExpr::getVal2() has a special case for this atomic.
4486     SubExprs.push_back(APIOrderedArgs[3]); // Order
4487     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4488     SubExprs.push_back(APIOrderedArgs[2]); // Val2
4489     break;
4490   case C11CmpXchg:
4491     SubExprs.push_back(APIOrderedArgs[3]); // Order
4492     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4493     SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
4494     SubExprs.push_back(APIOrderedArgs[2]); // Val2
4495     break;
4496   case GNUCmpXchg:
4497     SubExprs.push_back(APIOrderedArgs[4]); // Order
4498     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4499     SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
4500     SubExprs.push_back(APIOrderedArgs[2]); // Val2
4501     SubExprs.push_back(APIOrderedArgs[3]); // Weak
4502     break;
4503   }
4504 
4505   if (SubExprs.size() >= 2 && Form != Init) {
4506     llvm::APSInt Result(32);
4507     if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
4508         !isValidOrderingForOp(Result.getSExtValue(), Op))
4509       Diag(SubExprs[1]->getBeginLoc(),
4510            diag::warn_atomic_op_has_invalid_memory_order)
4511           << SubExprs[1]->getSourceRange();
4512   }
4513 
4514   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
4515     auto *Scope = Args[Args.size() - 1];
4516     llvm::APSInt Result(32);
4517     if (Scope->isIntegerConstantExpr(Result, Context) &&
4518         !ScopeModel->isValid(Result.getZExtValue())) {
4519       Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
4520           << Scope->getSourceRange();
4521     }
4522     SubExprs.push_back(Scope);
4523   }
4524 
4525   AtomicExpr *AE = new (Context)
4526       AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
4527 
4528   if ((Op == AtomicExpr::AO__c11_atomic_load ||
4529        Op == AtomicExpr::AO__c11_atomic_store ||
4530        Op == AtomicExpr::AO__opencl_atomic_load ||
4531        Op == AtomicExpr::AO__opencl_atomic_store ) &&
4532       Context.AtomicUsesUnsupportedLibcall(AE))
4533     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
4534         << ((Op == AtomicExpr::AO__c11_atomic_load ||
4535              Op == AtomicExpr::AO__opencl_atomic_load)
4536                 ? 0
4537                 : 1);
4538 
4539   return AE;
4540 }
4541 
4542 /// checkBuiltinArgument - Given a call to a builtin function, perform
4543 /// normal type-checking on the given argument, updating the call in
4544 /// place.  This is useful when a builtin function requires custom
4545 /// type-checking for some of its arguments but not necessarily all of
4546 /// them.
4547 ///
4548 /// Returns true on error.
4549 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
4550   FunctionDecl *Fn = E->getDirectCallee();
4551   assert(Fn && "builtin call without direct callee!");
4552 
4553   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
4554   InitializedEntity Entity =
4555     InitializedEntity::InitializeParameter(S.Context, Param);
4556 
4557   ExprResult Arg = E->getArg(0);
4558   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
4559   if (Arg.isInvalid())
4560     return true;
4561 
4562   E->setArg(ArgIndex, Arg.get());
4563   return false;
4564 }
4565 
4566 /// We have a call to a function like __sync_fetch_and_add, which is an
4567 /// overloaded function based on the pointer type of its first argument.
4568 /// The main BuildCallExpr routines have already promoted the types of
4569 /// arguments because all of these calls are prototyped as void(...).
4570 ///
4571 /// This function goes through and does final semantic checking for these
4572 /// builtins, as well as generating any warnings.
4573 ExprResult
4574 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
4575   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
4576   Expr *Callee = TheCall->getCallee();
4577   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
4578   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4579 
4580   // Ensure that we have at least one argument to do type inference from.
4581   if (TheCall->getNumArgs() < 1) {
4582     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
4583         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
4584     return ExprError();
4585   }
4586 
4587   // Inspect the first argument of the atomic builtin.  This should always be
4588   // a pointer type, whose element is an integral scalar or pointer type.
4589   // Because it is a pointer type, we don't have to worry about any implicit
4590   // casts here.
4591   // FIXME: We don't allow floating point scalars as input.
4592   Expr *FirstArg = TheCall->getArg(0);
4593   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
4594   if (FirstArgResult.isInvalid())
4595     return ExprError();
4596   FirstArg = FirstArgResult.get();
4597   TheCall->setArg(0, FirstArg);
4598 
4599   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
4600   if (!pointerType) {
4601     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
4602         << FirstArg->getType() << FirstArg->getSourceRange();
4603     return ExprError();
4604   }
4605 
4606   QualType ValType = pointerType->getPointeeType();
4607   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
4608       !ValType->isBlockPointerType()) {
4609     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
4610         << FirstArg->getType() << FirstArg->getSourceRange();
4611     return ExprError();
4612   }
4613 
4614   if (ValType.isConstQualified()) {
4615     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
4616         << FirstArg->getType() << FirstArg->getSourceRange();
4617     return ExprError();
4618   }
4619 
4620   switch (ValType.getObjCLifetime()) {
4621   case Qualifiers::OCL_None:
4622   case Qualifiers::OCL_ExplicitNone:
4623     // okay
4624     break;
4625 
4626   case Qualifiers::OCL_Weak:
4627   case Qualifiers::OCL_Strong:
4628   case Qualifiers::OCL_Autoreleasing:
4629     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
4630         << ValType << FirstArg->getSourceRange();
4631     return ExprError();
4632   }
4633 
4634   // Strip any qualifiers off ValType.
4635   ValType = ValType.getUnqualifiedType();
4636 
4637   // The majority of builtins return a value, but a few have special return
4638   // types, so allow them to override appropriately below.
4639   QualType ResultType = ValType;
4640 
4641   // We need to figure out which concrete builtin this maps onto.  For example,
4642   // __sync_fetch_and_add with a 2 byte object turns into
4643   // __sync_fetch_and_add_2.
4644 #define BUILTIN_ROW(x) \
4645   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
4646     Builtin::BI##x##_8, Builtin::BI##x##_16 }
4647 
4648   static const unsigned BuiltinIndices[][5] = {
4649     BUILTIN_ROW(__sync_fetch_and_add),
4650     BUILTIN_ROW(__sync_fetch_and_sub),
4651     BUILTIN_ROW(__sync_fetch_and_or),
4652     BUILTIN_ROW(__sync_fetch_and_and),
4653     BUILTIN_ROW(__sync_fetch_and_xor),
4654     BUILTIN_ROW(__sync_fetch_and_nand),
4655 
4656     BUILTIN_ROW(__sync_add_and_fetch),
4657     BUILTIN_ROW(__sync_sub_and_fetch),
4658     BUILTIN_ROW(__sync_and_and_fetch),
4659     BUILTIN_ROW(__sync_or_and_fetch),
4660     BUILTIN_ROW(__sync_xor_and_fetch),
4661     BUILTIN_ROW(__sync_nand_and_fetch),
4662 
4663     BUILTIN_ROW(__sync_val_compare_and_swap),
4664     BUILTIN_ROW(__sync_bool_compare_and_swap),
4665     BUILTIN_ROW(__sync_lock_test_and_set),
4666     BUILTIN_ROW(__sync_lock_release),
4667     BUILTIN_ROW(__sync_swap)
4668   };
4669 #undef BUILTIN_ROW
4670 
4671   // Determine the index of the size.
4672   unsigned SizeIndex;
4673   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
4674   case 1: SizeIndex = 0; break;
4675   case 2: SizeIndex = 1; break;
4676   case 4: SizeIndex = 2; break;
4677   case 8: SizeIndex = 3; break;
4678   case 16: SizeIndex = 4; break;
4679   default:
4680     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
4681         << FirstArg->getType() << FirstArg->getSourceRange();
4682     return ExprError();
4683   }
4684 
4685   // Each of these builtins has one pointer argument, followed by some number of
4686   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
4687   // that we ignore.  Find out which row of BuiltinIndices to read from as well
4688   // as the number of fixed args.
4689   unsigned BuiltinID = FDecl->getBuiltinID();
4690   unsigned BuiltinIndex, NumFixed = 1;
4691   bool WarnAboutSemanticsChange = false;
4692   switch (BuiltinID) {
4693   default: llvm_unreachable("Unknown overloaded atomic builtin!");
4694   case Builtin::BI__sync_fetch_and_add:
4695   case Builtin::BI__sync_fetch_and_add_1:
4696   case Builtin::BI__sync_fetch_and_add_2:
4697   case Builtin::BI__sync_fetch_and_add_4:
4698   case Builtin::BI__sync_fetch_and_add_8:
4699   case Builtin::BI__sync_fetch_and_add_16:
4700     BuiltinIndex = 0;
4701     break;
4702 
4703   case Builtin::BI__sync_fetch_and_sub:
4704   case Builtin::BI__sync_fetch_and_sub_1:
4705   case Builtin::BI__sync_fetch_and_sub_2:
4706   case Builtin::BI__sync_fetch_and_sub_4:
4707   case Builtin::BI__sync_fetch_and_sub_8:
4708   case Builtin::BI__sync_fetch_and_sub_16:
4709     BuiltinIndex = 1;
4710     break;
4711 
4712   case Builtin::BI__sync_fetch_and_or:
4713   case Builtin::BI__sync_fetch_and_or_1:
4714   case Builtin::BI__sync_fetch_and_or_2:
4715   case Builtin::BI__sync_fetch_and_or_4:
4716   case Builtin::BI__sync_fetch_and_or_8:
4717   case Builtin::BI__sync_fetch_and_or_16:
4718     BuiltinIndex = 2;
4719     break;
4720 
4721   case Builtin::BI__sync_fetch_and_and:
4722   case Builtin::BI__sync_fetch_and_and_1:
4723   case Builtin::BI__sync_fetch_and_and_2:
4724   case Builtin::BI__sync_fetch_and_and_4:
4725   case Builtin::BI__sync_fetch_and_and_8:
4726   case Builtin::BI__sync_fetch_and_and_16:
4727     BuiltinIndex = 3;
4728     break;
4729 
4730   case Builtin::BI__sync_fetch_and_xor:
4731   case Builtin::BI__sync_fetch_and_xor_1:
4732   case Builtin::BI__sync_fetch_and_xor_2:
4733   case Builtin::BI__sync_fetch_and_xor_4:
4734   case Builtin::BI__sync_fetch_and_xor_8:
4735   case Builtin::BI__sync_fetch_and_xor_16:
4736     BuiltinIndex = 4;
4737     break;
4738 
4739   case Builtin::BI__sync_fetch_and_nand:
4740   case Builtin::BI__sync_fetch_and_nand_1:
4741   case Builtin::BI__sync_fetch_and_nand_2:
4742   case Builtin::BI__sync_fetch_and_nand_4:
4743   case Builtin::BI__sync_fetch_and_nand_8:
4744   case Builtin::BI__sync_fetch_and_nand_16:
4745     BuiltinIndex = 5;
4746     WarnAboutSemanticsChange = true;
4747     break;
4748 
4749   case Builtin::BI__sync_add_and_fetch:
4750   case Builtin::BI__sync_add_and_fetch_1:
4751   case Builtin::BI__sync_add_and_fetch_2:
4752   case Builtin::BI__sync_add_and_fetch_4:
4753   case Builtin::BI__sync_add_and_fetch_8:
4754   case Builtin::BI__sync_add_and_fetch_16:
4755     BuiltinIndex = 6;
4756     break;
4757 
4758   case Builtin::BI__sync_sub_and_fetch:
4759   case Builtin::BI__sync_sub_and_fetch_1:
4760   case Builtin::BI__sync_sub_and_fetch_2:
4761   case Builtin::BI__sync_sub_and_fetch_4:
4762   case Builtin::BI__sync_sub_and_fetch_8:
4763   case Builtin::BI__sync_sub_and_fetch_16:
4764     BuiltinIndex = 7;
4765     break;
4766 
4767   case Builtin::BI__sync_and_and_fetch:
4768   case Builtin::BI__sync_and_and_fetch_1:
4769   case Builtin::BI__sync_and_and_fetch_2:
4770   case Builtin::BI__sync_and_and_fetch_4:
4771   case Builtin::BI__sync_and_and_fetch_8:
4772   case Builtin::BI__sync_and_and_fetch_16:
4773     BuiltinIndex = 8;
4774     break;
4775 
4776   case Builtin::BI__sync_or_and_fetch:
4777   case Builtin::BI__sync_or_and_fetch_1:
4778   case Builtin::BI__sync_or_and_fetch_2:
4779   case Builtin::BI__sync_or_and_fetch_4:
4780   case Builtin::BI__sync_or_and_fetch_8:
4781   case Builtin::BI__sync_or_and_fetch_16:
4782     BuiltinIndex = 9;
4783     break;
4784 
4785   case Builtin::BI__sync_xor_and_fetch:
4786   case Builtin::BI__sync_xor_and_fetch_1:
4787   case Builtin::BI__sync_xor_and_fetch_2:
4788   case Builtin::BI__sync_xor_and_fetch_4:
4789   case Builtin::BI__sync_xor_and_fetch_8:
4790   case Builtin::BI__sync_xor_and_fetch_16:
4791     BuiltinIndex = 10;
4792     break;
4793 
4794   case Builtin::BI__sync_nand_and_fetch:
4795   case Builtin::BI__sync_nand_and_fetch_1:
4796   case Builtin::BI__sync_nand_and_fetch_2:
4797   case Builtin::BI__sync_nand_and_fetch_4:
4798   case Builtin::BI__sync_nand_and_fetch_8:
4799   case Builtin::BI__sync_nand_and_fetch_16:
4800     BuiltinIndex = 11;
4801     WarnAboutSemanticsChange = true;
4802     break;
4803 
4804   case Builtin::BI__sync_val_compare_and_swap:
4805   case Builtin::BI__sync_val_compare_and_swap_1:
4806   case Builtin::BI__sync_val_compare_and_swap_2:
4807   case Builtin::BI__sync_val_compare_and_swap_4:
4808   case Builtin::BI__sync_val_compare_and_swap_8:
4809   case Builtin::BI__sync_val_compare_and_swap_16:
4810     BuiltinIndex = 12;
4811     NumFixed = 2;
4812     break;
4813 
4814   case Builtin::BI__sync_bool_compare_and_swap:
4815   case Builtin::BI__sync_bool_compare_and_swap_1:
4816   case Builtin::BI__sync_bool_compare_and_swap_2:
4817   case Builtin::BI__sync_bool_compare_and_swap_4:
4818   case Builtin::BI__sync_bool_compare_and_swap_8:
4819   case Builtin::BI__sync_bool_compare_and_swap_16:
4820     BuiltinIndex = 13;
4821     NumFixed = 2;
4822     ResultType = Context.BoolTy;
4823     break;
4824 
4825   case Builtin::BI__sync_lock_test_and_set:
4826   case Builtin::BI__sync_lock_test_and_set_1:
4827   case Builtin::BI__sync_lock_test_and_set_2:
4828   case Builtin::BI__sync_lock_test_and_set_4:
4829   case Builtin::BI__sync_lock_test_and_set_8:
4830   case Builtin::BI__sync_lock_test_and_set_16:
4831     BuiltinIndex = 14;
4832     break;
4833 
4834   case Builtin::BI__sync_lock_release:
4835   case Builtin::BI__sync_lock_release_1:
4836   case Builtin::BI__sync_lock_release_2:
4837   case Builtin::BI__sync_lock_release_4:
4838   case Builtin::BI__sync_lock_release_8:
4839   case Builtin::BI__sync_lock_release_16:
4840     BuiltinIndex = 15;
4841     NumFixed = 0;
4842     ResultType = Context.VoidTy;
4843     break;
4844 
4845   case Builtin::BI__sync_swap:
4846   case Builtin::BI__sync_swap_1:
4847   case Builtin::BI__sync_swap_2:
4848   case Builtin::BI__sync_swap_4:
4849   case Builtin::BI__sync_swap_8:
4850   case Builtin::BI__sync_swap_16:
4851     BuiltinIndex = 16;
4852     break;
4853   }
4854 
4855   // Now that we know how many fixed arguments we expect, first check that we
4856   // have at least that many.
4857   if (TheCall->getNumArgs() < 1+NumFixed) {
4858     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
4859         << 0 << 1 + NumFixed << TheCall->getNumArgs()
4860         << Callee->getSourceRange();
4861     return ExprError();
4862   }
4863 
4864   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
4865       << Callee->getSourceRange();
4866 
4867   if (WarnAboutSemanticsChange) {
4868     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
4869         << Callee->getSourceRange();
4870   }
4871 
4872   // Get the decl for the concrete builtin from this, we can tell what the
4873   // concrete integer type we should convert to is.
4874   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
4875   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
4876   FunctionDecl *NewBuiltinDecl;
4877   if (NewBuiltinID == BuiltinID)
4878     NewBuiltinDecl = FDecl;
4879   else {
4880     // Perform builtin lookup to avoid redeclaring it.
4881     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
4882     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
4883     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
4884     assert(Res.getFoundDecl());
4885     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
4886     if (!NewBuiltinDecl)
4887       return ExprError();
4888   }
4889 
4890   // The first argument --- the pointer --- has a fixed type; we
4891   // deduce the types of the rest of the arguments accordingly.  Walk
4892   // the remaining arguments, converting them to the deduced value type.
4893   for (unsigned i = 0; i != NumFixed; ++i) {
4894     ExprResult Arg = TheCall->getArg(i+1);
4895 
4896     // GCC does an implicit conversion to the pointer or integer ValType.  This
4897     // can fail in some cases (1i -> int**), check for this error case now.
4898     // Initialize the argument.
4899     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
4900                                                    ValType, /*consume*/ false);
4901     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4902     if (Arg.isInvalid())
4903       return ExprError();
4904 
4905     // Okay, we have something that *can* be converted to the right type.  Check
4906     // to see if there is a potentially weird extension going on here.  This can
4907     // happen when you do an atomic operation on something like an char* and
4908     // pass in 42.  The 42 gets converted to char.  This is even more strange
4909     // for things like 45.123 -> char, etc.
4910     // FIXME: Do this check.
4911     TheCall->setArg(i+1, Arg.get());
4912   }
4913 
4914   // Create a new DeclRefExpr to refer to the new decl.
4915   DeclRefExpr *NewDRE = DeclRefExpr::Create(
4916       Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
4917       /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
4918       DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
4919 
4920   // Set the callee in the CallExpr.
4921   // FIXME: This loses syntactic information.
4922   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
4923   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
4924                                               CK_BuiltinFnToFnPtr);
4925   TheCall->setCallee(PromotedCall.get());
4926 
4927   // Change the result type of the call to match the original value type. This
4928   // is arbitrary, but the codegen for these builtins ins design to handle it
4929   // gracefully.
4930   TheCall->setType(ResultType);
4931 
4932   return TheCallResult;
4933 }
4934 
4935 /// SemaBuiltinNontemporalOverloaded - We have a call to
4936 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
4937 /// overloaded function based on the pointer type of its last argument.
4938 ///
4939 /// This function goes through and does final semantic checking for these
4940 /// builtins.
4941 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
4942   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
4943   DeclRefExpr *DRE =
4944       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4945   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4946   unsigned BuiltinID = FDecl->getBuiltinID();
4947   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
4948           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
4949          "Unexpected nontemporal load/store builtin!");
4950   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
4951   unsigned numArgs = isStore ? 2 : 1;
4952 
4953   // Ensure that we have the proper number of arguments.
4954   if (checkArgCount(*this, TheCall, numArgs))
4955     return ExprError();
4956 
4957   // Inspect the last argument of the nontemporal builtin.  This should always
4958   // be a pointer type, from which we imply the type of the memory access.
4959   // Because it is a pointer type, we don't have to worry about any implicit
4960   // casts here.
4961   Expr *PointerArg = TheCall->getArg(numArgs - 1);
4962   ExprResult PointerArgResult =
4963       DefaultFunctionArrayLvalueConversion(PointerArg);
4964 
4965   if (PointerArgResult.isInvalid())
4966     return ExprError();
4967   PointerArg = PointerArgResult.get();
4968   TheCall->setArg(numArgs - 1, PointerArg);
4969 
4970   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
4971   if (!pointerType) {
4972     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
4973         << PointerArg->getType() << PointerArg->getSourceRange();
4974     return ExprError();
4975   }
4976 
4977   QualType ValType = pointerType->getPointeeType();
4978 
4979   // Strip any qualifiers off ValType.
4980   ValType = ValType.getUnqualifiedType();
4981   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
4982       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
4983       !ValType->isVectorType()) {
4984     Diag(DRE->getBeginLoc(),
4985          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
4986         << PointerArg->getType() << PointerArg->getSourceRange();
4987     return ExprError();
4988   }
4989 
4990   if (!isStore) {
4991     TheCall->setType(ValType);
4992     return TheCallResult;
4993   }
4994 
4995   ExprResult ValArg = TheCall->getArg(0);
4996   InitializedEntity Entity = InitializedEntity::InitializeParameter(
4997       Context, ValType, /*consume*/ false);
4998   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
4999   if (ValArg.isInvalid())
5000     return ExprError();
5001 
5002   TheCall->setArg(0, ValArg.get());
5003   TheCall->setType(Context.VoidTy);
5004   return TheCallResult;
5005 }
5006 
5007 /// CheckObjCString - Checks that the argument to the builtin
5008 /// CFString constructor is correct
5009 /// Note: It might also make sense to do the UTF-16 conversion here (would
5010 /// simplify the backend).
5011 bool Sema::CheckObjCString(Expr *Arg) {
5012   Arg = Arg->IgnoreParenCasts();
5013   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
5014 
5015   if (!Literal || !Literal->isAscii()) {
5016     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
5017         << Arg->getSourceRange();
5018     return true;
5019   }
5020 
5021   if (Literal->containsNonAsciiOrNull()) {
5022     StringRef String = Literal->getString();
5023     unsigned NumBytes = String.size();
5024     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
5025     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
5026     llvm::UTF16 *ToPtr = &ToBuf[0];
5027 
5028     llvm::ConversionResult Result =
5029         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
5030                                  ToPtr + NumBytes, llvm::strictConversion);
5031     // Check for conversion failure.
5032     if (Result != llvm::conversionOK)
5033       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
5034           << Arg->getSourceRange();
5035   }
5036   return false;
5037 }
5038 
5039 /// CheckObjCString - Checks that the format string argument to the os_log()
5040 /// and os_trace() functions is correct, and converts it to const char *.
5041 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5042   Arg = Arg->IgnoreParenCasts();
5043   auto *Literal = dyn_cast<StringLiteral>(Arg);
5044   if (!Literal) {
5045     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
5046       Literal = ObjcLiteral->getString();
5047     }
5048   }
5049 
5050   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
5051     return ExprError(
5052         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
5053         << Arg->getSourceRange());
5054   }
5055 
5056   ExprResult Result(Literal);
5057   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
5058   InitializedEntity Entity =
5059       InitializedEntity::InitializeParameter(Context, ResultTy, false);
5060   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
5061   return Result;
5062 }
5063 
5064 /// Check that the user is calling the appropriate va_start builtin for the
5065 /// target and calling convention.
5066 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5067   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5068   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
5069   bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
5070                     TT.getArch() == llvm::Triple::aarch64_32);
5071   bool IsWindows = TT.isOSWindows();
5072   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5073   if (IsX64 || IsAArch64) {
5074     CallingConv CC = CC_C;
5075     if (const FunctionDecl *FD = S.getCurFunctionDecl())
5076       CC = FD->getType()->castAs<FunctionType>()->getCallConv();
5077     if (IsMSVAStart) {
5078       // Don't allow this in System V ABI functions.
5079       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
5080         return S.Diag(Fn->getBeginLoc(),
5081                       diag::err_ms_va_start_used_in_sysv_function);
5082     } else {
5083       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
5084       // On x64 Windows, don't allow this in System V ABI functions.
5085       // (Yes, that means there's no corresponding way to support variadic
5086       // System V ABI functions on Windows.)
5087       if ((IsWindows && CC == CC_X86_64SysV) ||
5088           (!IsWindows && CC == CC_Win64))
5089         return S.Diag(Fn->getBeginLoc(),
5090                       diag::err_va_start_used_in_wrong_abi_function)
5091                << !IsWindows;
5092     }
5093     return false;
5094   }
5095 
5096   if (IsMSVAStart)
5097     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
5098   return false;
5099 }
5100 
5101 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
5102                                              ParmVarDecl **LastParam = nullptr) {
5103   // Determine whether the current function, block, or obj-c method is variadic
5104   // and get its parameter list.
5105   bool IsVariadic = false;
5106   ArrayRef<ParmVarDecl *> Params;
5107   DeclContext *Caller = S.CurContext;
5108   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
5109     IsVariadic = Block->isVariadic();
5110     Params = Block->parameters();
5111   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
5112     IsVariadic = FD->isVariadic();
5113     Params = FD->parameters();
5114   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
5115     IsVariadic = MD->isVariadic();
5116     // FIXME: This isn't correct for methods (results in bogus warning).
5117     Params = MD->parameters();
5118   } else if (isa<CapturedDecl>(Caller)) {
5119     // We don't support va_start in a CapturedDecl.
5120     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
5121     return true;
5122   } else {
5123     // This must be some other declcontext that parses exprs.
5124     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
5125     return true;
5126   }
5127 
5128   if (!IsVariadic) {
5129     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
5130     return true;
5131   }
5132 
5133   if (LastParam)
5134     *LastParam = Params.empty() ? nullptr : Params.back();
5135 
5136   return false;
5137 }
5138 
5139 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
5140 /// for validity.  Emit an error and return true on failure; return false
5141 /// on success.
5142 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5143   Expr *Fn = TheCall->getCallee();
5144 
5145   if (checkVAStartABI(*this, BuiltinID, Fn))
5146     return true;
5147 
5148   if (TheCall->getNumArgs() > 2) {
5149     Diag(TheCall->getArg(2)->getBeginLoc(),
5150          diag::err_typecheck_call_too_many_args)
5151         << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5152         << Fn->getSourceRange()
5153         << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5154                        (*(TheCall->arg_end() - 1))->getEndLoc());
5155     return true;
5156   }
5157 
5158   if (TheCall->getNumArgs() < 2) {
5159     return Diag(TheCall->getEndLoc(),
5160                 diag::err_typecheck_call_too_few_args_at_least)
5161            << 0 /*function call*/ << 2 << TheCall->getNumArgs();
5162   }
5163 
5164   // Type-check the first argument normally.
5165   if (checkBuiltinArgument(*this, TheCall, 0))
5166     return true;
5167 
5168   // Check that the current function is variadic, and get its last parameter.
5169   ParmVarDecl *LastParam;
5170   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
5171     return true;
5172 
5173   // Verify that the second argument to the builtin is the last argument of the
5174   // current function or method.
5175   bool SecondArgIsLastNamedArgument = false;
5176   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
5177 
5178   // These are valid if SecondArgIsLastNamedArgument is false after the next
5179   // block.
5180   QualType Type;
5181   SourceLocation ParamLoc;
5182   bool IsCRegister = false;
5183 
5184   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
5185     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
5186       SecondArgIsLastNamedArgument = PV == LastParam;
5187 
5188       Type = PV->getType();
5189       ParamLoc = PV->getLocation();
5190       IsCRegister =
5191           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
5192     }
5193   }
5194 
5195   if (!SecondArgIsLastNamedArgument)
5196     Diag(TheCall->getArg(1)->getBeginLoc(),
5197          diag::warn_second_arg_of_va_start_not_last_named_param);
5198   else if (IsCRegister || Type->isReferenceType() ||
5199            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
5200              // Promotable integers are UB, but enumerations need a bit of
5201              // extra checking to see what their promotable type actually is.
5202              if (!Type->isPromotableIntegerType())
5203                return false;
5204              if (!Type->isEnumeralType())
5205                return true;
5206              const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
5207              return !(ED &&
5208                       Context.typesAreCompatible(ED->getPromotionType(), Type));
5209            }()) {
5210     unsigned Reason = 0;
5211     if (Type->isReferenceType())  Reason = 1;
5212     else if (IsCRegister)         Reason = 2;
5213     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
5214     Diag(ParamLoc, diag::note_parameter_type) << Type;
5215   }
5216 
5217   TheCall->setType(Context.VoidTy);
5218   return false;
5219 }
5220 
5221 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
5222   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
5223   //                 const char *named_addr);
5224 
5225   Expr *Func = Call->getCallee();
5226 
5227   if (Call->getNumArgs() < 3)
5228     return Diag(Call->getEndLoc(),
5229                 diag::err_typecheck_call_too_few_args_at_least)
5230            << 0 /*function call*/ << 3 << Call->getNumArgs();
5231 
5232   // Type-check the first argument normally.
5233   if (checkBuiltinArgument(*this, Call, 0))
5234     return true;
5235 
5236   // Check that the current function is variadic.
5237   if (checkVAStartIsInVariadicFunction(*this, Func))
5238     return true;
5239 
5240   // __va_start on Windows does not validate the parameter qualifiers
5241 
5242   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
5243   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
5244 
5245   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
5246   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
5247 
5248   const QualType &ConstCharPtrTy =
5249       Context.getPointerType(Context.CharTy.withConst());
5250   if (!Arg1Ty->isPointerType() ||
5251       Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
5252     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5253         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
5254         << 0                                      /* qualifier difference */
5255         << 3                                      /* parameter mismatch */
5256         << 2 << Arg1->getType() << ConstCharPtrTy;
5257 
5258   const QualType SizeTy = Context.getSizeType();
5259   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
5260     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5261         << Arg2->getType() << SizeTy << 1 /* different class */
5262         << 0                              /* qualifier difference */
5263         << 3                              /* parameter mismatch */
5264         << 3 << Arg2->getType() << SizeTy;
5265 
5266   return false;
5267 }
5268 
5269 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
5270 /// friends.  This is declared to take (...), so we have to check everything.
5271 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
5272   if (TheCall->getNumArgs() < 2)
5273     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5274            << 0 << 2 << TheCall->getNumArgs() /*function call*/;
5275   if (TheCall->getNumArgs() > 2)
5276     return Diag(TheCall->getArg(2)->getBeginLoc(),
5277                 diag::err_typecheck_call_too_many_args)
5278            << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5279            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5280                           (*(TheCall->arg_end() - 1))->getEndLoc());
5281 
5282   ExprResult OrigArg0 = TheCall->getArg(0);
5283   ExprResult OrigArg1 = TheCall->getArg(1);
5284 
5285   // Do standard promotions between the two arguments, returning their common
5286   // type.
5287   QualType Res = UsualArithmeticConversions(
5288       OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
5289   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
5290     return true;
5291 
5292   // Make sure any conversions are pushed back into the call; this is
5293   // type safe since unordered compare builtins are declared as "_Bool
5294   // foo(...)".
5295   TheCall->setArg(0, OrigArg0.get());
5296   TheCall->setArg(1, OrigArg1.get());
5297 
5298   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
5299     return false;
5300 
5301   // If the common type isn't a real floating type, then the arguments were
5302   // invalid for this operation.
5303   if (Res.isNull() || !Res->isRealFloatingType())
5304     return Diag(OrigArg0.get()->getBeginLoc(),
5305                 diag::err_typecheck_call_invalid_ordered_compare)
5306            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
5307            << SourceRange(OrigArg0.get()->getBeginLoc(),
5308                           OrigArg1.get()->getEndLoc());
5309 
5310   return false;
5311 }
5312 
5313 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
5314 /// __builtin_isnan and friends.  This is declared to take (...), so we have
5315 /// to check everything. We expect the last argument to be a floating point
5316 /// value.
5317 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
5318   if (TheCall->getNumArgs() < NumArgs)
5319     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5320            << 0 << NumArgs << TheCall->getNumArgs() /*function call*/;
5321   if (TheCall->getNumArgs() > NumArgs)
5322     return Diag(TheCall->getArg(NumArgs)->getBeginLoc(),
5323                 diag::err_typecheck_call_too_many_args)
5324            << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
5325            << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(),
5326                           (*(TheCall->arg_end() - 1))->getEndLoc());
5327 
5328   // __builtin_fpclassify is the only case where NumArgs != 1, so we can count
5329   // on all preceding parameters just being int.  Try all of those.
5330   for (unsigned i = 0; i < NumArgs - 1; ++i) {
5331     Expr *Arg = TheCall->getArg(i);
5332 
5333     if (Arg->isTypeDependent())
5334       return false;
5335 
5336     ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);
5337 
5338     if (Res.isInvalid())
5339       return true;
5340     TheCall->setArg(i, Res.get());
5341   }
5342 
5343   Expr *OrigArg = TheCall->getArg(NumArgs-1);
5344 
5345   if (OrigArg->isTypeDependent())
5346     return false;
5347 
5348   // Usual Unary Conversions will convert half to float, which we want for
5349   // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
5350   // type how it is, but do normal L->Rvalue conversions.
5351   if (Context.getTargetInfo().useFP16ConversionIntrinsics())
5352     OrigArg = UsualUnaryConversions(OrigArg).get();
5353   else
5354     OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
5355   TheCall->setArg(NumArgs - 1, OrigArg);
5356 
5357   // This operation requires a non-_Complex floating-point number.
5358   if (!OrigArg->getType()->isRealFloatingType())
5359     return Diag(OrigArg->getBeginLoc(),
5360                 diag::err_typecheck_call_invalid_unary_fp)
5361            << OrigArg->getType() << OrigArg->getSourceRange();
5362 
5363   return false;
5364 }
5365 
5366 // Customized Sema Checking for VSX builtins that have the following signature:
5367 // vector [...] builtinName(vector [...], vector [...], const int);
5368 // Which takes the same type of vectors (any legal vector type) for the first
5369 // two arguments and takes compile time constant for the third argument.
5370 // Example builtins are :
5371 // vector double vec_xxpermdi(vector double, vector double, int);
5372 // vector short vec_xxsldwi(vector short, vector short, int);
5373 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
5374   unsigned ExpectedNumArgs = 3;
5375   if (TheCall->getNumArgs() < ExpectedNumArgs)
5376     return Diag(TheCall->getEndLoc(),
5377                 diag::err_typecheck_call_too_few_args_at_least)
5378            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5379            << TheCall->getSourceRange();
5380 
5381   if (TheCall->getNumArgs() > ExpectedNumArgs)
5382     return Diag(TheCall->getEndLoc(),
5383                 diag::err_typecheck_call_too_many_args_at_most)
5384            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5385            << TheCall->getSourceRange();
5386 
5387   // Check the third argument is a compile time constant
5388   llvm::APSInt Value;
5389   if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
5390     return Diag(TheCall->getBeginLoc(),
5391                 diag::err_vsx_builtin_nonconstant_argument)
5392            << 3 /* argument index */ << TheCall->getDirectCallee()
5393            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5394                           TheCall->getArg(2)->getEndLoc());
5395 
5396   QualType Arg1Ty = TheCall->getArg(0)->getType();
5397   QualType Arg2Ty = TheCall->getArg(1)->getType();
5398 
5399   // Check the type of argument 1 and argument 2 are vectors.
5400   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
5401   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
5402       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
5403     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
5404            << TheCall->getDirectCallee()
5405            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5406                           TheCall->getArg(1)->getEndLoc());
5407   }
5408 
5409   // Check the first two arguments are the same type.
5410   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
5411     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
5412            << TheCall->getDirectCallee()
5413            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5414                           TheCall->getArg(1)->getEndLoc());
5415   }
5416 
5417   // When default clang type checking is turned off and the customized type
5418   // checking is used, the returning type of the function must be explicitly
5419   // set. Otherwise it is _Bool by default.
5420   TheCall->setType(Arg1Ty);
5421 
5422   return false;
5423 }
5424 
5425 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
5426 // This is declared to take (...), so we have to check everything.
5427 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
5428   if (TheCall->getNumArgs() < 2)
5429     return ExprError(Diag(TheCall->getEndLoc(),
5430                           diag::err_typecheck_call_too_few_args_at_least)
5431                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5432                      << TheCall->getSourceRange());
5433 
5434   // Determine which of the following types of shufflevector we're checking:
5435   // 1) unary, vector mask: (lhs, mask)
5436   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
5437   QualType resType = TheCall->getArg(0)->getType();
5438   unsigned numElements = 0;
5439 
5440   if (!TheCall->getArg(0)->isTypeDependent() &&
5441       !TheCall->getArg(1)->isTypeDependent()) {
5442     QualType LHSType = TheCall->getArg(0)->getType();
5443     QualType RHSType = TheCall->getArg(1)->getType();
5444 
5445     if (!LHSType->isVectorType() || !RHSType->isVectorType())
5446       return ExprError(
5447           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
5448           << TheCall->getDirectCallee()
5449           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5450                          TheCall->getArg(1)->getEndLoc()));
5451 
5452     numElements = LHSType->castAs<VectorType>()->getNumElements();
5453     unsigned numResElements = TheCall->getNumArgs() - 2;
5454 
5455     // Check to see if we have a call with 2 vector arguments, the unary shuffle
5456     // with mask.  If so, verify that RHS is an integer vector type with the
5457     // same number of elts as lhs.
5458     if (TheCall->getNumArgs() == 2) {
5459       if (!RHSType->hasIntegerRepresentation() ||
5460           RHSType->castAs<VectorType>()->getNumElements() != numElements)
5461         return ExprError(Diag(TheCall->getBeginLoc(),
5462                               diag::err_vec_builtin_incompatible_vector)
5463                          << TheCall->getDirectCallee()
5464                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
5465                                         TheCall->getArg(1)->getEndLoc()));
5466     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
5467       return ExprError(Diag(TheCall->getBeginLoc(),
5468                             diag::err_vec_builtin_incompatible_vector)
5469                        << TheCall->getDirectCallee()
5470                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5471                                       TheCall->getArg(1)->getEndLoc()));
5472     } else if (numElements != numResElements) {
5473       QualType eltType = LHSType->castAs<VectorType>()->getElementType();
5474       resType = Context.getVectorType(eltType, numResElements,
5475                                       VectorType::GenericVector);
5476     }
5477   }
5478 
5479   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
5480     if (TheCall->getArg(i)->isTypeDependent() ||
5481         TheCall->getArg(i)->isValueDependent())
5482       continue;
5483 
5484     llvm::APSInt Result(32);
5485     if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
5486       return ExprError(Diag(TheCall->getBeginLoc(),
5487                             diag::err_shufflevector_nonconstant_argument)
5488                        << TheCall->getArg(i)->getSourceRange());
5489 
5490     // Allow -1 which will be translated to undef in the IR.
5491     if (Result.isSigned() && Result.isAllOnesValue())
5492       continue;
5493 
5494     if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
5495       return ExprError(Diag(TheCall->getBeginLoc(),
5496                             diag::err_shufflevector_argument_too_large)
5497                        << TheCall->getArg(i)->getSourceRange());
5498   }
5499 
5500   SmallVector<Expr*, 32> exprs;
5501 
5502   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
5503     exprs.push_back(TheCall->getArg(i));
5504     TheCall->setArg(i, nullptr);
5505   }
5506 
5507   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
5508                                          TheCall->getCallee()->getBeginLoc(),
5509                                          TheCall->getRParenLoc());
5510 }
5511 
5512 /// SemaConvertVectorExpr - Handle __builtin_convertvector
5513 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
5514                                        SourceLocation BuiltinLoc,
5515                                        SourceLocation RParenLoc) {
5516   ExprValueKind VK = VK_RValue;
5517   ExprObjectKind OK = OK_Ordinary;
5518   QualType DstTy = TInfo->getType();
5519   QualType SrcTy = E->getType();
5520 
5521   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
5522     return ExprError(Diag(BuiltinLoc,
5523                           diag::err_convertvector_non_vector)
5524                      << E->getSourceRange());
5525   if (!DstTy->isVectorType() && !DstTy->isDependentType())
5526     return ExprError(Diag(BuiltinLoc,
5527                           diag::err_convertvector_non_vector_type));
5528 
5529   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
5530     unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
5531     unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
5532     if (SrcElts != DstElts)
5533       return ExprError(Diag(BuiltinLoc,
5534                             diag::err_convertvector_incompatible_vector)
5535                        << E->getSourceRange());
5536   }
5537 
5538   return new (Context)
5539       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5540 }
5541 
5542 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
5543 // This is declared to take (const void*, ...) and can take two
5544 // optional constant int args.
5545 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
5546   unsigned NumArgs = TheCall->getNumArgs();
5547 
5548   if (NumArgs > 3)
5549     return Diag(TheCall->getEndLoc(),
5550                 diag::err_typecheck_call_too_many_args_at_most)
5551            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
5552 
5553   // Argument 0 is checked for us and the remaining arguments must be
5554   // constant integers.
5555   for (unsigned i = 1; i != NumArgs; ++i)
5556     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
5557       return true;
5558 
5559   return false;
5560 }
5561 
5562 /// SemaBuiltinAssume - Handle __assume (MS Extension).
5563 // __assume does not evaluate its arguments, and should warn if its argument
5564 // has side effects.
5565 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
5566   Expr *Arg = TheCall->getArg(0);
5567   if (Arg->isInstantiationDependent()) return false;
5568 
5569   if (Arg->HasSideEffects(Context))
5570     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
5571         << Arg->getSourceRange()
5572         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
5573 
5574   return false;
5575 }
5576 
5577 /// Handle __builtin_alloca_with_align. This is declared
5578 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
5579 /// than 8.
5580 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
5581   // The alignment must be a constant integer.
5582   Expr *Arg = TheCall->getArg(1);
5583 
5584   // We can't check the value of a dependent argument.
5585   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
5586     if (const auto *UE =
5587             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
5588       if (UE->getKind() == UETT_AlignOf ||
5589           UE->getKind() == UETT_PreferredAlignOf)
5590         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
5591             << Arg->getSourceRange();
5592 
5593     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
5594 
5595     if (!Result.isPowerOf2())
5596       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5597              << Arg->getSourceRange();
5598 
5599     if (Result < Context.getCharWidth())
5600       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
5601              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
5602 
5603     if (Result > std::numeric_limits<int32_t>::max())
5604       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
5605              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
5606   }
5607 
5608   return false;
5609 }
5610 
5611 /// Handle __builtin_assume_aligned. This is declared
5612 /// as (const void*, size_t, ...) and can take one optional constant int arg.
5613 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
5614   unsigned NumArgs = TheCall->getNumArgs();
5615 
5616   if (NumArgs > 3)
5617     return Diag(TheCall->getEndLoc(),
5618                 diag::err_typecheck_call_too_many_args_at_most)
5619            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
5620 
5621   // The alignment must be a constant integer.
5622   Expr *Arg = TheCall->getArg(1);
5623 
5624   // We can't check the value of a dependent argument.
5625   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
5626     llvm::APSInt Result;
5627     if (SemaBuiltinConstantArg(TheCall, 1, Result))
5628       return true;
5629 
5630     if (!Result.isPowerOf2())
5631       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5632              << Arg->getSourceRange();
5633 
5634     if (Result > Sema::MaximumAlignment)
5635       Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
5636           << Arg->getSourceRange() << Sema::MaximumAlignment;
5637   }
5638 
5639   if (NumArgs > 2) {
5640     ExprResult Arg(TheCall->getArg(2));
5641     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5642       Context.getSizeType(), false);
5643     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5644     if (Arg.isInvalid()) return true;
5645     TheCall->setArg(2, Arg.get());
5646   }
5647 
5648   return false;
5649 }
5650 
5651 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
5652   unsigned BuiltinID =
5653       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
5654   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
5655 
5656   unsigned NumArgs = TheCall->getNumArgs();
5657   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
5658   if (NumArgs < NumRequiredArgs) {
5659     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5660            << 0 /* function call */ << NumRequiredArgs << NumArgs
5661            << TheCall->getSourceRange();
5662   }
5663   if (NumArgs >= NumRequiredArgs + 0x100) {
5664     return Diag(TheCall->getEndLoc(),
5665                 diag::err_typecheck_call_too_many_args_at_most)
5666            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
5667            << TheCall->getSourceRange();
5668   }
5669   unsigned i = 0;
5670 
5671   // For formatting call, check buffer arg.
5672   if (!IsSizeCall) {
5673     ExprResult Arg(TheCall->getArg(i));
5674     InitializedEntity Entity = InitializedEntity::InitializeParameter(
5675         Context, Context.VoidPtrTy, false);
5676     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5677     if (Arg.isInvalid())
5678       return true;
5679     TheCall->setArg(i, Arg.get());
5680     i++;
5681   }
5682 
5683   // Check string literal arg.
5684   unsigned FormatIdx = i;
5685   {
5686     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
5687     if (Arg.isInvalid())
5688       return true;
5689     TheCall->setArg(i, Arg.get());
5690     i++;
5691   }
5692 
5693   // Make sure variadic args are scalar.
5694   unsigned FirstDataArg = i;
5695   while (i < NumArgs) {
5696     ExprResult Arg = DefaultVariadicArgumentPromotion(
5697         TheCall->getArg(i), VariadicFunction, nullptr);
5698     if (Arg.isInvalid())
5699       return true;
5700     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
5701     if (ArgSize.getQuantity() >= 0x100) {
5702       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
5703              << i << (int)ArgSize.getQuantity() << 0xff
5704              << TheCall->getSourceRange();
5705     }
5706     TheCall->setArg(i, Arg.get());
5707     i++;
5708   }
5709 
5710   // Check formatting specifiers. NOTE: We're only doing this for the non-size
5711   // call to avoid duplicate diagnostics.
5712   if (!IsSizeCall) {
5713     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
5714     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
5715     bool Success = CheckFormatArguments(
5716         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
5717         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
5718         CheckedVarArgs);
5719     if (!Success)
5720       return true;
5721   }
5722 
5723   if (IsSizeCall) {
5724     TheCall->setType(Context.getSizeType());
5725   } else {
5726     TheCall->setType(Context.VoidPtrTy);
5727   }
5728   return false;
5729 }
5730 
5731 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
5732 /// TheCall is a constant expression.
5733 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
5734                                   llvm::APSInt &Result) {
5735   Expr *Arg = TheCall->getArg(ArgNum);
5736   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5737   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5738 
5739   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
5740 
5741   if (!Arg->isIntegerConstantExpr(Result, Context))
5742     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
5743            << FDecl->getDeclName() << Arg->getSourceRange();
5744 
5745   return false;
5746 }
5747 
5748 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
5749 /// TheCall is a constant expression in the range [Low, High].
5750 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
5751                                        int Low, int High, bool RangeIsError) {
5752   if (isConstantEvaluated())
5753     return false;
5754   llvm::APSInt Result;
5755 
5756   // We can't check the value of a dependent argument.
5757   Expr *Arg = TheCall->getArg(ArgNum);
5758   if (Arg->isTypeDependent() || Arg->isValueDependent())
5759     return false;
5760 
5761   // Check constant-ness first.
5762   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
5763     return true;
5764 
5765   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
5766     if (RangeIsError)
5767       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
5768              << Result.toString(10) << Low << High << Arg->getSourceRange();
5769     else
5770       // Defer the warning until we know if the code will be emitted so that
5771       // dead code can ignore this.
5772       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
5773                           PDiag(diag::warn_argument_invalid_range)
5774                               << Result.toString(10) << Low << High
5775                               << Arg->getSourceRange());
5776   }
5777 
5778   return false;
5779 }
5780 
5781 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
5782 /// TheCall is a constant expression is a multiple of Num..
5783 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
5784                                           unsigned Num) {
5785   llvm::APSInt Result;
5786 
5787   // We can't check the value of a dependent argument.
5788   Expr *Arg = TheCall->getArg(ArgNum);
5789   if (Arg->isTypeDependent() || Arg->isValueDependent())
5790     return false;
5791 
5792   // Check constant-ness first.
5793   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
5794     return true;
5795 
5796   if (Result.getSExtValue() % Num != 0)
5797     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
5798            << Num << Arg->getSourceRange();
5799 
5800   return false;
5801 }
5802 
5803 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
5804 /// constant expression representing a power of 2.
5805 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
5806   llvm::APSInt Result;
5807 
5808   // We can't check the value of a dependent argument.
5809   Expr *Arg = TheCall->getArg(ArgNum);
5810   if (Arg->isTypeDependent() || Arg->isValueDependent())
5811     return false;
5812 
5813   // Check constant-ness first.
5814   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
5815     return true;
5816 
5817   // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
5818   // and only if x is a power of 2.
5819   if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
5820     return false;
5821 
5822   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
5823          << Arg->getSourceRange();
5824 }
5825 
5826 static bool IsShiftedByte(llvm::APSInt Value) {
5827   if (Value.isNegative())
5828     return false;
5829 
5830   // Check if it's a shifted byte, by shifting it down
5831   while (true) {
5832     // If the value fits in the bottom byte, the check passes.
5833     if (Value < 0x100)
5834       return true;
5835 
5836     // Otherwise, if the value has _any_ bits in the bottom byte, the check
5837     // fails.
5838     if ((Value & 0xFF) != 0)
5839       return false;
5840 
5841     // If the bottom 8 bits are all 0, but something above that is nonzero,
5842     // then shifting the value right by 8 bits won't affect whether it's a
5843     // shifted byte or not. So do that, and go round again.
5844     Value >>= 8;
5845   }
5846 }
5847 
5848 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
5849 /// a constant expression representing an arbitrary byte value shifted left by
5850 /// a multiple of 8 bits.
5851 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
5852                                              unsigned ArgBits) {
5853   llvm::APSInt Result;
5854 
5855   // We can't check the value of a dependent argument.
5856   Expr *Arg = TheCall->getArg(ArgNum);
5857   if (Arg->isTypeDependent() || Arg->isValueDependent())
5858     return false;
5859 
5860   // Check constant-ness first.
5861   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
5862     return true;
5863 
5864   // Truncate to the given size.
5865   Result = Result.getLoBits(ArgBits);
5866   Result.setIsUnsigned(true);
5867 
5868   if (IsShiftedByte(Result))
5869     return false;
5870 
5871   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
5872          << Arg->getSourceRange();
5873 }
5874 
5875 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
5876 /// TheCall is a constant expression representing either a shifted byte value,
5877 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
5878 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
5879 /// Arm MVE intrinsics.
5880 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
5881                                                    int ArgNum,
5882                                                    unsigned ArgBits) {
5883   llvm::APSInt Result;
5884 
5885   // We can't check the value of a dependent argument.
5886   Expr *Arg = TheCall->getArg(ArgNum);
5887   if (Arg->isTypeDependent() || Arg->isValueDependent())
5888     return false;
5889 
5890   // Check constant-ness first.
5891   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
5892     return true;
5893 
5894   // Truncate to the given size.
5895   Result = Result.getLoBits(ArgBits);
5896   Result.setIsUnsigned(true);
5897 
5898   // Check to see if it's in either of the required forms.
5899   if (IsShiftedByte(Result) ||
5900       (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
5901     return false;
5902 
5903   return Diag(TheCall->getBeginLoc(),
5904               diag::err_argument_not_shifted_byte_or_xxff)
5905          << Arg->getSourceRange();
5906 }
5907 
5908 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
5909 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
5910   if (BuiltinID == AArch64::BI__builtin_arm_irg) {
5911     if (checkArgCount(*this, TheCall, 2))
5912       return true;
5913     Expr *Arg0 = TheCall->getArg(0);
5914     Expr *Arg1 = TheCall->getArg(1);
5915 
5916     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
5917     if (FirstArg.isInvalid())
5918       return true;
5919     QualType FirstArgType = FirstArg.get()->getType();
5920     if (!FirstArgType->isAnyPointerType())
5921       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
5922                << "first" << FirstArgType << Arg0->getSourceRange();
5923     TheCall->setArg(0, FirstArg.get());
5924 
5925     ExprResult SecArg = DefaultLvalueConversion(Arg1);
5926     if (SecArg.isInvalid())
5927       return true;
5928     QualType SecArgType = SecArg.get()->getType();
5929     if (!SecArgType->isIntegerType())
5930       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
5931                << "second" << SecArgType << Arg1->getSourceRange();
5932 
5933     // Derive the return type from the pointer argument.
5934     TheCall->setType(FirstArgType);
5935     return false;
5936   }
5937 
5938   if (BuiltinID == AArch64::BI__builtin_arm_addg) {
5939     if (checkArgCount(*this, TheCall, 2))
5940       return true;
5941 
5942     Expr *Arg0 = TheCall->getArg(0);
5943     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
5944     if (FirstArg.isInvalid())
5945       return true;
5946     QualType FirstArgType = FirstArg.get()->getType();
5947     if (!FirstArgType->isAnyPointerType())
5948       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
5949                << "first" << FirstArgType << Arg0->getSourceRange();
5950     TheCall->setArg(0, FirstArg.get());
5951 
5952     // Derive the return type from the pointer argument.
5953     TheCall->setType(FirstArgType);
5954 
5955     // Second arg must be an constant in range [0,15]
5956     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
5957   }
5958 
5959   if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
5960     if (checkArgCount(*this, TheCall, 2))
5961       return true;
5962     Expr *Arg0 = TheCall->getArg(0);
5963     Expr *Arg1 = TheCall->getArg(1);
5964 
5965     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
5966     if (FirstArg.isInvalid())
5967       return true;
5968     QualType FirstArgType = FirstArg.get()->getType();
5969     if (!FirstArgType->isAnyPointerType())
5970       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
5971                << "first" << FirstArgType << Arg0->getSourceRange();
5972 
5973     QualType SecArgType = Arg1->getType();
5974     if (!SecArgType->isIntegerType())
5975       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
5976                << "second" << SecArgType << Arg1->getSourceRange();
5977     TheCall->setType(Context.IntTy);
5978     return false;
5979   }
5980 
5981   if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
5982       BuiltinID == AArch64::BI__builtin_arm_stg) {
5983     if (checkArgCount(*this, TheCall, 1))
5984       return true;
5985     Expr *Arg0 = TheCall->getArg(0);
5986     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
5987     if (FirstArg.isInvalid())
5988       return true;
5989 
5990     QualType FirstArgType = FirstArg.get()->getType();
5991     if (!FirstArgType->isAnyPointerType())
5992       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
5993                << "first" << FirstArgType << Arg0->getSourceRange();
5994     TheCall->setArg(0, FirstArg.get());
5995 
5996     // Derive the return type from the pointer argument.
5997     if (BuiltinID == AArch64::BI__builtin_arm_ldg)
5998       TheCall->setType(FirstArgType);
5999     return false;
6000   }
6001 
6002   if (BuiltinID == AArch64::BI__builtin_arm_subp) {
6003     Expr *ArgA = TheCall->getArg(0);
6004     Expr *ArgB = TheCall->getArg(1);
6005 
6006     ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
6007     ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
6008 
6009     if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
6010       return true;
6011 
6012     QualType ArgTypeA = ArgExprA.get()->getType();
6013     QualType ArgTypeB = ArgExprB.get()->getType();
6014 
6015     auto isNull = [&] (Expr *E) -> bool {
6016       return E->isNullPointerConstant(
6017                         Context, Expr::NPC_ValueDependentIsNotNull); };
6018 
6019     // argument should be either a pointer or null
6020     if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
6021       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6022         << "first" << ArgTypeA << ArgA->getSourceRange();
6023 
6024     if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
6025       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6026         << "second" << ArgTypeB << ArgB->getSourceRange();
6027 
6028     // Ensure Pointee types are compatible
6029     if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
6030         ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
6031       QualType pointeeA = ArgTypeA->getPointeeType();
6032       QualType pointeeB = ArgTypeB->getPointeeType();
6033       if (!Context.typesAreCompatible(
6034              Context.getCanonicalType(pointeeA).getUnqualifiedType(),
6035              Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
6036         return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
6037           << ArgTypeA <<  ArgTypeB << ArgA->getSourceRange()
6038           << ArgB->getSourceRange();
6039       }
6040     }
6041 
6042     // at least one argument should be pointer type
6043     if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
6044       return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
6045         <<  ArgTypeA << ArgTypeB << ArgA->getSourceRange();
6046 
6047     if (isNull(ArgA)) // adopt type of the other pointer
6048       ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
6049 
6050     if (isNull(ArgB))
6051       ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
6052 
6053     TheCall->setArg(0, ArgExprA.get());
6054     TheCall->setArg(1, ArgExprB.get());
6055     TheCall->setType(Context.LongLongTy);
6056     return false;
6057   }
6058   assert(false && "Unhandled ARM MTE intrinsic");
6059   return true;
6060 }
6061 
6062 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
6063 /// TheCall is an ARM/AArch64 special register string literal.
6064 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
6065                                     int ArgNum, unsigned ExpectedFieldNum,
6066                                     bool AllowName) {
6067   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
6068                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
6069                       BuiltinID == ARM::BI__builtin_arm_rsr ||
6070                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
6071                       BuiltinID == ARM::BI__builtin_arm_wsr ||
6072                       BuiltinID == ARM::BI__builtin_arm_wsrp;
6073   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
6074                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
6075                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
6076                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
6077                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
6078                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
6079   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
6080 
6081   // We can't check the value of a dependent argument.
6082   Expr *Arg = TheCall->getArg(ArgNum);
6083   if (Arg->isTypeDependent() || Arg->isValueDependent())
6084     return false;
6085 
6086   // Check if the argument is a string literal.
6087   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
6088     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
6089            << Arg->getSourceRange();
6090 
6091   // Check the type of special register given.
6092   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
6093   SmallVector<StringRef, 6> Fields;
6094   Reg.split(Fields, ":");
6095 
6096   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
6097     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6098            << Arg->getSourceRange();
6099 
6100   // If the string is the name of a register then we cannot check that it is
6101   // valid here but if the string is of one the forms described in ACLE then we
6102   // can check that the supplied fields are integers and within the valid
6103   // ranges.
6104   if (Fields.size() > 1) {
6105     bool FiveFields = Fields.size() == 5;
6106 
6107     bool ValidString = true;
6108     if (IsARMBuiltin) {
6109       ValidString &= Fields[0].startswith_lower("cp") ||
6110                      Fields[0].startswith_lower("p");
6111       if (ValidString)
6112         Fields[0] =
6113           Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
6114 
6115       ValidString &= Fields[2].startswith_lower("c");
6116       if (ValidString)
6117         Fields[2] = Fields[2].drop_front(1);
6118 
6119       if (FiveFields) {
6120         ValidString &= Fields[3].startswith_lower("c");
6121         if (ValidString)
6122           Fields[3] = Fields[3].drop_front(1);
6123       }
6124     }
6125 
6126     SmallVector<int, 5> Ranges;
6127     if (FiveFields)
6128       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
6129     else
6130       Ranges.append({15, 7, 15});
6131 
6132     for (unsigned i=0; i<Fields.size(); ++i) {
6133       int IntField;
6134       ValidString &= !Fields[i].getAsInteger(10, IntField);
6135       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
6136     }
6137 
6138     if (!ValidString)
6139       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6140              << Arg->getSourceRange();
6141   } else if (IsAArch64Builtin && Fields.size() == 1) {
6142     // If the register name is one of those that appear in the condition below
6143     // and the special register builtin being used is one of the write builtins,
6144     // then we require that the argument provided for writing to the register
6145     // is an integer constant expression. This is because it will be lowered to
6146     // an MSR (immediate) instruction, so we need to know the immediate at
6147     // compile time.
6148     if (TheCall->getNumArgs() != 2)
6149       return false;
6150 
6151     std::string RegLower = Reg.lower();
6152     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
6153         RegLower != "pan" && RegLower != "uao")
6154       return false;
6155 
6156     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6157   }
6158 
6159   return false;
6160 }
6161 
6162 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
6163 /// This checks that the target supports __builtin_longjmp and
6164 /// that val is a constant 1.
6165 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
6166   if (!Context.getTargetInfo().hasSjLjLowering())
6167     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
6168            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6169 
6170   Expr *Arg = TheCall->getArg(1);
6171   llvm::APSInt Result;
6172 
6173   // TODO: This is less than ideal. Overload this to take a value.
6174   if (SemaBuiltinConstantArg(TheCall, 1, Result))
6175     return true;
6176 
6177   if (Result != 1)
6178     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
6179            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
6180 
6181   return false;
6182 }
6183 
6184 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
6185 /// This checks that the target supports __builtin_setjmp.
6186 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
6187   if (!Context.getTargetInfo().hasSjLjLowering())
6188     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
6189            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6190   return false;
6191 }
6192 
6193 namespace {
6194 
6195 class UncoveredArgHandler {
6196   enum { Unknown = -1, AllCovered = -2 };
6197 
6198   signed FirstUncoveredArg = Unknown;
6199   SmallVector<const Expr *, 4> DiagnosticExprs;
6200 
6201 public:
6202   UncoveredArgHandler() = default;
6203 
6204   bool hasUncoveredArg() const {
6205     return (FirstUncoveredArg >= 0);
6206   }
6207 
6208   unsigned getUncoveredArg() const {
6209     assert(hasUncoveredArg() && "no uncovered argument");
6210     return FirstUncoveredArg;
6211   }
6212 
6213   void setAllCovered() {
6214     // A string has been found with all arguments covered, so clear out
6215     // the diagnostics.
6216     DiagnosticExprs.clear();
6217     FirstUncoveredArg = AllCovered;
6218   }
6219 
6220   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
6221     assert(NewFirstUncoveredArg >= 0 && "Outside range");
6222 
6223     // Don't update if a previous string covers all arguments.
6224     if (FirstUncoveredArg == AllCovered)
6225       return;
6226 
6227     // UncoveredArgHandler tracks the highest uncovered argument index
6228     // and with it all the strings that match this index.
6229     if (NewFirstUncoveredArg == FirstUncoveredArg)
6230       DiagnosticExprs.push_back(StrExpr);
6231     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
6232       DiagnosticExprs.clear();
6233       DiagnosticExprs.push_back(StrExpr);
6234       FirstUncoveredArg = NewFirstUncoveredArg;
6235     }
6236   }
6237 
6238   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
6239 };
6240 
6241 enum StringLiteralCheckType {
6242   SLCT_NotALiteral,
6243   SLCT_UncheckedLiteral,
6244   SLCT_CheckedLiteral
6245 };
6246 
6247 } // namespace
6248 
6249 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
6250                                      BinaryOperatorKind BinOpKind,
6251                                      bool AddendIsRight) {
6252   unsigned BitWidth = Offset.getBitWidth();
6253   unsigned AddendBitWidth = Addend.getBitWidth();
6254   // There might be negative interim results.
6255   if (Addend.isUnsigned()) {
6256     Addend = Addend.zext(++AddendBitWidth);
6257     Addend.setIsSigned(true);
6258   }
6259   // Adjust the bit width of the APSInts.
6260   if (AddendBitWidth > BitWidth) {
6261     Offset = Offset.sext(AddendBitWidth);
6262     BitWidth = AddendBitWidth;
6263   } else if (BitWidth > AddendBitWidth) {
6264     Addend = Addend.sext(BitWidth);
6265   }
6266 
6267   bool Ov = false;
6268   llvm::APSInt ResOffset = Offset;
6269   if (BinOpKind == BO_Add)
6270     ResOffset = Offset.sadd_ov(Addend, Ov);
6271   else {
6272     assert(AddendIsRight && BinOpKind == BO_Sub &&
6273            "operator must be add or sub with addend on the right");
6274     ResOffset = Offset.ssub_ov(Addend, Ov);
6275   }
6276 
6277   // We add an offset to a pointer here so we should support an offset as big as
6278   // possible.
6279   if (Ov) {
6280     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
6281            "index (intermediate) result too big");
6282     Offset = Offset.sext(2 * BitWidth);
6283     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
6284     return;
6285   }
6286 
6287   Offset = ResOffset;
6288 }
6289 
6290 namespace {
6291 
6292 // This is a wrapper class around StringLiteral to support offsetted string
6293 // literals as format strings. It takes the offset into account when returning
6294 // the string and its length or the source locations to display notes correctly.
6295 class FormatStringLiteral {
6296   const StringLiteral *FExpr;
6297   int64_t Offset;
6298 
6299  public:
6300   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
6301       : FExpr(fexpr), Offset(Offset) {}
6302 
6303   StringRef getString() const {
6304     return FExpr->getString().drop_front(Offset);
6305   }
6306 
6307   unsigned getByteLength() const {
6308     return FExpr->getByteLength() - getCharByteWidth() * Offset;
6309   }
6310 
6311   unsigned getLength() const { return FExpr->getLength() - Offset; }
6312   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
6313 
6314   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
6315 
6316   QualType getType() const { return FExpr->getType(); }
6317 
6318   bool isAscii() const { return FExpr->isAscii(); }
6319   bool isWide() const { return FExpr->isWide(); }
6320   bool isUTF8() const { return FExpr->isUTF8(); }
6321   bool isUTF16() const { return FExpr->isUTF16(); }
6322   bool isUTF32() const { return FExpr->isUTF32(); }
6323   bool isPascal() const { return FExpr->isPascal(); }
6324 
6325   SourceLocation getLocationOfByte(
6326       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
6327       const TargetInfo &Target, unsigned *StartToken = nullptr,
6328       unsigned *StartTokenByteOffset = nullptr) const {
6329     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
6330                                     StartToken, StartTokenByteOffset);
6331   }
6332 
6333   SourceLocation getBeginLoc() const LLVM_READONLY {
6334     return FExpr->getBeginLoc().getLocWithOffset(Offset);
6335   }
6336 
6337   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
6338 };
6339 
6340 }  // namespace
6341 
6342 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
6343                               const Expr *OrigFormatExpr,
6344                               ArrayRef<const Expr *> Args,
6345                               bool HasVAListArg, unsigned format_idx,
6346                               unsigned firstDataArg,
6347                               Sema::FormatStringType Type,
6348                               bool inFunctionCall,
6349                               Sema::VariadicCallType CallType,
6350                               llvm::SmallBitVector &CheckedVarArgs,
6351                               UncoveredArgHandler &UncoveredArg,
6352                               bool IgnoreStringsWithoutSpecifiers);
6353 
6354 // Determine if an expression is a string literal or constant string.
6355 // If this function returns false on the arguments to a function expecting a
6356 // format string, we will usually need to emit a warning.
6357 // True string literals are then checked by CheckFormatString.
6358 static StringLiteralCheckType
6359 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
6360                       bool HasVAListArg, unsigned format_idx,
6361                       unsigned firstDataArg, Sema::FormatStringType Type,
6362                       Sema::VariadicCallType CallType, bool InFunctionCall,
6363                       llvm::SmallBitVector &CheckedVarArgs,
6364                       UncoveredArgHandler &UncoveredArg,
6365                       llvm::APSInt Offset,
6366                       bool IgnoreStringsWithoutSpecifiers = false) {
6367   if (S.isConstantEvaluated())
6368     return SLCT_NotALiteral;
6369  tryAgain:
6370   assert(Offset.isSigned() && "invalid offset");
6371 
6372   if (E->isTypeDependent() || E->isValueDependent())
6373     return SLCT_NotALiteral;
6374 
6375   E = E->IgnoreParenCasts();
6376 
6377   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
6378     // Technically -Wformat-nonliteral does not warn about this case.
6379     // The behavior of printf and friends in this case is implementation
6380     // dependent.  Ideally if the format string cannot be null then
6381     // it should have a 'nonnull' attribute in the function prototype.
6382     return SLCT_UncheckedLiteral;
6383 
6384   switch (E->getStmtClass()) {
6385   case Stmt::BinaryConditionalOperatorClass:
6386   case Stmt::ConditionalOperatorClass: {
6387     // The expression is a literal if both sub-expressions were, and it was
6388     // completely checked only if both sub-expressions were checked.
6389     const AbstractConditionalOperator *C =
6390         cast<AbstractConditionalOperator>(E);
6391 
6392     // Determine whether it is necessary to check both sub-expressions, for
6393     // example, because the condition expression is a constant that can be
6394     // evaluated at compile time.
6395     bool CheckLeft = true, CheckRight = true;
6396 
6397     bool Cond;
6398     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
6399                                                  S.isConstantEvaluated())) {
6400       if (Cond)
6401         CheckRight = false;
6402       else
6403         CheckLeft = false;
6404     }
6405 
6406     // We need to maintain the offsets for the right and the left hand side
6407     // separately to check if every possible indexed expression is a valid
6408     // string literal. They might have different offsets for different string
6409     // literals in the end.
6410     StringLiteralCheckType Left;
6411     if (!CheckLeft)
6412       Left = SLCT_UncheckedLiteral;
6413     else {
6414       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
6415                                    HasVAListArg, format_idx, firstDataArg,
6416                                    Type, CallType, InFunctionCall,
6417                                    CheckedVarArgs, UncoveredArg, Offset,
6418                                    IgnoreStringsWithoutSpecifiers);
6419       if (Left == SLCT_NotALiteral || !CheckRight) {
6420         return Left;
6421       }
6422     }
6423 
6424     StringLiteralCheckType Right = checkFormatStringExpr(
6425         S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
6426         Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6427         IgnoreStringsWithoutSpecifiers);
6428 
6429     return (CheckLeft && Left < Right) ? Left : Right;
6430   }
6431 
6432   case Stmt::ImplicitCastExprClass:
6433     E = cast<ImplicitCastExpr>(E)->getSubExpr();
6434     goto tryAgain;
6435 
6436   case Stmt::OpaqueValueExprClass:
6437     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
6438       E = src;
6439       goto tryAgain;
6440     }
6441     return SLCT_NotALiteral;
6442 
6443   case Stmt::PredefinedExprClass:
6444     // While __func__, etc., are technically not string literals, they
6445     // cannot contain format specifiers and thus are not a security
6446     // liability.
6447     return SLCT_UncheckedLiteral;
6448 
6449   case Stmt::DeclRefExprClass: {
6450     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6451 
6452     // As an exception, do not flag errors for variables binding to
6453     // const string literals.
6454     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
6455       bool isConstant = false;
6456       QualType T = DR->getType();
6457 
6458       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
6459         isConstant = AT->getElementType().isConstant(S.Context);
6460       } else if (const PointerType *PT = T->getAs<PointerType>()) {
6461         isConstant = T.isConstant(S.Context) &&
6462                      PT->getPointeeType().isConstant(S.Context);
6463       } else if (T->isObjCObjectPointerType()) {
6464         // In ObjC, there is usually no "const ObjectPointer" type,
6465         // so don't check if the pointee type is constant.
6466         isConstant = T.isConstant(S.Context);
6467       }
6468 
6469       if (isConstant) {
6470         if (const Expr *Init = VD->getAnyInitializer()) {
6471           // Look through initializers like const char c[] = { "foo" }
6472           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
6473             if (InitList->isStringLiteralInit())
6474               Init = InitList->getInit(0)->IgnoreParenImpCasts();
6475           }
6476           return checkFormatStringExpr(S, Init, Args,
6477                                        HasVAListArg, format_idx,
6478                                        firstDataArg, Type, CallType,
6479                                        /*InFunctionCall*/ false, CheckedVarArgs,
6480                                        UncoveredArg, Offset);
6481         }
6482       }
6483 
6484       // For vprintf* functions (i.e., HasVAListArg==true), we add a
6485       // special check to see if the format string is a function parameter
6486       // of the function calling the printf function.  If the function
6487       // has an attribute indicating it is a printf-like function, then we
6488       // should suppress warnings concerning non-literals being used in a call
6489       // to a vprintf function.  For example:
6490       //
6491       // void
6492       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
6493       //      va_list ap;
6494       //      va_start(ap, fmt);
6495       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
6496       //      ...
6497       // }
6498       if (HasVAListArg) {
6499         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
6500           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
6501             int PVIndex = PV->getFunctionScopeIndex() + 1;
6502             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
6503               // adjust for implicit parameter
6504               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6505                 if (MD->isInstance())
6506                   ++PVIndex;
6507               // We also check if the formats are compatible.
6508               // We can't pass a 'scanf' string to a 'printf' function.
6509               if (PVIndex == PVFormat->getFormatIdx() &&
6510                   Type == S.GetFormatStringType(PVFormat))
6511                 return SLCT_UncheckedLiteral;
6512             }
6513           }
6514         }
6515       }
6516     }
6517 
6518     return SLCT_NotALiteral;
6519   }
6520 
6521   case Stmt::CallExprClass:
6522   case Stmt::CXXMemberCallExprClass: {
6523     const CallExpr *CE = cast<CallExpr>(E);
6524     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
6525       bool IsFirst = true;
6526       StringLiteralCheckType CommonResult;
6527       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
6528         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
6529         StringLiteralCheckType Result = checkFormatStringExpr(
6530             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
6531             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6532             IgnoreStringsWithoutSpecifiers);
6533         if (IsFirst) {
6534           CommonResult = Result;
6535           IsFirst = false;
6536         }
6537       }
6538       if (!IsFirst)
6539         return CommonResult;
6540 
6541       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
6542         unsigned BuiltinID = FD->getBuiltinID();
6543         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
6544             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
6545           const Expr *Arg = CE->getArg(0);
6546           return checkFormatStringExpr(S, Arg, Args,
6547                                        HasVAListArg, format_idx,
6548                                        firstDataArg, Type, CallType,
6549                                        InFunctionCall, CheckedVarArgs,
6550                                        UncoveredArg, Offset,
6551                                        IgnoreStringsWithoutSpecifiers);
6552         }
6553       }
6554     }
6555 
6556     return SLCT_NotALiteral;
6557   }
6558   case Stmt::ObjCMessageExprClass: {
6559     const auto *ME = cast<ObjCMessageExpr>(E);
6560     if (const auto *MD = ME->getMethodDecl()) {
6561       if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
6562         // As a special case heuristic, if we're using the method -[NSBundle
6563         // localizedStringForKey:value:table:], ignore any key strings that lack
6564         // format specifiers. The idea is that if the key doesn't have any
6565         // format specifiers then its probably just a key to map to the
6566         // localized strings. If it does have format specifiers though, then its
6567         // likely that the text of the key is the format string in the
6568         // programmer's language, and should be checked.
6569         const ObjCInterfaceDecl *IFace;
6570         if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
6571             IFace->getIdentifier()->isStr("NSBundle") &&
6572             MD->getSelector().isKeywordSelector(
6573                 {"localizedStringForKey", "value", "table"})) {
6574           IgnoreStringsWithoutSpecifiers = true;
6575         }
6576 
6577         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
6578         return checkFormatStringExpr(
6579             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
6580             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6581             IgnoreStringsWithoutSpecifiers);
6582       }
6583     }
6584 
6585     return SLCT_NotALiteral;
6586   }
6587   case Stmt::ObjCStringLiteralClass:
6588   case Stmt::StringLiteralClass: {
6589     const StringLiteral *StrE = nullptr;
6590 
6591     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
6592       StrE = ObjCFExpr->getString();
6593     else
6594       StrE = cast<StringLiteral>(E);
6595 
6596     if (StrE) {
6597       if (Offset.isNegative() || Offset > StrE->getLength()) {
6598         // TODO: It would be better to have an explicit warning for out of
6599         // bounds literals.
6600         return SLCT_NotALiteral;
6601       }
6602       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
6603       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
6604                         firstDataArg, Type, InFunctionCall, CallType,
6605                         CheckedVarArgs, UncoveredArg,
6606                         IgnoreStringsWithoutSpecifiers);
6607       return SLCT_CheckedLiteral;
6608     }
6609 
6610     return SLCT_NotALiteral;
6611   }
6612   case Stmt::BinaryOperatorClass: {
6613     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
6614 
6615     // A string literal + an int offset is still a string literal.
6616     if (BinOp->isAdditiveOp()) {
6617       Expr::EvalResult LResult, RResult;
6618 
6619       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
6620           LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
6621       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
6622           RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
6623 
6624       if (LIsInt != RIsInt) {
6625         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
6626 
6627         if (LIsInt) {
6628           if (BinOpKind == BO_Add) {
6629             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
6630             E = BinOp->getRHS();
6631             goto tryAgain;
6632           }
6633         } else {
6634           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
6635           E = BinOp->getLHS();
6636           goto tryAgain;
6637         }
6638       }
6639     }
6640 
6641     return SLCT_NotALiteral;
6642   }
6643   case Stmt::UnaryOperatorClass: {
6644     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
6645     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
6646     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
6647       Expr::EvalResult IndexResult;
6648       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
6649                                        Expr::SE_NoSideEffects,
6650                                        S.isConstantEvaluated())) {
6651         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
6652                    /*RHS is int*/ true);
6653         E = ASE->getBase();
6654         goto tryAgain;
6655       }
6656     }
6657 
6658     return SLCT_NotALiteral;
6659   }
6660 
6661   default:
6662     return SLCT_NotALiteral;
6663   }
6664 }
6665 
6666 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
6667   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
6668       .Case("scanf", FST_Scanf)
6669       .Cases("printf", "printf0", FST_Printf)
6670       .Cases("NSString", "CFString", FST_NSString)
6671       .Case("strftime", FST_Strftime)
6672       .Case("strfmon", FST_Strfmon)
6673       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
6674       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
6675       .Case("os_trace", FST_OSLog)
6676       .Case("os_log", FST_OSLog)
6677       .Default(FST_Unknown);
6678 }
6679 
6680 /// CheckFormatArguments - Check calls to printf and scanf (and similar
6681 /// functions) for correct use of format strings.
6682 /// Returns true if a format string has been fully checked.
6683 bool Sema::CheckFormatArguments(const FormatAttr *Format,
6684                                 ArrayRef<const Expr *> Args,
6685                                 bool IsCXXMember,
6686                                 VariadicCallType CallType,
6687                                 SourceLocation Loc, SourceRange Range,
6688                                 llvm::SmallBitVector &CheckedVarArgs) {
6689   FormatStringInfo FSI;
6690   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
6691     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
6692                                 FSI.FirstDataArg, GetFormatStringType(Format),
6693                                 CallType, Loc, Range, CheckedVarArgs);
6694   return false;
6695 }
6696 
6697 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
6698                                 bool HasVAListArg, unsigned format_idx,
6699                                 unsigned firstDataArg, FormatStringType Type,
6700                                 VariadicCallType CallType,
6701                                 SourceLocation Loc, SourceRange Range,
6702                                 llvm::SmallBitVector &CheckedVarArgs) {
6703   // CHECK: printf/scanf-like function is called with no format string.
6704   if (format_idx >= Args.size()) {
6705     Diag(Loc, diag::warn_missing_format_string) << Range;
6706     return false;
6707   }
6708 
6709   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
6710 
6711   // CHECK: format string is not a string literal.
6712   //
6713   // Dynamically generated format strings are difficult to
6714   // automatically vet at compile time.  Requiring that format strings
6715   // are string literals: (1) permits the checking of format strings by
6716   // the compiler and thereby (2) can practically remove the source of
6717   // many format string exploits.
6718 
6719   // Format string can be either ObjC string (e.g. @"%d") or
6720   // C string (e.g. "%d")
6721   // ObjC string uses the same format specifiers as C string, so we can use
6722   // the same format string checking logic for both ObjC and C strings.
6723   UncoveredArgHandler UncoveredArg;
6724   StringLiteralCheckType CT =
6725       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
6726                             format_idx, firstDataArg, Type, CallType,
6727                             /*IsFunctionCall*/ true, CheckedVarArgs,
6728                             UncoveredArg,
6729                             /*no string offset*/ llvm::APSInt(64, false) = 0);
6730 
6731   // Generate a diagnostic where an uncovered argument is detected.
6732   if (UncoveredArg.hasUncoveredArg()) {
6733     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
6734     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
6735     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
6736   }
6737 
6738   if (CT != SLCT_NotALiteral)
6739     // Literal format string found, check done!
6740     return CT == SLCT_CheckedLiteral;
6741 
6742   // Strftime is particular as it always uses a single 'time' argument,
6743   // so it is safe to pass a non-literal string.
6744   if (Type == FST_Strftime)
6745     return false;
6746 
6747   // Do not emit diag when the string param is a macro expansion and the
6748   // format is either NSString or CFString. This is a hack to prevent
6749   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
6750   // which are usually used in place of NS and CF string literals.
6751   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
6752   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
6753     return false;
6754 
6755   // If there are no arguments specified, warn with -Wformat-security, otherwise
6756   // warn only with -Wformat-nonliteral.
6757   if (Args.size() == firstDataArg) {
6758     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
6759       << OrigFormatExpr->getSourceRange();
6760     switch (Type) {
6761     default:
6762       break;
6763     case FST_Kprintf:
6764     case FST_FreeBSDKPrintf:
6765     case FST_Printf:
6766       Diag(FormatLoc, diag::note_format_security_fixit)
6767         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
6768       break;
6769     case FST_NSString:
6770       Diag(FormatLoc, diag::note_format_security_fixit)
6771         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
6772       break;
6773     }
6774   } else {
6775     Diag(FormatLoc, diag::warn_format_nonliteral)
6776       << OrigFormatExpr->getSourceRange();
6777   }
6778   return false;
6779 }
6780 
6781 namespace {
6782 
6783 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
6784 protected:
6785   Sema &S;
6786   const FormatStringLiteral *FExpr;
6787   const Expr *OrigFormatExpr;
6788   const Sema::FormatStringType FSType;
6789   const unsigned FirstDataArg;
6790   const unsigned NumDataArgs;
6791   const char *Beg; // Start of format string.
6792   const bool HasVAListArg;
6793   ArrayRef<const Expr *> Args;
6794   unsigned FormatIdx;
6795   llvm::SmallBitVector CoveredArgs;
6796   bool usesPositionalArgs = false;
6797   bool atFirstArg = true;
6798   bool inFunctionCall;
6799   Sema::VariadicCallType CallType;
6800   llvm::SmallBitVector &CheckedVarArgs;
6801   UncoveredArgHandler &UncoveredArg;
6802 
6803 public:
6804   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
6805                      const Expr *origFormatExpr,
6806                      const Sema::FormatStringType type, unsigned firstDataArg,
6807                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
6808                      ArrayRef<const Expr *> Args, unsigned formatIdx,
6809                      bool inFunctionCall, Sema::VariadicCallType callType,
6810                      llvm::SmallBitVector &CheckedVarArgs,
6811                      UncoveredArgHandler &UncoveredArg)
6812       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
6813         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
6814         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
6815         inFunctionCall(inFunctionCall), CallType(callType),
6816         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
6817     CoveredArgs.resize(numDataArgs);
6818     CoveredArgs.reset();
6819   }
6820 
6821   void DoneProcessing();
6822 
6823   void HandleIncompleteSpecifier(const char *startSpecifier,
6824                                  unsigned specifierLen) override;
6825 
6826   void HandleInvalidLengthModifier(
6827                            const analyze_format_string::FormatSpecifier &FS,
6828                            const analyze_format_string::ConversionSpecifier &CS,
6829                            const char *startSpecifier, unsigned specifierLen,
6830                            unsigned DiagID);
6831 
6832   void HandleNonStandardLengthModifier(
6833                     const analyze_format_string::FormatSpecifier &FS,
6834                     const char *startSpecifier, unsigned specifierLen);
6835 
6836   void HandleNonStandardConversionSpecifier(
6837                     const analyze_format_string::ConversionSpecifier &CS,
6838                     const char *startSpecifier, unsigned specifierLen);
6839 
6840   void HandlePosition(const char *startPos, unsigned posLen) override;
6841 
6842   void HandleInvalidPosition(const char *startSpecifier,
6843                              unsigned specifierLen,
6844                              analyze_format_string::PositionContext p) override;
6845 
6846   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
6847 
6848   void HandleNullChar(const char *nullCharacter) override;
6849 
6850   template <typename Range>
6851   static void
6852   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
6853                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
6854                        bool IsStringLocation, Range StringRange,
6855                        ArrayRef<FixItHint> Fixit = None);
6856 
6857 protected:
6858   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
6859                                         const char *startSpec,
6860                                         unsigned specifierLen,
6861                                         const char *csStart, unsigned csLen);
6862 
6863   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
6864                                          const char *startSpec,
6865                                          unsigned specifierLen);
6866 
6867   SourceRange getFormatStringRange();
6868   CharSourceRange getSpecifierRange(const char *startSpecifier,
6869                                     unsigned specifierLen);
6870   SourceLocation getLocationOfByte(const char *x);
6871 
6872   const Expr *getDataArg(unsigned i) const;
6873 
6874   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
6875                     const analyze_format_string::ConversionSpecifier &CS,
6876                     const char *startSpecifier, unsigned specifierLen,
6877                     unsigned argIndex);
6878 
6879   template <typename Range>
6880   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
6881                             bool IsStringLocation, Range StringRange,
6882                             ArrayRef<FixItHint> Fixit = None);
6883 };
6884 
6885 } // namespace
6886 
6887 SourceRange CheckFormatHandler::getFormatStringRange() {
6888   return OrigFormatExpr->getSourceRange();
6889 }
6890 
6891 CharSourceRange CheckFormatHandler::
6892 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
6893   SourceLocation Start = getLocationOfByte(startSpecifier);
6894   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
6895 
6896   // Advance the end SourceLocation by one due to half-open ranges.
6897   End = End.getLocWithOffset(1);
6898 
6899   return CharSourceRange::getCharRange(Start, End);
6900 }
6901 
6902 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
6903   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
6904                                   S.getLangOpts(), S.Context.getTargetInfo());
6905 }
6906 
6907 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
6908                                                    unsigned specifierLen){
6909   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
6910                        getLocationOfByte(startSpecifier),
6911                        /*IsStringLocation*/true,
6912                        getSpecifierRange(startSpecifier, specifierLen));
6913 }
6914 
6915 void CheckFormatHandler::HandleInvalidLengthModifier(
6916     const analyze_format_string::FormatSpecifier &FS,
6917     const analyze_format_string::ConversionSpecifier &CS,
6918     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
6919   using namespace analyze_format_string;
6920 
6921   const LengthModifier &LM = FS.getLengthModifier();
6922   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
6923 
6924   // See if we know how to fix this length modifier.
6925   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
6926   if (FixedLM) {
6927     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
6928                          getLocationOfByte(LM.getStart()),
6929                          /*IsStringLocation*/true,
6930                          getSpecifierRange(startSpecifier, specifierLen));
6931 
6932     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
6933       << FixedLM->toString()
6934       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
6935 
6936   } else {
6937     FixItHint Hint;
6938     if (DiagID == diag::warn_format_nonsensical_length)
6939       Hint = FixItHint::CreateRemoval(LMRange);
6940 
6941     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
6942                          getLocationOfByte(LM.getStart()),
6943                          /*IsStringLocation*/true,
6944                          getSpecifierRange(startSpecifier, specifierLen),
6945                          Hint);
6946   }
6947 }
6948 
6949 void CheckFormatHandler::HandleNonStandardLengthModifier(
6950     const analyze_format_string::FormatSpecifier &FS,
6951     const char *startSpecifier, unsigned specifierLen) {
6952   using namespace analyze_format_string;
6953 
6954   const LengthModifier &LM = FS.getLengthModifier();
6955   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
6956 
6957   // See if we know how to fix this length modifier.
6958   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
6959   if (FixedLM) {
6960     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
6961                            << LM.toString() << 0,
6962                          getLocationOfByte(LM.getStart()),
6963                          /*IsStringLocation*/true,
6964                          getSpecifierRange(startSpecifier, specifierLen));
6965 
6966     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
6967       << FixedLM->toString()
6968       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
6969 
6970   } else {
6971     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
6972                            << LM.toString() << 0,
6973                          getLocationOfByte(LM.getStart()),
6974                          /*IsStringLocation*/true,
6975                          getSpecifierRange(startSpecifier, specifierLen));
6976   }
6977 }
6978 
6979 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
6980     const analyze_format_string::ConversionSpecifier &CS,
6981     const char *startSpecifier, unsigned specifierLen) {
6982   using namespace analyze_format_string;
6983 
6984   // See if we know how to fix this conversion specifier.
6985   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
6986   if (FixedCS) {
6987     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
6988                           << CS.toString() << /*conversion specifier*/1,
6989                          getLocationOfByte(CS.getStart()),
6990                          /*IsStringLocation*/true,
6991                          getSpecifierRange(startSpecifier, specifierLen));
6992 
6993     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
6994     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
6995       << FixedCS->toString()
6996       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
6997   } else {
6998     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
6999                           << CS.toString() << /*conversion specifier*/1,
7000                          getLocationOfByte(CS.getStart()),
7001                          /*IsStringLocation*/true,
7002                          getSpecifierRange(startSpecifier, specifierLen));
7003   }
7004 }
7005 
7006 void CheckFormatHandler::HandlePosition(const char *startPos,
7007                                         unsigned posLen) {
7008   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
7009                                getLocationOfByte(startPos),
7010                                /*IsStringLocation*/true,
7011                                getSpecifierRange(startPos, posLen));
7012 }
7013 
7014 void
7015 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
7016                                      analyze_format_string::PositionContext p) {
7017   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
7018                          << (unsigned) p,
7019                        getLocationOfByte(startPos), /*IsStringLocation*/true,
7020                        getSpecifierRange(startPos, posLen));
7021 }
7022 
7023 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
7024                                             unsigned posLen) {
7025   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
7026                                getLocationOfByte(startPos),
7027                                /*IsStringLocation*/true,
7028                                getSpecifierRange(startPos, posLen));
7029 }
7030 
7031 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
7032   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
7033     // The presence of a null character is likely an error.
7034     EmitFormatDiagnostic(
7035       S.PDiag(diag::warn_printf_format_string_contains_null_char),
7036       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
7037       getFormatStringRange());
7038   }
7039 }
7040 
7041 // Note that this may return NULL if there was an error parsing or building
7042 // one of the argument expressions.
7043 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
7044   return Args[FirstDataArg + i];
7045 }
7046 
7047 void CheckFormatHandler::DoneProcessing() {
7048   // Does the number of data arguments exceed the number of
7049   // format conversions in the format string?
7050   if (!HasVAListArg) {
7051       // Find any arguments that weren't covered.
7052     CoveredArgs.flip();
7053     signed notCoveredArg = CoveredArgs.find_first();
7054     if (notCoveredArg >= 0) {
7055       assert((unsigned)notCoveredArg < NumDataArgs);
7056       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
7057     } else {
7058       UncoveredArg.setAllCovered();
7059     }
7060   }
7061 }
7062 
7063 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
7064                                    const Expr *ArgExpr) {
7065   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
7066          "Invalid state");
7067 
7068   if (!ArgExpr)
7069     return;
7070 
7071   SourceLocation Loc = ArgExpr->getBeginLoc();
7072 
7073   if (S.getSourceManager().isInSystemMacro(Loc))
7074     return;
7075 
7076   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
7077   for (auto E : DiagnosticExprs)
7078     PDiag << E->getSourceRange();
7079 
7080   CheckFormatHandler::EmitFormatDiagnostic(
7081                                   S, IsFunctionCall, DiagnosticExprs[0],
7082                                   PDiag, Loc, /*IsStringLocation*/false,
7083                                   DiagnosticExprs[0]->getSourceRange());
7084 }
7085 
7086 bool
7087 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
7088                                                      SourceLocation Loc,
7089                                                      const char *startSpec,
7090                                                      unsigned specifierLen,
7091                                                      const char *csStart,
7092                                                      unsigned csLen) {
7093   bool keepGoing = true;
7094   if (argIndex < NumDataArgs) {
7095     // Consider the argument coverered, even though the specifier doesn't
7096     // make sense.
7097     CoveredArgs.set(argIndex);
7098   }
7099   else {
7100     // If argIndex exceeds the number of data arguments we
7101     // don't issue a warning because that is just a cascade of warnings (and
7102     // they may have intended '%%' anyway). We don't want to continue processing
7103     // the format string after this point, however, as we will like just get
7104     // gibberish when trying to match arguments.
7105     keepGoing = false;
7106   }
7107 
7108   StringRef Specifier(csStart, csLen);
7109 
7110   // If the specifier in non-printable, it could be the first byte of a UTF-8
7111   // sequence. In that case, print the UTF-8 code point. If not, print the byte
7112   // hex value.
7113   std::string CodePointStr;
7114   if (!llvm::sys::locale::isPrint(*csStart)) {
7115     llvm::UTF32 CodePoint;
7116     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
7117     const llvm::UTF8 *E =
7118         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
7119     llvm::ConversionResult Result =
7120         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
7121 
7122     if (Result != llvm::conversionOK) {
7123       unsigned char FirstChar = *csStart;
7124       CodePoint = (llvm::UTF32)FirstChar;
7125     }
7126 
7127     llvm::raw_string_ostream OS(CodePointStr);
7128     if (CodePoint < 256)
7129       OS << "\\x" << llvm::format("%02x", CodePoint);
7130     else if (CodePoint <= 0xFFFF)
7131       OS << "\\u" << llvm::format("%04x", CodePoint);
7132     else
7133       OS << "\\U" << llvm::format("%08x", CodePoint);
7134     OS.flush();
7135     Specifier = CodePointStr;
7136   }
7137 
7138   EmitFormatDiagnostic(
7139       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
7140       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
7141 
7142   return keepGoing;
7143 }
7144 
7145 void
7146 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
7147                                                       const char *startSpec,
7148                                                       unsigned specifierLen) {
7149   EmitFormatDiagnostic(
7150     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
7151     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
7152 }
7153 
7154 bool
7155 CheckFormatHandler::CheckNumArgs(
7156   const analyze_format_string::FormatSpecifier &FS,
7157   const analyze_format_string::ConversionSpecifier &CS,
7158   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
7159 
7160   if (argIndex >= NumDataArgs) {
7161     PartialDiagnostic PDiag = FS.usesPositionalArg()
7162       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
7163            << (argIndex+1) << NumDataArgs)
7164       : S.PDiag(diag::warn_printf_insufficient_data_args);
7165     EmitFormatDiagnostic(
7166       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
7167       getSpecifierRange(startSpecifier, specifierLen));
7168 
7169     // Since more arguments than conversion tokens are given, by extension
7170     // all arguments are covered, so mark this as so.
7171     UncoveredArg.setAllCovered();
7172     return false;
7173   }
7174   return true;
7175 }
7176 
7177 template<typename Range>
7178 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
7179                                               SourceLocation Loc,
7180                                               bool IsStringLocation,
7181                                               Range StringRange,
7182                                               ArrayRef<FixItHint> FixIt) {
7183   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
7184                        Loc, IsStringLocation, StringRange, FixIt);
7185 }
7186 
7187 /// If the format string is not within the function call, emit a note
7188 /// so that the function call and string are in diagnostic messages.
7189 ///
7190 /// \param InFunctionCall if true, the format string is within the function
7191 /// call and only one diagnostic message will be produced.  Otherwise, an
7192 /// extra note will be emitted pointing to location of the format string.
7193 ///
7194 /// \param ArgumentExpr the expression that is passed as the format string
7195 /// argument in the function call.  Used for getting locations when two
7196 /// diagnostics are emitted.
7197 ///
7198 /// \param PDiag the callee should already have provided any strings for the
7199 /// diagnostic message.  This function only adds locations and fixits
7200 /// to diagnostics.
7201 ///
7202 /// \param Loc primary location for diagnostic.  If two diagnostics are
7203 /// required, one will be at Loc and a new SourceLocation will be created for
7204 /// the other one.
7205 ///
7206 /// \param IsStringLocation if true, Loc points to the format string should be
7207 /// used for the note.  Otherwise, Loc points to the argument list and will
7208 /// be used with PDiag.
7209 ///
7210 /// \param StringRange some or all of the string to highlight.  This is
7211 /// templated so it can accept either a CharSourceRange or a SourceRange.
7212 ///
7213 /// \param FixIt optional fix it hint for the format string.
7214 template <typename Range>
7215 void CheckFormatHandler::EmitFormatDiagnostic(
7216     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
7217     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
7218     Range StringRange, ArrayRef<FixItHint> FixIt) {
7219   if (InFunctionCall) {
7220     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
7221     D << StringRange;
7222     D << FixIt;
7223   } else {
7224     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
7225       << ArgumentExpr->getSourceRange();
7226 
7227     const Sema::SemaDiagnosticBuilder &Note =
7228       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
7229              diag::note_format_string_defined);
7230 
7231     Note << StringRange;
7232     Note << FixIt;
7233   }
7234 }
7235 
7236 //===--- CHECK: Printf format string checking ------------------------------===//
7237 
7238 namespace {
7239 
7240 class CheckPrintfHandler : public CheckFormatHandler {
7241 public:
7242   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
7243                      const Expr *origFormatExpr,
7244                      const Sema::FormatStringType type, unsigned firstDataArg,
7245                      unsigned numDataArgs, bool isObjC, const char *beg,
7246                      bool hasVAListArg, ArrayRef<const Expr *> Args,
7247                      unsigned formatIdx, bool inFunctionCall,
7248                      Sema::VariadicCallType CallType,
7249                      llvm::SmallBitVector &CheckedVarArgs,
7250                      UncoveredArgHandler &UncoveredArg)
7251       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7252                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
7253                            inFunctionCall, CallType, CheckedVarArgs,
7254                            UncoveredArg) {}
7255 
7256   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
7257 
7258   /// Returns true if '%@' specifiers are allowed in the format string.
7259   bool allowsObjCArg() const {
7260     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
7261            FSType == Sema::FST_OSTrace;
7262   }
7263 
7264   bool HandleInvalidPrintfConversionSpecifier(
7265                                       const analyze_printf::PrintfSpecifier &FS,
7266                                       const char *startSpecifier,
7267                                       unsigned specifierLen) override;
7268 
7269   void handleInvalidMaskType(StringRef MaskType) override;
7270 
7271   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
7272                              const char *startSpecifier,
7273                              unsigned specifierLen) override;
7274   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7275                        const char *StartSpecifier,
7276                        unsigned SpecifierLen,
7277                        const Expr *E);
7278 
7279   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
7280                     const char *startSpecifier, unsigned specifierLen);
7281   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
7282                            const analyze_printf::OptionalAmount &Amt,
7283                            unsigned type,
7284                            const char *startSpecifier, unsigned specifierLen);
7285   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7286                   const analyze_printf::OptionalFlag &flag,
7287                   const char *startSpecifier, unsigned specifierLen);
7288   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
7289                          const analyze_printf::OptionalFlag &ignoredFlag,
7290                          const analyze_printf::OptionalFlag &flag,
7291                          const char *startSpecifier, unsigned specifierLen);
7292   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
7293                            const Expr *E);
7294 
7295   void HandleEmptyObjCModifierFlag(const char *startFlag,
7296                                    unsigned flagLen) override;
7297 
7298   void HandleInvalidObjCModifierFlag(const char *startFlag,
7299                                             unsigned flagLen) override;
7300 
7301   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
7302                                            const char *flagsEnd,
7303                                            const char *conversionPosition)
7304                                              override;
7305 };
7306 
7307 } // namespace
7308 
7309 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
7310                                       const analyze_printf::PrintfSpecifier &FS,
7311                                       const char *startSpecifier,
7312                                       unsigned specifierLen) {
7313   const analyze_printf::PrintfConversionSpecifier &CS =
7314     FS.getConversionSpecifier();
7315 
7316   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
7317                                           getLocationOfByte(CS.getStart()),
7318                                           startSpecifier, specifierLen,
7319                                           CS.getStart(), CS.getLength());
7320 }
7321 
7322 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
7323   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
7324 }
7325 
7326 bool CheckPrintfHandler::HandleAmount(
7327                                const analyze_format_string::OptionalAmount &Amt,
7328                                unsigned k, const char *startSpecifier,
7329                                unsigned specifierLen) {
7330   if (Amt.hasDataArgument()) {
7331     if (!HasVAListArg) {
7332       unsigned argIndex = Amt.getArgIndex();
7333       if (argIndex >= NumDataArgs) {
7334         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
7335                                << k,
7336                              getLocationOfByte(Amt.getStart()),
7337                              /*IsStringLocation*/true,
7338                              getSpecifierRange(startSpecifier, specifierLen));
7339         // Don't do any more checking.  We will just emit
7340         // spurious errors.
7341         return false;
7342       }
7343 
7344       // Type check the data argument.  It should be an 'int'.
7345       // Although not in conformance with C99, we also allow the argument to be
7346       // an 'unsigned int' as that is a reasonably safe case.  GCC also
7347       // doesn't emit a warning for that case.
7348       CoveredArgs.set(argIndex);
7349       const Expr *Arg = getDataArg(argIndex);
7350       if (!Arg)
7351         return false;
7352 
7353       QualType T = Arg->getType();
7354 
7355       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
7356       assert(AT.isValid());
7357 
7358       if (!AT.matchesType(S.Context, T)) {
7359         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
7360                                << k << AT.getRepresentativeTypeName(S.Context)
7361                                << T << Arg->getSourceRange(),
7362                              getLocationOfByte(Amt.getStart()),
7363                              /*IsStringLocation*/true,
7364                              getSpecifierRange(startSpecifier, specifierLen));
7365         // Don't do any more checking.  We will just emit
7366         // spurious errors.
7367         return false;
7368       }
7369     }
7370   }
7371   return true;
7372 }
7373 
7374 void CheckPrintfHandler::HandleInvalidAmount(
7375                                       const analyze_printf::PrintfSpecifier &FS,
7376                                       const analyze_printf::OptionalAmount &Amt,
7377                                       unsigned type,
7378                                       const char *startSpecifier,
7379                                       unsigned specifierLen) {
7380   const analyze_printf::PrintfConversionSpecifier &CS =
7381     FS.getConversionSpecifier();
7382 
7383   FixItHint fixit =
7384     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
7385       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
7386                                  Amt.getConstantLength()))
7387       : FixItHint();
7388 
7389   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
7390                          << type << CS.toString(),
7391                        getLocationOfByte(Amt.getStart()),
7392                        /*IsStringLocation*/true,
7393                        getSpecifierRange(startSpecifier, specifierLen),
7394                        fixit);
7395 }
7396 
7397 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7398                                     const analyze_printf::OptionalFlag &flag,
7399                                     const char *startSpecifier,
7400                                     unsigned specifierLen) {
7401   // Warn about pointless flag with a fixit removal.
7402   const analyze_printf::PrintfConversionSpecifier &CS =
7403     FS.getConversionSpecifier();
7404   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
7405                          << flag.toString() << CS.toString(),
7406                        getLocationOfByte(flag.getPosition()),
7407                        /*IsStringLocation*/true,
7408                        getSpecifierRange(startSpecifier, specifierLen),
7409                        FixItHint::CreateRemoval(
7410                          getSpecifierRange(flag.getPosition(), 1)));
7411 }
7412 
7413 void CheckPrintfHandler::HandleIgnoredFlag(
7414                                 const analyze_printf::PrintfSpecifier &FS,
7415                                 const analyze_printf::OptionalFlag &ignoredFlag,
7416                                 const analyze_printf::OptionalFlag &flag,
7417                                 const char *startSpecifier,
7418                                 unsigned specifierLen) {
7419   // Warn about ignored flag with a fixit removal.
7420   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
7421                          << ignoredFlag.toString() << flag.toString(),
7422                        getLocationOfByte(ignoredFlag.getPosition()),
7423                        /*IsStringLocation*/true,
7424                        getSpecifierRange(startSpecifier, specifierLen),
7425                        FixItHint::CreateRemoval(
7426                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
7427 }
7428 
7429 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
7430                                                      unsigned flagLen) {
7431   // Warn about an empty flag.
7432   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
7433                        getLocationOfByte(startFlag),
7434                        /*IsStringLocation*/true,
7435                        getSpecifierRange(startFlag, flagLen));
7436 }
7437 
7438 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
7439                                                        unsigned flagLen) {
7440   // Warn about an invalid flag.
7441   auto Range = getSpecifierRange(startFlag, flagLen);
7442   StringRef flag(startFlag, flagLen);
7443   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
7444                       getLocationOfByte(startFlag),
7445                       /*IsStringLocation*/true,
7446                       Range, FixItHint::CreateRemoval(Range));
7447 }
7448 
7449 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
7450     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
7451     // Warn about using '[...]' without a '@' conversion.
7452     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
7453     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
7454     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
7455                          getLocationOfByte(conversionPosition),
7456                          /*IsStringLocation*/true,
7457                          Range, FixItHint::CreateRemoval(Range));
7458 }
7459 
7460 // Determines if the specified is a C++ class or struct containing
7461 // a member with the specified name and kind (e.g. a CXXMethodDecl named
7462 // "c_str()").
7463 template<typename MemberKind>
7464 static llvm::SmallPtrSet<MemberKind*, 1>
7465 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
7466   const RecordType *RT = Ty->getAs<RecordType>();
7467   llvm::SmallPtrSet<MemberKind*, 1> Results;
7468 
7469   if (!RT)
7470     return Results;
7471   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
7472   if (!RD || !RD->getDefinition())
7473     return Results;
7474 
7475   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
7476                  Sema::LookupMemberName);
7477   R.suppressDiagnostics();
7478 
7479   // We just need to include all members of the right kind turned up by the
7480   // filter, at this point.
7481   if (S.LookupQualifiedName(R, RT->getDecl()))
7482     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7483       NamedDecl *decl = (*I)->getUnderlyingDecl();
7484       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
7485         Results.insert(FK);
7486     }
7487   return Results;
7488 }
7489 
7490 /// Check if we could call '.c_str()' on an object.
7491 ///
7492 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
7493 /// allow the call, or if it would be ambiguous).
7494 bool Sema::hasCStrMethod(const Expr *E) {
7495   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7496 
7497   MethodSet Results =
7498       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
7499   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7500        MI != ME; ++MI)
7501     if ((*MI)->getMinRequiredArguments() == 0)
7502       return true;
7503   return false;
7504 }
7505 
7506 // Check if a (w)string was passed when a (w)char* was needed, and offer a
7507 // better diagnostic if so. AT is assumed to be valid.
7508 // Returns true when a c_str() conversion method is found.
7509 bool CheckPrintfHandler::checkForCStrMembers(
7510     const analyze_printf::ArgType &AT, const Expr *E) {
7511   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7512 
7513   MethodSet Results =
7514       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
7515 
7516   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7517        MI != ME; ++MI) {
7518     const CXXMethodDecl *Method = *MI;
7519     if (Method->getMinRequiredArguments() == 0 &&
7520         AT.matchesType(S.Context, Method->getReturnType())) {
7521       // FIXME: Suggest parens if the expression needs them.
7522       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
7523       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
7524           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
7525       return true;
7526     }
7527   }
7528 
7529   return false;
7530 }
7531 
7532 bool
7533 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
7534                                             &FS,
7535                                           const char *startSpecifier,
7536                                           unsigned specifierLen) {
7537   using namespace analyze_format_string;
7538   using namespace analyze_printf;
7539 
7540   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
7541 
7542   if (FS.consumesDataArgument()) {
7543     if (atFirstArg) {
7544         atFirstArg = false;
7545         usesPositionalArgs = FS.usesPositionalArg();
7546     }
7547     else if (usesPositionalArgs != FS.usesPositionalArg()) {
7548       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
7549                                         startSpecifier, specifierLen);
7550       return false;
7551     }
7552   }
7553 
7554   // First check if the field width, precision, and conversion specifier
7555   // have matching data arguments.
7556   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
7557                     startSpecifier, specifierLen)) {
7558     return false;
7559   }
7560 
7561   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
7562                     startSpecifier, specifierLen)) {
7563     return false;
7564   }
7565 
7566   if (!CS.consumesDataArgument()) {
7567     // FIXME: Technically specifying a precision or field width here
7568     // makes no sense.  Worth issuing a warning at some point.
7569     return true;
7570   }
7571 
7572   // Consume the argument.
7573   unsigned argIndex = FS.getArgIndex();
7574   if (argIndex < NumDataArgs) {
7575     // The check to see if the argIndex is valid will come later.
7576     // We set the bit here because we may exit early from this
7577     // function if we encounter some other error.
7578     CoveredArgs.set(argIndex);
7579   }
7580 
7581   // FreeBSD kernel extensions.
7582   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
7583       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
7584     // We need at least two arguments.
7585     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
7586       return false;
7587 
7588     // Claim the second argument.
7589     CoveredArgs.set(argIndex + 1);
7590 
7591     // Type check the first argument (int for %b, pointer for %D)
7592     const Expr *Ex = getDataArg(argIndex);
7593     const analyze_printf::ArgType &AT =
7594       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
7595         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
7596     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
7597       EmitFormatDiagnostic(
7598           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7599               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
7600               << false << Ex->getSourceRange(),
7601           Ex->getBeginLoc(), /*IsStringLocation*/ false,
7602           getSpecifierRange(startSpecifier, specifierLen));
7603 
7604     // Type check the second argument (char * for both %b and %D)
7605     Ex = getDataArg(argIndex + 1);
7606     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
7607     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
7608       EmitFormatDiagnostic(
7609           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7610               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
7611               << false << Ex->getSourceRange(),
7612           Ex->getBeginLoc(), /*IsStringLocation*/ false,
7613           getSpecifierRange(startSpecifier, specifierLen));
7614 
7615      return true;
7616   }
7617 
7618   // Check for using an Objective-C specific conversion specifier
7619   // in a non-ObjC literal.
7620   if (!allowsObjCArg() && CS.isObjCArg()) {
7621     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7622                                                   specifierLen);
7623   }
7624 
7625   // %P can only be used with os_log.
7626   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
7627     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7628                                                   specifierLen);
7629   }
7630 
7631   // %n is not allowed with os_log.
7632   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
7633     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
7634                          getLocationOfByte(CS.getStart()),
7635                          /*IsStringLocation*/ false,
7636                          getSpecifierRange(startSpecifier, specifierLen));
7637 
7638     return true;
7639   }
7640 
7641   // Only scalars are allowed for os_trace.
7642   if (FSType == Sema::FST_OSTrace &&
7643       (CS.getKind() == ConversionSpecifier::PArg ||
7644        CS.getKind() == ConversionSpecifier::sArg ||
7645        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
7646     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7647                                                   specifierLen);
7648   }
7649 
7650   // Check for use of public/private annotation outside of os_log().
7651   if (FSType != Sema::FST_OSLog) {
7652     if (FS.isPublic().isSet()) {
7653       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
7654                                << "public",
7655                            getLocationOfByte(FS.isPublic().getPosition()),
7656                            /*IsStringLocation*/ false,
7657                            getSpecifierRange(startSpecifier, specifierLen));
7658     }
7659     if (FS.isPrivate().isSet()) {
7660       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
7661                                << "private",
7662                            getLocationOfByte(FS.isPrivate().getPosition()),
7663                            /*IsStringLocation*/ false,
7664                            getSpecifierRange(startSpecifier, specifierLen));
7665     }
7666   }
7667 
7668   // Check for invalid use of field width
7669   if (!FS.hasValidFieldWidth()) {
7670     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
7671         startSpecifier, specifierLen);
7672   }
7673 
7674   // Check for invalid use of precision
7675   if (!FS.hasValidPrecision()) {
7676     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
7677         startSpecifier, specifierLen);
7678   }
7679 
7680   // Precision is mandatory for %P specifier.
7681   if (CS.getKind() == ConversionSpecifier::PArg &&
7682       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
7683     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
7684                          getLocationOfByte(startSpecifier),
7685                          /*IsStringLocation*/ false,
7686                          getSpecifierRange(startSpecifier, specifierLen));
7687   }
7688 
7689   // Check each flag does not conflict with any other component.
7690   if (!FS.hasValidThousandsGroupingPrefix())
7691     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
7692   if (!FS.hasValidLeadingZeros())
7693     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
7694   if (!FS.hasValidPlusPrefix())
7695     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
7696   if (!FS.hasValidSpacePrefix())
7697     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
7698   if (!FS.hasValidAlternativeForm())
7699     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
7700   if (!FS.hasValidLeftJustified())
7701     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
7702 
7703   // Check that flags are not ignored by another flag
7704   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
7705     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
7706         startSpecifier, specifierLen);
7707   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
7708     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
7709             startSpecifier, specifierLen);
7710 
7711   // Check the length modifier is valid with the given conversion specifier.
7712   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
7713                                  S.getLangOpts()))
7714     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7715                                 diag::warn_format_nonsensical_length);
7716   else if (!FS.hasStandardLengthModifier())
7717     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
7718   else if (!FS.hasStandardLengthConversionCombination())
7719     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7720                                 diag::warn_format_non_standard_conversion_spec);
7721 
7722   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
7723     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
7724 
7725   // The remaining checks depend on the data arguments.
7726   if (HasVAListArg)
7727     return true;
7728 
7729   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
7730     return false;
7731 
7732   const Expr *Arg = getDataArg(argIndex);
7733   if (!Arg)
7734     return true;
7735 
7736   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
7737 }
7738 
7739 static bool requiresParensToAddCast(const Expr *E) {
7740   // FIXME: We should have a general way to reason about operator
7741   // precedence and whether parens are actually needed here.
7742   // Take care of a few common cases where they aren't.
7743   const Expr *Inside = E->IgnoreImpCasts();
7744   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
7745     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
7746 
7747   switch (Inside->getStmtClass()) {
7748   case Stmt::ArraySubscriptExprClass:
7749   case Stmt::CallExprClass:
7750   case Stmt::CharacterLiteralClass:
7751   case Stmt::CXXBoolLiteralExprClass:
7752   case Stmt::DeclRefExprClass:
7753   case Stmt::FloatingLiteralClass:
7754   case Stmt::IntegerLiteralClass:
7755   case Stmt::MemberExprClass:
7756   case Stmt::ObjCArrayLiteralClass:
7757   case Stmt::ObjCBoolLiteralExprClass:
7758   case Stmt::ObjCBoxedExprClass:
7759   case Stmt::ObjCDictionaryLiteralClass:
7760   case Stmt::ObjCEncodeExprClass:
7761   case Stmt::ObjCIvarRefExprClass:
7762   case Stmt::ObjCMessageExprClass:
7763   case Stmt::ObjCPropertyRefExprClass:
7764   case Stmt::ObjCStringLiteralClass:
7765   case Stmt::ObjCSubscriptRefExprClass:
7766   case Stmt::ParenExprClass:
7767   case Stmt::StringLiteralClass:
7768   case Stmt::UnaryOperatorClass:
7769     return false;
7770   default:
7771     return true;
7772   }
7773 }
7774 
7775 static std::pair<QualType, StringRef>
7776 shouldNotPrintDirectly(const ASTContext &Context,
7777                        QualType IntendedTy,
7778                        const Expr *E) {
7779   // Use a 'while' to peel off layers of typedefs.
7780   QualType TyTy = IntendedTy;
7781   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
7782     StringRef Name = UserTy->getDecl()->getName();
7783     QualType CastTy = llvm::StringSwitch<QualType>(Name)
7784       .Case("CFIndex", Context.getNSIntegerType())
7785       .Case("NSInteger", Context.getNSIntegerType())
7786       .Case("NSUInteger", Context.getNSUIntegerType())
7787       .Case("SInt32", Context.IntTy)
7788       .Case("UInt32", Context.UnsignedIntTy)
7789       .Default(QualType());
7790 
7791     if (!CastTy.isNull())
7792       return std::make_pair(CastTy, Name);
7793 
7794     TyTy = UserTy->desugar();
7795   }
7796 
7797   // Strip parens if necessary.
7798   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
7799     return shouldNotPrintDirectly(Context,
7800                                   PE->getSubExpr()->getType(),
7801                                   PE->getSubExpr());
7802 
7803   // If this is a conditional expression, then its result type is constructed
7804   // via usual arithmetic conversions and thus there might be no necessary
7805   // typedef sugar there.  Recurse to operands to check for NSInteger &
7806   // Co. usage condition.
7807   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
7808     QualType TrueTy, FalseTy;
7809     StringRef TrueName, FalseName;
7810 
7811     std::tie(TrueTy, TrueName) =
7812       shouldNotPrintDirectly(Context,
7813                              CO->getTrueExpr()->getType(),
7814                              CO->getTrueExpr());
7815     std::tie(FalseTy, FalseName) =
7816       shouldNotPrintDirectly(Context,
7817                              CO->getFalseExpr()->getType(),
7818                              CO->getFalseExpr());
7819 
7820     if (TrueTy == FalseTy)
7821       return std::make_pair(TrueTy, TrueName);
7822     else if (TrueTy.isNull())
7823       return std::make_pair(FalseTy, FalseName);
7824     else if (FalseTy.isNull())
7825       return std::make_pair(TrueTy, TrueName);
7826   }
7827 
7828   return std::make_pair(QualType(), StringRef());
7829 }
7830 
7831 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
7832 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
7833 /// type do not count.
7834 static bool
7835 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
7836   QualType From = ICE->getSubExpr()->getType();
7837   QualType To = ICE->getType();
7838   // It's an integer promotion if the destination type is the promoted
7839   // source type.
7840   if (ICE->getCastKind() == CK_IntegralCast &&
7841       From->isPromotableIntegerType() &&
7842       S.Context.getPromotedIntegerType(From) == To)
7843     return true;
7844   // Look through vector types, since we do default argument promotion for
7845   // those in OpenCL.
7846   if (const auto *VecTy = From->getAs<ExtVectorType>())
7847     From = VecTy->getElementType();
7848   if (const auto *VecTy = To->getAs<ExtVectorType>())
7849     To = VecTy->getElementType();
7850   // It's a floating promotion if the source type is a lower rank.
7851   return ICE->getCastKind() == CK_FloatingCast &&
7852          S.Context.getFloatingTypeOrder(From, To) < 0;
7853 }
7854 
7855 bool
7856 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7857                                     const char *StartSpecifier,
7858                                     unsigned SpecifierLen,
7859                                     const Expr *E) {
7860   using namespace analyze_format_string;
7861   using namespace analyze_printf;
7862 
7863   // Now type check the data expression that matches the
7864   // format specifier.
7865   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
7866   if (!AT.isValid())
7867     return true;
7868 
7869   QualType ExprTy = E->getType();
7870   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
7871     ExprTy = TET->getUnderlyingExpr()->getType();
7872   }
7873 
7874   // Diagnose attempts to print a boolean value as a character. Unlike other
7875   // -Wformat diagnostics, this is fine from a type perspective, but it still
7876   // doesn't make sense.
7877   if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
7878       E->isKnownToHaveBooleanValue()) {
7879     const CharSourceRange &CSR =
7880         getSpecifierRange(StartSpecifier, SpecifierLen);
7881     SmallString<4> FSString;
7882     llvm::raw_svector_ostream os(FSString);
7883     FS.toString(os);
7884     EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
7885                              << FSString,
7886                          E->getExprLoc(), false, CSR);
7887     return true;
7888   }
7889 
7890   analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
7891   if (Match == analyze_printf::ArgType::Match)
7892     return true;
7893 
7894   // Look through argument promotions for our error message's reported type.
7895   // This includes the integral and floating promotions, but excludes array
7896   // and function pointer decay (seeing that an argument intended to be a
7897   // string has type 'char [6]' is probably more confusing than 'char *') and
7898   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
7899   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
7900     if (isArithmeticArgumentPromotion(S, ICE)) {
7901       E = ICE->getSubExpr();
7902       ExprTy = E->getType();
7903 
7904       // Check if we didn't match because of an implicit cast from a 'char'
7905       // or 'short' to an 'int'.  This is done because printf is a varargs
7906       // function.
7907       if (ICE->getType() == S.Context.IntTy ||
7908           ICE->getType() == S.Context.UnsignedIntTy) {
7909         // All further checking is done on the subexpression
7910         const analyze_printf::ArgType::MatchKind ImplicitMatch =
7911             AT.matchesType(S.Context, ExprTy);
7912         if (ImplicitMatch == analyze_printf::ArgType::Match)
7913           return true;
7914         if (ImplicitMatch == ArgType::NoMatchPedantic ||
7915             ImplicitMatch == ArgType::NoMatchTypeConfusion)
7916           Match = ImplicitMatch;
7917       }
7918     }
7919   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
7920     // Special case for 'a', which has type 'int' in C.
7921     // Note, however, that we do /not/ want to treat multibyte constants like
7922     // 'MooV' as characters! This form is deprecated but still exists.
7923     if (ExprTy == S.Context.IntTy)
7924       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
7925         ExprTy = S.Context.CharTy;
7926   }
7927 
7928   // Look through enums to their underlying type.
7929   bool IsEnum = false;
7930   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
7931     ExprTy = EnumTy->getDecl()->getIntegerType();
7932     IsEnum = true;
7933   }
7934 
7935   // %C in an Objective-C context prints a unichar, not a wchar_t.
7936   // If the argument is an integer of some kind, believe the %C and suggest
7937   // a cast instead of changing the conversion specifier.
7938   QualType IntendedTy = ExprTy;
7939   if (isObjCContext() &&
7940       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
7941     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
7942         !ExprTy->isCharType()) {
7943       // 'unichar' is defined as a typedef of unsigned short, but we should
7944       // prefer using the typedef if it is visible.
7945       IntendedTy = S.Context.UnsignedShortTy;
7946 
7947       // While we are here, check if the value is an IntegerLiteral that happens
7948       // to be within the valid range.
7949       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
7950         const llvm::APInt &V = IL->getValue();
7951         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
7952           return true;
7953       }
7954 
7955       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
7956                           Sema::LookupOrdinaryName);
7957       if (S.LookupName(Result, S.getCurScope())) {
7958         NamedDecl *ND = Result.getFoundDecl();
7959         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
7960           if (TD->getUnderlyingType() == IntendedTy)
7961             IntendedTy = S.Context.getTypedefType(TD);
7962       }
7963     }
7964   }
7965 
7966   // Special-case some of Darwin's platform-independence types by suggesting
7967   // casts to primitive types that are known to be large enough.
7968   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
7969   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
7970     QualType CastTy;
7971     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
7972     if (!CastTy.isNull()) {
7973       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
7974       // (long in ASTContext). Only complain to pedants.
7975       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
7976           (AT.isSizeT() || AT.isPtrdiffT()) &&
7977           AT.matchesType(S.Context, CastTy))
7978         Match = ArgType::NoMatchPedantic;
7979       IntendedTy = CastTy;
7980       ShouldNotPrintDirectly = true;
7981     }
7982   }
7983 
7984   // We may be able to offer a FixItHint if it is a supported type.
7985   PrintfSpecifier fixedFS = FS;
7986   bool Success =
7987       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
7988 
7989   if (Success) {
7990     // Get the fix string from the fixed format specifier
7991     SmallString<16> buf;
7992     llvm::raw_svector_ostream os(buf);
7993     fixedFS.toString(os);
7994 
7995     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
7996 
7997     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
7998       unsigned Diag;
7999       switch (Match) {
8000       case ArgType::Match: llvm_unreachable("expected non-matching");
8001       case ArgType::NoMatchPedantic:
8002         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8003         break;
8004       case ArgType::NoMatchTypeConfusion:
8005         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8006         break;
8007       case ArgType::NoMatch:
8008         Diag = diag::warn_format_conversion_argument_type_mismatch;
8009         break;
8010       }
8011 
8012       // In this case, the specifier is wrong and should be changed to match
8013       // the argument.
8014       EmitFormatDiagnostic(S.PDiag(Diag)
8015                                << AT.getRepresentativeTypeName(S.Context)
8016                                << IntendedTy << IsEnum << E->getSourceRange(),
8017                            E->getBeginLoc(),
8018                            /*IsStringLocation*/ false, SpecRange,
8019                            FixItHint::CreateReplacement(SpecRange, os.str()));
8020     } else {
8021       // The canonical type for formatting this value is different from the
8022       // actual type of the expression. (This occurs, for example, with Darwin's
8023       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
8024       // should be printed as 'long' for 64-bit compatibility.)
8025       // Rather than emitting a normal format/argument mismatch, we want to
8026       // add a cast to the recommended type (and correct the format string
8027       // if necessary).
8028       SmallString<16> CastBuf;
8029       llvm::raw_svector_ostream CastFix(CastBuf);
8030       CastFix << "(";
8031       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
8032       CastFix << ")";
8033 
8034       SmallVector<FixItHint,4> Hints;
8035       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
8036         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
8037 
8038       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
8039         // If there's already a cast present, just replace it.
8040         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
8041         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
8042 
8043       } else if (!requiresParensToAddCast(E)) {
8044         // If the expression has high enough precedence,
8045         // just write the C-style cast.
8046         Hints.push_back(
8047             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8048       } else {
8049         // Otherwise, add parens around the expression as well as the cast.
8050         CastFix << "(";
8051         Hints.push_back(
8052             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8053 
8054         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
8055         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
8056       }
8057 
8058       if (ShouldNotPrintDirectly) {
8059         // The expression has a type that should not be printed directly.
8060         // We extract the name from the typedef because we don't want to show
8061         // the underlying type in the diagnostic.
8062         StringRef Name;
8063         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
8064           Name = TypedefTy->getDecl()->getName();
8065         else
8066           Name = CastTyName;
8067         unsigned Diag = Match == ArgType::NoMatchPedantic
8068                             ? diag::warn_format_argument_needs_cast_pedantic
8069                             : diag::warn_format_argument_needs_cast;
8070         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
8071                                            << E->getSourceRange(),
8072                              E->getBeginLoc(), /*IsStringLocation=*/false,
8073                              SpecRange, Hints);
8074       } else {
8075         // In this case, the expression could be printed using a different
8076         // specifier, but we've decided that the specifier is probably correct
8077         // and we should cast instead. Just use the normal warning message.
8078         EmitFormatDiagnostic(
8079             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8080                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
8081                 << E->getSourceRange(),
8082             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
8083       }
8084     }
8085   } else {
8086     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
8087                                                    SpecifierLen);
8088     // Since the warning for passing non-POD types to variadic functions
8089     // was deferred until now, we emit a warning for non-POD
8090     // arguments here.
8091     switch (S.isValidVarArgType(ExprTy)) {
8092     case Sema::VAK_Valid:
8093     case Sema::VAK_ValidInCXX11: {
8094       unsigned Diag;
8095       switch (Match) {
8096       case ArgType::Match: llvm_unreachable("expected non-matching");
8097       case ArgType::NoMatchPedantic:
8098         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8099         break;
8100       case ArgType::NoMatchTypeConfusion:
8101         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8102         break;
8103       case ArgType::NoMatch:
8104         Diag = diag::warn_format_conversion_argument_type_mismatch;
8105         break;
8106       }
8107 
8108       EmitFormatDiagnostic(
8109           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
8110                         << IsEnum << CSR << E->getSourceRange(),
8111           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8112       break;
8113     }
8114     case Sema::VAK_Undefined:
8115     case Sema::VAK_MSVCUndefined:
8116       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
8117                                << S.getLangOpts().CPlusPlus11 << ExprTy
8118                                << CallType
8119                                << AT.getRepresentativeTypeName(S.Context) << CSR
8120                                << E->getSourceRange(),
8121                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8122       checkForCStrMembers(AT, E);
8123       break;
8124 
8125     case Sema::VAK_Invalid:
8126       if (ExprTy->isObjCObjectType())
8127         EmitFormatDiagnostic(
8128             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
8129                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
8130                 << AT.getRepresentativeTypeName(S.Context) << CSR
8131                 << E->getSourceRange(),
8132             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8133       else
8134         // FIXME: If this is an initializer list, suggest removing the braces
8135         // or inserting a cast to the target type.
8136         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
8137             << isa<InitListExpr>(E) << ExprTy << CallType
8138             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
8139       break;
8140     }
8141 
8142     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
8143            "format string specifier index out of range");
8144     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
8145   }
8146 
8147   return true;
8148 }
8149 
8150 //===--- CHECK: Scanf format string checking ------------------------------===//
8151 
8152 namespace {
8153 
8154 class CheckScanfHandler : public CheckFormatHandler {
8155 public:
8156   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
8157                     const Expr *origFormatExpr, Sema::FormatStringType type,
8158                     unsigned firstDataArg, unsigned numDataArgs,
8159                     const char *beg, bool hasVAListArg,
8160                     ArrayRef<const Expr *> Args, unsigned formatIdx,
8161                     bool inFunctionCall, Sema::VariadicCallType CallType,
8162                     llvm::SmallBitVector &CheckedVarArgs,
8163                     UncoveredArgHandler &UncoveredArg)
8164       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8165                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
8166                            inFunctionCall, CallType, CheckedVarArgs,
8167                            UncoveredArg) {}
8168 
8169   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
8170                             const char *startSpecifier,
8171                             unsigned specifierLen) override;
8172 
8173   bool HandleInvalidScanfConversionSpecifier(
8174           const analyze_scanf::ScanfSpecifier &FS,
8175           const char *startSpecifier,
8176           unsigned specifierLen) override;
8177 
8178   void HandleIncompleteScanList(const char *start, const char *end) override;
8179 };
8180 
8181 } // namespace
8182 
8183 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
8184                                                  const char *end) {
8185   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
8186                        getLocationOfByte(end), /*IsStringLocation*/true,
8187                        getSpecifierRange(start, end - start));
8188 }
8189 
8190 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
8191                                         const analyze_scanf::ScanfSpecifier &FS,
8192                                         const char *startSpecifier,
8193                                         unsigned specifierLen) {
8194   const analyze_scanf::ScanfConversionSpecifier &CS =
8195     FS.getConversionSpecifier();
8196 
8197   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8198                                           getLocationOfByte(CS.getStart()),
8199                                           startSpecifier, specifierLen,
8200                                           CS.getStart(), CS.getLength());
8201 }
8202 
8203 bool CheckScanfHandler::HandleScanfSpecifier(
8204                                        const analyze_scanf::ScanfSpecifier &FS,
8205                                        const char *startSpecifier,
8206                                        unsigned specifierLen) {
8207   using namespace analyze_scanf;
8208   using namespace analyze_format_string;
8209 
8210   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
8211 
8212   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
8213   // be used to decide if we are using positional arguments consistently.
8214   if (FS.consumesDataArgument()) {
8215     if (atFirstArg) {
8216       atFirstArg = false;
8217       usesPositionalArgs = FS.usesPositionalArg();
8218     }
8219     else if (usesPositionalArgs != FS.usesPositionalArg()) {
8220       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8221                                         startSpecifier, specifierLen);
8222       return false;
8223     }
8224   }
8225 
8226   // Check if the field with is non-zero.
8227   const OptionalAmount &Amt = FS.getFieldWidth();
8228   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
8229     if (Amt.getConstantAmount() == 0) {
8230       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
8231                                                    Amt.getConstantLength());
8232       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
8233                            getLocationOfByte(Amt.getStart()),
8234                            /*IsStringLocation*/true, R,
8235                            FixItHint::CreateRemoval(R));
8236     }
8237   }
8238 
8239   if (!FS.consumesDataArgument()) {
8240     // FIXME: Technically specifying a precision or field width here
8241     // makes no sense.  Worth issuing a warning at some point.
8242     return true;
8243   }
8244 
8245   // Consume the argument.
8246   unsigned argIndex = FS.getArgIndex();
8247   if (argIndex < NumDataArgs) {
8248       // The check to see if the argIndex is valid will come later.
8249       // We set the bit here because we may exit early from this
8250       // function if we encounter some other error.
8251     CoveredArgs.set(argIndex);
8252   }
8253 
8254   // Check the length modifier is valid with the given conversion specifier.
8255   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8256                                  S.getLangOpts()))
8257     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8258                                 diag::warn_format_nonsensical_length);
8259   else if (!FS.hasStandardLengthModifier())
8260     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8261   else if (!FS.hasStandardLengthConversionCombination())
8262     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8263                                 diag::warn_format_non_standard_conversion_spec);
8264 
8265   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8266     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8267 
8268   // The remaining checks depend on the data arguments.
8269   if (HasVAListArg)
8270     return true;
8271 
8272   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8273     return false;
8274 
8275   // Check that the argument type matches the format specifier.
8276   const Expr *Ex = getDataArg(argIndex);
8277   if (!Ex)
8278     return true;
8279 
8280   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
8281 
8282   if (!AT.isValid()) {
8283     return true;
8284   }
8285 
8286   analyze_format_string::ArgType::MatchKind Match =
8287       AT.matchesType(S.Context, Ex->getType());
8288   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
8289   if (Match == analyze_format_string::ArgType::Match)
8290     return true;
8291 
8292   ScanfSpecifier fixedFS = FS;
8293   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
8294                                  S.getLangOpts(), S.Context);
8295 
8296   unsigned Diag =
8297       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
8298                : diag::warn_format_conversion_argument_type_mismatch;
8299 
8300   if (Success) {
8301     // Get the fix string from the fixed format specifier.
8302     SmallString<128> buf;
8303     llvm::raw_svector_ostream os(buf);
8304     fixedFS.toString(os);
8305 
8306     EmitFormatDiagnostic(
8307         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
8308                       << Ex->getType() << false << Ex->getSourceRange(),
8309         Ex->getBeginLoc(),
8310         /*IsStringLocation*/ false,
8311         getSpecifierRange(startSpecifier, specifierLen),
8312         FixItHint::CreateReplacement(
8313             getSpecifierRange(startSpecifier, specifierLen), os.str()));
8314   } else {
8315     EmitFormatDiagnostic(S.PDiag(Diag)
8316                              << AT.getRepresentativeTypeName(S.Context)
8317                              << Ex->getType() << false << Ex->getSourceRange(),
8318                          Ex->getBeginLoc(),
8319                          /*IsStringLocation*/ false,
8320                          getSpecifierRange(startSpecifier, specifierLen));
8321   }
8322 
8323   return true;
8324 }
8325 
8326 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
8327                               const Expr *OrigFormatExpr,
8328                               ArrayRef<const Expr *> Args,
8329                               bool HasVAListArg, unsigned format_idx,
8330                               unsigned firstDataArg,
8331                               Sema::FormatStringType Type,
8332                               bool inFunctionCall,
8333                               Sema::VariadicCallType CallType,
8334                               llvm::SmallBitVector &CheckedVarArgs,
8335                               UncoveredArgHandler &UncoveredArg,
8336                               bool IgnoreStringsWithoutSpecifiers) {
8337   // CHECK: is the format string a wide literal?
8338   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
8339     CheckFormatHandler::EmitFormatDiagnostic(
8340         S, inFunctionCall, Args[format_idx],
8341         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
8342         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8343     return;
8344   }
8345 
8346   // Str - The format string.  NOTE: this is NOT null-terminated!
8347   StringRef StrRef = FExpr->getString();
8348   const char *Str = StrRef.data();
8349   // Account for cases where the string literal is truncated in a declaration.
8350   const ConstantArrayType *T =
8351     S.Context.getAsConstantArrayType(FExpr->getType());
8352   assert(T && "String literal not of constant array type!");
8353   size_t TypeSize = T->getSize().getZExtValue();
8354   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8355   const unsigned numDataArgs = Args.size() - firstDataArg;
8356 
8357   if (IgnoreStringsWithoutSpecifiers &&
8358       !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
8359           Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
8360     return;
8361 
8362   // Emit a warning if the string literal is truncated and does not contain an
8363   // embedded null character.
8364   if (TypeSize <= StrRef.size() &&
8365       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
8366     CheckFormatHandler::EmitFormatDiagnostic(
8367         S, inFunctionCall, Args[format_idx],
8368         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
8369         FExpr->getBeginLoc(),
8370         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
8371     return;
8372   }
8373 
8374   // CHECK: empty format string?
8375   if (StrLen == 0 && numDataArgs > 0) {
8376     CheckFormatHandler::EmitFormatDiagnostic(
8377         S, inFunctionCall, Args[format_idx],
8378         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
8379         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8380     return;
8381   }
8382 
8383   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
8384       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
8385       Type == Sema::FST_OSTrace) {
8386     CheckPrintfHandler H(
8387         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
8388         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
8389         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
8390         CheckedVarArgs, UncoveredArg);
8391 
8392     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
8393                                                   S.getLangOpts(),
8394                                                   S.Context.getTargetInfo(),
8395                                             Type == Sema::FST_FreeBSDKPrintf))
8396       H.DoneProcessing();
8397   } else if (Type == Sema::FST_Scanf) {
8398     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
8399                         numDataArgs, Str, HasVAListArg, Args, format_idx,
8400                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
8401 
8402     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
8403                                                  S.getLangOpts(),
8404                                                  S.Context.getTargetInfo()))
8405       H.DoneProcessing();
8406   } // TODO: handle other formats
8407 }
8408 
8409 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
8410   // Str - The format string.  NOTE: this is NOT null-terminated!
8411   StringRef StrRef = FExpr->getString();
8412   const char *Str = StrRef.data();
8413   // Account for cases where the string literal is truncated in a declaration.
8414   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
8415   assert(T && "String literal not of constant array type!");
8416   size_t TypeSize = T->getSize().getZExtValue();
8417   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8418   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
8419                                                          getLangOpts(),
8420                                                          Context.getTargetInfo());
8421 }
8422 
8423 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
8424 
8425 // Returns the related absolute value function that is larger, of 0 if one
8426 // does not exist.
8427 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
8428   switch (AbsFunction) {
8429   default:
8430     return 0;
8431 
8432   case Builtin::BI__builtin_abs:
8433     return Builtin::BI__builtin_labs;
8434   case Builtin::BI__builtin_labs:
8435     return Builtin::BI__builtin_llabs;
8436   case Builtin::BI__builtin_llabs:
8437     return 0;
8438 
8439   case Builtin::BI__builtin_fabsf:
8440     return Builtin::BI__builtin_fabs;
8441   case Builtin::BI__builtin_fabs:
8442     return Builtin::BI__builtin_fabsl;
8443   case Builtin::BI__builtin_fabsl:
8444     return 0;
8445 
8446   case Builtin::BI__builtin_cabsf:
8447     return Builtin::BI__builtin_cabs;
8448   case Builtin::BI__builtin_cabs:
8449     return Builtin::BI__builtin_cabsl;
8450   case Builtin::BI__builtin_cabsl:
8451     return 0;
8452 
8453   case Builtin::BIabs:
8454     return Builtin::BIlabs;
8455   case Builtin::BIlabs:
8456     return Builtin::BIllabs;
8457   case Builtin::BIllabs:
8458     return 0;
8459 
8460   case Builtin::BIfabsf:
8461     return Builtin::BIfabs;
8462   case Builtin::BIfabs:
8463     return Builtin::BIfabsl;
8464   case Builtin::BIfabsl:
8465     return 0;
8466 
8467   case Builtin::BIcabsf:
8468    return Builtin::BIcabs;
8469   case Builtin::BIcabs:
8470     return Builtin::BIcabsl;
8471   case Builtin::BIcabsl:
8472     return 0;
8473   }
8474 }
8475 
8476 // Returns the argument type of the absolute value function.
8477 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
8478                                              unsigned AbsType) {
8479   if (AbsType == 0)
8480     return QualType();
8481 
8482   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
8483   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
8484   if (Error != ASTContext::GE_None)
8485     return QualType();
8486 
8487   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
8488   if (!FT)
8489     return QualType();
8490 
8491   if (FT->getNumParams() != 1)
8492     return QualType();
8493 
8494   return FT->getParamType(0);
8495 }
8496 
8497 // Returns the best absolute value function, or zero, based on type and
8498 // current absolute value function.
8499 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
8500                                    unsigned AbsFunctionKind) {
8501   unsigned BestKind = 0;
8502   uint64_t ArgSize = Context.getTypeSize(ArgType);
8503   for (unsigned Kind = AbsFunctionKind; Kind != 0;
8504        Kind = getLargerAbsoluteValueFunction(Kind)) {
8505     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
8506     if (Context.getTypeSize(ParamType) >= ArgSize) {
8507       if (BestKind == 0)
8508         BestKind = Kind;
8509       else if (Context.hasSameType(ParamType, ArgType)) {
8510         BestKind = Kind;
8511         break;
8512       }
8513     }
8514   }
8515   return BestKind;
8516 }
8517 
8518 enum AbsoluteValueKind {
8519   AVK_Integer,
8520   AVK_Floating,
8521   AVK_Complex
8522 };
8523 
8524 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
8525   if (T->isIntegralOrEnumerationType())
8526     return AVK_Integer;
8527   if (T->isRealFloatingType())
8528     return AVK_Floating;
8529   if (T->isAnyComplexType())
8530     return AVK_Complex;
8531 
8532   llvm_unreachable("Type not integer, floating, or complex");
8533 }
8534 
8535 // Changes the absolute value function to a different type.  Preserves whether
8536 // the function is a builtin.
8537 static unsigned changeAbsFunction(unsigned AbsKind,
8538                                   AbsoluteValueKind ValueKind) {
8539   switch (ValueKind) {
8540   case AVK_Integer:
8541     switch (AbsKind) {
8542     default:
8543       return 0;
8544     case Builtin::BI__builtin_fabsf:
8545     case Builtin::BI__builtin_fabs:
8546     case Builtin::BI__builtin_fabsl:
8547     case Builtin::BI__builtin_cabsf:
8548     case Builtin::BI__builtin_cabs:
8549     case Builtin::BI__builtin_cabsl:
8550       return Builtin::BI__builtin_abs;
8551     case Builtin::BIfabsf:
8552     case Builtin::BIfabs:
8553     case Builtin::BIfabsl:
8554     case Builtin::BIcabsf:
8555     case Builtin::BIcabs:
8556     case Builtin::BIcabsl:
8557       return Builtin::BIabs;
8558     }
8559   case AVK_Floating:
8560     switch (AbsKind) {
8561     default:
8562       return 0;
8563     case Builtin::BI__builtin_abs:
8564     case Builtin::BI__builtin_labs:
8565     case Builtin::BI__builtin_llabs:
8566     case Builtin::BI__builtin_cabsf:
8567     case Builtin::BI__builtin_cabs:
8568     case Builtin::BI__builtin_cabsl:
8569       return Builtin::BI__builtin_fabsf;
8570     case Builtin::BIabs:
8571     case Builtin::BIlabs:
8572     case Builtin::BIllabs:
8573     case Builtin::BIcabsf:
8574     case Builtin::BIcabs:
8575     case Builtin::BIcabsl:
8576       return Builtin::BIfabsf;
8577     }
8578   case AVK_Complex:
8579     switch (AbsKind) {
8580     default:
8581       return 0;
8582     case Builtin::BI__builtin_abs:
8583     case Builtin::BI__builtin_labs:
8584     case Builtin::BI__builtin_llabs:
8585     case Builtin::BI__builtin_fabsf:
8586     case Builtin::BI__builtin_fabs:
8587     case Builtin::BI__builtin_fabsl:
8588       return Builtin::BI__builtin_cabsf;
8589     case Builtin::BIabs:
8590     case Builtin::BIlabs:
8591     case Builtin::BIllabs:
8592     case Builtin::BIfabsf:
8593     case Builtin::BIfabs:
8594     case Builtin::BIfabsl:
8595       return Builtin::BIcabsf;
8596     }
8597   }
8598   llvm_unreachable("Unable to convert function");
8599 }
8600 
8601 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
8602   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
8603   if (!FnInfo)
8604     return 0;
8605 
8606   switch (FDecl->getBuiltinID()) {
8607   default:
8608     return 0;
8609   case Builtin::BI__builtin_abs:
8610   case Builtin::BI__builtin_fabs:
8611   case Builtin::BI__builtin_fabsf:
8612   case Builtin::BI__builtin_fabsl:
8613   case Builtin::BI__builtin_labs:
8614   case Builtin::BI__builtin_llabs:
8615   case Builtin::BI__builtin_cabs:
8616   case Builtin::BI__builtin_cabsf:
8617   case Builtin::BI__builtin_cabsl:
8618   case Builtin::BIabs:
8619   case Builtin::BIlabs:
8620   case Builtin::BIllabs:
8621   case Builtin::BIfabs:
8622   case Builtin::BIfabsf:
8623   case Builtin::BIfabsl:
8624   case Builtin::BIcabs:
8625   case Builtin::BIcabsf:
8626   case Builtin::BIcabsl:
8627     return FDecl->getBuiltinID();
8628   }
8629   llvm_unreachable("Unknown Builtin type");
8630 }
8631 
8632 // If the replacement is valid, emit a note with replacement function.
8633 // Additionally, suggest including the proper header if not already included.
8634 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
8635                             unsigned AbsKind, QualType ArgType) {
8636   bool EmitHeaderHint = true;
8637   const char *HeaderName = nullptr;
8638   const char *FunctionName = nullptr;
8639   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
8640     FunctionName = "std::abs";
8641     if (ArgType->isIntegralOrEnumerationType()) {
8642       HeaderName = "cstdlib";
8643     } else if (ArgType->isRealFloatingType()) {
8644       HeaderName = "cmath";
8645     } else {
8646       llvm_unreachable("Invalid Type");
8647     }
8648 
8649     // Lookup all std::abs
8650     if (NamespaceDecl *Std = S.getStdNamespace()) {
8651       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
8652       R.suppressDiagnostics();
8653       S.LookupQualifiedName(R, Std);
8654 
8655       for (const auto *I : R) {
8656         const FunctionDecl *FDecl = nullptr;
8657         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
8658           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
8659         } else {
8660           FDecl = dyn_cast<FunctionDecl>(I);
8661         }
8662         if (!FDecl)
8663           continue;
8664 
8665         // Found std::abs(), check that they are the right ones.
8666         if (FDecl->getNumParams() != 1)
8667           continue;
8668 
8669         // Check that the parameter type can handle the argument.
8670         QualType ParamType = FDecl->getParamDecl(0)->getType();
8671         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
8672             S.Context.getTypeSize(ArgType) <=
8673                 S.Context.getTypeSize(ParamType)) {
8674           // Found a function, don't need the header hint.
8675           EmitHeaderHint = false;
8676           break;
8677         }
8678       }
8679     }
8680   } else {
8681     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
8682     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
8683 
8684     if (HeaderName) {
8685       DeclarationName DN(&S.Context.Idents.get(FunctionName));
8686       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
8687       R.suppressDiagnostics();
8688       S.LookupName(R, S.getCurScope());
8689 
8690       if (R.isSingleResult()) {
8691         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
8692         if (FD && FD->getBuiltinID() == AbsKind) {
8693           EmitHeaderHint = false;
8694         } else {
8695           return;
8696         }
8697       } else if (!R.empty()) {
8698         return;
8699       }
8700     }
8701   }
8702 
8703   S.Diag(Loc, diag::note_replace_abs_function)
8704       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
8705 
8706   if (!HeaderName)
8707     return;
8708 
8709   if (!EmitHeaderHint)
8710     return;
8711 
8712   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
8713                                                     << FunctionName;
8714 }
8715 
8716 template <std::size_t StrLen>
8717 static bool IsStdFunction(const FunctionDecl *FDecl,
8718                           const char (&Str)[StrLen]) {
8719   if (!FDecl)
8720     return false;
8721   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
8722     return false;
8723   if (!FDecl->isInStdNamespace())
8724     return false;
8725 
8726   return true;
8727 }
8728 
8729 // Warn when using the wrong abs() function.
8730 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
8731                                       const FunctionDecl *FDecl) {
8732   if (Call->getNumArgs() != 1)
8733     return;
8734 
8735   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
8736   bool IsStdAbs = IsStdFunction(FDecl, "abs");
8737   if (AbsKind == 0 && !IsStdAbs)
8738     return;
8739 
8740   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
8741   QualType ParamType = Call->getArg(0)->getType();
8742 
8743   // Unsigned types cannot be negative.  Suggest removing the absolute value
8744   // function call.
8745   if (ArgType->isUnsignedIntegerType()) {
8746     const char *FunctionName =
8747         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
8748     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
8749     Diag(Call->getExprLoc(), diag::note_remove_abs)
8750         << FunctionName
8751         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
8752     return;
8753   }
8754 
8755   // Taking the absolute value of a pointer is very suspicious, they probably
8756   // wanted to index into an array, dereference a pointer, call a function, etc.
8757   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
8758     unsigned DiagType = 0;
8759     if (ArgType->isFunctionType())
8760       DiagType = 1;
8761     else if (ArgType->isArrayType())
8762       DiagType = 2;
8763 
8764     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
8765     return;
8766   }
8767 
8768   // std::abs has overloads which prevent most of the absolute value problems
8769   // from occurring.
8770   if (IsStdAbs)
8771     return;
8772 
8773   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
8774   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
8775 
8776   // The argument and parameter are the same kind.  Check if they are the right
8777   // size.
8778   if (ArgValueKind == ParamValueKind) {
8779     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
8780       return;
8781 
8782     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
8783     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
8784         << FDecl << ArgType << ParamType;
8785 
8786     if (NewAbsKind == 0)
8787       return;
8788 
8789     emitReplacement(*this, Call->getExprLoc(),
8790                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
8791     return;
8792   }
8793 
8794   // ArgValueKind != ParamValueKind
8795   // The wrong type of absolute value function was used.  Attempt to find the
8796   // proper one.
8797   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
8798   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
8799   if (NewAbsKind == 0)
8800     return;
8801 
8802   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
8803       << FDecl << ParamValueKind << ArgValueKind;
8804 
8805   emitReplacement(*this, Call->getExprLoc(),
8806                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
8807 }
8808 
8809 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
8810 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
8811                                 const FunctionDecl *FDecl) {
8812   if (!Call || !FDecl) return;
8813 
8814   // Ignore template specializations and macros.
8815   if (inTemplateInstantiation()) return;
8816   if (Call->getExprLoc().isMacroID()) return;
8817 
8818   // Only care about the one template argument, two function parameter std::max
8819   if (Call->getNumArgs() != 2) return;
8820   if (!IsStdFunction(FDecl, "max")) return;
8821   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
8822   if (!ArgList) return;
8823   if (ArgList->size() != 1) return;
8824 
8825   // Check that template type argument is unsigned integer.
8826   const auto& TA = ArgList->get(0);
8827   if (TA.getKind() != TemplateArgument::Type) return;
8828   QualType ArgType = TA.getAsType();
8829   if (!ArgType->isUnsignedIntegerType()) return;
8830 
8831   // See if either argument is a literal zero.
8832   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
8833     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
8834     if (!MTE) return false;
8835     const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
8836     if (!Num) return false;
8837     if (Num->getValue() != 0) return false;
8838     return true;
8839   };
8840 
8841   const Expr *FirstArg = Call->getArg(0);
8842   const Expr *SecondArg = Call->getArg(1);
8843   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
8844   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
8845 
8846   // Only warn when exactly one argument is zero.
8847   if (IsFirstArgZero == IsSecondArgZero) return;
8848 
8849   SourceRange FirstRange = FirstArg->getSourceRange();
8850   SourceRange SecondRange = SecondArg->getSourceRange();
8851 
8852   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
8853 
8854   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
8855       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
8856 
8857   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
8858   SourceRange RemovalRange;
8859   if (IsFirstArgZero) {
8860     RemovalRange = SourceRange(FirstRange.getBegin(),
8861                                SecondRange.getBegin().getLocWithOffset(-1));
8862   } else {
8863     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
8864                                SecondRange.getEnd());
8865   }
8866 
8867   Diag(Call->getExprLoc(), diag::note_remove_max_call)
8868         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
8869         << FixItHint::CreateRemoval(RemovalRange);
8870 }
8871 
8872 //===--- CHECK: Standard memory functions ---------------------------------===//
8873 
8874 /// Takes the expression passed to the size_t parameter of functions
8875 /// such as memcmp, strncat, etc and warns if it's a comparison.
8876 ///
8877 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
8878 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
8879                                            IdentifierInfo *FnName,
8880                                            SourceLocation FnLoc,
8881                                            SourceLocation RParenLoc) {
8882   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
8883   if (!Size)
8884     return false;
8885 
8886   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
8887   if (!Size->isComparisonOp() && !Size->isLogicalOp())
8888     return false;
8889 
8890   SourceRange SizeRange = Size->getSourceRange();
8891   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
8892       << SizeRange << FnName;
8893   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
8894       << FnName
8895       << FixItHint::CreateInsertion(
8896              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
8897       << FixItHint::CreateRemoval(RParenLoc);
8898   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
8899       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
8900       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
8901                                     ")");
8902 
8903   return true;
8904 }
8905 
8906 /// Determine whether the given type is or contains a dynamic class type
8907 /// (e.g., whether it has a vtable).
8908 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
8909                                                      bool &IsContained) {
8910   // Look through array types while ignoring qualifiers.
8911   const Type *Ty = T->getBaseElementTypeUnsafe();
8912   IsContained = false;
8913 
8914   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
8915   RD = RD ? RD->getDefinition() : nullptr;
8916   if (!RD || RD->isInvalidDecl())
8917     return nullptr;
8918 
8919   if (RD->isDynamicClass())
8920     return RD;
8921 
8922   // Check all the fields.  If any bases were dynamic, the class is dynamic.
8923   // It's impossible for a class to transitively contain itself by value, so
8924   // infinite recursion is impossible.
8925   for (auto *FD : RD->fields()) {
8926     bool SubContained;
8927     if (const CXXRecordDecl *ContainedRD =
8928             getContainedDynamicClass(FD->getType(), SubContained)) {
8929       IsContained = true;
8930       return ContainedRD;
8931     }
8932   }
8933 
8934   return nullptr;
8935 }
8936 
8937 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
8938   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
8939     if (Unary->getKind() == UETT_SizeOf)
8940       return Unary;
8941   return nullptr;
8942 }
8943 
8944 /// If E is a sizeof expression, returns its argument expression,
8945 /// otherwise returns NULL.
8946 static const Expr *getSizeOfExprArg(const Expr *E) {
8947   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
8948     if (!SizeOf->isArgumentType())
8949       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
8950   return nullptr;
8951 }
8952 
8953 /// If E is a sizeof expression, returns its argument type.
8954 static QualType getSizeOfArgType(const Expr *E) {
8955   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
8956     return SizeOf->getTypeOfArgument();
8957   return QualType();
8958 }
8959 
8960 namespace {
8961 
8962 struct SearchNonTrivialToInitializeField
8963     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
8964   using Super =
8965       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
8966 
8967   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
8968 
8969   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
8970                      SourceLocation SL) {
8971     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
8972       asDerived().visitArray(PDIK, AT, SL);
8973       return;
8974     }
8975 
8976     Super::visitWithKind(PDIK, FT, SL);
8977   }
8978 
8979   void visitARCStrong(QualType FT, SourceLocation SL) {
8980     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
8981   }
8982   void visitARCWeak(QualType FT, SourceLocation SL) {
8983     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
8984   }
8985   void visitStruct(QualType FT, SourceLocation SL) {
8986     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
8987       visit(FD->getType(), FD->getLocation());
8988   }
8989   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
8990                   const ArrayType *AT, SourceLocation SL) {
8991     visit(getContext().getBaseElementType(AT), SL);
8992   }
8993   void visitTrivial(QualType FT, SourceLocation SL) {}
8994 
8995   static void diag(QualType RT, const Expr *E, Sema &S) {
8996     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
8997   }
8998 
8999   ASTContext &getContext() { return S.getASTContext(); }
9000 
9001   const Expr *E;
9002   Sema &S;
9003 };
9004 
9005 struct SearchNonTrivialToCopyField
9006     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
9007   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
9008 
9009   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
9010 
9011   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
9012                      SourceLocation SL) {
9013     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9014       asDerived().visitArray(PCK, AT, SL);
9015       return;
9016     }
9017 
9018     Super::visitWithKind(PCK, FT, SL);
9019   }
9020 
9021   void visitARCStrong(QualType FT, SourceLocation SL) {
9022     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9023   }
9024   void visitARCWeak(QualType FT, SourceLocation SL) {
9025     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9026   }
9027   void visitStruct(QualType FT, SourceLocation SL) {
9028     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9029       visit(FD->getType(), FD->getLocation());
9030   }
9031   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
9032                   SourceLocation SL) {
9033     visit(getContext().getBaseElementType(AT), SL);
9034   }
9035   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
9036                 SourceLocation SL) {}
9037   void visitTrivial(QualType FT, SourceLocation SL) {}
9038   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
9039 
9040   static void diag(QualType RT, const Expr *E, Sema &S) {
9041     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
9042   }
9043 
9044   ASTContext &getContext() { return S.getASTContext(); }
9045 
9046   const Expr *E;
9047   Sema &S;
9048 };
9049 
9050 }
9051 
9052 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
9053 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
9054   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
9055 
9056   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
9057     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
9058       return false;
9059 
9060     return doesExprLikelyComputeSize(BO->getLHS()) ||
9061            doesExprLikelyComputeSize(BO->getRHS());
9062   }
9063 
9064   return getAsSizeOfExpr(SizeofExpr) != nullptr;
9065 }
9066 
9067 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
9068 ///
9069 /// \code
9070 ///   #define MACRO 0
9071 ///   foo(MACRO);
9072 ///   foo(0);
9073 /// \endcode
9074 ///
9075 /// This should return true for the first call to foo, but not for the second
9076 /// (regardless of whether foo is a macro or function).
9077 static bool isArgumentExpandedFromMacro(SourceManager &SM,
9078                                         SourceLocation CallLoc,
9079                                         SourceLocation ArgLoc) {
9080   if (!CallLoc.isMacroID())
9081     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
9082 
9083   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
9084          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
9085 }
9086 
9087 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
9088 /// last two arguments transposed.
9089 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
9090   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
9091     return;
9092 
9093   const Expr *SizeArg =
9094     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
9095 
9096   auto isLiteralZero = [](const Expr *E) {
9097     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
9098   };
9099 
9100   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
9101   SourceLocation CallLoc = Call->getRParenLoc();
9102   SourceManager &SM = S.getSourceManager();
9103   if (isLiteralZero(SizeArg) &&
9104       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
9105 
9106     SourceLocation DiagLoc = SizeArg->getExprLoc();
9107 
9108     // Some platforms #define bzero to __builtin_memset. See if this is the
9109     // case, and if so, emit a better diagnostic.
9110     if (BId == Builtin::BIbzero ||
9111         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
9112                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
9113       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
9114       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
9115     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
9116       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
9117       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
9118     }
9119     return;
9120   }
9121 
9122   // If the second argument to a memset is a sizeof expression and the third
9123   // isn't, this is also likely an error. This should catch
9124   // 'memset(buf, sizeof(buf), 0xff)'.
9125   if (BId == Builtin::BImemset &&
9126       doesExprLikelyComputeSize(Call->getArg(1)) &&
9127       !doesExprLikelyComputeSize(Call->getArg(2))) {
9128     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
9129     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
9130     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
9131     return;
9132   }
9133 }
9134 
9135 /// Check for dangerous or invalid arguments to memset().
9136 ///
9137 /// This issues warnings on known problematic, dangerous or unspecified
9138 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
9139 /// function calls.
9140 ///
9141 /// \param Call The call expression to diagnose.
9142 void Sema::CheckMemaccessArguments(const CallExpr *Call,
9143                                    unsigned BId,
9144                                    IdentifierInfo *FnName) {
9145   assert(BId != 0);
9146 
9147   // It is possible to have a non-standard definition of memset.  Validate
9148   // we have enough arguments, and if not, abort further checking.
9149   unsigned ExpectedNumArgs =
9150       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
9151   if (Call->getNumArgs() < ExpectedNumArgs)
9152     return;
9153 
9154   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
9155                       BId == Builtin::BIstrndup ? 1 : 2);
9156   unsigned LenArg =
9157       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
9158   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
9159 
9160   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
9161                                      Call->getBeginLoc(), Call->getRParenLoc()))
9162     return;
9163 
9164   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
9165   CheckMemaccessSize(*this, BId, Call);
9166 
9167   // We have special checking when the length is a sizeof expression.
9168   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
9169   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
9170   llvm::FoldingSetNodeID SizeOfArgID;
9171 
9172   // Although widely used, 'bzero' is not a standard function. Be more strict
9173   // with the argument types before allowing diagnostics and only allow the
9174   // form bzero(ptr, sizeof(...)).
9175   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9176   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
9177     return;
9178 
9179   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
9180     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
9181     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
9182 
9183     QualType DestTy = Dest->getType();
9184     QualType PointeeTy;
9185     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
9186       PointeeTy = DestPtrTy->getPointeeType();
9187 
9188       // Never warn about void type pointers. This can be used to suppress
9189       // false positives.
9190       if (PointeeTy->isVoidType())
9191         continue;
9192 
9193       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
9194       // actually comparing the expressions for equality. Because computing the
9195       // expression IDs can be expensive, we only do this if the diagnostic is
9196       // enabled.
9197       if (SizeOfArg &&
9198           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
9199                            SizeOfArg->getExprLoc())) {
9200         // We only compute IDs for expressions if the warning is enabled, and
9201         // cache the sizeof arg's ID.
9202         if (SizeOfArgID == llvm::FoldingSetNodeID())
9203           SizeOfArg->Profile(SizeOfArgID, Context, true);
9204         llvm::FoldingSetNodeID DestID;
9205         Dest->Profile(DestID, Context, true);
9206         if (DestID == SizeOfArgID) {
9207           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
9208           //       over sizeof(src) as well.
9209           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
9210           StringRef ReadableName = FnName->getName();
9211 
9212           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
9213             if (UnaryOp->getOpcode() == UO_AddrOf)
9214               ActionIdx = 1; // If its an address-of operator, just remove it.
9215           if (!PointeeTy->isIncompleteType() &&
9216               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
9217             ActionIdx = 2; // If the pointee's size is sizeof(char),
9218                            // suggest an explicit length.
9219 
9220           // If the function is defined as a builtin macro, do not show macro
9221           // expansion.
9222           SourceLocation SL = SizeOfArg->getExprLoc();
9223           SourceRange DSR = Dest->getSourceRange();
9224           SourceRange SSR = SizeOfArg->getSourceRange();
9225           SourceManager &SM = getSourceManager();
9226 
9227           if (SM.isMacroArgExpansion(SL)) {
9228             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
9229             SL = SM.getSpellingLoc(SL);
9230             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
9231                              SM.getSpellingLoc(DSR.getEnd()));
9232             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
9233                              SM.getSpellingLoc(SSR.getEnd()));
9234           }
9235 
9236           DiagRuntimeBehavior(SL, SizeOfArg,
9237                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
9238                                 << ReadableName
9239                                 << PointeeTy
9240                                 << DestTy
9241                                 << DSR
9242                                 << SSR);
9243           DiagRuntimeBehavior(SL, SizeOfArg,
9244                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
9245                                 << ActionIdx
9246                                 << SSR);
9247 
9248           break;
9249         }
9250       }
9251 
9252       // Also check for cases where the sizeof argument is the exact same
9253       // type as the memory argument, and where it points to a user-defined
9254       // record type.
9255       if (SizeOfArgTy != QualType()) {
9256         if (PointeeTy->isRecordType() &&
9257             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
9258           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
9259                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
9260                                 << FnName << SizeOfArgTy << ArgIdx
9261                                 << PointeeTy << Dest->getSourceRange()
9262                                 << LenExpr->getSourceRange());
9263           break;
9264         }
9265       }
9266     } else if (DestTy->isArrayType()) {
9267       PointeeTy = DestTy;
9268     }
9269 
9270     if (PointeeTy == QualType())
9271       continue;
9272 
9273     // Always complain about dynamic classes.
9274     bool IsContained;
9275     if (const CXXRecordDecl *ContainedRD =
9276             getContainedDynamicClass(PointeeTy, IsContained)) {
9277 
9278       unsigned OperationType = 0;
9279       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
9280       // "overwritten" if we're warning about the destination for any call
9281       // but memcmp; otherwise a verb appropriate to the call.
9282       if (ArgIdx != 0 || IsCmp) {
9283         if (BId == Builtin::BImemcpy)
9284           OperationType = 1;
9285         else if(BId == Builtin::BImemmove)
9286           OperationType = 2;
9287         else if (IsCmp)
9288           OperationType = 3;
9289       }
9290 
9291       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9292                           PDiag(diag::warn_dyn_class_memaccess)
9293                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
9294                               << IsContained << ContainedRD << OperationType
9295                               << Call->getCallee()->getSourceRange());
9296     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
9297              BId != Builtin::BImemset)
9298       DiagRuntimeBehavior(
9299         Dest->getExprLoc(), Dest,
9300         PDiag(diag::warn_arc_object_memaccess)
9301           << ArgIdx << FnName << PointeeTy
9302           << Call->getCallee()->getSourceRange());
9303     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
9304       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
9305           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
9306         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9307                             PDiag(diag::warn_cstruct_memaccess)
9308                                 << ArgIdx << FnName << PointeeTy << 0);
9309         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
9310       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
9311                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
9312         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9313                             PDiag(diag::warn_cstruct_memaccess)
9314                                 << ArgIdx << FnName << PointeeTy << 1);
9315         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
9316       } else {
9317         continue;
9318       }
9319     } else
9320       continue;
9321 
9322     DiagRuntimeBehavior(
9323       Dest->getExprLoc(), Dest,
9324       PDiag(diag::note_bad_memaccess_silence)
9325         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
9326     break;
9327   }
9328 }
9329 
9330 // A little helper routine: ignore addition and subtraction of integer literals.
9331 // This intentionally does not ignore all integer constant expressions because
9332 // we don't want to remove sizeof().
9333 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
9334   Ex = Ex->IgnoreParenCasts();
9335 
9336   while (true) {
9337     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
9338     if (!BO || !BO->isAdditiveOp())
9339       break;
9340 
9341     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
9342     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
9343 
9344     if (isa<IntegerLiteral>(RHS))
9345       Ex = LHS;
9346     else if (isa<IntegerLiteral>(LHS))
9347       Ex = RHS;
9348     else
9349       break;
9350   }
9351 
9352   return Ex;
9353 }
9354 
9355 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
9356                                                       ASTContext &Context) {
9357   // Only handle constant-sized or VLAs, but not flexible members.
9358   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
9359     // Only issue the FIXIT for arrays of size > 1.
9360     if (CAT->getSize().getSExtValue() <= 1)
9361       return false;
9362   } else if (!Ty->isVariableArrayType()) {
9363     return false;
9364   }
9365   return true;
9366 }
9367 
9368 // Warn if the user has made the 'size' argument to strlcpy or strlcat
9369 // be the size of the source, instead of the destination.
9370 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
9371                                     IdentifierInfo *FnName) {
9372 
9373   // Don't crash if the user has the wrong number of arguments
9374   unsigned NumArgs = Call->getNumArgs();
9375   if ((NumArgs != 3) && (NumArgs != 4))
9376     return;
9377 
9378   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
9379   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
9380   const Expr *CompareWithSrc = nullptr;
9381 
9382   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
9383                                      Call->getBeginLoc(), Call->getRParenLoc()))
9384     return;
9385 
9386   // Look for 'strlcpy(dst, x, sizeof(x))'
9387   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
9388     CompareWithSrc = Ex;
9389   else {
9390     // Look for 'strlcpy(dst, x, strlen(x))'
9391     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
9392       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
9393           SizeCall->getNumArgs() == 1)
9394         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
9395     }
9396   }
9397 
9398   if (!CompareWithSrc)
9399     return;
9400 
9401   // Determine if the argument to sizeof/strlen is equal to the source
9402   // argument.  In principle there's all kinds of things you could do
9403   // here, for instance creating an == expression and evaluating it with
9404   // EvaluateAsBooleanCondition, but this uses a more direct technique:
9405   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
9406   if (!SrcArgDRE)
9407     return;
9408 
9409   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
9410   if (!CompareWithSrcDRE ||
9411       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
9412     return;
9413 
9414   const Expr *OriginalSizeArg = Call->getArg(2);
9415   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
9416       << OriginalSizeArg->getSourceRange() << FnName;
9417 
9418   // Output a FIXIT hint if the destination is an array (rather than a
9419   // pointer to an array).  This could be enhanced to handle some
9420   // pointers if we know the actual size, like if DstArg is 'array+2'
9421   // we could say 'sizeof(array)-2'.
9422   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
9423   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
9424     return;
9425 
9426   SmallString<128> sizeString;
9427   llvm::raw_svector_ostream OS(sizeString);
9428   OS << "sizeof(";
9429   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9430   OS << ")";
9431 
9432   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
9433       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
9434                                       OS.str());
9435 }
9436 
9437 /// Check if two expressions refer to the same declaration.
9438 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
9439   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
9440     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
9441       return D1->getDecl() == D2->getDecl();
9442   return false;
9443 }
9444 
9445 static const Expr *getStrlenExprArg(const Expr *E) {
9446   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
9447     const FunctionDecl *FD = CE->getDirectCallee();
9448     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
9449       return nullptr;
9450     return CE->getArg(0)->IgnoreParenCasts();
9451   }
9452   return nullptr;
9453 }
9454 
9455 // Warn on anti-patterns as the 'size' argument to strncat.
9456 // The correct size argument should look like following:
9457 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
9458 void Sema::CheckStrncatArguments(const CallExpr *CE,
9459                                  IdentifierInfo *FnName) {
9460   // Don't crash if the user has the wrong number of arguments.
9461   if (CE->getNumArgs() < 3)
9462     return;
9463   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
9464   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
9465   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
9466 
9467   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
9468                                      CE->getRParenLoc()))
9469     return;
9470 
9471   // Identify common expressions, which are wrongly used as the size argument
9472   // to strncat and may lead to buffer overflows.
9473   unsigned PatternType = 0;
9474   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
9475     // - sizeof(dst)
9476     if (referToTheSameDecl(SizeOfArg, DstArg))
9477       PatternType = 1;
9478     // - sizeof(src)
9479     else if (referToTheSameDecl(SizeOfArg, SrcArg))
9480       PatternType = 2;
9481   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
9482     if (BE->getOpcode() == BO_Sub) {
9483       const Expr *L = BE->getLHS()->IgnoreParenCasts();
9484       const Expr *R = BE->getRHS()->IgnoreParenCasts();
9485       // - sizeof(dst) - strlen(dst)
9486       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
9487           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
9488         PatternType = 1;
9489       // - sizeof(src) - (anything)
9490       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
9491         PatternType = 2;
9492     }
9493   }
9494 
9495   if (PatternType == 0)
9496     return;
9497 
9498   // Generate the diagnostic.
9499   SourceLocation SL = LenArg->getBeginLoc();
9500   SourceRange SR = LenArg->getSourceRange();
9501   SourceManager &SM = getSourceManager();
9502 
9503   // If the function is defined as a builtin macro, do not show macro expansion.
9504   if (SM.isMacroArgExpansion(SL)) {
9505     SL = SM.getSpellingLoc(SL);
9506     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
9507                      SM.getSpellingLoc(SR.getEnd()));
9508   }
9509 
9510   // Check if the destination is an array (rather than a pointer to an array).
9511   QualType DstTy = DstArg->getType();
9512   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
9513                                                                     Context);
9514   if (!isKnownSizeArray) {
9515     if (PatternType == 1)
9516       Diag(SL, diag::warn_strncat_wrong_size) << SR;
9517     else
9518       Diag(SL, diag::warn_strncat_src_size) << SR;
9519     return;
9520   }
9521 
9522   if (PatternType == 1)
9523     Diag(SL, diag::warn_strncat_large_size) << SR;
9524   else
9525     Diag(SL, diag::warn_strncat_src_size) << SR;
9526 
9527   SmallString<128> sizeString;
9528   llvm::raw_svector_ostream OS(sizeString);
9529   OS << "sizeof(";
9530   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9531   OS << ") - ";
9532   OS << "strlen(";
9533   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9534   OS << ") - 1";
9535 
9536   Diag(SL, diag::note_strncat_wrong_size)
9537     << FixItHint::CreateReplacement(SR, OS.str());
9538 }
9539 
9540 void
9541 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
9542                          SourceLocation ReturnLoc,
9543                          bool isObjCMethod,
9544                          const AttrVec *Attrs,
9545                          const FunctionDecl *FD) {
9546   // Check if the return value is null but should not be.
9547   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
9548        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
9549       CheckNonNullExpr(*this, RetValExp))
9550     Diag(ReturnLoc, diag::warn_null_ret)
9551       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
9552 
9553   // C++11 [basic.stc.dynamic.allocation]p4:
9554   //   If an allocation function declared with a non-throwing
9555   //   exception-specification fails to allocate storage, it shall return
9556   //   a null pointer. Any other allocation function that fails to allocate
9557   //   storage shall indicate failure only by throwing an exception [...]
9558   if (FD) {
9559     OverloadedOperatorKind Op = FD->getOverloadedOperator();
9560     if (Op == OO_New || Op == OO_Array_New) {
9561       const FunctionProtoType *Proto
9562         = FD->getType()->castAs<FunctionProtoType>();
9563       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
9564           CheckNonNullExpr(*this, RetValExp))
9565         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
9566           << FD << getLangOpts().CPlusPlus11;
9567     }
9568   }
9569 }
9570 
9571 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
9572 
9573 /// Check for comparisons of floating point operands using != and ==.
9574 /// Issue a warning if these are no self-comparisons, as they are not likely
9575 /// to do what the programmer intended.
9576 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
9577   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
9578   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
9579 
9580   // Special case: check for x == x (which is OK).
9581   // Do not emit warnings for such cases.
9582   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
9583     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
9584       if (DRL->getDecl() == DRR->getDecl())
9585         return;
9586 
9587   // Special case: check for comparisons against literals that can be exactly
9588   //  represented by APFloat.  In such cases, do not emit a warning.  This
9589   //  is a heuristic: often comparison against such literals are used to
9590   //  detect if a value in a variable has not changed.  This clearly can
9591   //  lead to false negatives.
9592   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
9593     if (FLL->isExact())
9594       return;
9595   } else
9596     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
9597       if (FLR->isExact())
9598         return;
9599 
9600   // Check for comparisons with builtin types.
9601   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
9602     if (CL->getBuiltinCallee())
9603       return;
9604 
9605   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
9606     if (CR->getBuiltinCallee())
9607       return;
9608 
9609   // Emit the diagnostic.
9610   Diag(Loc, diag::warn_floatingpoint_eq)
9611     << LHS->getSourceRange() << RHS->getSourceRange();
9612 }
9613 
9614 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
9615 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
9616 
9617 namespace {
9618 
9619 /// Structure recording the 'active' range of an integer-valued
9620 /// expression.
9621 struct IntRange {
9622   /// The number of bits active in the int.
9623   unsigned Width;
9624 
9625   /// True if the int is known not to have negative values.
9626   bool NonNegative;
9627 
9628   IntRange(unsigned Width, bool NonNegative)
9629       : Width(Width), NonNegative(NonNegative) {}
9630 
9631   /// Returns the range of the bool type.
9632   static IntRange forBoolType() {
9633     return IntRange(1, true);
9634   }
9635 
9636   /// Returns the range of an opaque value of the given integral type.
9637   static IntRange forValueOfType(ASTContext &C, QualType T) {
9638     return forValueOfCanonicalType(C,
9639                           T->getCanonicalTypeInternal().getTypePtr());
9640   }
9641 
9642   /// Returns the range of an opaque value of a canonical integral type.
9643   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
9644     assert(T->isCanonicalUnqualified());
9645 
9646     if (const VectorType *VT = dyn_cast<VectorType>(T))
9647       T = VT->getElementType().getTypePtr();
9648     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
9649       T = CT->getElementType().getTypePtr();
9650     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
9651       T = AT->getValueType().getTypePtr();
9652 
9653     if (!C.getLangOpts().CPlusPlus) {
9654       // For enum types in C code, use the underlying datatype.
9655       if (const EnumType *ET = dyn_cast<EnumType>(T))
9656         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
9657     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
9658       // For enum types in C++, use the known bit width of the enumerators.
9659       EnumDecl *Enum = ET->getDecl();
9660       // In C++11, enums can have a fixed underlying type. Use this type to
9661       // compute the range.
9662       if (Enum->isFixed()) {
9663         return IntRange(C.getIntWidth(QualType(T, 0)),
9664                         !ET->isSignedIntegerOrEnumerationType());
9665       }
9666 
9667       unsigned NumPositive = Enum->getNumPositiveBits();
9668       unsigned NumNegative = Enum->getNumNegativeBits();
9669 
9670       if (NumNegative == 0)
9671         return IntRange(NumPositive, true/*NonNegative*/);
9672       else
9673         return IntRange(std::max(NumPositive + 1, NumNegative),
9674                         false/*NonNegative*/);
9675     }
9676 
9677     const BuiltinType *BT = cast<BuiltinType>(T);
9678     assert(BT->isInteger());
9679 
9680     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
9681   }
9682 
9683   /// Returns the "target" range of a canonical integral type, i.e.
9684   /// the range of values expressible in the type.
9685   ///
9686   /// This matches forValueOfCanonicalType except that enums have the
9687   /// full range of their type, not the range of their enumerators.
9688   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
9689     assert(T->isCanonicalUnqualified());
9690 
9691     if (const VectorType *VT = dyn_cast<VectorType>(T))
9692       T = VT->getElementType().getTypePtr();
9693     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
9694       T = CT->getElementType().getTypePtr();
9695     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
9696       T = AT->getValueType().getTypePtr();
9697     if (const EnumType *ET = dyn_cast<EnumType>(T))
9698       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
9699 
9700     const BuiltinType *BT = cast<BuiltinType>(T);
9701     assert(BT->isInteger());
9702 
9703     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
9704   }
9705 
9706   /// Returns the supremum of two ranges: i.e. their conservative merge.
9707   static IntRange join(IntRange L, IntRange R) {
9708     return IntRange(std::max(L.Width, R.Width),
9709                     L.NonNegative && R.NonNegative);
9710   }
9711 
9712   /// Returns the infinum of two ranges: i.e. their aggressive merge.
9713   static IntRange meet(IntRange L, IntRange R) {
9714     return IntRange(std::min(L.Width, R.Width),
9715                     L.NonNegative || R.NonNegative);
9716   }
9717 };
9718 
9719 } // namespace
9720 
9721 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
9722                               unsigned MaxWidth) {
9723   if (value.isSigned() && value.isNegative())
9724     return IntRange(value.getMinSignedBits(), false);
9725 
9726   if (value.getBitWidth() > MaxWidth)
9727     value = value.trunc(MaxWidth);
9728 
9729   // isNonNegative() just checks the sign bit without considering
9730   // signedness.
9731   return IntRange(value.getActiveBits(), true);
9732 }
9733 
9734 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
9735                               unsigned MaxWidth) {
9736   if (result.isInt())
9737     return GetValueRange(C, result.getInt(), MaxWidth);
9738 
9739   if (result.isVector()) {
9740     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
9741     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
9742       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
9743       R = IntRange::join(R, El);
9744     }
9745     return R;
9746   }
9747 
9748   if (result.isComplexInt()) {
9749     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
9750     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
9751     return IntRange::join(R, I);
9752   }
9753 
9754   // This can happen with lossless casts to intptr_t of "based" lvalues.
9755   // Assume it might use arbitrary bits.
9756   // FIXME: The only reason we need to pass the type in here is to get
9757   // the sign right on this one case.  It would be nice if APValue
9758   // preserved this.
9759   assert(result.isLValue() || result.isAddrLabelDiff());
9760   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
9761 }
9762 
9763 static QualType GetExprType(const Expr *E) {
9764   QualType Ty = E->getType();
9765   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
9766     Ty = AtomicRHS->getValueType();
9767   return Ty;
9768 }
9769 
9770 /// Pseudo-evaluate the given integer expression, estimating the
9771 /// range of values it might take.
9772 ///
9773 /// \param MaxWidth - the width to which the value will be truncated
9774 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
9775                              bool InConstantContext) {
9776   E = E->IgnoreParens();
9777 
9778   // Try a full evaluation first.
9779   Expr::EvalResult result;
9780   if (E->EvaluateAsRValue(result, C, InConstantContext))
9781     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
9782 
9783   // I think we only want to look through implicit casts here; if the
9784   // user has an explicit widening cast, we should treat the value as
9785   // being of the new, wider type.
9786   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
9787     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
9788       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext);
9789 
9790     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
9791 
9792     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
9793                          CE->getCastKind() == CK_BooleanToSignedIntegral;
9794 
9795     // Assume that non-integer casts can span the full range of the type.
9796     if (!isIntegerCast)
9797       return OutputTypeRange;
9798 
9799     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
9800                                      std::min(MaxWidth, OutputTypeRange.Width),
9801                                      InConstantContext);
9802 
9803     // Bail out if the subexpr's range is as wide as the cast type.
9804     if (SubRange.Width >= OutputTypeRange.Width)
9805       return OutputTypeRange;
9806 
9807     // Otherwise, we take the smaller width, and we're non-negative if
9808     // either the output type or the subexpr is.
9809     return IntRange(SubRange.Width,
9810                     SubRange.NonNegative || OutputTypeRange.NonNegative);
9811   }
9812 
9813   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
9814     // If we can fold the condition, just take that operand.
9815     bool CondResult;
9816     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
9817       return GetExprRange(C,
9818                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
9819                           MaxWidth, InConstantContext);
9820 
9821     // Otherwise, conservatively merge.
9822     IntRange L =
9823         GetExprRange(C, CO->getTrueExpr(), MaxWidth, InConstantContext);
9824     IntRange R =
9825         GetExprRange(C, CO->getFalseExpr(), MaxWidth, InConstantContext);
9826     return IntRange::join(L, R);
9827   }
9828 
9829   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
9830     switch (BO->getOpcode()) {
9831     case BO_Cmp:
9832       llvm_unreachable("builtin <=> should have class type");
9833 
9834     // Boolean-valued operations are single-bit and positive.
9835     case BO_LAnd:
9836     case BO_LOr:
9837     case BO_LT:
9838     case BO_GT:
9839     case BO_LE:
9840     case BO_GE:
9841     case BO_EQ:
9842     case BO_NE:
9843       return IntRange::forBoolType();
9844 
9845     // The type of the assignments is the type of the LHS, so the RHS
9846     // is not necessarily the same type.
9847     case BO_MulAssign:
9848     case BO_DivAssign:
9849     case BO_RemAssign:
9850     case BO_AddAssign:
9851     case BO_SubAssign:
9852     case BO_XorAssign:
9853     case BO_OrAssign:
9854       // TODO: bitfields?
9855       return IntRange::forValueOfType(C, GetExprType(E));
9856 
9857     // Simple assignments just pass through the RHS, which will have
9858     // been coerced to the LHS type.
9859     case BO_Assign:
9860       // TODO: bitfields?
9861       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
9862 
9863     // Operations with opaque sources are black-listed.
9864     case BO_PtrMemD:
9865     case BO_PtrMemI:
9866       return IntRange::forValueOfType(C, GetExprType(E));
9867 
9868     // Bitwise-and uses the *infinum* of the two source ranges.
9869     case BO_And:
9870     case BO_AndAssign:
9871       return IntRange::meet(
9872           GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext),
9873           GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext));
9874 
9875     // Left shift gets black-listed based on a judgement call.
9876     case BO_Shl:
9877       // ...except that we want to treat '1 << (blah)' as logically
9878       // positive.  It's an important idiom.
9879       if (IntegerLiteral *I
9880             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
9881         if (I->getValue() == 1) {
9882           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
9883           return IntRange(R.Width, /*NonNegative*/ true);
9884         }
9885       }
9886       LLVM_FALLTHROUGH;
9887 
9888     case BO_ShlAssign:
9889       return IntRange::forValueOfType(C, GetExprType(E));
9890 
9891     // Right shift by a constant can narrow its left argument.
9892     case BO_Shr:
9893     case BO_ShrAssign: {
9894       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext);
9895 
9896       // If the shift amount is a positive constant, drop the width by
9897       // that much.
9898       llvm::APSInt shift;
9899       if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
9900           shift.isNonNegative()) {
9901         unsigned zext = shift.getZExtValue();
9902         if (zext >= L.Width)
9903           L.Width = (L.NonNegative ? 0 : 1);
9904         else
9905           L.Width -= zext;
9906       }
9907 
9908       return L;
9909     }
9910 
9911     // Comma acts as its right operand.
9912     case BO_Comma:
9913       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
9914 
9915     // Black-list pointer subtractions.
9916     case BO_Sub:
9917       if (BO->getLHS()->getType()->isPointerType())
9918         return IntRange::forValueOfType(C, GetExprType(E));
9919       break;
9920 
9921     // The width of a division result is mostly determined by the size
9922     // of the LHS.
9923     case BO_Div: {
9924       // Don't 'pre-truncate' the operands.
9925       unsigned opWidth = C.getIntWidth(GetExprType(E));
9926       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext);
9927 
9928       // If the divisor is constant, use that.
9929       llvm::APSInt divisor;
9930       if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
9931         unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
9932         if (log2 >= L.Width)
9933           L.Width = (L.NonNegative ? 0 : 1);
9934         else
9935           L.Width = std::min(L.Width - log2, MaxWidth);
9936         return L;
9937       }
9938 
9939       // Otherwise, just use the LHS's width.
9940       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext);
9941       return IntRange(L.Width, L.NonNegative && R.NonNegative);
9942     }
9943 
9944     // The result of a remainder can't be larger than the result of
9945     // either side.
9946     case BO_Rem: {
9947       // Don't 'pre-truncate' the operands.
9948       unsigned opWidth = C.getIntWidth(GetExprType(E));
9949       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext);
9950       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext);
9951 
9952       IntRange meet = IntRange::meet(L, R);
9953       meet.Width = std::min(meet.Width, MaxWidth);
9954       return meet;
9955     }
9956 
9957     // The default behavior is okay for these.
9958     case BO_Mul:
9959     case BO_Add:
9960     case BO_Xor:
9961     case BO_Or:
9962       break;
9963     }
9964 
9965     // The default case is to treat the operation as if it were closed
9966     // on the narrowest type that encompasses both operands.
9967     IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext);
9968     IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
9969     return IntRange::join(L, R);
9970   }
9971 
9972   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
9973     switch (UO->getOpcode()) {
9974     // Boolean-valued operations are white-listed.
9975     case UO_LNot:
9976       return IntRange::forBoolType();
9977 
9978     // Operations with opaque sources are black-listed.
9979     case UO_Deref:
9980     case UO_AddrOf: // should be impossible
9981       return IntRange::forValueOfType(C, GetExprType(E));
9982 
9983     default:
9984       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext);
9985     }
9986   }
9987 
9988   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
9989     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext);
9990 
9991   if (const auto *BitField = E->getSourceBitField())
9992     return IntRange(BitField->getBitWidthValue(C),
9993                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
9994 
9995   return IntRange::forValueOfType(C, GetExprType(E));
9996 }
9997 
9998 static IntRange GetExprRange(ASTContext &C, const Expr *E,
9999                              bool InConstantContext) {
10000   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext);
10001 }
10002 
10003 /// Checks whether the given value, which currently has the given
10004 /// source semantics, has the same value when coerced through the
10005 /// target semantics.
10006 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
10007                                  const llvm::fltSemantics &Src,
10008                                  const llvm::fltSemantics &Tgt) {
10009   llvm::APFloat truncated = value;
10010 
10011   bool ignored;
10012   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
10013   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
10014 
10015   return truncated.bitwiseIsEqual(value);
10016 }
10017 
10018 /// Checks whether the given value, which currently has the given
10019 /// source semantics, has the same value when coerced through the
10020 /// target semantics.
10021 ///
10022 /// The value might be a vector of floats (or a complex number).
10023 static bool IsSameFloatAfterCast(const APValue &value,
10024                                  const llvm::fltSemantics &Src,
10025                                  const llvm::fltSemantics &Tgt) {
10026   if (value.isFloat())
10027     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
10028 
10029   if (value.isVector()) {
10030     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
10031       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
10032         return false;
10033     return true;
10034   }
10035 
10036   assert(value.isComplexFloat());
10037   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
10038           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
10039 }
10040 
10041 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
10042                                        bool IsListInit = false);
10043 
10044 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
10045   // Suppress cases where we are comparing against an enum constant.
10046   if (const DeclRefExpr *DR =
10047       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
10048     if (isa<EnumConstantDecl>(DR->getDecl()))
10049       return true;
10050 
10051   // Suppress cases where the value is expanded from a macro, unless that macro
10052   // is how a language represents a boolean literal. This is the case in both C
10053   // and Objective-C.
10054   SourceLocation BeginLoc = E->getBeginLoc();
10055   if (BeginLoc.isMacroID()) {
10056     StringRef MacroName = Lexer::getImmediateMacroName(
10057         BeginLoc, S.getSourceManager(), S.getLangOpts());
10058     return MacroName != "YES" && MacroName != "NO" &&
10059            MacroName != "true" && MacroName != "false";
10060   }
10061 
10062   return false;
10063 }
10064 
10065 static bool isKnownToHaveUnsignedValue(Expr *E) {
10066   return E->getType()->isIntegerType() &&
10067          (!E->getType()->isSignedIntegerType() ||
10068           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
10069 }
10070 
10071 namespace {
10072 /// The promoted range of values of a type. In general this has the
10073 /// following structure:
10074 ///
10075 ///     |-----------| . . . |-----------|
10076 ///     ^           ^       ^           ^
10077 ///    Min       HoleMin  HoleMax      Max
10078 ///
10079 /// ... where there is only a hole if a signed type is promoted to unsigned
10080 /// (in which case Min and Max are the smallest and largest representable
10081 /// values).
10082 struct PromotedRange {
10083   // Min, or HoleMax if there is a hole.
10084   llvm::APSInt PromotedMin;
10085   // Max, or HoleMin if there is a hole.
10086   llvm::APSInt PromotedMax;
10087 
10088   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
10089     if (R.Width == 0)
10090       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
10091     else if (R.Width >= BitWidth && !Unsigned) {
10092       // Promotion made the type *narrower*. This happens when promoting
10093       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
10094       // Treat all values of 'signed int' as being in range for now.
10095       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
10096       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
10097     } else {
10098       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
10099                         .extOrTrunc(BitWidth);
10100       PromotedMin.setIsUnsigned(Unsigned);
10101 
10102       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
10103                         .extOrTrunc(BitWidth);
10104       PromotedMax.setIsUnsigned(Unsigned);
10105     }
10106   }
10107 
10108   // Determine whether this range is contiguous (has no hole).
10109   bool isContiguous() const { return PromotedMin <= PromotedMax; }
10110 
10111   // Where a constant value is within the range.
10112   enum ComparisonResult {
10113     LT = 0x1,
10114     LE = 0x2,
10115     GT = 0x4,
10116     GE = 0x8,
10117     EQ = 0x10,
10118     NE = 0x20,
10119     InRangeFlag = 0x40,
10120 
10121     Less = LE | LT | NE,
10122     Min = LE | InRangeFlag,
10123     InRange = InRangeFlag,
10124     Max = GE | InRangeFlag,
10125     Greater = GE | GT | NE,
10126 
10127     OnlyValue = LE | GE | EQ | InRangeFlag,
10128     InHole = NE
10129   };
10130 
10131   ComparisonResult compare(const llvm::APSInt &Value) const {
10132     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
10133            Value.isUnsigned() == PromotedMin.isUnsigned());
10134     if (!isContiguous()) {
10135       assert(Value.isUnsigned() && "discontiguous range for signed compare");
10136       if (Value.isMinValue()) return Min;
10137       if (Value.isMaxValue()) return Max;
10138       if (Value >= PromotedMin) return InRange;
10139       if (Value <= PromotedMax) return InRange;
10140       return InHole;
10141     }
10142 
10143     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
10144     case -1: return Less;
10145     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
10146     case 1:
10147       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
10148       case -1: return InRange;
10149       case 0: return Max;
10150       case 1: return Greater;
10151       }
10152     }
10153 
10154     llvm_unreachable("impossible compare result");
10155   }
10156 
10157   static llvm::Optional<StringRef>
10158   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
10159     if (Op == BO_Cmp) {
10160       ComparisonResult LTFlag = LT, GTFlag = GT;
10161       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
10162 
10163       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
10164       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
10165       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
10166       return llvm::None;
10167     }
10168 
10169     ComparisonResult TrueFlag, FalseFlag;
10170     if (Op == BO_EQ) {
10171       TrueFlag = EQ;
10172       FalseFlag = NE;
10173     } else if (Op == BO_NE) {
10174       TrueFlag = NE;
10175       FalseFlag = EQ;
10176     } else {
10177       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
10178         TrueFlag = LT;
10179         FalseFlag = GE;
10180       } else {
10181         TrueFlag = GT;
10182         FalseFlag = LE;
10183       }
10184       if (Op == BO_GE || Op == BO_LE)
10185         std::swap(TrueFlag, FalseFlag);
10186     }
10187     if (R & TrueFlag)
10188       return StringRef("true");
10189     if (R & FalseFlag)
10190       return StringRef("false");
10191     return llvm::None;
10192   }
10193 };
10194 }
10195 
10196 static bool HasEnumType(Expr *E) {
10197   // Strip off implicit integral promotions.
10198   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
10199     if (ICE->getCastKind() != CK_IntegralCast &&
10200         ICE->getCastKind() != CK_NoOp)
10201       break;
10202     E = ICE->getSubExpr();
10203   }
10204 
10205   return E->getType()->isEnumeralType();
10206 }
10207 
10208 static int classifyConstantValue(Expr *Constant) {
10209   // The values of this enumeration are used in the diagnostics
10210   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
10211   enum ConstantValueKind {
10212     Miscellaneous = 0,
10213     LiteralTrue,
10214     LiteralFalse
10215   };
10216   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
10217     return BL->getValue() ? ConstantValueKind::LiteralTrue
10218                           : ConstantValueKind::LiteralFalse;
10219   return ConstantValueKind::Miscellaneous;
10220 }
10221 
10222 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
10223                                         Expr *Constant, Expr *Other,
10224                                         const llvm::APSInt &Value,
10225                                         bool RhsConstant) {
10226   if (S.inTemplateInstantiation())
10227     return false;
10228 
10229   Expr *OriginalOther = Other;
10230 
10231   Constant = Constant->IgnoreParenImpCasts();
10232   Other = Other->IgnoreParenImpCasts();
10233 
10234   // Suppress warnings on tautological comparisons between values of the same
10235   // enumeration type. There are only two ways we could warn on this:
10236   //  - If the constant is outside the range of representable values of
10237   //    the enumeration. In such a case, we should warn about the cast
10238   //    to enumeration type, not about the comparison.
10239   //  - If the constant is the maximum / minimum in-range value. For an
10240   //    enumeratin type, such comparisons can be meaningful and useful.
10241   if (Constant->getType()->isEnumeralType() &&
10242       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
10243     return false;
10244 
10245   // TODO: Investigate using GetExprRange() to get tighter bounds
10246   // on the bit ranges.
10247   QualType OtherT = Other->getType();
10248   if (const auto *AT = OtherT->getAs<AtomicType>())
10249     OtherT = AT->getValueType();
10250   IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
10251 
10252   // Special case for ObjC BOOL on targets where its a typedef for a signed char
10253   // (Namely, macOS).
10254   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
10255                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
10256                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
10257 
10258   // Whether we're treating Other as being a bool because of the form of
10259   // expression despite it having another type (typically 'int' in C).
10260   bool OtherIsBooleanDespiteType =
10261       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
10262   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
10263     OtherRange = IntRange::forBoolType();
10264 
10265   // Determine the promoted range of the other type and see if a comparison of
10266   // the constant against that range is tautological.
10267   PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
10268                                    Value.isUnsigned());
10269   auto Cmp = OtherPromotedRange.compare(Value);
10270   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
10271   if (!Result)
10272     return false;
10273 
10274   // Suppress the diagnostic for an in-range comparison if the constant comes
10275   // from a macro or enumerator. We don't want to diagnose
10276   //
10277   //   some_long_value <= INT_MAX
10278   //
10279   // when sizeof(int) == sizeof(long).
10280   bool InRange = Cmp & PromotedRange::InRangeFlag;
10281   if (InRange && IsEnumConstOrFromMacro(S, Constant))
10282     return false;
10283 
10284   // If this is a comparison to an enum constant, include that
10285   // constant in the diagnostic.
10286   const EnumConstantDecl *ED = nullptr;
10287   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
10288     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
10289 
10290   // Should be enough for uint128 (39 decimal digits)
10291   SmallString<64> PrettySourceValue;
10292   llvm::raw_svector_ostream OS(PrettySourceValue);
10293   if (ED) {
10294     OS << '\'' << *ED << "' (" << Value << ")";
10295   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
10296                Constant->IgnoreParenImpCasts())) {
10297     OS << (BL->getValue() ? "YES" : "NO");
10298   } else {
10299     OS << Value;
10300   }
10301 
10302   if (IsObjCSignedCharBool) {
10303     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
10304                           S.PDiag(diag::warn_tautological_compare_objc_bool)
10305                               << OS.str() << *Result);
10306     return true;
10307   }
10308 
10309   // FIXME: We use a somewhat different formatting for the in-range cases and
10310   // cases involving boolean values for historical reasons. We should pick a
10311   // consistent way of presenting these diagnostics.
10312   if (!InRange || Other->isKnownToHaveBooleanValue()) {
10313 
10314     S.DiagRuntimeBehavior(
10315         E->getOperatorLoc(), E,
10316         S.PDiag(!InRange ? diag::warn_out_of_range_compare
10317                          : diag::warn_tautological_bool_compare)
10318             << OS.str() << classifyConstantValue(Constant) << OtherT
10319             << OtherIsBooleanDespiteType << *Result
10320             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
10321   } else {
10322     unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
10323                         ? (HasEnumType(OriginalOther)
10324                                ? diag::warn_unsigned_enum_always_true_comparison
10325                                : diag::warn_unsigned_always_true_comparison)
10326                         : diag::warn_tautological_constant_compare;
10327 
10328     S.Diag(E->getOperatorLoc(), Diag)
10329         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
10330         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
10331   }
10332 
10333   return true;
10334 }
10335 
10336 /// Analyze the operands of the given comparison.  Implements the
10337 /// fallback case from AnalyzeComparison.
10338 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
10339   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10340   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10341 }
10342 
10343 /// Implements -Wsign-compare.
10344 ///
10345 /// \param E the binary operator to check for warnings
10346 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
10347   // The type the comparison is being performed in.
10348   QualType T = E->getLHS()->getType();
10349 
10350   // Only analyze comparison operators where both sides have been converted to
10351   // the same type.
10352   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
10353     return AnalyzeImpConvsInComparison(S, E);
10354 
10355   // Don't analyze value-dependent comparisons directly.
10356   if (E->isValueDependent())
10357     return AnalyzeImpConvsInComparison(S, E);
10358 
10359   Expr *LHS = E->getLHS();
10360   Expr *RHS = E->getRHS();
10361 
10362   if (T->isIntegralType(S.Context)) {
10363     llvm::APSInt RHSValue;
10364     llvm::APSInt LHSValue;
10365 
10366     bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
10367     bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
10368 
10369     // We don't care about expressions whose result is a constant.
10370     if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
10371       return AnalyzeImpConvsInComparison(S, E);
10372 
10373     // We only care about expressions where just one side is literal
10374     if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
10375       // Is the constant on the RHS or LHS?
10376       const bool RhsConstant = IsRHSIntegralLiteral;
10377       Expr *Const = RhsConstant ? RHS : LHS;
10378       Expr *Other = RhsConstant ? LHS : RHS;
10379       const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
10380 
10381       // Check whether an integer constant comparison results in a value
10382       // of 'true' or 'false'.
10383       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
10384         return AnalyzeImpConvsInComparison(S, E);
10385     }
10386   }
10387 
10388   if (!T->hasUnsignedIntegerRepresentation()) {
10389     // We don't do anything special if this isn't an unsigned integral
10390     // comparison:  we're only interested in integral comparisons, and
10391     // signed comparisons only happen in cases we don't care to warn about.
10392     return AnalyzeImpConvsInComparison(S, E);
10393   }
10394 
10395   LHS = LHS->IgnoreParenImpCasts();
10396   RHS = RHS->IgnoreParenImpCasts();
10397 
10398   if (!S.getLangOpts().CPlusPlus) {
10399     // Avoid warning about comparison of integers with different signs when
10400     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
10401     // the type of `E`.
10402     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
10403       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10404     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
10405       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10406   }
10407 
10408   // Check to see if one of the (unmodified) operands is of different
10409   // signedness.
10410   Expr *signedOperand, *unsignedOperand;
10411   if (LHS->getType()->hasSignedIntegerRepresentation()) {
10412     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
10413            "unsigned comparison between two signed integer expressions?");
10414     signedOperand = LHS;
10415     unsignedOperand = RHS;
10416   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
10417     signedOperand = RHS;
10418     unsignedOperand = LHS;
10419   } else {
10420     return AnalyzeImpConvsInComparison(S, E);
10421   }
10422 
10423   // Otherwise, calculate the effective range of the signed operand.
10424   IntRange signedRange =
10425       GetExprRange(S.Context, signedOperand, S.isConstantEvaluated());
10426 
10427   // Go ahead and analyze implicit conversions in the operands.  Note
10428   // that we skip the implicit conversions on both sides.
10429   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
10430   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
10431 
10432   // If the signed range is non-negative, -Wsign-compare won't fire.
10433   if (signedRange.NonNegative)
10434     return;
10435 
10436   // For (in)equality comparisons, if the unsigned operand is a
10437   // constant which cannot collide with a overflowed signed operand,
10438   // then reinterpreting the signed operand as unsigned will not
10439   // change the result of the comparison.
10440   if (E->isEqualityOp()) {
10441     unsigned comparisonWidth = S.Context.getIntWidth(T);
10442     IntRange unsignedRange =
10443         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated());
10444 
10445     // We should never be unable to prove that the unsigned operand is
10446     // non-negative.
10447     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
10448 
10449     if (unsignedRange.Width < comparisonWidth)
10450       return;
10451   }
10452 
10453   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
10454                         S.PDiag(diag::warn_mixed_sign_comparison)
10455                             << LHS->getType() << RHS->getType()
10456                             << LHS->getSourceRange() << RHS->getSourceRange());
10457 }
10458 
10459 /// Analyzes an attempt to assign the given value to a bitfield.
10460 ///
10461 /// Returns true if there was something fishy about the attempt.
10462 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
10463                                       SourceLocation InitLoc) {
10464   assert(Bitfield->isBitField());
10465   if (Bitfield->isInvalidDecl())
10466     return false;
10467 
10468   // White-list bool bitfields.
10469   QualType BitfieldType = Bitfield->getType();
10470   if (BitfieldType->isBooleanType())
10471      return false;
10472 
10473   if (BitfieldType->isEnumeralType()) {
10474     EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
10475     // If the underlying enum type was not explicitly specified as an unsigned
10476     // type and the enum contain only positive values, MSVC++ will cause an
10477     // inconsistency by storing this as a signed type.
10478     if (S.getLangOpts().CPlusPlus11 &&
10479         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
10480         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
10481         BitfieldEnumDecl->getNumNegativeBits() == 0) {
10482       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
10483         << BitfieldEnumDecl->getNameAsString();
10484     }
10485   }
10486 
10487   if (Bitfield->getType()->isBooleanType())
10488     return false;
10489 
10490   // Ignore value- or type-dependent expressions.
10491   if (Bitfield->getBitWidth()->isValueDependent() ||
10492       Bitfield->getBitWidth()->isTypeDependent() ||
10493       Init->isValueDependent() ||
10494       Init->isTypeDependent())
10495     return false;
10496 
10497   Expr *OriginalInit = Init->IgnoreParenImpCasts();
10498   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
10499 
10500   Expr::EvalResult Result;
10501   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
10502                                    Expr::SE_AllowSideEffects)) {
10503     // The RHS is not constant.  If the RHS has an enum type, make sure the
10504     // bitfield is wide enough to hold all the values of the enum without
10505     // truncation.
10506     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
10507       EnumDecl *ED = EnumTy->getDecl();
10508       bool SignedBitfield = BitfieldType->isSignedIntegerType();
10509 
10510       // Enum types are implicitly signed on Windows, so check if there are any
10511       // negative enumerators to see if the enum was intended to be signed or
10512       // not.
10513       bool SignedEnum = ED->getNumNegativeBits() > 0;
10514 
10515       // Check for surprising sign changes when assigning enum values to a
10516       // bitfield of different signedness.  If the bitfield is signed and we
10517       // have exactly the right number of bits to store this unsigned enum,
10518       // suggest changing the enum to an unsigned type. This typically happens
10519       // on Windows where unfixed enums always use an underlying type of 'int'.
10520       unsigned DiagID = 0;
10521       if (SignedEnum && !SignedBitfield) {
10522         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
10523       } else if (SignedBitfield && !SignedEnum &&
10524                  ED->getNumPositiveBits() == FieldWidth) {
10525         DiagID = diag::warn_signed_bitfield_enum_conversion;
10526       }
10527 
10528       if (DiagID) {
10529         S.Diag(InitLoc, DiagID) << Bitfield << ED;
10530         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
10531         SourceRange TypeRange =
10532             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
10533         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
10534             << SignedEnum << TypeRange;
10535       }
10536 
10537       // Compute the required bitwidth. If the enum has negative values, we need
10538       // one more bit than the normal number of positive bits to represent the
10539       // sign bit.
10540       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
10541                                                   ED->getNumNegativeBits())
10542                                        : ED->getNumPositiveBits();
10543 
10544       // Check the bitwidth.
10545       if (BitsNeeded > FieldWidth) {
10546         Expr *WidthExpr = Bitfield->getBitWidth();
10547         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
10548             << Bitfield << ED;
10549         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
10550             << BitsNeeded << ED << WidthExpr->getSourceRange();
10551       }
10552     }
10553 
10554     return false;
10555   }
10556 
10557   llvm::APSInt Value = Result.Val.getInt();
10558 
10559   unsigned OriginalWidth = Value.getBitWidth();
10560 
10561   if (!Value.isSigned() || Value.isNegative())
10562     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
10563       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
10564         OriginalWidth = Value.getMinSignedBits();
10565 
10566   if (OriginalWidth <= FieldWidth)
10567     return false;
10568 
10569   // Compute the value which the bitfield will contain.
10570   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
10571   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
10572 
10573   // Check whether the stored value is equal to the original value.
10574   TruncatedValue = TruncatedValue.extend(OriginalWidth);
10575   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
10576     return false;
10577 
10578   // Special-case bitfields of width 1: booleans are naturally 0/1, and
10579   // therefore don't strictly fit into a signed bitfield of width 1.
10580   if (FieldWidth == 1 && Value == 1)
10581     return false;
10582 
10583   std::string PrettyValue = Value.toString(10);
10584   std::string PrettyTrunc = TruncatedValue.toString(10);
10585 
10586   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
10587     << PrettyValue << PrettyTrunc << OriginalInit->getType()
10588     << Init->getSourceRange();
10589 
10590   return true;
10591 }
10592 
10593 /// Analyze the given simple or compound assignment for warning-worthy
10594 /// operations.
10595 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
10596   // Just recurse on the LHS.
10597   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10598 
10599   // We want to recurse on the RHS as normal unless we're assigning to
10600   // a bitfield.
10601   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
10602     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
10603                                   E->getOperatorLoc())) {
10604       // Recurse, ignoring any implicit conversions on the RHS.
10605       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
10606                                         E->getOperatorLoc());
10607     }
10608   }
10609 
10610   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10611 
10612   // Diagnose implicitly sequentially-consistent atomic assignment.
10613   if (E->getLHS()->getType()->isAtomicType())
10614     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
10615 }
10616 
10617 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
10618 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
10619                             SourceLocation CContext, unsigned diag,
10620                             bool pruneControlFlow = false) {
10621   if (pruneControlFlow) {
10622     S.DiagRuntimeBehavior(E->getExprLoc(), E,
10623                           S.PDiag(diag)
10624                               << SourceType << T << E->getSourceRange()
10625                               << SourceRange(CContext));
10626     return;
10627   }
10628   S.Diag(E->getExprLoc(), diag)
10629     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
10630 }
10631 
10632 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
10633 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
10634                             SourceLocation CContext,
10635                             unsigned diag, bool pruneControlFlow = false) {
10636   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
10637 }
10638 
10639 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
10640   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
10641       S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
10642 }
10643 
10644 static void adornObjCBoolConversionDiagWithTernaryFixit(
10645     Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
10646   Expr *Ignored = SourceExpr->IgnoreImplicit();
10647   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
10648     Ignored = OVE->getSourceExpr();
10649   bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
10650                      isa<BinaryOperator>(Ignored) ||
10651                      isa<CXXOperatorCallExpr>(Ignored);
10652   SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
10653   if (NeedsParens)
10654     Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
10655             << FixItHint::CreateInsertion(EndLoc, ")");
10656   Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
10657 }
10658 
10659 /// Diagnose an implicit cast from a floating point value to an integer value.
10660 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
10661                                     SourceLocation CContext) {
10662   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
10663   const bool PruneWarnings = S.inTemplateInstantiation();
10664 
10665   Expr *InnerE = E->IgnoreParenImpCasts();
10666   // We also want to warn on, e.g., "int i = -1.234"
10667   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
10668     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
10669       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
10670 
10671   const bool IsLiteral =
10672       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
10673 
10674   llvm::APFloat Value(0.0);
10675   bool IsConstant =
10676     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
10677   if (!IsConstant) {
10678     if (isObjCSignedCharBool(S, T)) {
10679       return adornObjCBoolConversionDiagWithTernaryFixit(
10680           S, E,
10681           S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
10682               << E->getType());
10683     }
10684 
10685     return DiagnoseImpCast(S, E, T, CContext,
10686                            diag::warn_impcast_float_integer, PruneWarnings);
10687   }
10688 
10689   bool isExact = false;
10690 
10691   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
10692                             T->hasUnsignedIntegerRepresentation());
10693   llvm::APFloat::opStatus Result = Value.convertToInteger(
10694       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
10695 
10696   // FIXME: Force the precision of the source value down so we don't print
10697   // digits which are usually useless (we don't really care here if we
10698   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
10699   // would automatically print the shortest representation, but it's a bit
10700   // tricky to implement.
10701   SmallString<16> PrettySourceValue;
10702   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
10703   precision = (precision * 59 + 195) / 196;
10704   Value.toString(PrettySourceValue, precision);
10705 
10706   if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
10707     return adornObjCBoolConversionDiagWithTernaryFixit(
10708         S, E,
10709         S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
10710             << PrettySourceValue);
10711   }
10712 
10713   if (Result == llvm::APFloat::opOK && isExact) {
10714     if (IsLiteral) return;
10715     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
10716                            PruneWarnings);
10717   }
10718 
10719   // Conversion of a floating-point value to a non-bool integer where the
10720   // integral part cannot be represented by the integer type is undefined.
10721   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
10722     return DiagnoseImpCast(
10723         S, E, T, CContext,
10724         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
10725                   : diag::warn_impcast_float_to_integer_out_of_range,
10726         PruneWarnings);
10727 
10728   unsigned DiagID = 0;
10729   if (IsLiteral) {
10730     // Warn on floating point literal to integer.
10731     DiagID = diag::warn_impcast_literal_float_to_integer;
10732   } else if (IntegerValue == 0) {
10733     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
10734       return DiagnoseImpCast(S, E, T, CContext,
10735                              diag::warn_impcast_float_integer, PruneWarnings);
10736     }
10737     // Warn on non-zero to zero conversion.
10738     DiagID = diag::warn_impcast_float_to_integer_zero;
10739   } else {
10740     if (IntegerValue.isUnsigned()) {
10741       if (!IntegerValue.isMaxValue()) {
10742         return DiagnoseImpCast(S, E, T, CContext,
10743                                diag::warn_impcast_float_integer, PruneWarnings);
10744       }
10745     } else {  // IntegerValue.isSigned()
10746       if (!IntegerValue.isMaxSignedValue() &&
10747           !IntegerValue.isMinSignedValue()) {
10748         return DiagnoseImpCast(S, E, T, CContext,
10749                                diag::warn_impcast_float_integer, PruneWarnings);
10750       }
10751     }
10752     // Warn on evaluatable floating point expression to integer conversion.
10753     DiagID = diag::warn_impcast_float_to_integer;
10754   }
10755 
10756   SmallString<16> PrettyTargetValue;
10757   if (IsBool)
10758     PrettyTargetValue = Value.isZero() ? "false" : "true";
10759   else
10760     IntegerValue.toString(PrettyTargetValue);
10761 
10762   if (PruneWarnings) {
10763     S.DiagRuntimeBehavior(E->getExprLoc(), E,
10764                           S.PDiag(DiagID)
10765                               << E->getType() << T.getUnqualifiedType()
10766                               << PrettySourceValue << PrettyTargetValue
10767                               << E->getSourceRange() << SourceRange(CContext));
10768   } else {
10769     S.Diag(E->getExprLoc(), DiagID)
10770         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
10771         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
10772   }
10773 }
10774 
10775 /// Analyze the given compound assignment for the possible losing of
10776 /// floating-point precision.
10777 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
10778   assert(isa<CompoundAssignOperator>(E) &&
10779          "Must be compound assignment operation");
10780   // Recurse on the LHS and RHS in here
10781   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10782   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10783 
10784   if (E->getLHS()->getType()->isAtomicType())
10785     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
10786 
10787   // Now check the outermost expression
10788   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
10789   const auto *RBT = cast<CompoundAssignOperator>(E)
10790                         ->getComputationResultType()
10791                         ->getAs<BuiltinType>();
10792 
10793   // The below checks assume source is floating point.
10794   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
10795 
10796   // If source is floating point but target is an integer.
10797   if (ResultBT->isInteger())
10798     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
10799                            E->getExprLoc(), diag::warn_impcast_float_integer);
10800 
10801   if (!ResultBT->isFloatingPoint())
10802     return;
10803 
10804   // If both source and target are floating points, warn about losing precision.
10805   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
10806       QualType(ResultBT, 0), QualType(RBT, 0));
10807   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
10808     // warn about dropping FP rank.
10809     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
10810                     diag::warn_impcast_float_result_precision);
10811 }
10812 
10813 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
10814                                       IntRange Range) {
10815   if (!Range.Width) return "0";
10816 
10817   llvm::APSInt ValueInRange = Value;
10818   ValueInRange.setIsSigned(!Range.NonNegative);
10819   ValueInRange = ValueInRange.trunc(Range.Width);
10820   return ValueInRange.toString(10);
10821 }
10822 
10823 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
10824   if (!isa<ImplicitCastExpr>(Ex))
10825     return false;
10826 
10827   Expr *InnerE = Ex->IgnoreParenImpCasts();
10828   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
10829   const Type *Source =
10830     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
10831   if (Target->isDependentType())
10832     return false;
10833 
10834   const BuiltinType *FloatCandidateBT =
10835     dyn_cast<BuiltinType>(ToBool ? Source : Target);
10836   const Type *BoolCandidateType = ToBool ? Target : Source;
10837 
10838   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
10839           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
10840 }
10841 
10842 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
10843                                              SourceLocation CC) {
10844   unsigned NumArgs = TheCall->getNumArgs();
10845   for (unsigned i = 0; i < NumArgs; ++i) {
10846     Expr *CurrA = TheCall->getArg(i);
10847     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
10848       continue;
10849 
10850     bool IsSwapped = ((i > 0) &&
10851         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
10852     IsSwapped |= ((i < (NumArgs - 1)) &&
10853         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
10854     if (IsSwapped) {
10855       // Warn on this floating-point to bool conversion.
10856       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
10857                       CurrA->getType(), CC,
10858                       diag::warn_impcast_floating_point_to_bool);
10859     }
10860   }
10861 }
10862 
10863 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
10864                                    SourceLocation CC) {
10865   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
10866                         E->getExprLoc()))
10867     return;
10868 
10869   // Don't warn on functions which have return type nullptr_t.
10870   if (isa<CallExpr>(E))
10871     return;
10872 
10873   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
10874   const Expr::NullPointerConstantKind NullKind =
10875       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
10876   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
10877     return;
10878 
10879   // Return if target type is a safe conversion.
10880   if (T->isAnyPointerType() || T->isBlockPointerType() ||
10881       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
10882     return;
10883 
10884   SourceLocation Loc = E->getSourceRange().getBegin();
10885 
10886   // Venture through the macro stacks to get to the source of macro arguments.
10887   // The new location is a better location than the complete location that was
10888   // passed in.
10889   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
10890   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
10891 
10892   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
10893   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
10894     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
10895         Loc, S.SourceMgr, S.getLangOpts());
10896     if (MacroName == "NULL")
10897       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
10898   }
10899 
10900   // Only warn if the null and context location are in the same macro expansion.
10901   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
10902     return;
10903 
10904   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
10905       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
10906       << FixItHint::CreateReplacement(Loc,
10907                                       S.getFixItZeroLiteralForType(T, Loc));
10908 }
10909 
10910 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
10911                                   ObjCArrayLiteral *ArrayLiteral);
10912 
10913 static void
10914 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
10915                            ObjCDictionaryLiteral *DictionaryLiteral);
10916 
10917 /// Check a single element within a collection literal against the
10918 /// target element type.
10919 static void checkObjCCollectionLiteralElement(Sema &S,
10920                                               QualType TargetElementType,
10921                                               Expr *Element,
10922                                               unsigned ElementKind) {
10923   // Skip a bitcast to 'id' or qualified 'id'.
10924   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
10925     if (ICE->getCastKind() == CK_BitCast &&
10926         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
10927       Element = ICE->getSubExpr();
10928   }
10929 
10930   QualType ElementType = Element->getType();
10931   ExprResult ElementResult(Element);
10932   if (ElementType->getAs<ObjCObjectPointerType>() &&
10933       S.CheckSingleAssignmentConstraints(TargetElementType,
10934                                          ElementResult,
10935                                          false, false)
10936         != Sema::Compatible) {
10937     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
10938         << ElementType << ElementKind << TargetElementType
10939         << Element->getSourceRange();
10940   }
10941 
10942   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
10943     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
10944   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
10945     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
10946 }
10947 
10948 /// Check an Objective-C array literal being converted to the given
10949 /// target type.
10950 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
10951                                   ObjCArrayLiteral *ArrayLiteral) {
10952   if (!S.NSArrayDecl)
10953     return;
10954 
10955   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
10956   if (!TargetObjCPtr)
10957     return;
10958 
10959   if (TargetObjCPtr->isUnspecialized() ||
10960       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
10961         != S.NSArrayDecl->getCanonicalDecl())
10962     return;
10963 
10964   auto TypeArgs = TargetObjCPtr->getTypeArgs();
10965   if (TypeArgs.size() != 1)
10966     return;
10967 
10968   QualType TargetElementType = TypeArgs[0];
10969   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
10970     checkObjCCollectionLiteralElement(S, TargetElementType,
10971                                       ArrayLiteral->getElement(I),
10972                                       0);
10973   }
10974 }
10975 
10976 /// Check an Objective-C dictionary literal being converted to the given
10977 /// target type.
10978 static void
10979 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
10980                            ObjCDictionaryLiteral *DictionaryLiteral) {
10981   if (!S.NSDictionaryDecl)
10982     return;
10983 
10984   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
10985   if (!TargetObjCPtr)
10986     return;
10987 
10988   if (TargetObjCPtr->isUnspecialized() ||
10989       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
10990         != S.NSDictionaryDecl->getCanonicalDecl())
10991     return;
10992 
10993   auto TypeArgs = TargetObjCPtr->getTypeArgs();
10994   if (TypeArgs.size() != 2)
10995     return;
10996 
10997   QualType TargetKeyType = TypeArgs[0];
10998   QualType TargetObjectType = TypeArgs[1];
10999   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
11000     auto Element = DictionaryLiteral->getKeyValueElement(I);
11001     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
11002     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
11003   }
11004 }
11005 
11006 // Helper function to filter out cases for constant width constant conversion.
11007 // Don't warn on char array initialization or for non-decimal values.
11008 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
11009                                           SourceLocation CC) {
11010   // If initializing from a constant, and the constant starts with '0',
11011   // then it is a binary, octal, or hexadecimal.  Allow these constants
11012   // to fill all the bits, even if there is a sign change.
11013   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
11014     const char FirstLiteralCharacter =
11015         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
11016     if (FirstLiteralCharacter == '0')
11017       return false;
11018   }
11019 
11020   // If the CC location points to a '{', and the type is char, then assume
11021   // assume it is an array initialization.
11022   if (CC.isValid() && T->isCharType()) {
11023     const char FirstContextCharacter =
11024         S.getSourceManager().getCharacterData(CC)[0];
11025     if (FirstContextCharacter == '{')
11026       return false;
11027   }
11028 
11029   return true;
11030 }
11031 
11032 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
11033   const auto *IL = dyn_cast<IntegerLiteral>(E);
11034   if (!IL) {
11035     if (auto *UO = dyn_cast<UnaryOperator>(E)) {
11036       if (UO->getOpcode() == UO_Minus)
11037         return dyn_cast<IntegerLiteral>(UO->getSubExpr());
11038     }
11039   }
11040 
11041   return IL;
11042 }
11043 
11044 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
11045   E = E->IgnoreParenImpCasts();
11046   SourceLocation ExprLoc = E->getExprLoc();
11047 
11048   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11049     BinaryOperator::Opcode Opc = BO->getOpcode();
11050     Expr::EvalResult Result;
11051     // Do not diagnose unsigned shifts.
11052     if (Opc == BO_Shl) {
11053       const auto *LHS = getIntegerLiteral(BO->getLHS());
11054       const auto *RHS = getIntegerLiteral(BO->getRHS());
11055       if (LHS && LHS->getValue() == 0)
11056         S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
11057       else if (!E->isValueDependent() && LHS && RHS &&
11058                RHS->getValue().isNonNegative() &&
11059                E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
11060         S.Diag(ExprLoc, diag::warn_left_shift_always)
11061             << (Result.Val.getInt() != 0);
11062       else if (E->getType()->isSignedIntegerType())
11063         S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
11064     }
11065   }
11066 
11067   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11068     const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
11069     const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
11070     if (!LHS || !RHS)
11071       return;
11072     if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
11073         (RHS->getValue() == 0 || RHS->getValue() == 1))
11074       // Do not diagnose common idioms.
11075       return;
11076     if (LHS->getValue() != 0 && RHS->getValue() != 0)
11077       S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
11078   }
11079 }
11080 
11081 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
11082                                     SourceLocation CC,
11083                                     bool *ICContext = nullptr,
11084                                     bool IsListInit = false) {
11085   if (E->isTypeDependent() || E->isValueDependent()) return;
11086 
11087   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
11088   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
11089   if (Source == Target) return;
11090   if (Target->isDependentType()) return;
11091 
11092   // If the conversion context location is invalid don't complain. We also
11093   // don't want to emit a warning if the issue occurs from the expansion of
11094   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
11095   // delay this check as long as possible. Once we detect we are in that
11096   // scenario, we just return.
11097   if (CC.isInvalid())
11098     return;
11099 
11100   if (Source->isAtomicType())
11101     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
11102 
11103   // Diagnose implicit casts to bool.
11104   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
11105     if (isa<StringLiteral>(E))
11106       // Warn on string literal to bool.  Checks for string literals in logical
11107       // and expressions, for instance, assert(0 && "error here"), are
11108       // prevented by a check in AnalyzeImplicitConversions().
11109       return DiagnoseImpCast(S, E, T, CC,
11110                              diag::warn_impcast_string_literal_to_bool);
11111     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
11112         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
11113       // This covers the literal expressions that evaluate to Objective-C
11114       // objects.
11115       return DiagnoseImpCast(S, E, T, CC,
11116                              diag::warn_impcast_objective_c_literal_to_bool);
11117     }
11118     if (Source->isPointerType() || Source->canDecayToPointerType()) {
11119       // Warn on pointer to bool conversion that is always true.
11120       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
11121                                      SourceRange(CC));
11122     }
11123   }
11124 
11125   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
11126   // is a typedef for signed char (macOS), then that constant value has to be 1
11127   // or 0.
11128   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
11129     Expr::EvalResult Result;
11130     if (E->EvaluateAsInt(Result, S.getASTContext(),
11131                          Expr::SE_AllowSideEffects)) {
11132       if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
11133         adornObjCBoolConversionDiagWithTernaryFixit(
11134             S, E,
11135             S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
11136                 << Result.Val.getInt().toString(10));
11137       }
11138       return;
11139     }
11140   }
11141 
11142   // Check implicit casts from Objective-C collection literals to specialized
11143   // collection types, e.g., NSArray<NSString *> *.
11144   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
11145     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
11146   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
11147     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
11148 
11149   // Strip vector types.
11150   if (isa<VectorType>(Source)) {
11151     if (!isa<VectorType>(Target)) {
11152       if (S.SourceMgr.isInSystemMacro(CC))
11153         return;
11154       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
11155     }
11156 
11157     // If the vector cast is cast between two vectors of the same size, it is
11158     // a bitcast, not a conversion.
11159     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
11160       return;
11161 
11162     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
11163     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
11164   }
11165   if (auto VecTy = dyn_cast<VectorType>(Target))
11166     Target = VecTy->getElementType().getTypePtr();
11167 
11168   // Strip complex types.
11169   if (isa<ComplexType>(Source)) {
11170     if (!isa<ComplexType>(Target)) {
11171       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
11172         return;
11173 
11174       return DiagnoseImpCast(S, E, T, CC,
11175                              S.getLangOpts().CPlusPlus
11176                                  ? diag::err_impcast_complex_scalar
11177                                  : diag::warn_impcast_complex_scalar);
11178     }
11179 
11180     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
11181     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
11182   }
11183 
11184   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
11185   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
11186 
11187   // If the source is floating point...
11188   if (SourceBT && SourceBT->isFloatingPoint()) {
11189     // ...and the target is floating point...
11190     if (TargetBT && TargetBT->isFloatingPoint()) {
11191       // ...then warn if we're dropping FP rank.
11192 
11193       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
11194           QualType(SourceBT, 0), QualType(TargetBT, 0));
11195       if (Order > 0) {
11196         // Don't warn about float constants that are precisely
11197         // representable in the target type.
11198         Expr::EvalResult result;
11199         if (E->EvaluateAsRValue(result, S.Context)) {
11200           // Value might be a float, a float vector, or a float complex.
11201           if (IsSameFloatAfterCast(result.Val,
11202                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
11203                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
11204             return;
11205         }
11206 
11207         if (S.SourceMgr.isInSystemMacro(CC))
11208           return;
11209 
11210         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
11211       }
11212       // ... or possibly if we're increasing rank, too
11213       else if (Order < 0) {
11214         if (S.SourceMgr.isInSystemMacro(CC))
11215           return;
11216 
11217         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
11218       }
11219       return;
11220     }
11221 
11222     // If the target is integral, always warn.
11223     if (TargetBT && TargetBT->isInteger()) {
11224       if (S.SourceMgr.isInSystemMacro(CC))
11225         return;
11226 
11227       DiagnoseFloatingImpCast(S, E, T, CC);
11228     }
11229 
11230     // Detect the case where a call result is converted from floating-point to
11231     // to bool, and the final argument to the call is converted from bool, to
11232     // discover this typo:
11233     //
11234     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
11235     //
11236     // FIXME: This is an incredibly special case; is there some more general
11237     // way to detect this class of misplaced-parentheses bug?
11238     if (Target->isBooleanType() && isa<CallExpr>(E)) {
11239       // Check last argument of function call to see if it is an
11240       // implicit cast from a type matching the type the result
11241       // is being cast to.
11242       CallExpr *CEx = cast<CallExpr>(E);
11243       if (unsigned NumArgs = CEx->getNumArgs()) {
11244         Expr *LastA = CEx->getArg(NumArgs - 1);
11245         Expr *InnerE = LastA->IgnoreParenImpCasts();
11246         if (isa<ImplicitCastExpr>(LastA) &&
11247             InnerE->getType()->isBooleanType()) {
11248           // Warn on this floating-point to bool conversion
11249           DiagnoseImpCast(S, E, T, CC,
11250                           diag::warn_impcast_floating_point_to_bool);
11251         }
11252       }
11253     }
11254     return;
11255   }
11256 
11257   // Valid casts involving fixed point types should be accounted for here.
11258   if (Source->isFixedPointType()) {
11259     if (Target->isUnsaturatedFixedPointType()) {
11260       Expr::EvalResult Result;
11261       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
11262                                   S.isConstantEvaluated())) {
11263         APFixedPoint Value = Result.Val.getFixedPoint();
11264         APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
11265         APFixedPoint MinVal = S.Context.getFixedPointMin(T);
11266         if (Value > MaxVal || Value < MinVal) {
11267           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11268                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11269                                     << Value.toString() << T
11270                                     << E->getSourceRange()
11271                                     << clang::SourceRange(CC));
11272           return;
11273         }
11274       }
11275     } else if (Target->isIntegerType()) {
11276       Expr::EvalResult Result;
11277       if (!S.isConstantEvaluated() &&
11278           E->EvaluateAsFixedPoint(Result, S.Context,
11279                                   Expr::SE_AllowSideEffects)) {
11280         APFixedPoint FXResult = Result.Val.getFixedPoint();
11281 
11282         bool Overflowed;
11283         llvm::APSInt IntResult = FXResult.convertToInt(
11284             S.Context.getIntWidth(T),
11285             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
11286 
11287         if (Overflowed) {
11288           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11289                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11290                                     << FXResult.toString() << T
11291                                     << E->getSourceRange()
11292                                     << clang::SourceRange(CC));
11293           return;
11294         }
11295       }
11296     }
11297   } else if (Target->isUnsaturatedFixedPointType()) {
11298     if (Source->isIntegerType()) {
11299       Expr::EvalResult Result;
11300       if (!S.isConstantEvaluated() &&
11301           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
11302         llvm::APSInt Value = Result.Val.getInt();
11303 
11304         bool Overflowed;
11305         APFixedPoint IntResult = APFixedPoint::getFromIntValue(
11306             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
11307 
11308         if (Overflowed) {
11309           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11310                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11311                                     << Value.toString(/*Radix=*/10) << T
11312                                     << E->getSourceRange()
11313                                     << clang::SourceRange(CC));
11314           return;
11315         }
11316       }
11317     }
11318   }
11319 
11320   // If we are casting an integer type to a floating point type without
11321   // initialization-list syntax, we might lose accuracy if the floating
11322   // point type has a narrower significand than the integer type.
11323   if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
11324       TargetBT->isFloatingType() && !IsListInit) {
11325     // Determine the number of precision bits in the source integer type.
11326     IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated());
11327     unsigned int SourcePrecision = SourceRange.Width;
11328 
11329     // Determine the number of precision bits in the
11330     // target floating point type.
11331     unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
11332         S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
11333 
11334     if (SourcePrecision > 0 && TargetPrecision > 0 &&
11335         SourcePrecision > TargetPrecision) {
11336 
11337       llvm::APSInt SourceInt;
11338       if (E->isIntegerConstantExpr(SourceInt, S.Context)) {
11339         // If the source integer is a constant, convert it to the target
11340         // floating point type. Issue a warning if the value changes
11341         // during the whole conversion.
11342         llvm::APFloat TargetFloatValue(
11343             S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
11344         llvm::APFloat::opStatus ConversionStatus =
11345             TargetFloatValue.convertFromAPInt(
11346                 SourceInt, SourceBT->isSignedInteger(),
11347                 llvm::APFloat::rmNearestTiesToEven);
11348 
11349         if (ConversionStatus != llvm::APFloat::opOK) {
11350           std::string PrettySourceValue = SourceInt.toString(10);
11351           SmallString<32> PrettyTargetValue;
11352           TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
11353 
11354           S.DiagRuntimeBehavior(
11355               E->getExprLoc(), E,
11356               S.PDiag(diag::warn_impcast_integer_float_precision_constant)
11357                   << PrettySourceValue << PrettyTargetValue << E->getType() << T
11358                   << E->getSourceRange() << clang::SourceRange(CC));
11359         }
11360       } else {
11361         // Otherwise, the implicit conversion may lose precision.
11362         DiagnoseImpCast(S, E, T, CC,
11363                         diag::warn_impcast_integer_float_precision);
11364       }
11365     }
11366   }
11367 
11368   DiagnoseNullConversion(S, E, T, CC);
11369 
11370   S.DiscardMisalignedMemberAddress(Target, E);
11371 
11372   if (Target->isBooleanType())
11373     DiagnoseIntInBoolContext(S, E);
11374 
11375   if (!Source->isIntegerType() || !Target->isIntegerType())
11376     return;
11377 
11378   // TODO: remove this early return once the false positives for constant->bool
11379   // in templates, macros, etc, are reduced or removed.
11380   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
11381     return;
11382 
11383   if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
11384       !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
11385     return adornObjCBoolConversionDiagWithTernaryFixit(
11386         S, E,
11387         S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
11388             << E->getType());
11389   }
11390 
11391   IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated());
11392   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
11393 
11394   if (SourceRange.Width > TargetRange.Width) {
11395     // If the source is a constant, use a default-on diagnostic.
11396     // TODO: this should happen for bitfield stores, too.
11397     Expr::EvalResult Result;
11398     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
11399                          S.isConstantEvaluated())) {
11400       llvm::APSInt Value(32);
11401       Value = Result.Val.getInt();
11402 
11403       if (S.SourceMgr.isInSystemMacro(CC))
11404         return;
11405 
11406       std::string PrettySourceValue = Value.toString(10);
11407       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
11408 
11409       S.DiagRuntimeBehavior(
11410           E->getExprLoc(), E,
11411           S.PDiag(diag::warn_impcast_integer_precision_constant)
11412               << PrettySourceValue << PrettyTargetValue << E->getType() << T
11413               << E->getSourceRange() << clang::SourceRange(CC));
11414       return;
11415     }
11416 
11417     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
11418     if (S.SourceMgr.isInSystemMacro(CC))
11419       return;
11420 
11421     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
11422       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
11423                              /* pruneControlFlow */ true);
11424     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
11425   }
11426 
11427   if (TargetRange.Width > SourceRange.Width) {
11428     if (auto *UO = dyn_cast<UnaryOperator>(E))
11429       if (UO->getOpcode() == UO_Minus)
11430         if (Source->isUnsignedIntegerType()) {
11431           if (Target->isUnsignedIntegerType())
11432             return DiagnoseImpCast(S, E, T, CC,
11433                                    diag::warn_impcast_high_order_zero_bits);
11434           if (Target->isSignedIntegerType())
11435             return DiagnoseImpCast(S, E, T, CC,
11436                                    diag::warn_impcast_nonnegative_result);
11437         }
11438   }
11439 
11440   if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
11441       SourceRange.NonNegative && Source->isSignedIntegerType()) {
11442     // Warn when doing a signed to signed conversion, warn if the positive
11443     // source value is exactly the width of the target type, which will
11444     // cause a negative value to be stored.
11445 
11446     Expr::EvalResult Result;
11447     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
11448         !S.SourceMgr.isInSystemMacro(CC)) {
11449       llvm::APSInt Value = Result.Val.getInt();
11450       if (isSameWidthConstantConversion(S, E, T, CC)) {
11451         std::string PrettySourceValue = Value.toString(10);
11452         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
11453 
11454         S.DiagRuntimeBehavior(
11455             E->getExprLoc(), E,
11456             S.PDiag(diag::warn_impcast_integer_precision_constant)
11457                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
11458                 << E->getSourceRange() << clang::SourceRange(CC));
11459         return;
11460       }
11461     }
11462 
11463     // Fall through for non-constants to give a sign conversion warning.
11464   }
11465 
11466   if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
11467       (!TargetRange.NonNegative && SourceRange.NonNegative &&
11468        SourceRange.Width == TargetRange.Width)) {
11469     if (S.SourceMgr.isInSystemMacro(CC))
11470       return;
11471 
11472     unsigned DiagID = diag::warn_impcast_integer_sign;
11473 
11474     // Traditionally, gcc has warned about this under -Wsign-compare.
11475     // We also want to warn about it in -Wconversion.
11476     // So if -Wconversion is off, use a completely identical diagnostic
11477     // in the sign-compare group.
11478     // The conditional-checking code will
11479     if (ICContext) {
11480       DiagID = diag::warn_impcast_integer_sign_conditional;
11481       *ICContext = true;
11482     }
11483 
11484     return DiagnoseImpCast(S, E, T, CC, DiagID);
11485   }
11486 
11487   // Diagnose conversions between different enumeration types.
11488   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
11489   // type, to give us better diagnostics.
11490   QualType SourceType = E->getType();
11491   if (!S.getLangOpts().CPlusPlus) {
11492     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11493       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
11494         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
11495         SourceType = S.Context.getTypeDeclType(Enum);
11496         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
11497       }
11498   }
11499 
11500   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
11501     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
11502       if (SourceEnum->getDecl()->hasNameForLinkage() &&
11503           TargetEnum->getDecl()->hasNameForLinkage() &&
11504           SourceEnum != TargetEnum) {
11505         if (S.SourceMgr.isInSystemMacro(CC))
11506           return;
11507 
11508         return DiagnoseImpCast(S, E, SourceType, T, CC,
11509                                diag::warn_impcast_different_enum_types);
11510       }
11511 }
11512 
11513 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
11514                                      SourceLocation CC, QualType T);
11515 
11516 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
11517                                     SourceLocation CC, bool &ICContext) {
11518   E = E->IgnoreParenImpCasts();
11519 
11520   if (isa<ConditionalOperator>(E))
11521     return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
11522 
11523   AnalyzeImplicitConversions(S, E, CC);
11524   if (E->getType() != T)
11525     return CheckImplicitConversion(S, E, T, CC, &ICContext);
11526 }
11527 
11528 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
11529                                      SourceLocation CC, QualType T) {
11530   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
11531 
11532   bool Suspicious = false;
11533   CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
11534   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
11535 
11536   if (T->isBooleanType())
11537     DiagnoseIntInBoolContext(S, E);
11538 
11539   // If -Wconversion would have warned about either of the candidates
11540   // for a signedness conversion to the context type...
11541   if (!Suspicious) return;
11542 
11543   // ...but it's currently ignored...
11544   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
11545     return;
11546 
11547   // ...then check whether it would have warned about either of the
11548   // candidates for a signedness conversion to the condition type.
11549   if (E->getType() == T) return;
11550 
11551   Suspicious = false;
11552   CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
11553                           E->getType(), CC, &Suspicious);
11554   if (!Suspicious)
11555     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
11556                             E->getType(), CC, &Suspicious);
11557 }
11558 
11559 /// Check conversion of given expression to boolean.
11560 /// Input argument E is a logical expression.
11561 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
11562   if (S.getLangOpts().Bool)
11563     return;
11564   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
11565     return;
11566   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
11567 }
11568 
11569 /// AnalyzeImplicitConversions - Find and report any interesting
11570 /// implicit conversions in the given expression.  There are a couple
11571 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
11572 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
11573                                        bool IsListInit/*= false*/) {
11574   QualType T = OrigE->getType();
11575   Expr *E = OrigE->IgnoreParenImpCasts();
11576 
11577   // Propagate whether we are in a C++ list initialization expression.
11578   // If so, we do not issue warnings for implicit int-float conversion
11579   // precision loss, because C++11 narrowing already handles it.
11580   IsListInit =
11581       IsListInit || (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
11582 
11583   if (E->isTypeDependent() || E->isValueDependent())
11584     return;
11585 
11586   if (const auto *UO = dyn_cast<UnaryOperator>(E))
11587     if (UO->getOpcode() == UO_Not &&
11588         UO->getSubExpr()->isKnownToHaveBooleanValue())
11589       S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
11590           << OrigE->getSourceRange() << T->isBooleanType()
11591           << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
11592 
11593   // For conditional operators, we analyze the arguments as if they
11594   // were being fed directly into the output.
11595   if (isa<ConditionalOperator>(E)) {
11596     ConditionalOperator *CO = cast<ConditionalOperator>(E);
11597     CheckConditionalOperator(S, CO, CC, T);
11598     return;
11599   }
11600 
11601   // Check implicit argument conversions for function calls.
11602   if (CallExpr *Call = dyn_cast<CallExpr>(E))
11603     CheckImplicitArgumentConversions(S, Call, CC);
11604 
11605   // Go ahead and check any implicit conversions we might have skipped.
11606   // The non-canonical typecheck is just an optimization;
11607   // CheckImplicitConversion will filter out dead implicit conversions.
11608   if (E->getType() != T)
11609     CheckImplicitConversion(S, E, T, CC, nullptr, IsListInit);
11610 
11611   // Now continue drilling into this expression.
11612 
11613   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
11614     // The bound subexpressions in a PseudoObjectExpr are not reachable
11615     // as transitive children.
11616     // FIXME: Use a more uniform representation for this.
11617     for (auto *SE : POE->semantics())
11618       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
11619         AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC, IsListInit);
11620   }
11621 
11622   // Skip past explicit casts.
11623   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
11624     E = CE->getSubExpr()->IgnoreParenImpCasts();
11625     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
11626       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
11627     return AnalyzeImplicitConversions(S, E, CC, IsListInit);
11628   }
11629 
11630   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11631     // Do a somewhat different check with comparison operators.
11632     if (BO->isComparisonOp())
11633       return AnalyzeComparison(S, BO);
11634 
11635     // And with simple assignments.
11636     if (BO->getOpcode() == BO_Assign)
11637       return AnalyzeAssignment(S, BO);
11638     // And with compound assignments.
11639     if (BO->isAssignmentOp())
11640       return AnalyzeCompoundAssignment(S, BO);
11641   }
11642 
11643   // These break the otherwise-useful invariant below.  Fortunately,
11644   // we don't really need to recurse into them, because any internal
11645   // expressions should have been analyzed already when they were
11646   // built into statements.
11647   if (isa<StmtExpr>(E)) return;
11648 
11649   // Don't descend into unevaluated contexts.
11650   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
11651 
11652   // Now just recurse over the expression's children.
11653   CC = E->getExprLoc();
11654   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
11655   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
11656   for (Stmt *SubStmt : E->children()) {
11657     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
11658     if (!ChildExpr)
11659       continue;
11660 
11661     if (IsLogicalAndOperator &&
11662         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
11663       // Ignore checking string literals that are in logical and operators.
11664       // This is a common pattern for asserts.
11665       continue;
11666     AnalyzeImplicitConversions(S, ChildExpr, CC, IsListInit);
11667   }
11668 
11669   if (BO && BO->isLogicalOp()) {
11670     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
11671     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
11672       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
11673 
11674     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
11675     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
11676       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
11677   }
11678 
11679   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
11680     if (U->getOpcode() == UO_LNot) {
11681       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
11682     } else if (U->getOpcode() != UO_AddrOf) {
11683       if (U->getSubExpr()->getType()->isAtomicType())
11684         S.Diag(U->getSubExpr()->getBeginLoc(),
11685                diag::warn_atomic_implicit_seq_cst);
11686     }
11687   }
11688 }
11689 
11690 /// Diagnose integer type and any valid implicit conversion to it.
11691 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
11692   // Taking into account implicit conversions,
11693   // allow any integer.
11694   if (!E->getType()->isIntegerType()) {
11695     S.Diag(E->getBeginLoc(),
11696            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
11697     return true;
11698   }
11699   // Potentially emit standard warnings for implicit conversions if enabled
11700   // using -Wconversion.
11701   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
11702   return false;
11703 }
11704 
11705 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
11706 // Returns true when emitting a warning about taking the address of a reference.
11707 static bool CheckForReference(Sema &SemaRef, const Expr *E,
11708                               const PartialDiagnostic &PD) {
11709   E = E->IgnoreParenImpCasts();
11710 
11711   const FunctionDecl *FD = nullptr;
11712 
11713   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11714     if (!DRE->getDecl()->getType()->isReferenceType())
11715       return false;
11716   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
11717     if (!M->getMemberDecl()->getType()->isReferenceType())
11718       return false;
11719   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
11720     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
11721       return false;
11722     FD = Call->getDirectCallee();
11723   } else {
11724     return false;
11725   }
11726 
11727   SemaRef.Diag(E->getExprLoc(), PD);
11728 
11729   // If possible, point to location of function.
11730   if (FD) {
11731     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
11732   }
11733 
11734   return true;
11735 }
11736 
11737 // Returns true if the SourceLocation is expanded from any macro body.
11738 // Returns false if the SourceLocation is invalid, is from not in a macro
11739 // expansion, or is from expanded from a top-level macro argument.
11740 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
11741   if (Loc.isInvalid())
11742     return false;
11743 
11744   while (Loc.isMacroID()) {
11745     if (SM.isMacroBodyExpansion(Loc))
11746       return true;
11747     Loc = SM.getImmediateMacroCallerLoc(Loc);
11748   }
11749 
11750   return false;
11751 }
11752 
11753 /// Diagnose pointers that are always non-null.
11754 /// \param E the expression containing the pointer
11755 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
11756 /// compared to a null pointer
11757 /// \param IsEqual True when the comparison is equal to a null pointer
11758 /// \param Range Extra SourceRange to highlight in the diagnostic
11759 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
11760                                         Expr::NullPointerConstantKind NullKind,
11761                                         bool IsEqual, SourceRange Range) {
11762   if (!E)
11763     return;
11764 
11765   // Don't warn inside macros.
11766   if (E->getExprLoc().isMacroID()) {
11767     const SourceManager &SM = getSourceManager();
11768     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
11769         IsInAnyMacroBody(SM, Range.getBegin()))
11770       return;
11771   }
11772   E = E->IgnoreImpCasts();
11773 
11774   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
11775 
11776   if (isa<CXXThisExpr>(E)) {
11777     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
11778                                 : diag::warn_this_bool_conversion;
11779     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
11780     return;
11781   }
11782 
11783   bool IsAddressOf = false;
11784 
11785   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
11786     if (UO->getOpcode() != UO_AddrOf)
11787       return;
11788     IsAddressOf = true;
11789     E = UO->getSubExpr();
11790   }
11791 
11792   if (IsAddressOf) {
11793     unsigned DiagID = IsCompare
11794                           ? diag::warn_address_of_reference_null_compare
11795                           : diag::warn_address_of_reference_bool_conversion;
11796     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
11797                                          << IsEqual;
11798     if (CheckForReference(*this, E, PD)) {
11799       return;
11800     }
11801   }
11802 
11803   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
11804     bool IsParam = isa<NonNullAttr>(NonnullAttr);
11805     std::string Str;
11806     llvm::raw_string_ostream S(Str);
11807     E->printPretty(S, nullptr, getPrintingPolicy());
11808     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
11809                                 : diag::warn_cast_nonnull_to_bool;
11810     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
11811       << E->getSourceRange() << Range << IsEqual;
11812     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
11813   };
11814 
11815   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
11816   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
11817     if (auto *Callee = Call->getDirectCallee()) {
11818       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
11819         ComplainAboutNonnullParamOrCall(A);
11820         return;
11821       }
11822     }
11823   }
11824 
11825   // Expect to find a single Decl.  Skip anything more complicated.
11826   ValueDecl *D = nullptr;
11827   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
11828     D = R->getDecl();
11829   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
11830     D = M->getMemberDecl();
11831   }
11832 
11833   // Weak Decls can be null.
11834   if (!D || D->isWeak())
11835     return;
11836 
11837   // Check for parameter decl with nonnull attribute
11838   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
11839     if (getCurFunction() &&
11840         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
11841       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
11842         ComplainAboutNonnullParamOrCall(A);
11843         return;
11844       }
11845 
11846       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
11847         // Skip function template not specialized yet.
11848         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
11849           return;
11850         auto ParamIter = llvm::find(FD->parameters(), PV);
11851         assert(ParamIter != FD->param_end());
11852         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
11853 
11854         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
11855           if (!NonNull->args_size()) {
11856               ComplainAboutNonnullParamOrCall(NonNull);
11857               return;
11858           }
11859 
11860           for (const ParamIdx &ArgNo : NonNull->args()) {
11861             if (ArgNo.getASTIndex() == ParamNo) {
11862               ComplainAboutNonnullParamOrCall(NonNull);
11863               return;
11864             }
11865           }
11866         }
11867       }
11868     }
11869   }
11870 
11871   QualType T = D->getType();
11872   const bool IsArray = T->isArrayType();
11873   const bool IsFunction = T->isFunctionType();
11874 
11875   // Address of function is used to silence the function warning.
11876   if (IsAddressOf && IsFunction) {
11877     return;
11878   }
11879 
11880   // Found nothing.
11881   if (!IsAddressOf && !IsFunction && !IsArray)
11882     return;
11883 
11884   // Pretty print the expression for the diagnostic.
11885   std::string Str;
11886   llvm::raw_string_ostream S(Str);
11887   E->printPretty(S, nullptr, getPrintingPolicy());
11888 
11889   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
11890                               : diag::warn_impcast_pointer_to_bool;
11891   enum {
11892     AddressOf,
11893     FunctionPointer,
11894     ArrayPointer
11895   } DiagType;
11896   if (IsAddressOf)
11897     DiagType = AddressOf;
11898   else if (IsFunction)
11899     DiagType = FunctionPointer;
11900   else if (IsArray)
11901     DiagType = ArrayPointer;
11902   else
11903     llvm_unreachable("Could not determine diagnostic.");
11904   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
11905                                 << Range << IsEqual;
11906 
11907   if (!IsFunction)
11908     return;
11909 
11910   // Suggest '&' to silence the function warning.
11911   Diag(E->getExprLoc(), diag::note_function_warning_silence)
11912       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
11913 
11914   // Check to see if '()' fixit should be emitted.
11915   QualType ReturnType;
11916   UnresolvedSet<4> NonTemplateOverloads;
11917   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
11918   if (ReturnType.isNull())
11919     return;
11920 
11921   if (IsCompare) {
11922     // There are two cases here.  If there is null constant, the only suggest
11923     // for a pointer return type.  If the null is 0, then suggest if the return
11924     // type is a pointer or an integer type.
11925     if (!ReturnType->isPointerType()) {
11926       if (NullKind == Expr::NPCK_ZeroExpression ||
11927           NullKind == Expr::NPCK_ZeroLiteral) {
11928         if (!ReturnType->isIntegerType())
11929           return;
11930       } else {
11931         return;
11932       }
11933     }
11934   } else { // !IsCompare
11935     // For function to bool, only suggest if the function pointer has bool
11936     // return type.
11937     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
11938       return;
11939   }
11940   Diag(E->getExprLoc(), diag::note_function_to_function_call)
11941       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
11942 }
11943 
11944 /// Diagnoses "dangerous" implicit conversions within the given
11945 /// expression (which is a full expression).  Implements -Wconversion
11946 /// and -Wsign-compare.
11947 ///
11948 /// \param CC the "context" location of the implicit conversion, i.e.
11949 ///   the most location of the syntactic entity requiring the implicit
11950 ///   conversion
11951 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
11952   // Don't diagnose in unevaluated contexts.
11953   if (isUnevaluatedContext())
11954     return;
11955 
11956   // Don't diagnose for value- or type-dependent expressions.
11957   if (E->isTypeDependent() || E->isValueDependent())
11958     return;
11959 
11960   // Check for array bounds violations in cases where the check isn't triggered
11961   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
11962   // ArraySubscriptExpr is on the RHS of a variable initialization.
11963   CheckArrayAccess(E);
11964 
11965   // This is not the right CC for (e.g.) a variable initialization.
11966   AnalyzeImplicitConversions(*this, E, CC);
11967 }
11968 
11969 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
11970 /// Input argument E is a logical expression.
11971 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
11972   ::CheckBoolLikeConversion(*this, E, CC);
11973 }
11974 
11975 /// Diagnose when expression is an integer constant expression and its evaluation
11976 /// results in integer overflow
11977 void Sema::CheckForIntOverflow (Expr *E) {
11978   // Use a work list to deal with nested struct initializers.
11979   SmallVector<Expr *, 2> Exprs(1, E);
11980 
11981   do {
11982     Expr *OriginalE = Exprs.pop_back_val();
11983     Expr *E = OriginalE->IgnoreParenCasts();
11984 
11985     if (isa<BinaryOperator>(E)) {
11986       E->EvaluateForOverflow(Context);
11987       continue;
11988     }
11989 
11990     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
11991       Exprs.append(InitList->inits().begin(), InitList->inits().end());
11992     else if (isa<ObjCBoxedExpr>(OriginalE))
11993       E->EvaluateForOverflow(Context);
11994     else if (auto Call = dyn_cast<CallExpr>(E))
11995       Exprs.append(Call->arg_begin(), Call->arg_end());
11996     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
11997       Exprs.append(Message->arg_begin(), Message->arg_end());
11998   } while (!Exprs.empty());
11999 }
12000 
12001 namespace {
12002 
12003 /// Visitor for expressions which looks for unsequenced operations on the
12004 /// same object.
12005 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
12006   using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
12007 
12008   /// A tree of sequenced regions within an expression. Two regions are
12009   /// unsequenced if one is an ancestor or a descendent of the other. When we
12010   /// finish processing an expression with sequencing, such as a comma
12011   /// expression, we fold its tree nodes into its parent, since they are
12012   /// unsequenced with respect to nodes we will visit later.
12013   class SequenceTree {
12014     struct Value {
12015       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
12016       unsigned Parent : 31;
12017       unsigned Merged : 1;
12018     };
12019     SmallVector<Value, 8> Values;
12020 
12021   public:
12022     /// A region within an expression which may be sequenced with respect
12023     /// to some other region.
12024     class Seq {
12025       friend class SequenceTree;
12026 
12027       unsigned Index;
12028 
12029       explicit Seq(unsigned N) : Index(N) {}
12030 
12031     public:
12032       Seq() : Index(0) {}
12033     };
12034 
12035     SequenceTree() { Values.push_back(Value(0)); }
12036     Seq root() const { return Seq(0); }
12037 
12038     /// Create a new sequence of operations, which is an unsequenced
12039     /// subset of \p Parent. This sequence of operations is sequenced with
12040     /// respect to other children of \p Parent.
12041     Seq allocate(Seq Parent) {
12042       Values.push_back(Value(Parent.Index));
12043       return Seq(Values.size() - 1);
12044     }
12045 
12046     /// Merge a sequence of operations into its parent.
12047     void merge(Seq S) {
12048       Values[S.Index].Merged = true;
12049     }
12050 
12051     /// Determine whether two operations are unsequenced. This operation
12052     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
12053     /// should have been merged into its parent as appropriate.
12054     bool isUnsequenced(Seq Cur, Seq Old) {
12055       unsigned C = representative(Cur.Index);
12056       unsigned Target = representative(Old.Index);
12057       while (C >= Target) {
12058         if (C == Target)
12059           return true;
12060         C = Values[C].Parent;
12061       }
12062       return false;
12063     }
12064 
12065   private:
12066     /// Pick a representative for a sequence.
12067     unsigned representative(unsigned K) {
12068       if (Values[K].Merged)
12069         // Perform path compression as we go.
12070         return Values[K].Parent = representative(Values[K].Parent);
12071       return K;
12072     }
12073   };
12074 
12075   /// An object for which we can track unsequenced uses.
12076   using Object = const NamedDecl *;
12077 
12078   /// Different flavors of object usage which we track. We only track the
12079   /// least-sequenced usage of each kind.
12080   enum UsageKind {
12081     /// A read of an object. Multiple unsequenced reads are OK.
12082     UK_Use,
12083 
12084     /// A modification of an object which is sequenced before the value
12085     /// computation of the expression, such as ++n in C++.
12086     UK_ModAsValue,
12087 
12088     /// A modification of an object which is not sequenced before the value
12089     /// computation of the expression, such as n++.
12090     UK_ModAsSideEffect,
12091 
12092     UK_Count = UK_ModAsSideEffect + 1
12093   };
12094 
12095   /// Bundle together a sequencing region and the expression corresponding
12096   /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
12097   struct Usage {
12098     const Expr *UsageExpr;
12099     SequenceTree::Seq Seq;
12100 
12101     Usage() : UsageExpr(nullptr), Seq() {}
12102   };
12103 
12104   struct UsageInfo {
12105     Usage Uses[UK_Count];
12106 
12107     /// Have we issued a diagnostic for this object already?
12108     bool Diagnosed;
12109 
12110     UsageInfo() : Uses(), Diagnosed(false) {}
12111   };
12112   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
12113 
12114   Sema &SemaRef;
12115 
12116   /// Sequenced regions within the expression.
12117   SequenceTree Tree;
12118 
12119   /// Declaration modifications and references which we have seen.
12120   UsageInfoMap UsageMap;
12121 
12122   /// The region we are currently within.
12123   SequenceTree::Seq Region;
12124 
12125   /// Filled in with declarations which were modified as a side-effect
12126   /// (that is, post-increment operations).
12127   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
12128 
12129   /// Expressions to check later. We defer checking these to reduce
12130   /// stack usage.
12131   SmallVectorImpl<const Expr *> &WorkList;
12132 
12133   /// RAII object wrapping the visitation of a sequenced subexpression of an
12134   /// expression. At the end of this process, the side-effects of the evaluation
12135   /// become sequenced with respect to the value computation of the result, so
12136   /// we downgrade any UK_ModAsSideEffect within the evaluation to
12137   /// UK_ModAsValue.
12138   struct SequencedSubexpression {
12139     SequencedSubexpression(SequenceChecker &Self)
12140       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
12141       Self.ModAsSideEffect = &ModAsSideEffect;
12142     }
12143 
12144     ~SequencedSubexpression() {
12145       for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
12146         // Add a new usage with usage kind UK_ModAsValue, and then restore
12147         // the previous usage with UK_ModAsSideEffect (thus clearing it if
12148         // the previous one was empty).
12149         UsageInfo &UI = Self.UsageMap[M.first];
12150         auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
12151         Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
12152         SideEffectUsage = M.second;
12153       }
12154       Self.ModAsSideEffect = OldModAsSideEffect;
12155     }
12156 
12157     SequenceChecker &Self;
12158     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
12159     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
12160   };
12161 
12162   /// RAII object wrapping the visitation of a subexpression which we might
12163   /// choose to evaluate as a constant. If any subexpression is evaluated and
12164   /// found to be non-constant, this allows us to suppress the evaluation of
12165   /// the outer expression.
12166   class EvaluationTracker {
12167   public:
12168     EvaluationTracker(SequenceChecker &Self)
12169         : Self(Self), Prev(Self.EvalTracker) {
12170       Self.EvalTracker = this;
12171     }
12172 
12173     ~EvaluationTracker() {
12174       Self.EvalTracker = Prev;
12175       if (Prev)
12176         Prev->EvalOK &= EvalOK;
12177     }
12178 
12179     bool evaluate(const Expr *E, bool &Result) {
12180       if (!EvalOK || E->isValueDependent())
12181         return false;
12182       EvalOK = E->EvaluateAsBooleanCondition(
12183           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
12184       return EvalOK;
12185     }
12186 
12187   private:
12188     SequenceChecker &Self;
12189     EvaluationTracker *Prev;
12190     bool EvalOK = true;
12191   } *EvalTracker = nullptr;
12192 
12193   /// Find the object which is produced by the specified expression,
12194   /// if any.
12195   Object getObject(const Expr *E, bool Mod) const {
12196     E = E->IgnoreParenCasts();
12197     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
12198       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
12199         return getObject(UO->getSubExpr(), Mod);
12200     } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12201       if (BO->getOpcode() == BO_Comma)
12202         return getObject(BO->getRHS(), Mod);
12203       if (Mod && BO->isAssignmentOp())
12204         return getObject(BO->getLHS(), Mod);
12205     } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
12206       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
12207       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
12208         return ME->getMemberDecl();
12209     } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12210       // FIXME: If this is a reference, map through to its value.
12211       return DRE->getDecl();
12212     return nullptr;
12213   }
12214 
12215   /// Note that an object \p O was modified or used by an expression
12216   /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
12217   /// the object \p O as obtained via the \p UsageMap.
12218   void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
12219     // Get the old usage for the given object and usage kind.
12220     Usage &U = UI.Uses[UK];
12221     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
12222       // If we have a modification as side effect and are in a sequenced
12223       // subexpression, save the old Usage so that we can restore it later
12224       // in SequencedSubexpression::~SequencedSubexpression.
12225       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
12226         ModAsSideEffect->push_back(std::make_pair(O, U));
12227       // Then record the new usage with the current sequencing region.
12228       U.UsageExpr = UsageExpr;
12229       U.Seq = Region;
12230     }
12231   }
12232 
12233   /// Check whether a modification or use of an object \p O in an expression
12234   /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
12235   /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
12236   /// \p IsModMod is true when we are checking for a mod-mod unsequenced
12237   /// usage and false we are checking for a mod-use unsequenced usage.
12238   void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
12239                   UsageKind OtherKind, bool IsModMod) {
12240     if (UI.Diagnosed)
12241       return;
12242 
12243     const Usage &U = UI.Uses[OtherKind];
12244     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
12245       return;
12246 
12247     const Expr *Mod = U.UsageExpr;
12248     const Expr *ModOrUse = UsageExpr;
12249     if (OtherKind == UK_Use)
12250       std::swap(Mod, ModOrUse);
12251 
12252     SemaRef.DiagRuntimeBehavior(
12253         Mod->getExprLoc(), {Mod, ModOrUse},
12254         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
12255                                : diag::warn_unsequenced_mod_use)
12256             << O << SourceRange(ModOrUse->getExprLoc()));
12257     UI.Diagnosed = true;
12258   }
12259 
12260   // A note on note{Pre, Post}{Use, Mod}:
12261   //
12262   // (It helps to follow the algorithm with an expression such as
12263   //  "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
12264   //  operations before C++17 and both are well-defined in C++17).
12265   //
12266   // When visiting a node which uses/modify an object we first call notePreUse
12267   // or notePreMod before visiting its sub-expression(s). At this point the
12268   // children of the current node have not yet been visited and so the eventual
12269   // uses/modifications resulting from the children of the current node have not
12270   // been recorded yet.
12271   //
12272   // We then visit the children of the current node. After that notePostUse or
12273   // notePostMod is called. These will 1) detect an unsequenced modification
12274   // as side effect (as in "k++ + k") and 2) add a new usage with the
12275   // appropriate usage kind.
12276   //
12277   // We also have to be careful that some operation sequences modification as
12278   // side effect as well (for example: || or ,). To account for this we wrap
12279   // the visitation of such a sub-expression (for example: the LHS of || or ,)
12280   // with SequencedSubexpression. SequencedSubexpression is an RAII object
12281   // which record usages which are modifications as side effect, and then
12282   // downgrade them (or more accurately restore the previous usage which was a
12283   // modification as side effect) when exiting the scope of the sequenced
12284   // subexpression.
12285 
12286   void notePreUse(Object O, const Expr *UseExpr) {
12287     UsageInfo &UI = UsageMap[O];
12288     // Uses conflict with other modifications.
12289     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
12290   }
12291 
12292   void notePostUse(Object O, const Expr *UseExpr) {
12293     UsageInfo &UI = UsageMap[O];
12294     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
12295                /*IsModMod=*/false);
12296     addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
12297   }
12298 
12299   void notePreMod(Object O, const Expr *ModExpr) {
12300     UsageInfo &UI = UsageMap[O];
12301     // Modifications conflict with other modifications and with uses.
12302     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
12303     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
12304   }
12305 
12306   void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
12307     UsageInfo &UI = UsageMap[O];
12308     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
12309                /*IsModMod=*/true);
12310     addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
12311   }
12312 
12313 public:
12314   SequenceChecker(Sema &S, const Expr *E,
12315                   SmallVectorImpl<const Expr *> &WorkList)
12316       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
12317     Visit(E);
12318     // Silence a -Wunused-private-field since WorkList is now unused.
12319     // TODO: Evaluate if it can be used, and if not remove it.
12320     (void)this->WorkList;
12321   }
12322 
12323   void VisitStmt(const Stmt *S) {
12324     // Skip all statements which aren't expressions for now.
12325   }
12326 
12327   void VisitExpr(const Expr *E) {
12328     // By default, just recurse to evaluated subexpressions.
12329     Base::VisitStmt(E);
12330   }
12331 
12332   void VisitCastExpr(const CastExpr *E) {
12333     Object O = Object();
12334     if (E->getCastKind() == CK_LValueToRValue)
12335       O = getObject(E->getSubExpr(), false);
12336 
12337     if (O)
12338       notePreUse(O, E);
12339     VisitExpr(E);
12340     if (O)
12341       notePostUse(O, E);
12342   }
12343 
12344   void VisitSequencedExpressions(const Expr *SequencedBefore,
12345                                  const Expr *SequencedAfter) {
12346     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
12347     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
12348     SequenceTree::Seq OldRegion = Region;
12349 
12350     {
12351       SequencedSubexpression SeqBefore(*this);
12352       Region = BeforeRegion;
12353       Visit(SequencedBefore);
12354     }
12355 
12356     Region = AfterRegion;
12357     Visit(SequencedAfter);
12358 
12359     Region = OldRegion;
12360 
12361     Tree.merge(BeforeRegion);
12362     Tree.merge(AfterRegion);
12363   }
12364 
12365   void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
12366     // C++17 [expr.sub]p1:
12367     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
12368     //   expression E1 is sequenced before the expression E2.
12369     if (SemaRef.getLangOpts().CPlusPlus17)
12370       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
12371     else {
12372       Visit(ASE->getLHS());
12373       Visit(ASE->getRHS());
12374     }
12375   }
12376 
12377   void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
12378   void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
12379   void VisitBinPtrMem(const BinaryOperator *BO) {
12380     // C++17 [expr.mptr.oper]p4:
12381     //  Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
12382     //  the expression E1 is sequenced before the expression E2.
12383     if (SemaRef.getLangOpts().CPlusPlus17)
12384       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12385     else {
12386       Visit(BO->getLHS());
12387       Visit(BO->getRHS());
12388     }
12389   }
12390 
12391   void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
12392   void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
12393   void VisitBinShlShr(const BinaryOperator *BO) {
12394     // C++17 [expr.shift]p4:
12395     //  The expression E1 is sequenced before the expression E2.
12396     if (SemaRef.getLangOpts().CPlusPlus17)
12397       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12398     else {
12399       Visit(BO->getLHS());
12400       Visit(BO->getRHS());
12401     }
12402   }
12403 
12404   void VisitBinComma(const BinaryOperator *BO) {
12405     // C++11 [expr.comma]p1:
12406     //   Every value computation and side effect associated with the left
12407     //   expression is sequenced before every value computation and side
12408     //   effect associated with the right expression.
12409     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12410   }
12411 
12412   void VisitBinAssign(const BinaryOperator *BO) {
12413     SequenceTree::Seq RHSRegion;
12414     SequenceTree::Seq LHSRegion;
12415     if (SemaRef.getLangOpts().CPlusPlus17) {
12416       RHSRegion = Tree.allocate(Region);
12417       LHSRegion = Tree.allocate(Region);
12418     } else {
12419       RHSRegion = Region;
12420       LHSRegion = Region;
12421     }
12422     SequenceTree::Seq OldRegion = Region;
12423 
12424     // C++11 [expr.ass]p1:
12425     //  [...] the assignment is sequenced after the value computation
12426     //  of the right and left operands, [...]
12427     //
12428     // so check it before inspecting the operands and update the
12429     // map afterwards.
12430     Object O = getObject(BO->getLHS(), /*Mod=*/true);
12431     if (O)
12432       notePreMod(O, BO);
12433 
12434     if (SemaRef.getLangOpts().CPlusPlus17) {
12435       // C++17 [expr.ass]p1:
12436       //  [...] The right operand is sequenced before the left operand. [...]
12437       {
12438         SequencedSubexpression SeqBefore(*this);
12439         Region = RHSRegion;
12440         Visit(BO->getRHS());
12441       }
12442 
12443       Region = LHSRegion;
12444       Visit(BO->getLHS());
12445 
12446       if (O && isa<CompoundAssignOperator>(BO))
12447         notePostUse(O, BO);
12448 
12449     } else {
12450       // C++11 does not specify any sequencing between the LHS and RHS.
12451       Region = LHSRegion;
12452       Visit(BO->getLHS());
12453 
12454       if (O && isa<CompoundAssignOperator>(BO))
12455         notePostUse(O, BO);
12456 
12457       Region = RHSRegion;
12458       Visit(BO->getRHS());
12459     }
12460 
12461     // C++11 [expr.ass]p1:
12462     //  the assignment is sequenced [...] before the value computation of the
12463     //  assignment expression.
12464     // C11 6.5.16/3 has no such rule.
12465     Region = OldRegion;
12466     if (O)
12467       notePostMod(O, BO,
12468                   SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12469                                                   : UK_ModAsSideEffect);
12470     if (SemaRef.getLangOpts().CPlusPlus17) {
12471       Tree.merge(RHSRegion);
12472       Tree.merge(LHSRegion);
12473     }
12474   }
12475 
12476   void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
12477     VisitBinAssign(CAO);
12478   }
12479 
12480   void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12481   void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12482   void VisitUnaryPreIncDec(const UnaryOperator *UO) {
12483     Object O = getObject(UO->getSubExpr(), true);
12484     if (!O)
12485       return VisitExpr(UO);
12486 
12487     notePreMod(O, UO);
12488     Visit(UO->getSubExpr());
12489     // C++11 [expr.pre.incr]p1:
12490     //   the expression ++x is equivalent to x+=1
12491     notePostMod(O, UO,
12492                 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12493                                                 : UK_ModAsSideEffect);
12494   }
12495 
12496   void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12497   void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12498   void VisitUnaryPostIncDec(const UnaryOperator *UO) {
12499     Object O = getObject(UO->getSubExpr(), true);
12500     if (!O)
12501       return VisitExpr(UO);
12502 
12503     notePreMod(O, UO);
12504     Visit(UO->getSubExpr());
12505     notePostMod(O, UO, UK_ModAsSideEffect);
12506   }
12507 
12508   void VisitBinLOr(const BinaryOperator *BO) {
12509     // C++11 [expr.log.or]p2:
12510     //  If the second expression is evaluated, every value computation and
12511     //  side effect associated with the first expression is sequenced before
12512     //  every value computation and side effect associated with the
12513     //  second expression.
12514     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
12515     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
12516     SequenceTree::Seq OldRegion = Region;
12517 
12518     EvaluationTracker Eval(*this);
12519     {
12520       SequencedSubexpression Sequenced(*this);
12521       Region = LHSRegion;
12522       Visit(BO->getLHS());
12523     }
12524 
12525     // C++11 [expr.log.or]p1:
12526     //  [...] the second operand is not evaluated if the first operand
12527     //  evaluates to true.
12528     bool EvalResult = false;
12529     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
12530     bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
12531     if (ShouldVisitRHS) {
12532       Region = RHSRegion;
12533       Visit(BO->getRHS());
12534     }
12535 
12536     Region = OldRegion;
12537     Tree.merge(LHSRegion);
12538     Tree.merge(RHSRegion);
12539   }
12540 
12541   void VisitBinLAnd(const BinaryOperator *BO) {
12542     // C++11 [expr.log.and]p2:
12543     //  If the second expression is evaluated, every value computation and
12544     //  side effect associated with the first expression is sequenced before
12545     //  every value computation and side effect associated with the
12546     //  second expression.
12547     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
12548     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
12549     SequenceTree::Seq OldRegion = Region;
12550 
12551     EvaluationTracker Eval(*this);
12552     {
12553       SequencedSubexpression Sequenced(*this);
12554       Region = LHSRegion;
12555       Visit(BO->getLHS());
12556     }
12557 
12558     // C++11 [expr.log.and]p1:
12559     //  [...] the second operand is not evaluated if the first operand is false.
12560     bool EvalResult = false;
12561     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
12562     bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
12563     if (ShouldVisitRHS) {
12564       Region = RHSRegion;
12565       Visit(BO->getRHS());
12566     }
12567 
12568     Region = OldRegion;
12569     Tree.merge(LHSRegion);
12570     Tree.merge(RHSRegion);
12571   }
12572 
12573   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
12574     // C++11 [expr.cond]p1:
12575     //  [...] Every value computation and side effect associated with the first
12576     //  expression is sequenced before every value computation and side effect
12577     //  associated with the second or third expression.
12578     SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
12579 
12580     // No sequencing is specified between the true and false expression.
12581     // However since exactly one of both is going to be evaluated we can
12582     // consider them to be sequenced. This is needed to avoid warning on
12583     // something like "x ? y+= 1 : y += 2;" in the case where we will visit
12584     // both the true and false expressions because we can't evaluate x.
12585     // This will still allow us to detect an expression like (pre C++17)
12586     // "(x ? y += 1 : y += 2) = y".
12587     //
12588     // We don't wrap the visitation of the true and false expression with
12589     // SequencedSubexpression because we don't want to downgrade modifications
12590     // as side effect in the true and false expressions after the visition
12591     // is done. (for example in the expression "(x ? y++ : y++) + y" we should
12592     // not warn between the two "y++", but we should warn between the "y++"
12593     // and the "y".
12594     SequenceTree::Seq TrueRegion = Tree.allocate(Region);
12595     SequenceTree::Seq FalseRegion = Tree.allocate(Region);
12596     SequenceTree::Seq OldRegion = Region;
12597 
12598     EvaluationTracker Eval(*this);
12599     {
12600       SequencedSubexpression Sequenced(*this);
12601       Region = ConditionRegion;
12602       Visit(CO->getCond());
12603     }
12604 
12605     // C++11 [expr.cond]p1:
12606     // [...] The first expression is contextually converted to bool (Clause 4).
12607     // It is evaluated and if it is true, the result of the conditional
12608     // expression is the value of the second expression, otherwise that of the
12609     // third expression. Only one of the second and third expressions is
12610     // evaluated. [...]
12611     bool EvalResult = false;
12612     bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
12613     bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
12614     bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
12615     if (ShouldVisitTrueExpr) {
12616       Region = TrueRegion;
12617       Visit(CO->getTrueExpr());
12618     }
12619     if (ShouldVisitFalseExpr) {
12620       Region = FalseRegion;
12621       Visit(CO->getFalseExpr());
12622     }
12623 
12624     Region = OldRegion;
12625     Tree.merge(ConditionRegion);
12626     Tree.merge(TrueRegion);
12627     Tree.merge(FalseRegion);
12628   }
12629 
12630   void VisitCallExpr(const CallExpr *CE) {
12631     // C++11 [intro.execution]p15:
12632     //   When calling a function [...], every value computation and side effect
12633     //   associated with any argument expression, or with the postfix expression
12634     //   designating the called function, is sequenced before execution of every
12635     //   expression or statement in the body of the function [and thus before
12636     //   the value computation of its result].
12637     SequencedSubexpression Sequenced(*this);
12638     SemaRef.runWithSufficientStackSpace(CE->getExprLoc(),
12639                                         [&] { Base::VisitCallExpr(CE); });
12640 
12641     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
12642   }
12643 
12644   void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
12645     // This is a call, so all subexpressions are sequenced before the result.
12646     SequencedSubexpression Sequenced(*this);
12647 
12648     if (!CCE->isListInitialization())
12649       return VisitExpr(CCE);
12650 
12651     // In C++11, list initializations are sequenced.
12652     SmallVector<SequenceTree::Seq, 32> Elts;
12653     SequenceTree::Seq Parent = Region;
12654     for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
12655                                               E = CCE->arg_end();
12656          I != E; ++I) {
12657       Region = Tree.allocate(Parent);
12658       Elts.push_back(Region);
12659       Visit(*I);
12660     }
12661 
12662     // Forget that the initializers are sequenced.
12663     Region = Parent;
12664     for (unsigned I = 0; I < Elts.size(); ++I)
12665       Tree.merge(Elts[I]);
12666   }
12667 
12668   void VisitInitListExpr(const InitListExpr *ILE) {
12669     if (!SemaRef.getLangOpts().CPlusPlus11)
12670       return VisitExpr(ILE);
12671 
12672     // In C++11, list initializations are sequenced.
12673     SmallVector<SequenceTree::Seq, 32> Elts;
12674     SequenceTree::Seq Parent = Region;
12675     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
12676       const Expr *E = ILE->getInit(I);
12677       if (!E)
12678         continue;
12679       Region = Tree.allocate(Parent);
12680       Elts.push_back(Region);
12681       Visit(E);
12682     }
12683 
12684     // Forget that the initializers are sequenced.
12685     Region = Parent;
12686     for (unsigned I = 0; I < Elts.size(); ++I)
12687       Tree.merge(Elts[I]);
12688   }
12689 };
12690 
12691 } // namespace
12692 
12693 void Sema::CheckUnsequencedOperations(const Expr *E) {
12694   SmallVector<const Expr *, 8> WorkList;
12695   WorkList.push_back(E);
12696   while (!WorkList.empty()) {
12697     const Expr *Item = WorkList.pop_back_val();
12698     SequenceChecker(*this, Item, WorkList);
12699   }
12700 }
12701 
12702 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
12703                               bool IsConstexpr) {
12704   llvm::SaveAndRestore<bool> ConstantContext(
12705       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
12706   CheckImplicitConversions(E, CheckLoc);
12707   if (!E->isInstantiationDependent())
12708     CheckUnsequencedOperations(E);
12709   if (!IsConstexpr && !E->isValueDependent())
12710     CheckForIntOverflow(E);
12711   DiagnoseMisalignedMembers();
12712 }
12713 
12714 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
12715                                        FieldDecl *BitField,
12716                                        Expr *Init) {
12717   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
12718 }
12719 
12720 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
12721                                          SourceLocation Loc) {
12722   if (!PType->isVariablyModifiedType())
12723     return;
12724   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
12725     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
12726     return;
12727   }
12728   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
12729     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
12730     return;
12731   }
12732   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
12733     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
12734     return;
12735   }
12736 
12737   const ArrayType *AT = S.Context.getAsArrayType(PType);
12738   if (!AT)
12739     return;
12740 
12741   if (AT->getSizeModifier() != ArrayType::Star) {
12742     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
12743     return;
12744   }
12745 
12746   S.Diag(Loc, diag::err_array_star_in_function_definition);
12747 }
12748 
12749 /// CheckParmsForFunctionDef - Check that the parameters of the given
12750 /// function are appropriate for the definition of a function. This
12751 /// takes care of any checks that cannot be performed on the
12752 /// declaration itself, e.g., that the types of each of the function
12753 /// parameters are complete.
12754 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
12755                                     bool CheckParameterNames) {
12756   bool HasInvalidParm = false;
12757   for (ParmVarDecl *Param : Parameters) {
12758     // C99 6.7.5.3p4: the parameters in a parameter type list in a
12759     // function declarator that is part of a function definition of
12760     // that function shall not have incomplete type.
12761     //
12762     // This is also C++ [dcl.fct]p6.
12763     if (!Param->isInvalidDecl() &&
12764         RequireCompleteType(Param->getLocation(), Param->getType(),
12765                             diag::err_typecheck_decl_incomplete_type)) {
12766       Param->setInvalidDecl();
12767       HasInvalidParm = true;
12768     }
12769 
12770     // C99 6.9.1p5: If the declarator includes a parameter type list, the
12771     // declaration of each parameter shall include an identifier.
12772     if (CheckParameterNames &&
12773         Param->getIdentifier() == nullptr &&
12774         !Param->isImplicit() &&
12775         !getLangOpts().CPlusPlus)
12776       Diag(Param->getLocation(), diag::err_parameter_name_omitted);
12777 
12778     // C99 6.7.5.3p12:
12779     //   If the function declarator is not part of a definition of that
12780     //   function, parameters may have incomplete type and may use the [*]
12781     //   notation in their sequences of declarator specifiers to specify
12782     //   variable length array types.
12783     QualType PType = Param->getOriginalType();
12784     // FIXME: This diagnostic should point the '[*]' if source-location
12785     // information is added for it.
12786     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
12787 
12788     // If the parameter is a c++ class type and it has to be destructed in the
12789     // callee function, declare the destructor so that it can be called by the
12790     // callee function. Do not perform any direct access check on the dtor here.
12791     if (!Param->isInvalidDecl()) {
12792       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
12793         if (!ClassDecl->isInvalidDecl() &&
12794             !ClassDecl->hasIrrelevantDestructor() &&
12795             !ClassDecl->isDependentContext() &&
12796             ClassDecl->isParamDestroyedInCallee()) {
12797           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
12798           MarkFunctionReferenced(Param->getLocation(), Destructor);
12799           DiagnoseUseOfDecl(Destructor, Param->getLocation());
12800         }
12801       }
12802     }
12803 
12804     // Parameters with the pass_object_size attribute only need to be marked
12805     // constant at function definitions. Because we lack information about
12806     // whether we're on a declaration or definition when we're instantiating the
12807     // attribute, we need to check for constness here.
12808     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
12809       if (!Param->getType().isConstQualified())
12810         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
12811             << Attr->getSpelling() << 1;
12812 
12813     // Check for parameter names shadowing fields from the class.
12814     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
12815       // The owning context for the parameter should be the function, but we
12816       // want to see if this function's declaration context is a record.
12817       DeclContext *DC = Param->getDeclContext();
12818       if (DC && DC->isFunctionOrMethod()) {
12819         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
12820           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
12821                                      RD, /*DeclIsField*/ false);
12822       }
12823     }
12824   }
12825 
12826   return HasInvalidParm;
12827 }
12828 
12829 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr
12830 /// or MemberExpr.
12831 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
12832                               ASTContext &Context) {
12833   if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
12834     return Context.getDeclAlign(DRE->getDecl());
12835 
12836   if (const auto *ME = dyn_cast<MemberExpr>(E))
12837     return Context.getDeclAlign(ME->getMemberDecl());
12838 
12839   return TypeAlign;
12840 }
12841 
12842 /// CheckCastAlign - Implements -Wcast-align, which warns when a
12843 /// pointer cast increases the alignment requirements.
12844 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
12845   // This is actually a lot of work to potentially be doing on every
12846   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
12847   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
12848     return;
12849 
12850   // Ignore dependent types.
12851   if (T->isDependentType() || Op->getType()->isDependentType())
12852     return;
12853 
12854   // Require that the destination be a pointer type.
12855   const PointerType *DestPtr = T->getAs<PointerType>();
12856   if (!DestPtr) return;
12857 
12858   // If the destination has alignment 1, we're done.
12859   QualType DestPointee = DestPtr->getPointeeType();
12860   if (DestPointee->isIncompleteType()) return;
12861   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
12862   if (DestAlign.isOne()) return;
12863 
12864   // Require that the source be a pointer type.
12865   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
12866   if (!SrcPtr) return;
12867   QualType SrcPointee = SrcPtr->getPointeeType();
12868 
12869   // Whitelist casts from cv void*.  We already implicitly
12870   // whitelisted casts to cv void*, since they have alignment 1.
12871   // Also whitelist casts involving incomplete types, which implicitly
12872   // includes 'void'.
12873   if (SrcPointee->isIncompleteType()) return;
12874 
12875   CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
12876 
12877   if (auto *CE = dyn_cast<CastExpr>(Op)) {
12878     if (CE->getCastKind() == CK_ArrayToPointerDecay)
12879       SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
12880   } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
12881     if (UO->getOpcode() == UO_AddrOf)
12882       SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
12883   }
12884 
12885   if (SrcAlign >= DestAlign) return;
12886 
12887   Diag(TRange.getBegin(), diag::warn_cast_align)
12888     << Op->getType() << T
12889     << static_cast<unsigned>(SrcAlign.getQuantity())
12890     << static_cast<unsigned>(DestAlign.getQuantity())
12891     << TRange << Op->getSourceRange();
12892 }
12893 
12894 /// Check whether this array fits the idiom of a size-one tail padded
12895 /// array member of a struct.
12896 ///
12897 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
12898 /// commonly used to emulate flexible arrays in C89 code.
12899 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
12900                                     const NamedDecl *ND) {
12901   if (Size != 1 || !ND) return false;
12902 
12903   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
12904   if (!FD) return false;
12905 
12906   // Don't consider sizes resulting from macro expansions or template argument
12907   // substitution to form C89 tail-padded arrays.
12908 
12909   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
12910   while (TInfo) {
12911     TypeLoc TL = TInfo->getTypeLoc();
12912     // Look through typedefs.
12913     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
12914       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
12915       TInfo = TDL->getTypeSourceInfo();
12916       continue;
12917     }
12918     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
12919       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
12920       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
12921         return false;
12922     }
12923     break;
12924   }
12925 
12926   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
12927   if (!RD) return false;
12928   if (RD->isUnion()) return false;
12929   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
12930     if (!CRD->isStandardLayout()) return false;
12931   }
12932 
12933   // See if this is the last field decl in the record.
12934   const Decl *D = FD;
12935   while ((D = D->getNextDeclInContext()))
12936     if (isa<FieldDecl>(D))
12937       return false;
12938   return true;
12939 }
12940 
12941 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
12942                             const ArraySubscriptExpr *ASE,
12943                             bool AllowOnePastEnd, bool IndexNegated) {
12944   // Already diagnosed by the constant evaluator.
12945   if (isConstantEvaluated())
12946     return;
12947 
12948   IndexExpr = IndexExpr->IgnoreParenImpCasts();
12949   if (IndexExpr->isValueDependent())
12950     return;
12951 
12952   const Type *EffectiveType =
12953       BaseExpr->getType()->getPointeeOrArrayElementType();
12954   BaseExpr = BaseExpr->IgnoreParenCasts();
12955   const ConstantArrayType *ArrayTy =
12956       Context.getAsConstantArrayType(BaseExpr->getType());
12957 
12958   if (!ArrayTy)
12959     return;
12960 
12961   const Type *BaseType = ArrayTy->getElementType().getTypePtr();
12962   if (EffectiveType->isDependentType() || BaseType->isDependentType())
12963     return;
12964 
12965   Expr::EvalResult Result;
12966   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
12967     return;
12968 
12969   llvm::APSInt index = Result.Val.getInt();
12970   if (IndexNegated)
12971     index = -index;
12972 
12973   const NamedDecl *ND = nullptr;
12974   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
12975     ND = DRE->getDecl();
12976   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
12977     ND = ME->getMemberDecl();
12978 
12979   if (index.isUnsigned() || !index.isNegative()) {
12980     // It is possible that the type of the base expression after
12981     // IgnoreParenCasts is incomplete, even though the type of the base
12982     // expression before IgnoreParenCasts is complete (see PR39746 for an
12983     // example). In this case we have no information about whether the array
12984     // access exceeds the array bounds. However we can still diagnose an array
12985     // access which precedes the array bounds.
12986     if (BaseType->isIncompleteType())
12987       return;
12988 
12989     llvm::APInt size = ArrayTy->getSize();
12990     if (!size.isStrictlyPositive())
12991       return;
12992 
12993     if (BaseType != EffectiveType) {
12994       // Make sure we're comparing apples to apples when comparing index to size
12995       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
12996       uint64_t array_typesize = Context.getTypeSize(BaseType);
12997       // Handle ptrarith_typesize being zero, such as when casting to void*
12998       if (!ptrarith_typesize) ptrarith_typesize = 1;
12999       if (ptrarith_typesize != array_typesize) {
13000         // There's a cast to a different size type involved
13001         uint64_t ratio = array_typesize / ptrarith_typesize;
13002         // TODO: Be smarter about handling cases where array_typesize is not a
13003         // multiple of ptrarith_typesize
13004         if (ptrarith_typesize * ratio == array_typesize)
13005           size *= llvm::APInt(size.getBitWidth(), ratio);
13006       }
13007     }
13008 
13009     if (size.getBitWidth() > index.getBitWidth())
13010       index = index.zext(size.getBitWidth());
13011     else if (size.getBitWidth() < index.getBitWidth())
13012       size = size.zext(index.getBitWidth());
13013 
13014     // For array subscripting the index must be less than size, but for pointer
13015     // arithmetic also allow the index (offset) to be equal to size since
13016     // computing the next address after the end of the array is legal and
13017     // commonly done e.g. in C++ iterators and range-based for loops.
13018     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
13019       return;
13020 
13021     // Also don't warn for arrays of size 1 which are members of some
13022     // structure. These are often used to approximate flexible arrays in C89
13023     // code.
13024     if (IsTailPaddedMemberArray(*this, size, ND))
13025       return;
13026 
13027     // Suppress the warning if the subscript expression (as identified by the
13028     // ']' location) and the index expression are both from macro expansions
13029     // within a system header.
13030     if (ASE) {
13031       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
13032           ASE->getRBracketLoc());
13033       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
13034         SourceLocation IndexLoc =
13035             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
13036         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
13037           return;
13038       }
13039     }
13040 
13041     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
13042     if (ASE)
13043       DiagID = diag::warn_array_index_exceeds_bounds;
13044 
13045     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
13046                         PDiag(DiagID) << index.toString(10, true)
13047                                       << size.toString(10, true)
13048                                       << (unsigned)size.getLimitedValue(~0U)
13049                                       << IndexExpr->getSourceRange());
13050   } else {
13051     unsigned DiagID = diag::warn_array_index_precedes_bounds;
13052     if (!ASE) {
13053       DiagID = diag::warn_ptr_arith_precedes_bounds;
13054       if (index.isNegative()) index = -index;
13055     }
13056 
13057     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
13058                         PDiag(DiagID) << index.toString(10, true)
13059                                       << IndexExpr->getSourceRange());
13060   }
13061 
13062   if (!ND) {
13063     // Try harder to find a NamedDecl to point at in the note.
13064     while (const ArraySubscriptExpr *ASE =
13065            dyn_cast<ArraySubscriptExpr>(BaseExpr))
13066       BaseExpr = ASE->getBase()->IgnoreParenCasts();
13067     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
13068       ND = DRE->getDecl();
13069     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
13070       ND = ME->getMemberDecl();
13071   }
13072 
13073   if (ND)
13074     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
13075                         PDiag(diag::note_array_declared_here)
13076                             << ND->getDeclName());
13077 }
13078 
13079 void Sema::CheckArrayAccess(const Expr *expr) {
13080   int AllowOnePastEnd = 0;
13081   while (expr) {
13082     expr = expr->IgnoreParenImpCasts();
13083     switch (expr->getStmtClass()) {
13084       case Stmt::ArraySubscriptExprClass: {
13085         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
13086         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
13087                          AllowOnePastEnd > 0);
13088         expr = ASE->getBase();
13089         break;
13090       }
13091       case Stmt::MemberExprClass: {
13092         expr = cast<MemberExpr>(expr)->getBase();
13093         break;
13094       }
13095       case Stmt::OMPArraySectionExprClass: {
13096         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
13097         if (ASE->getLowerBound())
13098           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
13099                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
13100         return;
13101       }
13102       case Stmt::UnaryOperatorClass: {
13103         // Only unwrap the * and & unary operators
13104         const UnaryOperator *UO = cast<UnaryOperator>(expr);
13105         expr = UO->getSubExpr();
13106         switch (UO->getOpcode()) {
13107           case UO_AddrOf:
13108             AllowOnePastEnd++;
13109             break;
13110           case UO_Deref:
13111             AllowOnePastEnd--;
13112             break;
13113           default:
13114             return;
13115         }
13116         break;
13117       }
13118       case Stmt::ConditionalOperatorClass: {
13119         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
13120         if (const Expr *lhs = cond->getLHS())
13121           CheckArrayAccess(lhs);
13122         if (const Expr *rhs = cond->getRHS())
13123           CheckArrayAccess(rhs);
13124         return;
13125       }
13126       case Stmt::CXXOperatorCallExprClass: {
13127         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
13128         for (const auto *Arg : OCE->arguments())
13129           CheckArrayAccess(Arg);
13130         return;
13131       }
13132       default:
13133         return;
13134     }
13135   }
13136 }
13137 
13138 //===--- CHECK: Objective-C retain cycles ----------------------------------//
13139 
13140 namespace {
13141 
13142 struct RetainCycleOwner {
13143   VarDecl *Variable = nullptr;
13144   SourceRange Range;
13145   SourceLocation Loc;
13146   bool Indirect = false;
13147 
13148   RetainCycleOwner() = default;
13149 
13150   void setLocsFrom(Expr *e) {
13151     Loc = e->getExprLoc();
13152     Range = e->getSourceRange();
13153   }
13154 };
13155 
13156 } // namespace
13157 
13158 /// Consider whether capturing the given variable can possibly lead to
13159 /// a retain cycle.
13160 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
13161   // In ARC, it's captured strongly iff the variable has __strong
13162   // lifetime.  In MRR, it's captured strongly if the variable is
13163   // __block and has an appropriate type.
13164   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
13165     return false;
13166 
13167   owner.Variable = var;
13168   if (ref)
13169     owner.setLocsFrom(ref);
13170   return true;
13171 }
13172 
13173 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
13174   while (true) {
13175     e = e->IgnoreParens();
13176     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
13177       switch (cast->getCastKind()) {
13178       case CK_BitCast:
13179       case CK_LValueBitCast:
13180       case CK_LValueToRValue:
13181       case CK_ARCReclaimReturnedObject:
13182         e = cast->getSubExpr();
13183         continue;
13184 
13185       default:
13186         return false;
13187       }
13188     }
13189 
13190     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
13191       ObjCIvarDecl *ivar = ref->getDecl();
13192       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
13193         return false;
13194 
13195       // Try to find a retain cycle in the base.
13196       if (!findRetainCycleOwner(S, ref->getBase(), owner))
13197         return false;
13198 
13199       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
13200       owner.Indirect = true;
13201       return true;
13202     }
13203 
13204     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
13205       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
13206       if (!var) return false;
13207       return considerVariable(var, ref, owner);
13208     }
13209 
13210     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
13211       if (member->isArrow()) return false;
13212 
13213       // Don't count this as an indirect ownership.
13214       e = member->getBase();
13215       continue;
13216     }
13217 
13218     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
13219       // Only pay attention to pseudo-objects on property references.
13220       ObjCPropertyRefExpr *pre
13221         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
13222                                               ->IgnoreParens());
13223       if (!pre) return false;
13224       if (pre->isImplicitProperty()) return false;
13225       ObjCPropertyDecl *property = pre->getExplicitProperty();
13226       if (!property->isRetaining() &&
13227           !(property->getPropertyIvarDecl() &&
13228             property->getPropertyIvarDecl()->getType()
13229               .getObjCLifetime() == Qualifiers::OCL_Strong))
13230           return false;
13231 
13232       owner.Indirect = true;
13233       if (pre->isSuperReceiver()) {
13234         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
13235         if (!owner.Variable)
13236           return false;
13237         owner.Loc = pre->getLocation();
13238         owner.Range = pre->getSourceRange();
13239         return true;
13240       }
13241       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
13242                               ->getSourceExpr());
13243       continue;
13244     }
13245 
13246     // Array ivars?
13247 
13248     return false;
13249   }
13250 }
13251 
13252 namespace {
13253 
13254   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
13255     ASTContext &Context;
13256     VarDecl *Variable;
13257     Expr *Capturer = nullptr;
13258     bool VarWillBeReased = false;
13259 
13260     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
13261         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
13262           Context(Context), Variable(variable) {}
13263 
13264     void VisitDeclRefExpr(DeclRefExpr *ref) {
13265       if (ref->getDecl() == Variable && !Capturer)
13266         Capturer = ref;
13267     }
13268 
13269     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
13270       if (Capturer) return;
13271       Visit(ref->getBase());
13272       if (Capturer && ref->isFreeIvar())
13273         Capturer = ref;
13274     }
13275 
13276     void VisitBlockExpr(BlockExpr *block) {
13277       // Look inside nested blocks
13278       if (block->getBlockDecl()->capturesVariable(Variable))
13279         Visit(block->getBlockDecl()->getBody());
13280     }
13281 
13282     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
13283       if (Capturer) return;
13284       if (OVE->getSourceExpr())
13285         Visit(OVE->getSourceExpr());
13286     }
13287 
13288     void VisitBinaryOperator(BinaryOperator *BinOp) {
13289       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
13290         return;
13291       Expr *LHS = BinOp->getLHS();
13292       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
13293         if (DRE->getDecl() != Variable)
13294           return;
13295         if (Expr *RHS = BinOp->getRHS()) {
13296           RHS = RHS->IgnoreParenCasts();
13297           llvm::APSInt Value;
13298           VarWillBeReased =
13299             (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
13300         }
13301       }
13302     }
13303   };
13304 
13305 } // namespace
13306 
13307 /// Check whether the given argument is a block which captures a
13308 /// variable.
13309 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
13310   assert(owner.Variable && owner.Loc.isValid());
13311 
13312   e = e->IgnoreParenCasts();
13313 
13314   // Look through [^{...} copy] and Block_copy(^{...}).
13315   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
13316     Selector Cmd = ME->getSelector();
13317     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
13318       e = ME->getInstanceReceiver();
13319       if (!e)
13320         return nullptr;
13321       e = e->IgnoreParenCasts();
13322     }
13323   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
13324     if (CE->getNumArgs() == 1) {
13325       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
13326       if (Fn) {
13327         const IdentifierInfo *FnI = Fn->getIdentifier();
13328         if (FnI && FnI->isStr("_Block_copy")) {
13329           e = CE->getArg(0)->IgnoreParenCasts();
13330         }
13331       }
13332     }
13333   }
13334 
13335   BlockExpr *block = dyn_cast<BlockExpr>(e);
13336   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
13337     return nullptr;
13338 
13339   FindCaptureVisitor visitor(S.Context, owner.Variable);
13340   visitor.Visit(block->getBlockDecl()->getBody());
13341   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
13342 }
13343 
13344 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
13345                                 RetainCycleOwner &owner) {
13346   assert(capturer);
13347   assert(owner.Variable && owner.Loc.isValid());
13348 
13349   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
13350     << owner.Variable << capturer->getSourceRange();
13351   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
13352     << owner.Indirect << owner.Range;
13353 }
13354 
13355 /// Check for a keyword selector that starts with the word 'add' or
13356 /// 'set'.
13357 static bool isSetterLikeSelector(Selector sel) {
13358   if (sel.isUnarySelector()) return false;
13359 
13360   StringRef str = sel.getNameForSlot(0);
13361   while (!str.empty() && str.front() == '_') str = str.substr(1);
13362   if (str.startswith("set"))
13363     str = str.substr(3);
13364   else if (str.startswith("add")) {
13365     // Specially whitelist 'addOperationWithBlock:'.
13366     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
13367       return false;
13368     str = str.substr(3);
13369   }
13370   else
13371     return false;
13372 
13373   if (str.empty()) return true;
13374   return !isLowercase(str.front());
13375 }
13376 
13377 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
13378                                                     ObjCMessageExpr *Message) {
13379   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
13380                                                 Message->getReceiverInterface(),
13381                                                 NSAPI::ClassId_NSMutableArray);
13382   if (!IsMutableArray) {
13383     return None;
13384   }
13385 
13386   Selector Sel = Message->getSelector();
13387 
13388   Optional<NSAPI::NSArrayMethodKind> MKOpt =
13389     S.NSAPIObj->getNSArrayMethodKind(Sel);
13390   if (!MKOpt) {
13391     return None;
13392   }
13393 
13394   NSAPI::NSArrayMethodKind MK = *MKOpt;
13395 
13396   switch (MK) {
13397     case NSAPI::NSMutableArr_addObject:
13398     case NSAPI::NSMutableArr_insertObjectAtIndex:
13399     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
13400       return 0;
13401     case NSAPI::NSMutableArr_replaceObjectAtIndex:
13402       return 1;
13403 
13404     default:
13405       return None;
13406   }
13407 
13408   return None;
13409 }
13410 
13411 static
13412 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
13413                                                   ObjCMessageExpr *Message) {
13414   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
13415                                             Message->getReceiverInterface(),
13416                                             NSAPI::ClassId_NSMutableDictionary);
13417   if (!IsMutableDictionary) {
13418     return None;
13419   }
13420 
13421   Selector Sel = Message->getSelector();
13422 
13423   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
13424     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
13425   if (!MKOpt) {
13426     return None;
13427   }
13428 
13429   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
13430 
13431   switch (MK) {
13432     case NSAPI::NSMutableDict_setObjectForKey:
13433     case NSAPI::NSMutableDict_setValueForKey:
13434     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
13435       return 0;
13436 
13437     default:
13438       return None;
13439   }
13440 
13441   return None;
13442 }
13443 
13444 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
13445   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
13446                                                 Message->getReceiverInterface(),
13447                                                 NSAPI::ClassId_NSMutableSet);
13448 
13449   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
13450                                             Message->getReceiverInterface(),
13451                                             NSAPI::ClassId_NSMutableOrderedSet);
13452   if (!IsMutableSet && !IsMutableOrderedSet) {
13453     return None;
13454   }
13455 
13456   Selector Sel = Message->getSelector();
13457 
13458   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
13459   if (!MKOpt) {
13460     return None;
13461   }
13462 
13463   NSAPI::NSSetMethodKind MK = *MKOpt;
13464 
13465   switch (MK) {
13466     case NSAPI::NSMutableSet_addObject:
13467     case NSAPI::NSOrderedSet_setObjectAtIndex:
13468     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
13469     case NSAPI::NSOrderedSet_insertObjectAtIndex:
13470       return 0;
13471     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
13472       return 1;
13473   }
13474 
13475   return None;
13476 }
13477 
13478 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
13479   if (!Message->isInstanceMessage()) {
13480     return;
13481   }
13482 
13483   Optional<int> ArgOpt;
13484 
13485   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
13486       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
13487       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
13488     return;
13489   }
13490 
13491   int ArgIndex = *ArgOpt;
13492 
13493   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
13494   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
13495     Arg = OE->getSourceExpr()->IgnoreImpCasts();
13496   }
13497 
13498   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
13499     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
13500       if (ArgRE->isObjCSelfExpr()) {
13501         Diag(Message->getSourceRange().getBegin(),
13502              diag::warn_objc_circular_container)
13503           << ArgRE->getDecl() << StringRef("'super'");
13504       }
13505     }
13506   } else {
13507     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
13508 
13509     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
13510       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
13511     }
13512 
13513     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
13514       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
13515         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
13516           ValueDecl *Decl = ReceiverRE->getDecl();
13517           Diag(Message->getSourceRange().getBegin(),
13518                diag::warn_objc_circular_container)
13519             << Decl << Decl;
13520           if (!ArgRE->isObjCSelfExpr()) {
13521             Diag(Decl->getLocation(),
13522                  diag::note_objc_circular_container_declared_here)
13523               << Decl;
13524           }
13525         }
13526       }
13527     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
13528       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
13529         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
13530           ObjCIvarDecl *Decl = IvarRE->getDecl();
13531           Diag(Message->getSourceRange().getBegin(),
13532                diag::warn_objc_circular_container)
13533             << Decl << Decl;
13534           Diag(Decl->getLocation(),
13535                diag::note_objc_circular_container_declared_here)
13536             << Decl;
13537         }
13538       }
13539     }
13540   }
13541 }
13542 
13543 /// Check a message send to see if it's likely to cause a retain cycle.
13544 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
13545   // Only check instance methods whose selector looks like a setter.
13546   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
13547     return;
13548 
13549   // Try to find a variable that the receiver is strongly owned by.
13550   RetainCycleOwner owner;
13551   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
13552     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
13553       return;
13554   } else {
13555     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
13556     owner.Variable = getCurMethodDecl()->getSelfDecl();
13557     owner.Loc = msg->getSuperLoc();
13558     owner.Range = msg->getSuperLoc();
13559   }
13560 
13561   // Check whether the receiver is captured by any of the arguments.
13562   const ObjCMethodDecl *MD = msg->getMethodDecl();
13563   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
13564     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
13565       // noescape blocks should not be retained by the method.
13566       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
13567         continue;
13568       return diagnoseRetainCycle(*this, capturer, owner);
13569     }
13570   }
13571 }
13572 
13573 /// Check a property assign to see if it's likely to cause a retain cycle.
13574 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
13575   RetainCycleOwner owner;
13576   if (!findRetainCycleOwner(*this, receiver, owner))
13577     return;
13578 
13579   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
13580     diagnoseRetainCycle(*this, capturer, owner);
13581 }
13582 
13583 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
13584   RetainCycleOwner Owner;
13585   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
13586     return;
13587 
13588   // Because we don't have an expression for the variable, we have to set the
13589   // location explicitly here.
13590   Owner.Loc = Var->getLocation();
13591   Owner.Range = Var->getSourceRange();
13592 
13593   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
13594     diagnoseRetainCycle(*this, Capturer, Owner);
13595 }
13596 
13597 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
13598                                      Expr *RHS, bool isProperty) {
13599   // Check if RHS is an Objective-C object literal, which also can get
13600   // immediately zapped in a weak reference.  Note that we explicitly
13601   // allow ObjCStringLiterals, since those are designed to never really die.
13602   RHS = RHS->IgnoreParenImpCasts();
13603 
13604   // This enum needs to match with the 'select' in
13605   // warn_objc_arc_literal_assign (off-by-1).
13606   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
13607   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
13608     return false;
13609 
13610   S.Diag(Loc, diag::warn_arc_literal_assign)
13611     << (unsigned) Kind
13612     << (isProperty ? 0 : 1)
13613     << RHS->getSourceRange();
13614 
13615   return true;
13616 }
13617 
13618 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
13619                                     Qualifiers::ObjCLifetime LT,
13620                                     Expr *RHS, bool isProperty) {
13621   // Strip off any implicit cast added to get to the one ARC-specific.
13622   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
13623     if (cast->getCastKind() == CK_ARCConsumeObject) {
13624       S.Diag(Loc, diag::warn_arc_retained_assign)
13625         << (LT == Qualifiers::OCL_ExplicitNone)
13626         << (isProperty ? 0 : 1)
13627         << RHS->getSourceRange();
13628       return true;
13629     }
13630     RHS = cast->getSubExpr();
13631   }
13632 
13633   if (LT == Qualifiers::OCL_Weak &&
13634       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
13635     return true;
13636 
13637   return false;
13638 }
13639 
13640 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
13641                               QualType LHS, Expr *RHS) {
13642   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
13643 
13644   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
13645     return false;
13646 
13647   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
13648     return true;
13649 
13650   return false;
13651 }
13652 
13653 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
13654                               Expr *LHS, Expr *RHS) {
13655   QualType LHSType;
13656   // PropertyRef on LHS type need be directly obtained from
13657   // its declaration as it has a PseudoType.
13658   ObjCPropertyRefExpr *PRE
13659     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
13660   if (PRE && !PRE->isImplicitProperty()) {
13661     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
13662     if (PD)
13663       LHSType = PD->getType();
13664   }
13665 
13666   if (LHSType.isNull())
13667     LHSType = LHS->getType();
13668 
13669   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
13670 
13671   if (LT == Qualifiers::OCL_Weak) {
13672     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
13673       getCurFunction()->markSafeWeakUse(LHS);
13674   }
13675 
13676   if (checkUnsafeAssigns(Loc, LHSType, RHS))
13677     return;
13678 
13679   // FIXME. Check for other life times.
13680   if (LT != Qualifiers::OCL_None)
13681     return;
13682 
13683   if (PRE) {
13684     if (PRE->isImplicitProperty())
13685       return;
13686     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
13687     if (!PD)
13688       return;
13689 
13690     unsigned Attributes = PD->getPropertyAttributes();
13691     if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
13692       // when 'assign' attribute was not explicitly specified
13693       // by user, ignore it and rely on property type itself
13694       // for lifetime info.
13695       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
13696       if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
13697           LHSType->isObjCRetainableType())
13698         return;
13699 
13700       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
13701         if (cast->getCastKind() == CK_ARCConsumeObject) {
13702           Diag(Loc, diag::warn_arc_retained_property_assign)
13703           << RHS->getSourceRange();
13704           return;
13705         }
13706         RHS = cast->getSubExpr();
13707       }
13708     }
13709     else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
13710       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
13711         return;
13712     }
13713   }
13714 }
13715 
13716 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
13717 
13718 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
13719                                         SourceLocation StmtLoc,
13720                                         const NullStmt *Body) {
13721   // Do not warn if the body is a macro that expands to nothing, e.g:
13722   //
13723   // #define CALL(x)
13724   // if (condition)
13725   //   CALL(0);
13726   if (Body->hasLeadingEmptyMacro())
13727     return false;
13728 
13729   // Get line numbers of statement and body.
13730   bool StmtLineInvalid;
13731   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
13732                                                       &StmtLineInvalid);
13733   if (StmtLineInvalid)
13734     return false;
13735 
13736   bool BodyLineInvalid;
13737   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
13738                                                       &BodyLineInvalid);
13739   if (BodyLineInvalid)
13740     return false;
13741 
13742   // Warn if null statement and body are on the same line.
13743   if (StmtLine != BodyLine)
13744     return false;
13745 
13746   return true;
13747 }
13748 
13749 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
13750                                  const Stmt *Body,
13751                                  unsigned DiagID) {
13752   // Since this is a syntactic check, don't emit diagnostic for template
13753   // instantiations, this just adds noise.
13754   if (CurrentInstantiationScope)
13755     return;
13756 
13757   // The body should be a null statement.
13758   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
13759   if (!NBody)
13760     return;
13761 
13762   // Do the usual checks.
13763   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
13764     return;
13765 
13766   Diag(NBody->getSemiLoc(), DiagID);
13767   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
13768 }
13769 
13770 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
13771                                  const Stmt *PossibleBody) {
13772   assert(!CurrentInstantiationScope); // Ensured by caller
13773 
13774   SourceLocation StmtLoc;
13775   const Stmt *Body;
13776   unsigned DiagID;
13777   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
13778     StmtLoc = FS->getRParenLoc();
13779     Body = FS->getBody();
13780     DiagID = diag::warn_empty_for_body;
13781   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
13782     StmtLoc = WS->getCond()->getSourceRange().getEnd();
13783     Body = WS->getBody();
13784     DiagID = diag::warn_empty_while_body;
13785   } else
13786     return; // Neither `for' nor `while'.
13787 
13788   // The body should be a null statement.
13789   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
13790   if (!NBody)
13791     return;
13792 
13793   // Skip expensive checks if diagnostic is disabled.
13794   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
13795     return;
13796 
13797   // Do the usual checks.
13798   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
13799     return;
13800 
13801   // `for(...);' and `while(...);' are popular idioms, so in order to keep
13802   // noise level low, emit diagnostics only if for/while is followed by a
13803   // CompoundStmt, e.g.:
13804   //    for (int i = 0; i < n; i++);
13805   //    {
13806   //      a(i);
13807   //    }
13808   // or if for/while is followed by a statement with more indentation
13809   // than for/while itself:
13810   //    for (int i = 0; i < n; i++);
13811   //      a(i);
13812   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
13813   if (!ProbableTypo) {
13814     bool BodyColInvalid;
13815     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
13816         PossibleBody->getBeginLoc(), &BodyColInvalid);
13817     if (BodyColInvalid)
13818       return;
13819 
13820     bool StmtColInvalid;
13821     unsigned StmtCol =
13822         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
13823     if (StmtColInvalid)
13824       return;
13825 
13826     if (BodyCol > StmtCol)
13827       ProbableTypo = true;
13828   }
13829 
13830   if (ProbableTypo) {
13831     Diag(NBody->getSemiLoc(), DiagID);
13832     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
13833   }
13834 }
13835 
13836 //===--- CHECK: Warn on self move with std::move. -------------------------===//
13837 
13838 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
13839 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
13840                              SourceLocation OpLoc) {
13841   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
13842     return;
13843 
13844   if (inTemplateInstantiation())
13845     return;
13846 
13847   // Strip parens and casts away.
13848   LHSExpr = LHSExpr->IgnoreParenImpCasts();
13849   RHSExpr = RHSExpr->IgnoreParenImpCasts();
13850 
13851   // Check for a call expression
13852   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
13853   if (!CE || CE->getNumArgs() != 1)
13854     return;
13855 
13856   // Check for a call to std::move
13857   if (!CE->isCallToStdMove())
13858     return;
13859 
13860   // Get argument from std::move
13861   RHSExpr = CE->getArg(0);
13862 
13863   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
13864   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
13865 
13866   // Two DeclRefExpr's, check that the decls are the same.
13867   if (LHSDeclRef && RHSDeclRef) {
13868     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
13869       return;
13870     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
13871         RHSDeclRef->getDecl()->getCanonicalDecl())
13872       return;
13873 
13874     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
13875                                         << LHSExpr->getSourceRange()
13876                                         << RHSExpr->getSourceRange();
13877     return;
13878   }
13879 
13880   // Member variables require a different approach to check for self moves.
13881   // MemberExpr's are the same if every nested MemberExpr refers to the same
13882   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
13883   // the base Expr's are CXXThisExpr's.
13884   const Expr *LHSBase = LHSExpr;
13885   const Expr *RHSBase = RHSExpr;
13886   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
13887   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
13888   if (!LHSME || !RHSME)
13889     return;
13890 
13891   while (LHSME && RHSME) {
13892     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
13893         RHSME->getMemberDecl()->getCanonicalDecl())
13894       return;
13895 
13896     LHSBase = LHSME->getBase();
13897     RHSBase = RHSME->getBase();
13898     LHSME = dyn_cast<MemberExpr>(LHSBase);
13899     RHSME = dyn_cast<MemberExpr>(RHSBase);
13900   }
13901 
13902   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
13903   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
13904   if (LHSDeclRef && RHSDeclRef) {
13905     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
13906       return;
13907     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
13908         RHSDeclRef->getDecl()->getCanonicalDecl())
13909       return;
13910 
13911     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
13912                                         << LHSExpr->getSourceRange()
13913                                         << RHSExpr->getSourceRange();
13914     return;
13915   }
13916 
13917   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
13918     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
13919                                         << LHSExpr->getSourceRange()
13920                                         << RHSExpr->getSourceRange();
13921 }
13922 
13923 //===--- Layout compatibility ----------------------------------------------//
13924 
13925 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
13926 
13927 /// Check if two enumeration types are layout-compatible.
13928 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
13929   // C++11 [dcl.enum] p8:
13930   // Two enumeration types are layout-compatible if they have the same
13931   // underlying type.
13932   return ED1->isComplete() && ED2->isComplete() &&
13933          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
13934 }
13935 
13936 /// Check if two fields are layout-compatible.
13937 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
13938                                FieldDecl *Field2) {
13939   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
13940     return false;
13941 
13942   if (Field1->isBitField() != Field2->isBitField())
13943     return false;
13944 
13945   if (Field1->isBitField()) {
13946     // Make sure that the bit-fields are the same length.
13947     unsigned Bits1 = Field1->getBitWidthValue(C);
13948     unsigned Bits2 = Field2->getBitWidthValue(C);
13949 
13950     if (Bits1 != Bits2)
13951       return false;
13952   }
13953 
13954   return true;
13955 }
13956 
13957 /// Check if two standard-layout structs are layout-compatible.
13958 /// (C++11 [class.mem] p17)
13959 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
13960                                      RecordDecl *RD2) {
13961   // If both records are C++ classes, check that base classes match.
13962   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
13963     // If one of records is a CXXRecordDecl we are in C++ mode,
13964     // thus the other one is a CXXRecordDecl, too.
13965     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
13966     // Check number of base classes.
13967     if (D1CXX->getNumBases() != D2CXX->getNumBases())
13968       return false;
13969 
13970     // Check the base classes.
13971     for (CXXRecordDecl::base_class_const_iterator
13972                Base1 = D1CXX->bases_begin(),
13973            BaseEnd1 = D1CXX->bases_end(),
13974               Base2 = D2CXX->bases_begin();
13975          Base1 != BaseEnd1;
13976          ++Base1, ++Base2) {
13977       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
13978         return false;
13979     }
13980   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
13981     // If only RD2 is a C++ class, it should have zero base classes.
13982     if (D2CXX->getNumBases() > 0)
13983       return false;
13984   }
13985 
13986   // Check the fields.
13987   RecordDecl::field_iterator Field2 = RD2->field_begin(),
13988                              Field2End = RD2->field_end(),
13989                              Field1 = RD1->field_begin(),
13990                              Field1End = RD1->field_end();
13991   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
13992     if (!isLayoutCompatible(C, *Field1, *Field2))
13993       return false;
13994   }
13995   if (Field1 != Field1End || Field2 != Field2End)
13996     return false;
13997 
13998   return true;
13999 }
14000 
14001 /// Check if two standard-layout unions are layout-compatible.
14002 /// (C++11 [class.mem] p18)
14003 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
14004                                     RecordDecl *RD2) {
14005   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
14006   for (auto *Field2 : RD2->fields())
14007     UnmatchedFields.insert(Field2);
14008 
14009   for (auto *Field1 : RD1->fields()) {
14010     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
14011         I = UnmatchedFields.begin(),
14012         E = UnmatchedFields.end();
14013 
14014     for ( ; I != E; ++I) {
14015       if (isLayoutCompatible(C, Field1, *I)) {
14016         bool Result = UnmatchedFields.erase(*I);
14017         (void) Result;
14018         assert(Result);
14019         break;
14020       }
14021     }
14022     if (I == E)
14023       return false;
14024   }
14025 
14026   return UnmatchedFields.empty();
14027 }
14028 
14029 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
14030                                RecordDecl *RD2) {
14031   if (RD1->isUnion() != RD2->isUnion())
14032     return false;
14033 
14034   if (RD1->isUnion())
14035     return isLayoutCompatibleUnion(C, RD1, RD2);
14036   else
14037     return isLayoutCompatibleStruct(C, RD1, RD2);
14038 }
14039 
14040 /// Check if two types are layout-compatible in C++11 sense.
14041 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
14042   if (T1.isNull() || T2.isNull())
14043     return false;
14044 
14045   // C++11 [basic.types] p11:
14046   // If two types T1 and T2 are the same type, then T1 and T2 are
14047   // layout-compatible types.
14048   if (C.hasSameType(T1, T2))
14049     return true;
14050 
14051   T1 = T1.getCanonicalType().getUnqualifiedType();
14052   T2 = T2.getCanonicalType().getUnqualifiedType();
14053 
14054   const Type::TypeClass TC1 = T1->getTypeClass();
14055   const Type::TypeClass TC2 = T2->getTypeClass();
14056 
14057   if (TC1 != TC2)
14058     return false;
14059 
14060   if (TC1 == Type::Enum) {
14061     return isLayoutCompatible(C,
14062                               cast<EnumType>(T1)->getDecl(),
14063                               cast<EnumType>(T2)->getDecl());
14064   } else if (TC1 == Type::Record) {
14065     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
14066       return false;
14067 
14068     return isLayoutCompatible(C,
14069                               cast<RecordType>(T1)->getDecl(),
14070                               cast<RecordType>(T2)->getDecl());
14071   }
14072 
14073   return false;
14074 }
14075 
14076 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
14077 
14078 /// Given a type tag expression find the type tag itself.
14079 ///
14080 /// \param TypeExpr Type tag expression, as it appears in user's code.
14081 ///
14082 /// \param VD Declaration of an identifier that appears in a type tag.
14083 ///
14084 /// \param MagicValue Type tag magic value.
14085 ///
14086 /// \param isConstantEvaluated wether the evalaution should be performed in
14087 
14088 /// constant context.
14089 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
14090                             const ValueDecl **VD, uint64_t *MagicValue,
14091                             bool isConstantEvaluated) {
14092   while(true) {
14093     if (!TypeExpr)
14094       return false;
14095 
14096     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
14097 
14098     switch (TypeExpr->getStmtClass()) {
14099     case Stmt::UnaryOperatorClass: {
14100       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
14101       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
14102         TypeExpr = UO->getSubExpr();
14103         continue;
14104       }
14105       return false;
14106     }
14107 
14108     case Stmt::DeclRefExprClass: {
14109       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
14110       *VD = DRE->getDecl();
14111       return true;
14112     }
14113 
14114     case Stmt::IntegerLiteralClass: {
14115       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
14116       llvm::APInt MagicValueAPInt = IL->getValue();
14117       if (MagicValueAPInt.getActiveBits() <= 64) {
14118         *MagicValue = MagicValueAPInt.getZExtValue();
14119         return true;
14120       } else
14121         return false;
14122     }
14123 
14124     case Stmt::BinaryConditionalOperatorClass:
14125     case Stmt::ConditionalOperatorClass: {
14126       const AbstractConditionalOperator *ACO =
14127           cast<AbstractConditionalOperator>(TypeExpr);
14128       bool Result;
14129       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
14130                                                      isConstantEvaluated)) {
14131         if (Result)
14132           TypeExpr = ACO->getTrueExpr();
14133         else
14134           TypeExpr = ACO->getFalseExpr();
14135         continue;
14136       }
14137       return false;
14138     }
14139 
14140     case Stmt::BinaryOperatorClass: {
14141       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
14142       if (BO->getOpcode() == BO_Comma) {
14143         TypeExpr = BO->getRHS();
14144         continue;
14145       }
14146       return false;
14147     }
14148 
14149     default:
14150       return false;
14151     }
14152   }
14153 }
14154 
14155 /// Retrieve the C type corresponding to type tag TypeExpr.
14156 ///
14157 /// \param TypeExpr Expression that specifies a type tag.
14158 ///
14159 /// \param MagicValues Registered magic values.
14160 ///
14161 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
14162 ///        kind.
14163 ///
14164 /// \param TypeInfo Information about the corresponding C type.
14165 ///
14166 /// \param isConstantEvaluated wether the evalaution should be performed in
14167 /// constant context.
14168 ///
14169 /// \returns true if the corresponding C type was found.
14170 static bool GetMatchingCType(
14171     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
14172     const ASTContext &Ctx,
14173     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
14174         *MagicValues,
14175     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
14176     bool isConstantEvaluated) {
14177   FoundWrongKind = false;
14178 
14179   // Variable declaration that has type_tag_for_datatype attribute.
14180   const ValueDecl *VD = nullptr;
14181 
14182   uint64_t MagicValue;
14183 
14184   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
14185     return false;
14186 
14187   if (VD) {
14188     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
14189       if (I->getArgumentKind() != ArgumentKind) {
14190         FoundWrongKind = true;
14191         return false;
14192       }
14193       TypeInfo.Type = I->getMatchingCType();
14194       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
14195       TypeInfo.MustBeNull = I->getMustBeNull();
14196       return true;
14197     }
14198     return false;
14199   }
14200 
14201   if (!MagicValues)
14202     return false;
14203 
14204   llvm::DenseMap<Sema::TypeTagMagicValue,
14205                  Sema::TypeTagData>::const_iterator I =
14206       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
14207   if (I == MagicValues->end())
14208     return false;
14209 
14210   TypeInfo = I->second;
14211   return true;
14212 }
14213 
14214 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
14215                                       uint64_t MagicValue, QualType Type,
14216                                       bool LayoutCompatible,
14217                                       bool MustBeNull) {
14218   if (!TypeTagForDatatypeMagicValues)
14219     TypeTagForDatatypeMagicValues.reset(
14220         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
14221 
14222   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
14223   (*TypeTagForDatatypeMagicValues)[Magic] =
14224       TypeTagData(Type, LayoutCompatible, MustBeNull);
14225 }
14226 
14227 static bool IsSameCharType(QualType T1, QualType T2) {
14228   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
14229   if (!BT1)
14230     return false;
14231 
14232   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
14233   if (!BT2)
14234     return false;
14235 
14236   BuiltinType::Kind T1Kind = BT1->getKind();
14237   BuiltinType::Kind T2Kind = BT2->getKind();
14238 
14239   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
14240          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
14241          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
14242          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
14243 }
14244 
14245 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
14246                                     const ArrayRef<const Expr *> ExprArgs,
14247                                     SourceLocation CallSiteLoc) {
14248   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
14249   bool IsPointerAttr = Attr->getIsPointer();
14250 
14251   // Retrieve the argument representing the 'type_tag'.
14252   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
14253   if (TypeTagIdxAST >= ExprArgs.size()) {
14254     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
14255         << 0 << Attr->getTypeTagIdx().getSourceIndex();
14256     return;
14257   }
14258   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
14259   bool FoundWrongKind;
14260   TypeTagData TypeInfo;
14261   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
14262                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
14263                         TypeInfo, isConstantEvaluated())) {
14264     if (FoundWrongKind)
14265       Diag(TypeTagExpr->getExprLoc(),
14266            diag::warn_type_tag_for_datatype_wrong_kind)
14267         << TypeTagExpr->getSourceRange();
14268     return;
14269   }
14270 
14271   // Retrieve the argument representing the 'arg_idx'.
14272   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
14273   if (ArgumentIdxAST >= ExprArgs.size()) {
14274     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
14275         << 1 << Attr->getArgumentIdx().getSourceIndex();
14276     return;
14277   }
14278   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
14279   if (IsPointerAttr) {
14280     // Skip implicit cast of pointer to `void *' (as a function argument).
14281     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
14282       if (ICE->getType()->isVoidPointerType() &&
14283           ICE->getCastKind() == CK_BitCast)
14284         ArgumentExpr = ICE->getSubExpr();
14285   }
14286   QualType ArgumentType = ArgumentExpr->getType();
14287 
14288   // Passing a `void*' pointer shouldn't trigger a warning.
14289   if (IsPointerAttr && ArgumentType->isVoidPointerType())
14290     return;
14291 
14292   if (TypeInfo.MustBeNull) {
14293     // Type tag with matching void type requires a null pointer.
14294     if (!ArgumentExpr->isNullPointerConstant(Context,
14295                                              Expr::NPC_ValueDependentIsNotNull)) {
14296       Diag(ArgumentExpr->getExprLoc(),
14297            diag::warn_type_safety_null_pointer_required)
14298           << ArgumentKind->getName()
14299           << ArgumentExpr->getSourceRange()
14300           << TypeTagExpr->getSourceRange();
14301     }
14302     return;
14303   }
14304 
14305   QualType RequiredType = TypeInfo.Type;
14306   if (IsPointerAttr)
14307     RequiredType = Context.getPointerType(RequiredType);
14308 
14309   bool mismatch = false;
14310   if (!TypeInfo.LayoutCompatible) {
14311     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
14312 
14313     // C++11 [basic.fundamental] p1:
14314     // Plain char, signed char, and unsigned char are three distinct types.
14315     //
14316     // But we treat plain `char' as equivalent to `signed char' or `unsigned
14317     // char' depending on the current char signedness mode.
14318     if (mismatch)
14319       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
14320                                            RequiredType->getPointeeType())) ||
14321           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
14322         mismatch = false;
14323   } else
14324     if (IsPointerAttr)
14325       mismatch = !isLayoutCompatible(Context,
14326                                      ArgumentType->getPointeeType(),
14327                                      RequiredType->getPointeeType());
14328     else
14329       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
14330 
14331   if (mismatch)
14332     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
14333         << ArgumentType << ArgumentKind
14334         << TypeInfo.LayoutCompatible << RequiredType
14335         << ArgumentExpr->getSourceRange()
14336         << TypeTagExpr->getSourceRange();
14337 }
14338 
14339 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
14340                                          CharUnits Alignment) {
14341   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
14342 }
14343 
14344 void Sema::DiagnoseMisalignedMembers() {
14345   for (MisalignedMember &m : MisalignedMembers) {
14346     const NamedDecl *ND = m.RD;
14347     if (ND->getName().empty()) {
14348       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
14349         ND = TD;
14350     }
14351     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
14352         << m.MD << ND << m.E->getSourceRange();
14353   }
14354   MisalignedMembers.clear();
14355 }
14356 
14357 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
14358   E = E->IgnoreParens();
14359   if (!T->isPointerType() && !T->isIntegerType())
14360     return;
14361   if (isa<UnaryOperator>(E) &&
14362       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
14363     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
14364     if (isa<MemberExpr>(Op)) {
14365       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
14366       if (MA != MisalignedMembers.end() &&
14367           (T->isIntegerType() ||
14368            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
14369                                    Context.getTypeAlignInChars(
14370                                        T->getPointeeType()) <= MA->Alignment))))
14371         MisalignedMembers.erase(MA);
14372     }
14373   }
14374 }
14375 
14376 void Sema::RefersToMemberWithReducedAlignment(
14377     Expr *E,
14378     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
14379         Action) {
14380   const auto *ME = dyn_cast<MemberExpr>(E);
14381   if (!ME)
14382     return;
14383 
14384   // No need to check expressions with an __unaligned-qualified type.
14385   if (E->getType().getQualifiers().hasUnaligned())
14386     return;
14387 
14388   // For a chain of MemberExpr like "a.b.c.d" this list
14389   // will keep FieldDecl's like [d, c, b].
14390   SmallVector<FieldDecl *, 4> ReverseMemberChain;
14391   const MemberExpr *TopME = nullptr;
14392   bool AnyIsPacked = false;
14393   do {
14394     QualType BaseType = ME->getBase()->getType();
14395     if (BaseType->isDependentType())
14396       return;
14397     if (ME->isArrow())
14398       BaseType = BaseType->getPointeeType();
14399     RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
14400     if (RD->isInvalidDecl())
14401       return;
14402 
14403     ValueDecl *MD = ME->getMemberDecl();
14404     auto *FD = dyn_cast<FieldDecl>(MD);
14405     // We do not care about non-data members.
14406     if (!FD || FD->isInvalidDecl())
14407       return;
14408 
14409     AnyIsPacked =
14410         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
14411     ReverseMemberChain.push_back(FD);
14412 
14413     TopME = ME;
14414     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
14415   } while (ME);
14416   assert(TopME && "We did not compute a topmost MemberExpr!");
14417 
14418   // Not the scope of this diagnostic.
14419   if (!AnyIsPacked)
14420     return;
14421 
14422   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
14423   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
14424   // TODO: The innermost base of the member expression may be too complicated.
14425   // For now, just disregard these cases. This is left for future
14426   // improvement.
14427   if (!DRE && !isa<CXXThisExpr>(TopBase))
14428       return;
14429 
14430   // Alignment expected by the whole expression.
14431   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
14432 
14433   // No need to do anything else with this case.
14434   if (ExpectedAlignment.isOne())
14435     return;
14436 
14437   // Synthesize offset of the whole access.
14438   CharUnits Offset;
14439   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
14440        I++) {
14441     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
14442   }
14443 
14444   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
14445   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
14446       ReverseMemberChain.back()->getParent()->getTypeForDecl());
14447 
14448   // The base expression of the innermost MemberExpr may give
14449   // stronger guarantees than the class containing the member.
14450   if (DRE && !TopME->isArrow()) {
14451     const ValueDecl *VD = DRE->getDecl();
14452     if (!VD->getType()->isReferenceType())
14453       CompleteObjectAlignment =
14454           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
14455   }
14456 
14457   // Check if the synthesized offset fulfills the alignment.
14458   if (Offset % ExpectedAlignment != 0 ||
14459       // It may fulfill the offset it but the effective alignment may still be
14460       // lower than the expected expression alignment.
14461       CompleteObjectAlignment < ExpectedAlignment) {
14462     // If this happens, we want to determine a sensible culprit of this.
14463     // Intuitively, watching the chain of member expressions from right to
14464     // left, we start with the required alignment (as required by the field
14465     // type) but some packed attribute in that chain has reduced the alignment.
14466     // It may happen that another packed structure increases it again. But if
14467     // we are here such increase has not been enough. So pointing the first
14468     // FieldDecl that either is packed or else its RecordDecl is,
14469     // seems reasonable.
14470     FieldDecl *FD = nullptr;
14471     CharUnits Alignment;
14472     for (FieldDecl *FDI : ReverseMemberChain) {
14473       if (FDI->hasAttr<PackedAttr>() ||
14474           FDI->getParent()->hasAttr<PackedAttr>()) {
14475         FD = FDI;
14476         Alignment = std::min(
14477             Context.getTypeAlignInChars(FD->getType()),
14478             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
14479         break;
14480       }
14481     }
14482     assert(FD && "We did not find a packed FieldDecl!");
14483     Action(E, FD->getParent(), FD, Alignment);
14484   }
14485 }
14486 
14487 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
14488   using namespace std::placeholders;
14489 
14490   RefersToMemberWithReducedAlignment(
14491       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
14492                      _2, _3, _4));
14493 }
14494