1 //===- SemaChecking.cpp - Extra Semantic Checking -------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements extra semantic analysis beyond what is enforced
10 //  by the C type system.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/AST/APValue.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/Attr.h"
17 #include "clang/AST/AttrIterator.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclBase.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclarationName.h"
24 #include "clang/AST/EvaluatedExprVisitor.h"
25 #include "clang/AST/Expr.h"
26 #include "clang/AST/ExprCXX.h"
27 #include "clang/AST/ExprObjC.h"
28 #include "clang/AST/ExprOpenMP.h"
29 #include "clang/AST/FormatString.h"
30 #include "clang/AST/NSAPI.h"
31 #include "clang/AST/NonTrivialTypeVisitor.h"
32 #include "clang/AST/OperationKinds.h"
33 #include "clang/AST/RecordLayout.h"
34 #include "clang/AST/Stmt.h"
35 #include "clang/AST/TemplateBase.h"
36 #include "clang/AST/Type.h"
37 #include "clang/AST/TypeLoc.h"
38 #include "clang/AST/UnresolvedSet.h"
39 #include "clang/Basic/AddressSpaces.h"
40 #include "clang/Basic/CharInfo.h"
41 #include "clang/Basic/Diagnostic.h"
42 #include "clang/Basic/IdentifierTable.h"
43 #include "clang/Basic/LLVM.h"
44 #include "clang/Basic/LangOptions.h"
45 #include "clang/Basic/OpenCLOptions.h"
46 #include "clang/Basic/OperatorKinds.h"
47 #include "clang/Basic/PartialDiagnostic.h"
48 #include "clang/Basic/SourceLocation.h"
49 #include "clang/Basic/SourceManager.h"
50 #include "clang/Basic/Specifiers.h"
51 #include "clang/Basic/SyncScope.h"
52 #include "clang/Basic/TargetBuiltins.h"
53 #include "clang/Basic/TargetCXXABI.h"
54 #include "clang/Basic/TargetInfo.h"
55 #include "clang/Basic/TypeTraits.h"
56 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
57 #include "clang/Sema/Initialization.h"
58 #include "clang/Sema/Lookup.h"
59 #include "clang/Sema/Ownership.h"
60 #include "clang/Sema/Scope.h"
61 #include "clang/Sema/ScopeInfo.h"
62 #include "clang/Sema/Sema.h"
63 #include "clang/Sema/SemaInternal.h"
64 #include "llvm/ADT/APFloat.h"
65 #include "llvm/ADT/APInt.h"
66 #include "llvm/ADT/APSInt.h"
67 #include "llvm/ADT/ArrayRef.h"
68 #include "llvm/ADT/DenseMap.h"
69 #include "llvm/ADT/FoldingSet.h"
70 #include "llvm/ADT/None.h"
71 #include "llvm/ADT/Optional.h"
72 #include "llvm/ADT/STLExtras.h"
73 #include "llvm/ADT/SmallBitVector.h"
74 #include "llvm/ADT/SmallPtrSet.h"
75 #include "llvm/ADT/SmallString.h"
76 #include "llvm/ADT/SmallVector.h"
77 #include "llvm/ADT/StringRef.h"
78 #include "llvm/ADT/StringSet.h"
79 #include "llvm/ADT/StringSwitch.h"
80 #include "llvm/ADT/Triple.h"
81 #include "llvm/Support/AtomicOrdering.h"
82 #include "llvm/Support/Casting.h"
83 #include "llvm/Support/Compiler.h"
84 #include "llvm/Support/ConvertUTF.h"
85 #include "llvm/Support/ErrorHandling.h"
86 #include "llvm/Support/Format.h"
87 #include "llvm/Support/Locale.h"
88 #include "llvm/Support/MathExtras.h"
89 #include "llvm/Support/SaveAndRestore.h"
90 #include "llvm/Support/raw_ostream.h"
91 #include <algorithm>
92 #include <bitset>
93 #include <cassert>
94 #include <cstddef>
95 #include <cstdint>
96 #include <functional>
97 #include <limits>
98 #include <string>
99 #include <tuple>
100 #include <utility>
101 
102 using namespace clang;
103 using namespace sema;
104 
105 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
106                                                     unsigned ByteNo) const {
107   return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
108                                Context.getTargetInfo());
109 }
110 
111 /// Checks that a call expression's argument count is the desired number.
112 /// This is useful when doing custom type-checking.  Returns true on error.
113 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
114   unsigned argCount = call->getNumArgs();
115   if (argCount == desiredArgCount) return false;
116 
117   if (argCount < desiredArgCount)
118     return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args)
119            << 0 /*function call*/ << desiredArgCount << argCount
120            << call->getSourceRange();
121 
122   // Highlight all the excess arguments.
123   SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(),
124                     call->getArg(argCount - 1)->getEndLoc());
125 
126   return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
127     << 0 /*function call*/ << desiredArgCount << argCount
128     << call->getArg(1)->getSourceRange();
129 }
130 
131 /// Check that the first argument to __builtin_annotation is an integer
132 /// and the second argument is a non-wide string literal.
133 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
134   if (checkArgCount(S, TheCall, 2))
135     return true;
136 
137   // First argument should be an integer.
138   Expr *ValArg = TheCall->getArg(0);
139   QualType Ty = ValArg->getType();
140   if (!Ty->isIntegerType()) {
141     S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
142         << ValArg->getSourceRange();
143     return true;
144   }
145 
146   // Second argument should be a constant string.
147   Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
148   StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
149   if (!Literal || !Literal->isAscii()) {
150     S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
151         << StrArg->getSourceRange();
152     return true;
153   }
154 
155   TheCall->setType(Ty);
156   return false;
157 }
158 
159 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
160   // We need at least one argument.
161   if (TheCall->getNumArgs() < 1) {
162     S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
163         << 0 << 1 << TheCall->getNumArgs()
164         << TheCall->getCallee()->getSourceRange();
165     return true;
166   }
167 
168   // All arguments should be wide string literals.
169   for (Expr *Arg : TheCall->arguments()) {
170     auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
171     if (!Literal || !Literal->isWide()) {
172       S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
173           << Arg->getSourceRange();
174       return true;
175     }
176   }
177 
178   return false;
179 }
180 
181 /// Check that the argument to __builtin_addressof is a glvalue, and set the
182 /// result type to the corresponding pointer type.
183 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
184   if (checkArgCount(S, TheCall, 1))
185     return true;
186 
187   ExprResult Arg(TheCall->getArg(0));
188   QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
189   if (ResultType.isNull())
190     return true;
191 
192   TheCall->setArg(0, Arg.get());
193   TheCall->setType(ResultType);
194   return false;
195 }
196 
197 /// Check the number of arguments and set the result type to
198 /// the argument type.
199 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
200   if (checkArgCount(S, TheCall, 1))
201     return true;
202 
203   TheCall->setType(TheCall->getArg(0)->getType());
204   return false;
205 }
206 
207 /// Check that the value argument for __builtin_is_aligned(value, alignment) and
208 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
209 /// type (but not a function pointer) and that the alignment is a power-of-two.
210 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
211   if (checkArgCount(S, TheCall, 2))
212     return true;
213 
214   clang::Expr *Source = TheCall->getArg(0);
215   bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
216 
217   auto IsValidIntegerType = [](QualType Ty) {
218     return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
219   };
220   QualType SrcTy = Source->getType();
221   // We should also be able to use it with arrays (but not functions!).
222   if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
223     SrcTy = S.Context.getDecayedType(SrcTy);
224   }
225   if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
226       SrcTy->isFunctionPointerType()) {
227     // FIXME: this is not quite the right error message since we don't allow
228     // floating point types, or member pointers.
229     S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand)
230         << SrcTy;
231     return true;
232   }
233 
234   clang::Expr *AlignOp = TheCall->getArg(1);
235   if (!IsValidIntegerType(AlignOp->getType())) {
236     S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int)
237         << AlignOp->getType();
238     return true;
239   }
240   Expr::EvalResult AlignResult;
241   unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1;
242   // We can't check validity of alignment if it is value dependent.
243   if (!AlignOp->isValueDependent() &&
244       AlignOp->EvaluateAsInt(AlignResult, S.Context,
245                              Expr::SE_AllowSideEffects)) {
246     llvm::APSInt AlignValue = AlignResult.Val.getInt();
247     llvm::APSInt MaxValue(
248         llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits));
249     if (AlignValue < 1) {
250       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1;
251       return true;
252     }
253     if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) {
254       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big)
255           << MaxValue.toString(10);
256       return true;
257     }
258     if (!AlignValue.isPowerOf2()) {
259       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two);
260       return true;
261     }
262     if (AlignValue == 1) {
263       S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless)
264           << IsBooleanAlignBuiltin;
265     }
266   }
267 
268   ExprResult SrcArg = S.PerformCopyInitialization(
269       InitializedEntity::InitializeParameter(S.Context, SrcTy, false),
270       SourceLocation(), Source);
271   if (SrcArg.isInvalid())
272     return true;
273   TheCall->setArg(0, SrcArg.get());
274   ExprResult AlignArg =
275       S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
276                                       S.Context, AlignOp->getType(), false),
277                                   SourceLocation(), AlignOp);
278   if (AlignArg.isInvalid())
279     return true;
280   TheCall->setArg(1, AlignArg.get());
281   // For align_up/align_down, the return type is the same as the (potentially
282   // decayed) argument type including qualifiers. For is_aligned(), the result
283   // is always bool.
284   TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
285   return false;
286 }
287 
288 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall,
289                                 unsigned BuiltinID) {
290   if (checkArgCount(S, TheCall, 3))
291     return true;
292 
293   // First two arguments should be integers.
294   for (unsigned I = 0; I < 2; ++I) {
295     ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I));
296     if (Arg.isInvalid()) return true;
297     TheCall->setArg(I, Arg.get());
298 
299     QualType Ty = Arg.get()->getType();
300     if (!Ty->isIntegerType()) {
301       S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
302           << Ty << Arg.get()->getSourceRange();
303       return true;
304     }
305   }
306 
307   // Third argument should be a pointer to a non-const integer.
308   // IRGen correctly handles volatile, restrict, and address spaces, and
309   // the other qualifiers aren't possible.
310   {
311     ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(2));
312     if (Arg.isInvalid()) return true;
313     TheCall->setArg(2, Arg.get());
314 
315     QualType Ty = Arg.get()->getType();
316     const auto *PtrTy = Ty->getAs<PointerType>();
317     if (!PtrTy ||
318         !PtrTy->getPointeeType()->isIntegerType() ||
319         PtrTy->getPointeeType().isConstQualified()) {
320       S.Diag(Arg.get()->getBeginLoc(),
321              diag::err_overflow_builtin_must_be_ptr_int)
322         << Ty << Arg.get()->getSourceRange();
323       return true;
324     }
325   }
326 
327   // Disallow signed ExtIntType args larger than 128 bits to mul function until
328   // we improve backend support.
329   if (BuiltinID == Builtin::BI__builtin_mul_overflow) {
330     for (unsigned I = 0; I < 3; ++I) {
331       const auto Arg = TheCall->getArg(I);
332       // Third argument will be a pointer.
333       auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType();
334       if (Ty->isExtIntType() && Ty->isSignedIntegerType() &&
335           S.getASTContext().getIntWidth(Ty) > 128)
336         return S.Diag(Arg->getBeginLoc(),
337                       diag::err_overflow_builtin_ext_int_max_size)
338                << 128;
339     }
340   }
341 
342   return false;
343 }
344 
345 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
346   if (checkArgCount(S, BuiltinCall, 2))
347     return true;
348 
349   SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
350   Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
351   Expr *Call = BuiltinCall->getArg(0);
352   Expr *Chain = BuiltinCall->getArg(1);
353 
354   if (Call->getStmtClass() != Stmt::CallExprClass) {
355     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
356         << Call->getSourceRange();
357     return true;
358   }
359 
360   auto CE = cast<CallExpr>(Call);
361   if (CE->getCallee()->getType()->isBlockPointerType()) {
362     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
363         << Call->getSourceRange();
364     return true;
365   }
366 
367   const Decl *TargetDecl = CE->getCalleeDecl();
368   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
369     if (FD->getBuiltinID()) {
370       S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
371           << Call->getSourceRange();
372       return true;
373     }
374 
375   if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
376     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
377         << Call->getSourceRange();
378     return true;
379   }
380 
381   ExprResult ChainResult = S.UsualUnaryConversions(Chain);
382   if (ChainResult.isInvalid())
383     return true;
384   if (!ChainResult.get()->getType()->isPointerType()) {
385     S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
386         << Chain->getSourceRange();
387     return true;
388   }
389 
390   QualType ReturnTy = CE->getCallReturnType(S.Context);
391   QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
392   QualType BuiltinTy = S.Context.getFunctionType(
393       ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
394   QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
395 
396   Builtin =
397       S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
398 
399   BuiltinCall->setType(CE->getType());
400   BuiltinCall->setValueKind(CE->getValueKind());
401   BuiltinCall->setObjectKind(CE->getObjectKind());
402   BuiltinCall->setCallee(Builtin);
403   BuiltinCall->setArg(1, ChainResult.get());
404 
405   return false;
406 }
407 
408 namespace {
409 
410 class EstimateSizeFormatHandler
411     : public analyze_format_string::FormatStringHandler {
412   size_t Size;
413 
414 public:
415   EstimateSizeFormatHandler(StringRef Format)
416       : Size(std::min(Format.find(0), Format.size()) +
417              1 /* null byte always written by sprintf */) {}
418 
419   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
420                              const char *, unsigned SpecifierLen) override {
421 
422     const size_t FieldWidth = computeFieldWidth(FS);
423     const size_t Precision = computePrecision(FS);
424 
425     // The actual format.
426     switch (FS.getConversionSpecifier().getKind()) {
427     // Just a char.
428     case analyze_format_string::ConversionSpecifier::cArg:
429     case analyze_format_string::ConversionSpecifier::CArg:
430       Size += std::max(FieldWidth, (size_t)1);
431       break;
432     // Just an integer.
433     case analyze_format_string::ConversionSpecifier::dArg:
434     case analyze_format_string::ConversionSpecifier::DArg:
435     case analyze_format_string::ConversionSpecifier::iArg:
436     case analyze_format_string::ConversionSpecifier::oArg:
437     case analyze_format_string::ConversionSpecifier::OArg:
438     case analyze_format_string::ConversionSpecifier::uArg:
439     case analyze_format_string::ConversionSpecifier::UArg:
440     case analyze_format_string::ConversionSpecifier::xArg:
441     case analyze_format_string::ConversionSpecifier::XArg:
442       Size += std::max(FieldWidth, Precision);
443       break;
444 
445     // %g style conversion switches between %f or %e style dynamically.
446     // %f always takes less space, so default to it.
447     case analyze_format_string::ConversionSpecifier::gArg:
448     case analyze_format_string::ConversionSpecifier::GArg:
449 
450     // Floating point number in the form '[+]ddd.ddd'.
451     case analyze_format_string::ConversionSpecifier::fArg:
452     case analyze_format_string::ConversionSpecifier::FArg:
453       Size += std::max(FieldWidth, 1 /* integer part */ +
454                                        (Precision ? 1 + Precision
455                                                   : 0) /* period + decimal */);
456       break;
457 
458     // Floating point number in the form '[-]d.ddde[+-]dd'.
459     case analyze_format_string::ConversionSpecifier::eArg:
460     case analyze_format_string::ConversionSpecifier::EArg:
461       Size +=
462           std::max(FieldWidth,
463                    1 /* integer part */ +
464                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
465                        1 /* e or E letter */ + 2 /* exponent */);
466       break;
467 
468     // Floating point number in the form '[-]0xh.hhhhp±dd'.
469     case analyze_format_string::ConversionSpecifier::aArg:
470     case analyze_format_string::ConversionSpecifier::AArg:
471       Size +=
472           std::max(FieldWidth,
473                    2 /* 0x */ + 1 /* integer part */ +
474                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
475                        1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
476       break;
477 
478     // Just a string.
479     case analyze_format_string::ConversionSpecifier::sArg:
480     case analyze_format_string::ConversionSpecifier::SArg:
481       Size += FieldWidth;
482       break;
483 
484     // Just a pointer in the form '0xddd'.
485     case analyze_format_string::ConversionSpecifier::pArg:
486       Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
487       break;
488 
489     // A plain percent.
490     case analyze_format_string::ConversionSpecifier::PercentArg:
491       Size += 1;
492       break;
493 
494     default:
495       break;
496     }
497 
498     Size += FS.hasPlusPrefix() || FS.hasSpacePrefix();
499 
500     if (FS.hasAlternativeForm()) {
501       switch (FS.getConversionSpecifier().getKind()) {
502       default:
503         break;
504       // Force a leading '0'.
505       case analyze_format_string::ConversionSpecifier::oArg:
506         Size += 1;
507         break;
508       // Force a leading '0x'.
509       case analyze_format_string::ConversionSpecifier::xArg:
510       case analyze_format_string::ConversionSpecifier::XArg:
511         Size += 2;
512         break;
513       // Force a period '.' before decimal, even if precision is 0.
514       case analyze_format_string::ConversionSpecifier::aArg:
515       case analyze_format_string::ConversionSpecifier::AArg:
516       case analyze_format_string::ConversionSpecifier::eArg:
517       case analyze_format_string::ConversionSpecifier::EArg:
518       case analyze_format_string::ConversionSpecifier::fArg:
519       case analyze_format_string::ConversionSpecifier::FArg:
520       case analyze_format_string::ConversionSpecifier::gArg:
521       case analyze_format_string::ConversionSpecifier::GArg:
522         Size += (Precision ? 0 : 1);
523         break;
524       }
525     }
526     assert(SpecifierLen <= Size && "no underflow");
527     Size -= SpecifierLen;
528     return true;
529   }
530 
531   size_t getSizeLowerBound() const { return Size; }
532 
533 private:
534   static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
535     const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
536     size_t FieldWidth = 0;
537     if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant)
538       FieldWidth = FW.getConstantAmount();
539     return FieldWidth;
540   }
541 
542   static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
543     const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
544     size_t Precision = 0;
545 
546     // See man 3 printf for default precision value based on the specifier.
547     switch (FW.getHowSpecified()) {
548     case analyze_format_string::OptionalAmount::NotSpecified:
549       switch (FS.getConversionSpecifier().getKind()) {
550       default:
551         break;
552       case analyze_format_string::ConversionSpecifier::dArg: // %d
553       case analyze_format_string::ConversionSpecifier::DArg: // %D
554       case analyze_format_string::ConversionSpecifier::iArg: // %i
555         Precision = 1;
556         break;
557       case analyze_format_string::ConversionSpecifier::oArg: // %d
558       case analyze_format_string::ConversionSpecifier::OArg: // %D
559       case analyze_format_string::ConversionSpecifier::uArg: // %d
560       case analyze_format_string::ConversionSpecifier::UArg: // %D
561       case analyze_format_string::ConversionSpecifier::xArg: // %d
562       case analyze_format_string::ConversionSpecifier::XArg: // %D
563         Precision = 1;
564         break;
565       case analyze_format_string::ConversionSpecifier::fArg: // %f
566       case analyze_format_string::ConversionSpecifier::FArg: // %F
567       case analyze_format_string::ConversionSpecifier::eArg: // %e
568       case analyze_format_string::ConversionSpecifier::EArg: // %E
569       case analyze_format_string::ConversionSpecifier::gArg: // %g
570       case analyze_format_string::ConversionSpecifier::GArg: // %G
571         Precision = 6;
572         break;
573       case analyze_format_string::ConversionSpecifier::pArg: // %d
574         Precision = 1;
575         break;
576       }
577       break;
578     case analyze_format_string::OptionalAmount::Constant:
579       Precision = FW.getConstantAmount();
580       break;
581     default:
582       break;
583     }
584     return Precision;
585   }
586 };
587 
588 } // namespace
589 
590 /// Check a call to BuiltinID for buffer overflows. If BuiltinID is a
591 /// __builtin_*_chk function, then use the object size argument specified in the
592 /// source. Otherwise, infer the object size using __builtin_object_size.
593 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
594                                                CallExpr *TheCall) {
595   // FIXME: There are some more useful checks we could be doing here:
596   //  - Evaluate strlen of strcpy arguments, use as object size.
597 
598   if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
599       isConstantEvaluated())
600     return;
601 
602   unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true);
603   if (!BuiltinID)
604     return;
605 
606   const TargetInfo &TI = getASTContext().getTargetInfo();
607   unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
608 
609   unsigned DiagID = 0;
610   bool IsChkVariant = false;
611   Optional<llvm::APSInt> UsedSize;
612   unsigned SizeIndex, ObjectIndex;
613   switch (BuiltinID) {
614   default:
615     return;
616   case Builtin::BIsprintf:
617   case Builtin::BI__builtin___sprintf_chk: {
618     size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
619     auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
620 
621     if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) {
622 
623       if (!Format->isAscii() && !Format->isUTF8())
624         return;
625 
626       StringRef FormatStrRef = Format->getString();
627       EstimateSizeFormatHandler H(FormatStrRef);
628       const char *FormatBytes = FormatStrRef.data();
629       const ConstantArrayType *T =
630           Context.getAsConstantArrayType(Format->getType());
631       assert(T && "String literal not of constant array type!");
632       size_t TypeSize = T->getSize().getZExtValue();
633 
634       // In case there's a null byte somewhere.
635       size_t StrLen =
636           std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
637       if (!analyze_format_string::ParsePrintfString(
638               H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
639               Context.getTargetInfo(), false)) {
640         DiagID = diag::warn_fortify_source_format_overflow;
641         UsedSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
642                        .extOrTrunc(SizeTypeWidth);
643         if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
644           IsChkVariant = true;
645           ObjectIndex = 2;
646         } else {
647           IsChkVariant = false;
648           ObjectIndex = 0;
649         }
650         break;
651       }
652     }
653     return;
654   }
655   case Builtin::BI__builtin___memcpy_chk:
656   case Builtin::BI__builtin___memmove_chk:
657   case Builtin::BI__builtin___memset_chk:
658   case Builtin::BI__builtin___strlcat_chk:
659   case Builtin::BI__builtin___strlcpy_chk:
660   case Builtin::BI__builtin___strncat_chk:
661   case Builtin::BI__builtin___strncpy_chk:
662   case Builtin::BI__builtin___stpncpy_chk:
663   case Builtin::BI__builtin___memccpy_chk:
664   case Builtin::BI__builtin___mempcpy_chk: {
665     DiagID = diag::warn_builtin_chk_overflow;
666     IsChkVariant = true;
667     SizeIndex = TheCall->getNumArgs() - 2;
668     ObjectIndex = TheCall->getNumArgs() - 1;
669     break;
670   }
671 
672   case Builtin::BI__builtin___snprintf_chk:
673   case Builtin::BI__builtin___vsnprintf_chk: {
674     DiagID = diag::warn_builtin_chk_overflow;
675     IsChkVariant = true;
676     SizeIndex = 1;
677     ObjectIndex = 3;
678     break;
679   }
680 
681   case Builtin::BIstrncat:
682   case Builtin::BI__builtin_strncat:
683   case Builtin::BIstrncpy:
684   case Builtin::BI__builtin_strncpy:
685   case Builtin::BIstpncpy:
686   case Builtin::BI__builtin_stpncpy: {
687     // Whether these functions overflow depends on the runtime strlen of the
688     // string, not just the buffer size, so emitting the "always overflow"
689     // diagnostic isn't quite right. We should still diagnose passing a buffer
690     // size larger than the destination buffer though; this is a runtime abort
691     // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
692     DiagID = diag::warn_fortify_source_size_mismatch;
693     SizeIndex = TheCall->getNumArgs() - 1;
694     ObjectIndex = 0;
695     break;
696   }
697 
698   case Builtin::BImemcpy:
699   case Builtin::BI__builtin_memcpy:
700   case Builtin::BImemmove:
701   case Builtin::BI__builtin_memmove:
702   case Builtin::BImemset:
703   case Builtin::BI__builtin_memset:
704   case Builtin::BImempcpy:
705   case Builtin::BI__builtin_mempcpy: {
706     DiagID = diag::warn_fortify_source_overflow;
707     SizeIndex = TheCall->getNumArgs() - 1;
708     ObjectIndex = 0;
709     break;
710   }
711   case Builtin::BIsnprintf:
712   case Builtin::BI__builtin_snprintf:
713   case Builtin::BIvsnprintf:
714   case Builtin::BI__builtin_vsnprintf: {
715     DiagID = diag::warn_fortify_source_size_mismatch;
716     SizeIndex = 1;
717     ObjectIndex = 0;
718     break;
719   }
720   }
721 
722   llvm::APSInt ObjectSize;
723   // For __builtin___*_chk, the object size is explicitly provided by the caller
724   // (usually using __builtin_object_size). Use that value to check this call.
725   if (IsChkVariant) {
726     Expr::EvalResult Result;
727     Expr *SizeArg = TheCall->getArg(ObjectIndex);
728     if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
729       return;
730     ObjectSize = Result.Val.getInt();
731 
732   // Otherwise, try to evaluate an imaginary call to __builtin_object_size.
733   } else {
734     // If the parameter has a pass_object_size attribute, then we should use its
735     // (potentially) more strict checking mode. Otherwise, conservatively assume
736     // type 0.
737     int BOSType = 0;
738     if (const auto *POS =
739             FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>())
740       BOSType = POS->getType();
741 
742     Expr *ObjArg = TheCall->getArg(ObjectIndex);
743     uint64_t Result;
744     if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
745       return;
746     // Get the object size in the target's size_t width.
747     ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
748   }
749 
750   // Evaluate the number of bytes of the object that this call will use.
751   if (!UsedSize) {
752     Expr::EvalResult Result;
753     Expr *UsedSizeArg = TheCall->getArg(SizeIndex);
754     if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext()))
755       return;
756     UsedSize = Result.Val.getInt().extOrTrunc(SizeTypeWidth);
757   }
758 
759   if (UsedSize.getValue().ule(ObjectSize))
760     return;
761 
762   StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
763   // Skim off the details of whichever builtin was called to produce a better
764   // diagnostic, as it's unlikley that the user wrote the __builtin explicitly.
765   if (IsChkVariant) {
766     FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
767     FunctionName = FunctionName.drop_back(std::strlen("_chk"));
768   } else if (FunctionName.startswith("__builtin_")) {
769     FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
770   }
771 
772   DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
773                       PDiag(DiagID)
774                           << FunctionName << ObjectSize.toString(/*Radix=*/10)
775                           << UsedSize.getValue().toString(/*Radix=*/10));
776 }
777 
778 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
779                                      Scope::ScopeFlags NeededScopeFlags,
780                                      unsigned DiagID) {
781   // Scopes aren't available during instantiation. Fortunately, builtin
782   // functions cannot be template args so they cannot be formed through template
783   // instantiation. Therefore checking once during the parse is sufficient.
784   if (SemaRef.inTemplateInstantiation())
785     return false;
786 
787   Scope *S = SemaRef.getCurScope();
788   while (S && !S->isSEHExceptScope())
789     S = S->getParent();
790   if (!S || !(S->getFlags() & NeededScopeFlags)) {
791     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
792     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
793         << DRE->getDecl()->getIdentifier();
794     return true;
795   }
796 
797   return false;
798 }
799 
800 static inline bool isBlockPointer(Expr *Arg) {
801   return Arg->getType()->isBlockPointerType();
802 }
803 
804 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
805 /// void*, which is a requirement of device side enqueue.
806 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
807   const BlockPointerType *BPT =
808       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
809   ArrayRef<QualType> Params =
810       BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes();
811   unsigned ArgCounter = 0;
812   bool IllegalParams = false;
813   // Iterate through the block parameters until either one is found that is not
814   // a local void*, or the block is valid.
815   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
816        I != E; ++I, ++ArgCounter) {
817     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
818         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
819             LangAS::opencl_local) {
820       // Get the location of the error. If a block literal has been passed
821       // (BlockExpr) then we can point straight to the offending argument,
822       // else we just point to the variable reference.
823       SourceLocation ErrorLoc;
824       if (isa<BlockExpr>(BlockArg)) {
825         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
826         ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
827       } else if (isa<DeclRefExpr>(BlockArg)) {
828         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
829       }
830       S.Diag(ErrorLoc,
831              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
832       IllegalParams = true;
833     }
834   }
835 
836   return IllegalParams;
837 }
838 
839 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
840   if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
841     S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
842         << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
843     return true;
844   }
845   return false;
846 }
847 
848 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
849   if (checkArgCount(S, TheCall, 2))
850     return true;
851 
852   if (checkOpenCLSubgroupExt(S, TheCall))
853     return true;
854 
855   // First argument is an ndrange_t type.
856   Expr *NDRangeArg = TheCall->getArg(0);
857   if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
858     S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
859         << TheCall->getDirectCallee() << "'ndrange_t'";
860     return true;
861   }
862 
863   Expr *BlockArg = TheCall->getArg(1);
864   if (!isBlockPointer(BlockArg)) {
865     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
866         << TheCall->getDirectCallee() << "block";
867     return true;
868   }
869   return checkOpenCLBlockArgs(S, BlockArg);
870 }
871 
872 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
873 /// get_kernel_work_group_size
874 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
875 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
876   if (checkArgCount(S, TheCall, 1))
877     return true;
878 
879   Expr *BlockArg = TheCall->getArg(0);
880   if (!isBlockPointer(BlockArg)) {
881     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
882         << TheCall->getDirectCallee() << "block";
883     return true;
884   }
885   return checkOpenCLBlockArgs(S, BlockArg);
886 }
887 
888 /// Diagnose integer type and any valid implicit conversion to it.
889 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
890                                       const QualType &IntType);
891 
892 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
893                                             unsigned Start, unsigned End) {
894   bool IllegalParams = false;
895   for (unsigned I = Start; I <= End; ++I)
896     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
897                                               S.Context.getSizeType());
898   return IllegalParams;
899 }
900 
901 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
902 /// 'local void*' parameter of passed block.
903 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
904                                            Expr *BlockArg,
905                                            unsigned NumNonVarArgs) {
906   const BlockPointerType *BPT =
907       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
908   unsigned NumBlockParams =
909       BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams();
910   unsigned TotalNumArgs = TheCall->getNumArgs();
911 
912   // For each argument passed to the block, a corresponding uint needs to
913   // be passed to describe the size of the local memory.
914   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
915     S.Diag(TheCall->getBeginLoc(),
916            diag::err_opencl_enqueue_kernel_local_size_args);
917     return true;
918   }
919 
920   // Check that the sizes of the local memory are specified by integers.
921   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
922                                          TotalNumArgs - 1);
923 }
924 
925 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
926 /// overload formats specified in Table 6.13.17.1.
927 /// int enqueue_kernel(queue_t queue,
928 ///                    kernel_enqueue_flags_t flags,
929 ///                    const ndrange_t ndrange,
930 ///                    void (^block)(void))
931 /// int enqueue_kernel(queue_t queue,
932 ///                    kernel_enqueue_flags_t flags,
933 ///                    const ndrange_t ndrange,
934 ///                    uint num_events_in_wait_list,
935 ///                    clk_event_t *event_wait_list,
936 ///                    clk_event_t *event_ret,
937 ///                    void (^block)(void))
938 /// int enqueue_kernel(queue_t queue,
939 ///                    kernel_enqueue_flags_t flags,
940 ///                    const ndrange_t ndrange,
941 ///                    void (^block)(local void*, ...),
942 ///                    uint size0, ...)
943 /// int enqueue_kernel(queue_t queue,
944 ///                    kernel_enqueue_flags_t flags,
945 ///                    const ndrange_t ndrange,
946 ///                    uint num_events_in_wait_list,
947 ///                    clk_event_t *event_wait_list,
948 ///                    clk_event_t *event_ret,
949 ///                    void (^block)(local void*, ...),
950 ///                    uint size0, ...)
951 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
952   unsigned NumArgs = TheCall->getNumArgs();
953 
954   if (NumArgs < 4) {
955     S.Diag(TheCall->getBeginLoc(),
956            diag::err_typecheck_call_too_few_args_at_least)
957         << 0 << 4 << NumArgs;
958     return true;
959   }
960 
961   Expr *Arg0 = TheCall->getArg(0);
962   Expr *Arg1 = TheCall->getArg(1);
963   Expr *Arg2 = TheCall->getArg(2);
964   Expr *Arg3 = TheCall->getArg(3);
965 
966   // First argument always needs to be a queue_t type.
967   if (!Arg0->getType()->isQueueT()) {
968     S.Diag(TheCall->getArg(0)->getBeginLoc(),
969            diag::err_opencl_builtin_expected_type)
970         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
971     return true;
972   }
973 
974   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
975   if (!Arg1->getType()->isIntegerType()) {
976     S.Diag(TheCall->getArg(1)->getBeginLoc(),
977            diag::err_opencl_builtin_expected_type)
978         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
979     return true;
980   }
981 
982   // Third argument is always an ndrange_t type.
983   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
984     S.Diag(TheCall->getArg(2)->getBeginLoc(),
985            diag::err_opencl_builtin_expected_type)
986         << TheCall->getDirectCallee() << "'ndrange_t'";
987     return true;
988   }
989 
990   // With four arguments, there is only one form that the function could be
991   // called in: no events and no variable arguments.
992   if (NumArgs == 4) {
993     // check that the last argument is the right block type.
994     if (!isBlockPointer(Arg3)) {
995       S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
996           << TheCall->getDirectCallee() << "block";
997       return true;
998     }
999     // we have a block type, check the prototype
1000     const BlockPointerType *BPT =
1001         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
1002     if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) {
1003       S.Diag(Arg3->getBeginLoc(),
1004              diag::err_opencl_enqueue_kernel_blocks_no_args);
1005       return true;
1006     }
1007     return false;
1008   }
1009   // we can have block + varargs.
1010   if (isBlockPointer(Arg3))
1011     return (checkOpenCLBlockArgs(S, Arg3) ||
1012             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
1013   // last two cases with either exactly 7 args or 7 args and varargs.
1014   if (NumArgs >= 7) {
1015     // check common block argument.
1016     Expr *Arg6 = TheCall->getArg(6);
1017     if (!isBlockPointer(Arg6)) {
1018       S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1019           << TheCall->getDirectCallee() << "block";
1020       return true;
1021     }
1022     if (checkOpenCLBlockArgs(S, Arg6))
1023       return true;
1024 
1025     // Forth argument has to be any integer type.
1026     if (!Arg3->getType()->isIntegerType()) {
1027       S.Diag(TheCall->getArg(3)->getBeginLoc(),
1028              diag::err_opencl_builtin_expected_type)
1029           << TheCall->getDirectCallee() << "integer";
1030       return true;
1031     }
1032     // check remaining common arguments.
1033     Expr *Arg4 = TheCall->getArg(4);
1034     Expr *Arg5 = TheCall->getArg(5);
1035 
1036     // Fifth argument is always passed as a pointer to clk_event_t.
1037     if (!Arg4->isNullPointerConstant(S.Context,
1038                                      Expr::NPC_ValueDependentIsNotNull) &&
1039         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
1040       S.Diag(TheCall->getArg(4)->getBeginLoc(),
1041              diag::err_opencl_builtin_expected_type)
1042           << TheCall->getDirectCallee()
1043           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1044       return true;
1045     }
1046 
1047     // Sixth argument is always passed as a pointer to clk_event_t.
1048     if (!Arg5->isNullPointerConstant(S.Context,
1049                                      Expr::NPC_ValueDependentIsNotNull) &&
1050         !(Arg5->getType()->isPointerType() &&
1051           Arg5->getType()->getPointeeType()->isClkEventT())) {
1052       S.Diag(TheCall->getArg(5)->getBeginLoc(),
1053              diag::err_opencl_builtin_expected_type)
1054           << TheCall->getDirectCallee()
1055           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1056       return true;
1057     }
1058 
1059     if (NumArgs == 7)
1060       return false;
1061 
1062     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
1063   }
1064 
1065   // None of the specific case has been detected, give generic error
1066   S.Diag(TheCall->getBeginLoc(),
1067          diag::err_opencl_enqueue_kernel_incorrect_args);
1068   return true;
1069 }
1070 
1071 /// Returns OpenCL access qual.
1072 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
1073     return D->getAttr<OpenCLAccessAttr>();
1074 }
1075 
1076 /// Returns true if pipe element type is different from the pointer.
1077 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
1078   const Expr *Arg0 = Call->getArg(0);
1079   // First argument type should always be pipe.
1080   if (!Arg0->getType()->isPipeType()) {
1081     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1082         << Call->getDirectCallee() << Arg0->getSourceRange();
1083     return true;
1084   }
1085   OpenCLAccessAttr *AccessQual =
1086       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
1087   // Validates the access qualifier is compatible with the call.
1088   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
1089   // read_only and write_only, and assumed to be read_only if no qualifier is
1090   // specified.
1091   switch (Call->getDirectCallee()->getBuiltinID()) {
1092   case Builtin::BIread_pipe:
1093   case Builtin::BIreserve_read_pipe:
1094   case Builtin::BIcommit_read_pipe:
1095   case Builtin::BIwork_group_reserve_read_pipe:
1096   case Builtin::BIsub_group_reserve_read_pipe:
1097   case Builtin::BIwork_group_commit_read_pipe:
1098   case Builtin::BIsub_group_commit_read_pipe:
1099     if (!(!AccessQual || AccessQual->isReadOnly())) {
1100       S.Diag(Arg0->getBeginLoc(),
1101              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1102           << "read_only" << Arg0->getSourceRange();
1103       return true;
1104     }
1105     break;
1106   case Builtin::BIwrite_pipe:
1107   case Builtin::BIreserve_write_pipe:
1108   case Builtin::BIcommit_write_pipe:
1109   case Builtin::BIwork_group_reserve_write_pipe:
1110   case Builtin::BIsub_group_reserve_write_pipe:
1111   case Builtin::BIwork_group_commit_write_pipe:
1112   case Builtin::BIsub_group_commit_write_pipe:
1113     if (!(AccessQual && AccessQual->isWriteOnly())) {
1114       S.Diag(Arg0->getBeginLoc(),
1115              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1116           << "write_only" << Arg0->getSourceRange();
1117       return true;
1118     }
1119     break;
1120   default:
1121     break;
1122   }
1123   return false;
1124 }
1125 
1126 /// Returns true if pipe element type is different from the pointer.
1127 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
1128   const Expr *Arg0 = Call->getArg(0);
1129   const Expr *ArgIdx = Call->getArg(Idx);
1130   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
1131   const QualType EltTy = PipeTy->getElementType();
1132   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
1133   // The Idx argument should be a pointer and the type of the pointer and
1134   // the type of pipe element should also be the same.
1135   if (!ArgTy ||
1136       !S.Context.hasSameType(
1137           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
1138     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1139         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
1140         << ArgIdx->getType() << ArgIdx->getSourceRange();
1141     return true;
1142   }
1143   return false;
1144 }
1145 
1146 // Performs semantic analysis for the read/write_pipe call.
1147 // \param S Reference to the semantic analyzer.
1148 // \param Call A pointer to the builtin call.
1149 // \return True if a semantic error has been found, false otherwise.
1150 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
1151   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
1152   // functions have two forms.
1153   switch (Call->getNumArgs()) {
1154   case 2:
1155     if (checkOpenCLPipeArg(S, Call))
1156       return true;
1157     // The call with 2 arguments should be
1158     // read/write_pipe(pipe T, T*).
1159     // Check packet type T.
1160     if (checkOpenCLPipePacketType(S, Call, 1))
1161       return true;
1162     break;
1163 
1164   case 4: {
1165     if (checkOpenCLPipeArg(S, Call))
1166       return true;
1167     // The call with 4 arguments should be
1168     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
1169     // Check reserve_id_t.
1170     if (!Call->getArg(1)->getType()->isReserveIDT()) {
1171       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1172           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1173           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1174       return true;
1175     }
1176 
1177     // Check the index.
1178     const Expr *Arg2 = Call->getArg(2);
1179     if (!Arg2->getType()->isIntegerType() &&
1180         !Arg2->getType()->isUnsignedIntegerType()) {
1181       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1182           << Call->getDirectCallee() << S.Context.UnsignedIntTy
1183           << Arg2->getType() << Arg2->getSourceRange();
1184       return true;
1185     }
1186 
1187     // Check packet type T.
1188     if (checkOpenCLPipePacketType(S, Call, 3))
1189       return true;
1190   } break;
1191   default:
1192     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
1193         << Call->getDirectCallee() << Call->getSourceRange();
1194     return true;
1195   }
1196 
1197   return false;
1198 }
1199 
1200 // Performs a semantic analysis on the {work_group_/sub_group_
1201 //        /_}reserve_{read/write}_pipe
1202 // \param S Reference to the semantic analyzer.
1203 // \param Call The call to the builtin function to be analyzed.
1204 // \return True if a semantic error was found, false otherwise.
1205 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
1206   if (checkArgCount(S, Call, 2))
1207     return true;
1208 
1209   if (checkOpenCLPipeArg(S, Call))
1210     return true;
1211 
1212   // Check the reserve size.
1213   if (!Call->getArg(1)->getType()->isIntegerType() &&
1214       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
1215     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1216         << Call->getDirectCallee() << S.Context.UnsignedIntTy
1217         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1218     return true;
1219   }
1220 
1221   // Since return type of reserve_read/write_pipe built-in function is
1222   // reserve_id_t, which is not defined in the builtin def file , we used int
1223   // as return type and need to override the return type of these functions.
1224   Call->setType(S.Context.OCLReserveIDTy);
1225 
1226   return false;
1227 }
1228 
1229 // Performs a semantic analysis on {work_group_/sub_group_
1230 //        /_}commit_{read/write}_pipe
1231 // \param S Reference to the semantic analyzer.
1232 // \param Call The call to the builtin function to be analyzed.
1233 // \return True if a semantic error was found, false otherwise.
1234 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
1235   if (checkArgCount(S, Call, 2))
1236     return true;
1237 
1238   if (checkOpenCLPipeArg(S, Call))
1239     return true;
1240 
1241   // Check reserve_id_t.
1242   if (!Call->getArg(1)->getType()->isReserveIDT()) {
1243     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1244         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1245         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1246     return true;
1247   }
1248 
1249   return false;
1250 }
1251 
1252 // Performs a semantic analysis on the call to built-in Pipe
1253 //        Query Functions.
1254 // \param S Reference to the semantic analyzer.
1255 // \param Call The call to the builtin function to be analyzed.
1256 // \return True if a semantic error was found, false otherwise.
1257 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
1258   if (checkArgCount(S, Call, 1))
1259     return true;
1260 
1261   if (!Call->getArg(0)->getType()->isPipeType()) {
1262     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1263         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
1264     return true;
1265   }
1266 
1267   return false;
1268 }
1269 
1270 // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
1271 // Performs semantic analysis for the to_global/local/private call.
1272 // \param S Reference to the semantic analyzer.
1273 // \param BuiltinID ID of the builtin function.
1274 // \param Call A pointer to the builtin call.
1275 // \return True if a semantic error has been found, false otherwise.
1276 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
1277                                     CallExpr *Call) {
1278   if (checkArgCount(S, Call, 1))
1279     return true;
1280 
1281   auto RT = Call->getArg(0)->getType();
1282   if (!RT->isPointerType() || RT->getPointeeType()
1283       .getAddressSpace() == LangAS::opencl_constant) {
1284     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
1285         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
1286     return true;
1287   }
1288 
1289   if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
1290     S.Diag(Call->getArg(0)->getBeginLoc(),
1291            diag::warn_opencl_generic_address_space_arg)
1292         << Call->getDirectCallee()->getNameInfo().getAsString()
1293         << Call->getArg(0)->getSourceRange();
1294   }
1295 
1296   RT = RT->getPointeeType();
1297   auto Qual = RT.getQualifiers();
1298   switch (BuiltinID) {
1299   case Builtin::BIto_global:
1300     Qual.setAddressSpace(LangAS::opencl_global);
1301     break;
1302   case Builtin::BIto_local:
1303     Qual.setAddressSpace(LangAS::opencl_local);
1304     break;
1305   case Builtin::BIto_private:
1306     Qual.setAddressSpace(LangAS::opencl_private);
1307     break;
1308   default:
1309     llvm_unreachable("Invalid builtin function");
1310   }
1311   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
1312       RT.getUnqualifiedType(), Qual)));
1313 
1314   return false;
1315 }
1316 
1317 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
1318   if (checkArgCount(S, TheCall, 1))
1319     return ExprError();
1320 
1321   // Compute __builtin_launder's parameter type from the argument.
1322   // The parameter type is:
1323   //  * The type of the argument if it's not an array or function type,
1324   //  Otherwise,
1325   //  * The decayed argument type.
1326   QualType ParamTy = [&]() {
1327     QualType ArgTy = TheCall->getArg(0)->getType();
1328     if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1329       return S.Context.getPointerType(Ty->getElementType());
1330     if (ArgTy->isFunctionType()) {
1331       return S.Context.getPointerType(ArgTy);
1332     }
1333     return ArgTy;
1334   }();
1335 
1336   TheCall->setType(ParamTy);
1337 
1338   auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
1339     if (!ParamTy->isPointerType())
1340       return 0;
1341     if (ParamTy->isFunctionPointerType())
1342       return 1;
1343     if (ParamTy->isVoidPointerType())
1344       return 2;
1345     return llvm::Optional<unsigned>{};
1346   }();
1347   if (DiagSelect.hasValue()) {
1348     S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1349         << DiagSelect.getValue() << TheCall->getSourceRange();
1350     return ExprError();
1351   }
1352 
1353   // We either have an incomplete class type, or we have a class template
1354   // whose instantiation has not been forced. Example:
1355   //
1356   //   template <class T> struct Foo { T value; };
1357   //   Foo<int> *p = nullptr;
1358   //   auto *d = __builtin_launder(p);
1359   if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1360                             diag::err_incomplete_type))
1361     return ExprError();
1362 
1363   assert(ParamTy->getPointeeType()->isObjectType() &&
1364          "Unhandled non-object pointer case");
1365 
1366   InitializedEntity Entity =
1367       InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
1368   ExprResult Arg =
1369       S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1370   if (Arg.isInvalid())
1371     return ExprError();
1372   TheCall->setArg(0, Arg.get());
1373 
1374   return TheCall;
1375 }
1376 
1377 // Emit an error and return true if the current architecture is not in the list
1378 // of supported architectures.
1379 static bool
1380 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1381                           ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
1382   llvm::Triple::ArchType CurArch =
1383       S.getASTContext().getTargetInfo().getTriple().getArch();
1384   if (llvm::is_contained(SupportedArchs, CurArch))
1385     return false;
1386   S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1387       << TheCall->getSourceRange();
1388   return true;
1389 }
1390 
1391 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
1392                                  SourceLocation CallSiteLoc);
1393 
1394 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
1395                                       CallExpr *TheCall) {
1396   switch (TI.getTriple().getArch()) {
1397   default:
1398     // Some builtins don't require additional checking, so just consider these
1399     // acceptable.
1400     return false;
1401   case llvm::Triple::arm:
1402   case llvm::Triple::armeb:
1403   case llvm::Triple::thumb:
1404   case llvm::Triple::thumbeb:
1405     return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
1406   case llvm::Triple::aarch64:
1407   case llvm::Triple::aarch64_32:
1408   case llvm::Triple::aarch64_be:
1409     return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
1410   case llvm::Triple::bpfeb:
1411   case llvm::Triple::bpfel:
1412     return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
1413   case llvm::Triple::hexagon:
1414     return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
1415   case llvm::Triple::mips:
1416   case llvm::Triple::mipsel:
1417   case llvm::Triple::mips64:
1418   case llvm::Triple::mips64el:
1419     return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
1420   case llvm::Triple::systemz:
1421     return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
1422   case llvm::Triple::x86:
1423   case llvm::Triple::x86_64:
1424     return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall);
1425   case llvm::Triple::ppc:
1426   case llvm::Triple::ppcle:
1427   case llvm::Triple::ppc64:
1428   case llvm::Triple::ppc64le:
1429     return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
1430   case llvm::Triple::amdgcn:
1431     return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
1432   }
1433 }
1434 
1435 ExprResult
1436 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
1437                                CallExpr *TheCall) {
1438   ExprResult TheCallResult(TheCall);
1439 
1440   // Find out if any arguments are required to be integer constant expressions.
1441   unsigned ICEArguments = 0;
1442   ASTContext::GetBuiltinTypeError Error;
1443   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
1444   if (Error != ASTContext::GE_None)
1445     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
1446 
1447   // If any arguments are required to be ICE's, check and diagnose.
1448   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
1449     // Skip arguments not required to be ICE's.
1450     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
1451 
1452     llvm::APSInt Result;
1453     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
1454       return true;
1455     ICEArguments &= ~(1 << ArgNo);
1456   }
1457 
1458   switch (BuiltinID) {
1459   case Builtin::BI__builtin___CFStringMakeConstantString:
1460     assert(TheCall->getNumArgs() == 1 &&
1461            "Wrong # arguments to builtin CFStringMakeConstantString");
1462     if (CheckObjCString(TheCall->getArg(0)))
1463       return ExprError();
1464     break;
1465   case Builtin::BI__builtin_ms_va_start:
1466   case Builtin::BI__builtin_stdarg_start:
1467   case Builtin::BI__builtin_va_start:
1468     if (SemaBuiltinVAStart(BuiltinID, TheCall))
1469       return ExprError();
1470     break;
1471   case Builtin::BI__va_start: {
1472     switch (Context.getTargetInfo().getTriple().getArch()) {
1473     case llvm::Triple::aarch64:
1474     case llvm::Triple::arm:
1475     case llvm::Triple::thumb:
1476       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
1477         return ExprError();
1478       break;
1479     default:
1480       if (SemaBuiltinVAStart(BuiltinID, TheCall))
1481         return ExprError();
1482       break;
1483     }
1484     break;
1485   }
1486 
1487   // The acquire, release, and no fence variants are ARM and AArch64 only.
1488   case Builtin::BI_interlockedbittestandset_acq:
1489   case Builtin::BI_interlockedbittestandset_rel:
1490   case Builtin::BI_interlockedbittestandset_nf:
1491   case Builtin::BI_interlockedbittestandreset_acq:
1492   case Builtin::BI_interlockedbittestandreset_rel:
1493   case Builtin::BI_interlockedbittestandreset_nf:
1494     if (CheckBuiltinTargetSupport(
1495             *this, BuiltinID, TheCall,
1496             {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
1497       return ExprError();
1498     break;
1499 
1500   // The 64-bit bittest variants are x64, ARM, and AArch64 only.
1501   case Builtin::BI_bittest64:
1502   case Builtin::BI_bittestandcomplement64:
1503   case Builtin::BI_bittestandreset64:
1504   case Builtin::BI_bittestandset64:
1505   case Builtin::BI_interlockedbittestandreset64:
1506   case Builtin::BI_interlockedbittestandset64:
1507     if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
1508                                   {llvm::Triple::x86_64, llvm::Triple::arm,
1509                                    llvm::Triple::thumb, llvm::Triple::aarch64}))
1510       return ExprError();
1511     break;
1512 
1513   case Builtin::BI__builtin_isgreater:
1514   case Builtin::BI__builtin_isgreaterequal:
1515   case Builtin::BI__builtin_isless:
1516   case Builtin::BI__builtin_islessequal:
1517   case Builtin::BI__builtin_islessgreater:
1518   case Builtin::BI__builtin_isunordered:
1519     if (SemaBuiltinUnorderedCompare(TheCall))
1520       return ExprError();
1521     break;
1522   case Builtin::BI__builtin_fpclassify:
1523     if (SemaBuiltinFPClassification(TheCall, 6))
1524       return ExprError();
1525     break;
1526   case Builtin::BI__builtin_isfinite:
1527   case Builtin::BI__builtin_isinf:
1528   case Builtin::BI__builtin_isinf_sign:
1529   case Builtin::BI__builtin_isnan:
1530   case Builtin::BI__builtin_isnormal:
1531   case Builtin::BI__builtin_signbit:
1532   case Builtin::BI__builtin_signbitf:
1533   case Builtin::BI__builtin_signbitl:
1534     if (SemaBuiltinFPClassification(TheCall, 1))
1535       return ExprError();
1536     break;
1537   case Builtin::BI__builtin_shufflevector:
1538     return SemaBuiltinShuffleVector(TheCall);
1539     // TheCall will be freed by the smart pointer here, but that's fine, since
1540     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1541   case Builtin::BI__builtin_prefetch:
1542     if (SemaBuiltinPrefetch(TheCall))
1543       return ExprError();
1544     break;
1545   case Builtin::BI__builtin_alloca_with_align:
1546     if (SemaBuiltinAllocaWithAlign(TheCall))
1547       return ExprError();
1548     LLVM_FALLTHROUGH;
1549   case Builtin::BI__builtin_alloca:
1550     Diag(TheCall->getBeginLoc(), diag::warn_alloca)
1551         << TheCall->getDirectCallee();
1552     break;
1553   case Builtin::BI__assume:
1554   case Builtin::BI__builtin_assume:
1555     if (SemaBuiltinAssume(TheCall))
1556       return ExprError();
1557     break;
1558   case Builtin::BI__builtin_assume_aligned:
1559     if (SemaBuiltinAssumeAligned(TheCall))
1560       return ExprError();
1561     break;
1562   case Builtin::BI__builtin_dynamic_object_size:
1563   case Builtin::BI__builtin_object_size:
1564     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1565       return ExprError();
1566     break;
1567   case Builtin::BI__builtin_longjmp:
1568     if (SemaBuiltinLongjmp(TheCall))
1569       return ExprError();
1570     break;
1571   case Builtin::BI__builtin_setjmp:
1572     if (SemaBuiltinSetjmp(TheCall))
1573       return ExprError();
1574     break;
1575   case Builtin::BI__builtin_classify_type:
1576     if (checkArgCount(*this, TheCall, 1)) return true;
1577     TheCall->setType(Context.IntTy);
1578     break;
1579   case Builtin::BI__builtin_complex:
1580     if (SemaBuiltinComplex(TheCall))
1581       return ExprError();
1582     break;
1583   case Builtin::BI__builtin_constant_p: {
1584     if (checkArgCount(*this, TheCall, 1)) return true;
1585     ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
1586     if (Arg.isInvalid()) return true;
1587     TheCall->setArg(0, Arg.get());
1588     TheCall->setType(Context.IntTy);
1589     break;
1590   }
1591   case Builtin::BI__builtin_launder:
1592     return SemaBuiltinLaunder(*this, TheCall);
1593   case Builtin::BI__sync_fetch_and_add:
1594   case Builtin::BI__sync_fetch_and_add_1:
1595   case Builtin::BI__sync_fetch_and_add_2:
1596   case Builtin::BI__sync_fetch_and_add_4:
1597   case Builtin::BI__sync_fetch_and_add_8:
1598   case Builtin::BI__sync_fetch_and_add_16:
1599   case Builtin::BI__sync_fetch_and_sub:
1600   case Builtin::BI__sync_fetch_and_sub_1:
1601   case Builtin::BI__sync_fetch_and_sub_2:
1602   case Builtin::BI__sync_fetch_and_sub_4:
1603   case Builtin::BI__sync_fetch_and_sub_8:
1604   case Builtin::BI__sync_fetch_and_sub_16:
1605   case Builtin::BI__sync_fetch_and_or:
1606   case Builtin::BI__sync_fetch_and_or_1:
1607   case Builtin::BI__sync_fetch_and_or_2:
1608   case Builtin::BI__sync_fetch_and_or_4:
1609   case Builtin::BI__sync_fetch_and_or_8:
1610   case Builtin::BI__sync_fetch_and_or_16:
1611   case Builtin::BI__sync_fetch_and_and:
1612   case Builtin::BI__sync_fetch_and_and_1:
1613   case Builtin::BI__sync_fetch_and_and_2:
1614   case Builtin::BI__sync_fetch_and_and_4:
1615   case Builtin::BI__sync_fetch_and_and_8:
1616   case Builtin::BI__sync_fetch_and_and_16:
1617   case Builtin::BI__sync_fetch_and_xor:
1618   case Builtin::BI__sync_fetch_and_xor_1:
1619   case Builtin::BI__sync_fetch_and_xor_2:
1620   case Builtin::BI__sync_fetch_and_xor_4:
1621   case Builtin::BI__sync_fetch_and_xor_8:
1622   case Builtin::BI__sync_fetch_and_xor_16:
1623   case Builtin::BI__sync_fetch_and_nand:
1624   case Builtin::BI__sync_fetch_and_nand_1:
1625   case Builtin::BI__sync_fetch_and_nand_2:
1626   case Builtin::BI__sync_fetch_and_nand_4:
1627   case Builtin::BI__sync_fetch_and_nand_8:
1628   case Builtin::BI__sync_fetch_and_nand_16:
1629   case Builtin::BI__sync_add_and_fetch:
1630   case Builtin::BI__sync_add_and_fetch_1:
1631   case Builtin::BI__sync_add_and_fetch_2:
1632   case Builtin::BI__sync_add_and_fetch_4:
1633   case Builtin::BI__sync_add_and_fetch_8:
1634   case Builtin::BI__sync_add_and_fetch_16:
1635   case Builtin::BI__sync_sub_and_fetch:
1636   case Builtin::BI__sync_sub_and_fetch_1:
1637   case Builtin::BI__sync_sub_and_fetch_2:
1638   case Builtin::BI__sync_sub_and_fetch_4:
1639   case Builtin::BI__sync_sub_and_fetch_8:
1640   case Builtin::BI__sync_sub_and_fetch_16:
1641   case Builtin::BI__sync_and_and_fetch:
1642   case Builtin::BI__sync_and_and_fetch_1:
1643   case Builtin::BI__sync_and_and_fetch_2:
1644   case Builtin::BI__sync_and_and_fetch_4:
1645   case Builtin::BI__sync_and_and_fetch_8:
1646   case Builtin::BI__sync_and_and_fetch_16:
1647   case Builtin::BI__sync_or_and_fetch:
1648   case Builtin::BI__sync_or_and_fetch_1:
1649   case Builtin::BI__sync_or_and_fetch_2:
1650   case Builtin::BI__sync_or_and_fetch_4:
1651   case Builtin::BI__sync_or_and_fetch_8:
1652   case Builtin::BI__sync_or_and_fetch_16:
1653   case Builtin::BI__sync_xor_and_fetch:
1654   case Builtin::BI__sync_xor_and_fetch_1:
1655   case Builtin::BI__sync_xor_and_fetch_2:
1656   case Builtin::BI__sync_xor_and_fetch_4:
1657   case Builtin::BI__sync_xor_and_fetch_8:
1658   case Builtin::BI__sync_xor_and_fetch_16:
1659   case Builtin::BI__sync_nand_and_fetch:
1660   case Builtin::BI__sync_nand_and_fetch_1:
1661   case Builtin::BI__sync_nand_and_fetch_2:
1662   case Builtin::BI__sync_nand_and_fetch_4:
1663   case Builtin::BI__sync_nand_and_fetch_8:
1664   case Builtin::BI__sync_nand_and_fetch_16:
1665   case Builtin::BI__sync_val_compare_and_swap:
1666   case Builtin::BI__sync_val_compare_and_swap_1:
1667   case Builtin::BI__sync_val_compare_and_swap_2:
1668   case Builtin::BI__sync_val_compare_and_swap_4:
1669   case Builtin::BI__sync_val_compare_and_swap_8:
1670   case Builtin::BI__sync_val_compare_and_swap_16:
1671   case Builtin::BI__sync_bool_compare_and_swap:
1672   case Builtin::BI__sync_bool_compare_and_swap_1:
1673   case Builtin::BI__sync_bool_compare_and_swap_2:
1674   case Builtin::BI__sync_bool_compare_and_swap_4:
1675   case Builtin::BI__sync_bool_compare_and_swap_8:
1676   case Builtin::BI__sync_bool_compare_and_swap_16:
1677   case Builtin::BI__sync_lock_test_and_set:
1678   case Builtin::BI__sync_lock_test_and_set_1:
1679   case Builtin::BI__sync_lock_test_and_set_2:
1680   case Builtin::BI__sync_lock_test_and_set_4:
1681   case Builtin::BI__sync_lock_test_and_set_8:
1682   case Builtin::BI__sync_lock_test_and_set_16:
1683   case Builtin::BI__sync_lock_release:
1684   case Builtin::BI__sync_lock_release_1:
1685   case Builtin::BI__sync_lock_release_2:
1686   case Builtin::BI__sync_lock_release_4:
1687   case Builtin::BI__sync_lock_release_8:
1688   case Builtin::BI__sync_lock_release_16:
1689   case Builtin::BI__sync_swap:
1690   case Builtin::BI__sync_swap_1:
1691   case Builtin::BI__sync_swap_2:
1692   case Builtin::BI__sync_swap_4:
1693   case Builtin::BI__sync_swap_8:
1694   case Builtin::BI__sync_swap_16:
1695     return SemaBuiltinAtomicOverloaded(TheCallResult);
1696   case Builtin::BI__sync_synchronize:
1697     Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1698         << TheCall->getCallee()->getSourceRange();
1699     break;
1700   case Builtin::BI__builtin_nontemporal_load:
1701   case Builtin::BI__builtin_nontemporal_store:
1702     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1703   case Builtin::BI__builtin_memcpy_inline: {
1704     clang::Expr *SizeOp = TheCall->getArg(2);
1705     // We warn about copying to or from `nullptr` pointers when `size` is
1706     // greater than 0. When `size` is value dependent we cannot evaluate its
1707     // value so we bail out.
1708     if (SizeOp->isValueDependent())
1709       break;
1710     if (!SizeOp->EvaluateKnownConstInt(Context).isNullValue()) {
1711       CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
1712       CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
1713     }
1714     break;
1715   }
1716 #define BUILTIN(ID, TYPE, ATTRS)
1717 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1718   case Builtin::BI##ID: \
1719     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1720 #include "clang/Basic/Builtins.def"
1721   case Builtin::BI__annotation:
1722     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1723       return ExprError();
1724     break;
1725   case Builtin::BI__builtin_annotation:
1726     if (SemaBuiltinAnnotation(*this, TheCall))
1727       return ExprError();
1728     break;
1729   case Builtin::BI__builtin_addressof:
1730     if (SemaBuiltinAddressof(*this, TheCall))
1731       return ExprError();
1732     break;
1733   case Builtin::BI__builtin_is_aligned:
1734   case Builtin::BI__builtin_align_up:
1735   case Builtin::BI__builtin_align_down:
1736     if (SemaBuiltinAlignment(*this, TheCall, BuiltinID))
1737       return ExprError();
1738     break;
1739   case Builtin::BI__builtin_add_overflow:
1740   case Builtin::BI__builtin_sub_overflow:
1741   case Builtin::BI__builtin_mul_overflow:
1742     if (SemaBuiltinOverflow(*this, TheCall, BuiltinID))
1743       return ExprError();
1744     break;
1745   case Builtin::BI__builtin_operator_new:
1746   case Builtin::BI__builtin_operator_delete: {
1747     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1748     ExprResult Res =
1749         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1750     if (Res.isInvalid())
1751       CorrectDelayedTyposInExpr(TheCallResult.get());
1752     return Res;
1753   }
1754   case Builtin::BI__builtin_dump_struct: {
1755     // We first want to ensure we are called with 2 arguments
1756     if (checkArgCount(*this, TheCall, 2))
1757       return ExprError();
1758     // Ensure that the first argument is of type 'struct XX *'
1759     const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1760     const QualType PtrArgType = PtrArg->getType();
1761     if (!PtrArgType->isPointerType() ||
1762         !PtrArgType->getPointeeType()->isRecordType()) {
1763       Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1764           << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1765           << "structure pointer";
1766       return ExprError();
1767     }
1768 
1769     // Ensure that the second argument is of type 'FunctionType'
1770     const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1771     const QualType FnPtrArgType = FnPtrArg->getType();
1772     if (!FnPtrArgType->isPointerType()) {
1773       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1774           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1775           << FnPtrArgType << "'int (*)(const char *, ...)'";
1776       return ExprError();
1777     }
1778 
1779     const auto *FuncType =
1780         FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1781 
1782     if (!FuncType) {
1783       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1784           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1785           << FnPtrArgType << "'int (*)(const char *, ...)'";
1786       return ExprError();
1787     }
1788 
1789     if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1790       if (!FT->getNumParams()) {
1791         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1792             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1793             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1794         return ExprError();
1795       }
1796       QualType PT = FT->getParamType(0);
1797       if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1798           !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1799           !PT->getPointeeType().isConstQualified()) {
1800         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1801             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1802             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1803         return ExprError();
1804       }
1805     }
1806 
1807     TheCall->setType(Context.IntTy);
1808     break;
1809   }
1810   case Builtin::BI__builtin_expect_with_probability: {
1811     // We first want to ensure we are called with 3 arguments
1812     if (checkArgCount(*this, TheCall, 3))
1813       return ExprError();
1814     // then check probability is constant float in range [0.0, 1.0]
1815     const Expr *ProbArg = TheCall->getArg(2);
1816     SmallVector<PartialDiagnosticAt, 8> Notes;
1817     Expr::EvalResult Eval;
1818     Eval.Diag = &Notes;
1819     if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
1820         !Eval.Val.isFloat()) {
1821       Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
1822           << ProbArg->getSourceRange();
1823       for (const PartialDiagnosticAt &PDiag : Notes)
1824         Diag(PDiag.first, PDiag.second);
1825       return ExprError();
1826     }
1827     llvm::APFloat Probability = Eval.Val.getFloat();
1828     bool LoseInfo = false;
1829     Probability.convert(llvm::APFloat::IEEEdouble(),
1830                         llvm::RoundingMode::Dynamic, &LoseInfo);
1831     if (!(Probability >= llvm::APFloat(0.0) &&
1832           Probability <= llvm::APFloat(1.0))) {
1833       Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
1834           << ProbArg->getSourceRange();
1835       return ExprError();
1836     }
1837     break;
1838   }
1839   case Builtin::BI__builtin_preserve_access_index:
1840     if (SemaBuiltinPreserveAI(*this, TheCall))
1841       return ExprError();
1842     break;
1843   case Builtin::BI__builtin_call_with_static_chain:
1844     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1845       return ExprError();
1846     break;
1847   case Builtin::BI__exception_code:
1848   case Builtin::BI_exception_code:
1849     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1850                                  diag::err_seh___except_block))
1851       return ExprError();
1852     break;
1853   case Builtin::BI__exception_info:
1854   case Builtin::BI_exception_info:
1855     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1856                                  diag::err_seh___except_filter))
1857       return ExprError();
1858     break;
1859   case Builtin::BI__GetExceptionInfo:
1860     if (checkArgCount(*this, TheCall, 1))
1861       return ExprError();
1862 
1863     if (CheckCXXThrowOperand(
1864             TheCall->getBeginLoc(),
1865             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1866             TheCall))
1867       return ExprError();
1868 
1869     TheCall->setType(Context.VoidPtrTy);
1870     break;
1871   // OpenCL v2.0, s6.13.16 - Pipe functions
1872   case Builtin::BIread_pipe:
1873   case Builtin::BIwrite_pipe:
1874     // Since those two functions are declared with var args, we need a semantic
1875     // check for the argument.
1876     if (SemaBuiltinRWPipe(*this, TheCall))
1877       return ExprError();
1878     break;
1879   case Builtin::BIreserve_read_pipe:
1880   case Builtin::BIreserve_write_pipe:
1881   case Builtin::BIwork_group_reserve_read_pipe:
1882   case Builtin::BIwork_group_reserve_write_pipe:
1883     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1884       return ExprError();
1885     break;
1886   case Builtin::BIsub_group_reserve_read_pipe:
1887   case Builtin::BIsub_group_reserve_write_pipe:
1888     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1889         SemaBuiltinReserveRWPipe(*this, TheCall))
1890       return ExprError();
1891     break;
1892   case Builtin::BIcommit_read_pipe:
1893   case Builtin::BIcommit_write_pipe:
1894   case Builtin::BIwork_group_commit_read_pipe:
1895   case Builtin::BIwork_group_commit_write_pipe:
1896     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1897       return ExprError();
1898     break;
1899   case Builtin::BIsub_group_commit_read_pipe:
1900   case Builtin::BIsub_group_commit_write_pipe:
1901     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1902         SemaBuiltinCommitRWPipe(*this, TheCall))
1903       return ExprError();
1904     break;
1905   case Builtin::BIget_pipe_num_packets:
1906   case Builtin::BIget_pipe_max_packets:
1907     if (SemaBuiltinPipePackets(*this, TheCall))
1908       return ExprError();
1909     break;
1910   case Builtin::BIto_global:
1911   case Builtin::BIto_local:
1912   case Builtin::BIto_private:
1913     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1914       return ExprError();
1915     break;
1916   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1917   case Builtin::BIenqueue_kernel:
1918     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1919       return ExprError();
1920     break;
1921   case Builtin::BIget_kernel_work_group_size:
1922   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1923     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1924       return ExprError();
1925     break;
1926   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1927   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1928     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1929       return ExprError();
1930     break;
1931   case Builtin::BI__builtin_os_log_format:
1932     Cleanup.setExprNeedsCleanups(true);
1933     LLVM_FALLTHROUGH;
1934   case Builtin::BI__builtin_os_log_format_buffer_size:
1935     if (SemaBuiltinOSLogFormat(TheCall))
1936       return ExprError();
1937     break;
1938   case Builtin::BI__builtin_frame_address:
1939   case Builtin::BI__builtin_return_address: {
1940     if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
1941       return ExprError();
1942 
1943     // -Wframe-address warning if non-zero passed to builtin
1944     // return/frame address.
1945     Expr::EvalResult Result;
1946     if (TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
1947         Result.Val.getInt() != 0)
1948       Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
1949           << ((BuiltinID == Builtin::BI__builtin_return_address)
1950                   ? "__builtin_return_address"
1951                   : "__builtin_frame_address")
1952           << TheCall->getSourceRange();
1953     break;
1954   }
1955 
1956   case Builtin::BI__builtin_matrix_transpose:
1957     return SemaBuiltinMatrixTranspose(TheCall, TheCallResult);
1958 
1959   case Builtin::BI__builtin_matrix_column_major_load:
1960     return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
1961 
1962   case Builtin::BI__builtin_matrix_column_major_store:
1963     return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
1964   }
1965 
1966   // Since the target specific builtins for each arch overlap, only check those
1967   // of the arch we are compiling for.
1968   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1969     if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
1970       assert(Context.getAuxTargetInfo() &&
1971              "Aux Target Builtin, but not an aux target?");
1972 
1973       if (CheckTSBuiltinFunctionCall(
1974               *Context.getAuxTargetInfo(),
1975               Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
1976         return ExprError();
1977     } else {
1978       if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
1979                                      TheCall))
1980         return ExprError();
1981     }
1982   }
1983 
1984   return TheCallResult;
1985 }
1986 
1987 // Get the valid immediate range for the specified NEON type code.
1988 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1989   NeonTypeFlags Type(t);
1990   int IsQuad = ForceQuad ? true : Type.isQuad();
1991   switch (Type.getEltType()) {
1992   case NeonTypeFlags::Int8:
1993   case NeonTypeFlags::Poly8:
1994     return shift ? 7 : (8 << IsQuad) - 1;
1995   case NeonTypeFlags::Int16:
1996   case NeonTypeFlags::Poly16:
1997     return shift ? 15 : (4 << IsQuad) - 1;
1998   case NeonTypeFlags::Int32:
1999     return shift ? 31 : (2 << IsQuad) - 1;
2000   case NeonTypeFlags::Int64:
2001   case NeonTypeFlags::Poly64:
2002     return shift ? 63 : (1 << IsQuad) - 1;
2003   case NeonTypeFlags::Poly128:
2004     return shift ? 127 : (1 << IsQuad) - 1;
2005   case NeonTypeFlags::Float16:
2006     assert(!shift && "cannot shift float types!");
2007     return (4 << IsQuad) - 1;
2008   case NeonTypeFlags::Float32:
2009     assert(!shift && "cannot shift float types!");
2010     return (2 << IsQuad) - 1;
2011   case NeonTypeFlags::Float64:
2012     assert(!shift && "cannot shift float types!");
2013     return (1 << IsQuad) - 1;
2014   case NeonTypeFlags::BFloat16:
2015     assert(!shift && "cannot shift float types!");
2016     return (4 << IsQuad) - 1;
2017   }
2018   llvm_unreachable("Invalid NeonTypeFlag!");
2019 }
2020 
2021 /// getNeonEltType - Return the QualType corresponding to the elements of
2022 /// the vector type specified by the NeonTypeFlags.  This is used to check
2023 /// the pointer arguments for Neon load/store intrinsics.
2024 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
2025                                bool IsPolyUnsigned, bool IsInt64Long) {
2026   switch (Flags.getEltType()) {
2027   case NeonTypeFlags::Int8:
2028     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
2029   case NeonTypeFlags::Int16:
2030     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
2031   case NeonTypeFlags::Int32:
2032     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
2033   case NeonTypeFlags::Int64:
2034     if (IsInt64Long)
2035       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
2036     else
2037       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
2038                                 : Context.LongLongTy;
2039   case NeonTypeFlags::Poly8:
2040     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
2041   case NeonTypeFlags::Poly16:
2042     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
2043   case NeonTypeFlags::Poly64:
2044     if (IsInt64Long)
2045       return Context.UnsignedLongTy;
2046     else
2047       return Context.UnsignedLongLongTy;
2048   case NeonTypeFlags::Poly128:
2049     break;
2050   case NeonTypeFlags::Float16:
2051     return Context.HalfTy;
2052   case NeonTypeFlags::Float32:
2053     return Context.FloatTy;
2054   case NeonTypeFlags::Float64:
2055     return Context.DoubleTy;
2056   case NeonTypeFlags::BFloat16:
2057     return Context.BFloat16Ty;
2058   }
2059   llvm_unreachable("Invalid NeonTypeFlag!");
2060 }
2061 
2062 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2063   // Range check SVE intrinsics that take immediate values.
2064   SmallVector<std::tuple<int,int,int>, 3> ImmChecks;
2065 
2066   switch (BuiltinID) {
2067   default:
2068     return false;
2069 #define GET_SVE_IMMEDIATE_CHECK
2070 #include "clang/Basic/arm_sve_sema_rangechecks.inc"
2071 #undef GET_SVE_IMMEDIATE_CHECK
2072   }
2073 
2074   // Perform all the immediate checks for this builtin call.
2075   bool HasError = false;
2076   for (auto &I : ImmChecks) {
2077     int ArgNum, CheckTy, ElementSizeInBits;
2078     std::tie(ArgNum, CheckTy, ElementSizeInBits) = I;
2079 
2080     typedef bool(*OptionSetCheckFnTy)(int64_t Value);
2081 
2082     // Function that checks whether the operand (ArgNum) is an immediate
2083     // that is one of the predefined values.
2084     auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm,
2085                                    int ErrDiag) -> bool {
2086       // We can't check the value of a dependent argument.
2087       Expr *Arg = TheCall->getArg(ArgNum);
2088       if (Arg->isTypeDependent() || Arg->isValueDependent())
2089         return false;
2090 
2091       // Check constant-ness first.
2092       llvm::APSInt Imm;
2093       if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm))
2094         return true;
2095 
2096       if (!CheckImm(Imm.getSExtValue()))
2097         return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange();
2098       return false;
2099     };
2100 
2101     switch ((SVETypeFlags::ImmCheckType)CheckTy) {
2102     case SVETypeFlags::ImmCheck0_31:
2103       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31))
2104         HasError = true;
2105       break;
2106     case SVETypeFlags::ImmCheck0_13:
2107       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13))
2108         HasError = true;
2109       break;
2110     case SVETypeFlags::ImmCheck1_16:
2111       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16))
2112         HasError = true;
2113       break;
2114     case SVETypeFlags::ImmCheck0_7:
2115       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7))
2116         HasError = true;
2117       break;
2118     case SVETypeFlags::ImmCheckExtract:
2119       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2120                                       (2048 / ElementSizeInBits) - 1))
2121         HasError = true;
2122       break;
2123     case SVETypeFlags::ImmCheckShiftRight:
2124       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits))
2125         HasError = true;
2126       break;
2127     case SVETypeFlags::ImmCheckShiftRightNarrow:
2128       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1,
2129                                       ElementSizeInBits / 2))
2130         HasError = true;
2131       break;
2132     case SVETypeFlags::ImmCheckShiftLeft:
2133       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2134                                       ElementSizeInBits - 1))
2135         HasError = true;
2136       break;
2137     case SVETypeFlags::ImmCheckLaneIndex:
2138       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2139                                       (128 / (1 * ElementSizeInBits)) - 1))
2140         HasError = true;
2141       break;
2142     case SVETypeFlags::ImmCheckLaneIndexCompRotate:
2143       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2144                                       (128 / (2 * ElementSizeInBits)) - 1))
2145         HasError = true;
2146       break;
2147     case SVETypeFlags::ImmCheckLaneIndexDot:
2148       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2149                                       (128 / (4 * ElementSizeInBits)) - 1))
2150         HasError = true;
2151       break;
2152     case SVETypeFlags::ImmCheckComplexRot90_270:
2153       if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; },
2154                               diag::err_rotation_argument_to_cadd))
2155         HasError = true;
2156       break;
2157     case SVETypeFlags::ImmCheckComplexRotAll90:
2158       if (CheckImmediateInSet(
2159               [](int64_t V) {
2160                 return V == 0 || V == 90 || V == 180 || V == 270;
2161               },
2162               diag::err_rotation_argument_to_cmla))
2163         HasError = true;
2164       break;
2165     case SVETypeFlags::ImmCheck0_1:
2166       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1))
2167         HasError = true;
2168       break;
2169     case SVETypeFlags::ImmCheck0_2:
2170       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2))
2171         HasError = true;
2172       break;
2173     case SVETypeFlags::ImmCheck0_3:
2174       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3))
2175         HasError = true;
2176       break;
2177     }
2178   }
2179 
2180   return HasError;
2181 }
2182 
2183 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI,
2184                                         unsigned BuiltinID, CallExpr *TheCall) {
2185   llvm::APSInt Result;
2186   uint64_t mask = 0;
2187   unsigned TV = 0;
2188   int PtrArgNum = -1;
2189   bool HasConstPtr = false;
2190   switch (BuiltinID) {
2191 #define GET_NEON_OVERLOAD_CHECK
2192 #include "clang/Basic/arm_neon.inc"
2193 #include "clang/Basic/arm_fp16.inc"
2194 #undef GET_NEON_OVERLOAD_CHECK
2195   }
2196 
2197   // For NEON intrinsics which are overloaded on vector element type, validate
2198   // the immediate which specifies which variant to emit.
2199   unsigned ImmArg = TheCall->getNumArgs()-1;
2200   if (mask) {
2201     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
2202       return true;
2203 
2204     TV = Result.getLimitedValue(64);
2205     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
2206       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
2207              << TheCall->getArg(ImmArg)->getSourceRange();
2208   }
2209 
2210   if (PtrArgNum >= 0) {
2211     // Check that pointer arguments have the specified type.
2212     Expr *Arg = TheCall->getArg(PtrArgNum);
2213     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
2214       Arg = ICE->getSubExpr();
2215     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
2216     QualType RHSTy = RHS.get()->getType();
2217 
2218     llvm::Triple::ArchType Arch = TI.getTriple().getArch();
2219     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
2220                           Arch == llvm::Triple::aarch64_32 ||
2221                           Arch == llvm::Triple::aarch64_be;
2222     bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong;
2223     QualType EltTy =
2224         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
2225     if (HasConstPtr)
2226       EltTy = EltTy.withConst();
2227     QualType LHSTy = Context.getPointerType(EltTy);
2228     AssignConvertType ConvTy;
2229     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
2230     if (RHS.isInvalid())
2231       return true;
2232     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
2233                                  RHS.get(), AA_Assigning))
2234       return true;
2235   }
2236 
2237   // For NEON intrinsics which take an immediate value as part of the
2238   // instruction, range check them here.
2239   unsigned i = 0, l = 0, u = 0;
2240   switch (BuiltinID) {
2241   default:
2242     return false;
2243   #define GET_NEON_IMMEDIATE_CHECK
2244   #include "clang/Basic/arm_neon.inc"
2245   #include "clang/Basic/arm_fp16.inc"
2246   #undef GET_NEON_IMMEDIATE_CHECK
2247   }
2248 
2249   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2250 }
2251 
2252 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2253   switch (BuiltinID) {
2254   default:
2255     return false;
2256   #include "clang/Basic/arm_mve_builtin_sema.inc"
2257   }
2258 }
2259 
2260 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2261                                        CallExpr *TheCall) {
2262   bool Err = false;
2263   switch (BuiltinID) {
2264   default:
2265     return false;
2266 #include "clang/Basic/arm_cde_builtin_sema.inc"
2267   }
2268 
2269   if (Err)
2270     return true;
2271 
2272   return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true);
2273 }
2274 
2275 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI,
2276                                         const Expr *CoprocArg, bool WantCDE) {
2277   if (isConstantEvaluated())
2278     return false;
2279 
2280   // We can't check the value of a dependent argument.
2281   if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent())
2282     return false;
2283 
2284   llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context);
2285   int64_t CoprocNo = CoprocNoAP.getExtValue();
2286   assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative");
2287 
2288   uint32_t CDECoprocMask = TI.getARMCDECoprocMask();
2289   bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo));
2290 
2291   if (IsCDECoproc != WantCDE)
2292     return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc)
2293            << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange();
2294 
2295   return false;
2296 }
2297 
2298 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
2299                                         unsigned MaxWidth) {
2300   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
2301           BuiltinID == ARM::BI__builtin_arm_ldaex ||
2302           BuiltinID == ARM::BI__builtin_arm_strex ||
2303           BuiltinID == ARM::BI__builtin_arm_stlex ||
2304           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2305           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2306           BuiltinID == AArch64::BI__builtin_arm_strex ||
2307           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
2308          "unexpected ARM builtin");
2309   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
2310                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
2311                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2312                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
2313 
2314   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2315 
2316   // Ensure that we have the proper number of arguments.
2317   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
2318     return true;
2319 
2320   // Inspect the pointer argument of the atomic builtin.  This should always be
2321   // a pointer type, whose element is an integral scalar or pointer type.
2322   // Because it is a pointer type, we don't have to worry about any implicit
2323   // casts here.
2324   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
2325   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
2326   if (PointerArgRes.isInvalid())
2327     return true;
2328   PointerArg = PointerArgRes.get();
2329 
2330   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2331   if (!pointerType) {
2332     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
2333         << PointerArg->getType() << PointerArg->getSourceRange();
2334     return true;
2335   }
2336 
2337   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
2338   // task is to insert the appropriate casts into the AST. First work out just
2339   // what the appropriate type is.
2340   QualType ValType = pointerType->getPointeeType();
2341   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
2342   if (IsLdrex)
2343     AddrType.addConst();
2344 
2345   // Issue a warning if the cast is dodgy.
2346   CastKind CastNeeded = CK_NoOp;
2347   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
2348     CastNeeded = CK_BitCast;
2349     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
2350         << PointerArg->getType() << Context.getPointerType(AddrType)
2351         << AA_Passing << PointerArg->getSourceRange();
2352   }
2353 
2354   // Finally, do the cast and replace the argument with the corrected version.
2355   AddrType = Context.getPointerType(AddrType);
2356   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
2357   if (PointerArgRes.isInvalid())
2358     return true;
2359   PointerArg = PointerArgRes.get();
2360 
2361   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
2362 
2363   // In general, we allow ints, floats and pointers to be loaded and stored.
2364   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2365       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
2366     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
2367         << PointerArg->getType() << PointerArg->getSourceRange();
2368     return true;
2369   }
2370 
2371   // But ARM doesn't have instructions to deal with 128-bit versions.
2372   if (Context.getTypeSize(ValType) > MaxWidth) {
2373     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
2374     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
2375         << PointerArg->getType() << PointerArg->getSourceRange();
2376     return true;
2377   }
2378 
2379   switch (ValType.getObjCLifetime()) {
2380   case Qualifiers::OCL_None:
2381   case Qualifiers::OCL_ExplicitNone:
2382     // okay
2383     break;
2384 
2385   case Qualifiers::OCL_Weak:
2386   case Qualifiers::OCL_Strong:
2387   case Qualifiers::OCL_Autoreleasing:
2388     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
2389         << ValType << PointerArg->getSourceRange();
2390     return true;
2391   }
2392 
2393   if (IsLdrex) {
2394     TheCall->setType(ValType);
2395     return false;
2396   }
2397 
2398   // Initialize the argument to be stored.
2399   ExprResult ValArg = TheCall->getArg(0);
2400   InitializedEntity Entity = InitializedEntity::InitializeParameter(
2401       Context, ValType, /*consume*/ false);
2402   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2403   if (ValArg.isInvalid())
2404     return true;
2405   TheCall->setArg(0, ValArg.get());
2406 
2407   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
2408   // but the custom checker bypasses all default analysis.
2409   TheCall->setType(Context.IntTy);
2410   return false;
2411 }
2412 
2413 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2414                                        CallExpr *TheCall) {
2415   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
2416       BuiltinID == ARM::BI__builtin_arm_ldaex ||
2417       BuiltinID == ARM::BI__builtin_arm_strex ||
2418       BuiltinID == ARM::BI__builtin_arm_stlex) {
2419     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
2420   }
2421 
2422   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
2423     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2424       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
2425   }
2426 
2427   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2428       BuiltinID == ARM::BI__builtin_arm_wsr64)
2429     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
2430 
2431   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
2432       BuiltinID == ARM::BI__builtin_arm_rsrp ||
2433       BuiltinID == ARM::BI__builtin_arm_wsr ||
2434       BuiltinID == ARM::BI__builtin_arm_wsrp)
2435     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2436 
2437   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2438     return true;
2439   if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
2440     return true;
2441   if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall))
2442     return true;
2443 
2444   // For intrinsics which take an immediate value as part of the instruction,
2445   // range check them here.
2446   // FIXME: VFP Intrinsics should error if VFP not present.
2447   switch (BuiltinID) {
2448   default: return false;
2449   case ARM::BI__builtin_arm_ssat:
2450     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
2451   case ARM::BI__builtin_arm_usat:
2452     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
2453   case ARM::BI__builtin_arm_ssat16:
2454     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
2455   case ARM::BI__builtin_arm_usat16:
2456     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2457   case ARM::BI__builtin_arm_vcvtr_f:
2458   case ARM::BI__builtin_arm_vcvtr_d:
2459     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
2460   case ARM::BI__builtin_arm_dmb:
2461   case ARM::BI__builtin_arm_dsb:
2462   case ARM::BI__builtin_arm_isb:
2463   case ARM::BI__builtin_arm_dbg:
2464     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
2465   case ARM::BI__builtin_arm_cdp:
2466   case ARM::BI__builtin_arm_cdp2:
2467   case ARM::BI__builtin_arm_mcr:
2468   case ARM::BI__builtin_arm_mcr2:
2469   case ARM::BI__builtin_arm_mrc:
2470   case ARM::BI__builtin_arm_mrc2:
2471   case ARM::BI__builtin_arm_mcrr:
2472   case ARM::BI__builtin_arm_mcrr2:
2473   case ARM::BI__builtin_arm_mrrc:
2474   case ARM::BI__builtin_arm_mrrc2:
2475   case ARM::BI__builtin_arm_ldc:
2476   case ARM::BI__builtin_arm_ldcl:
2477   case ARM::BI__builtin_arm_ldc2:
2478   case ARM::BI__builtin_arm_ldc2l:
2479   case ARM::BI__builtin_arm_stc:
2480   case ARM::BI__builtin_arm_stcl:
2481   case ARM::BI__builtin_arm_stc2:
2482   case ARM::BI__builtin_arm_stc2l:
2483     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) ||
2484            CheckARMCoprocessorImmediate(TI, TheCall->getArg(0),
2485                                         /*WantCDE*/ false);
2486   }
2487 }
2488 
2489 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI,
2490                                            unsigned BuiltinID,
2491                                            CallExpr *TheCall) {
2492   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2493       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2494       BuiltinID == AArch64::BI__builtin_arm_strex ||
2495       BuiltinID == AArch64::BI__builtin_arm_stlex) {
2496     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
2497   }
2498 
2499   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
2500     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2501       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
2502       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
2503       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
2504   }
2505 
2506   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2507       BuiltinID == AArch64::BI__builtin_arm_wsr64)
2508     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2509 
2510   // Memory Tagging Extensions (MTE) Intrinsics
2511   if (BuiltinID == AArch64::BI__builtin_arm_irg ||
2512       BuiltinID == AArch64::BI__builtin_arm_addg ||
2513       BuiltinID == AArch64::BI__builtin_arm_gmi ||
2514       BuiltinID == AArch64::BI__builtin_arm_ldg ||
2515       BuiltinID == AArch64::BI__builtin_arm_stg ||
2516       BuiltinID == AArch64::BI__builtin_arm_subp) {
2517     return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
2518   }
2519 
2520   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
2521       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2522       BuiltinID == AArch64::BI__builtin_arm_wsr ||
2523       BuiltinID == AArch64::BI__builtin_arm_wsrp)
2524     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2525 
2526   // Only check the valid encoding range. Any constant in this range would be
2527   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
2528   // an exception for incorrect registers. This matches MSVC behavior.
2529   if (BuiltinID == AArch64::BI_ReadStatusReg ||
2530       BuiltinID == AArch64::BI_WriteStatusReg)
2531     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
2532 
2533   if (BuiltinID == AArch64::BI__getReg)
2534     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
2535 
2536   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2537     return true;
2538 
2539   if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall))
2540     return true;
2541 
2542   // For intrinsics which take an immediate value as part of the instruction,
2543   // range check them here.
2544   unsigned i = 0, l = 0, u = 0;
2545   switch (BuiltinID) {
2546   default: return false;
2547   case AArch64::BI__builtin_arm_dmb:
2548   case AArch64::BI__builtin_arm_dsb:
2549   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
2550   case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
2551   }
2552 
2553   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2554 }
2555 
2556 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) {
2557   if (Arg->getType()->getAsPlaceholderType())
2558     return false;
2559 
2560   // The first argument needs to be a record field access.
2561   // If it is an array element access, we delay decision
2562   // to BPF backend to check whether the access is a
2563   // field access or not.
2564   return (Arg->IgnoreParens()->getObjectKind() == OK_BitField ||
2565           dyn_cast<MemberExpr>(Arg->IgnoreParens()) ||
2566           dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens()));
2567 }
2568 
2569 static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S,
2570                             QualType VectorTy, QualType EltTy) {
2571   QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType();
2572   if (!Context.hasSameType(VectorEltTy, EltTy)) {
2573     S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types)
2574         << Call->getSourceRange() << VectorEltTy << EltTy;
2575     return false;
2576   }
2577   return true;
2578 }
2579 
2580 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) {
2581   QualType ArgType = Arg->getType();
2582   if (ArgType->getAsPlaceholderType())
2583     return false;
2584 
2585   // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type
2586   // format:
2587   //   1. __builtin_preserve_type_info(*(<type> *)0, flag);
2588   //   2. <type> var;
2589   //      __builtin_preserve_type_info(var, flag);
2590   if (!dyn_cast<DeclRefExpr>(Arg->IgnoreParens()) &&
2591       !dyn_cast<UnaryOperator>(Arg->IgnoreParens()))
2592     return false;
2593 
2594   // Typedef type.
2595   if (ArgType->getAs<TypedefType>())
2596     return true;
2597 
2598   // Record type or Enum type.
2599   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2600   if (const auto *RT = Ty->getAs<RecordType>()) {
2601     if (!RT->getDecl()->getDeclName().isEmpty())
2602       return true;
2603   } else if (const auto *ET = Ty->getAs<EnumType>()) {
2604     if (!ET->getDecl()->getDeclName().isEmpty())
2605       return true;
2606   }
2607 
2608   return false;
2609 }
2610 
2611 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) {
2612   QualType ArgType = Arg->getType();
2613   if (ArgType->getAsPlaceholderType())
2614     return false;
2615 
2616   // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type
2617   // format:
2618   //   __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>,
2619   //                                 flag);
2620   const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens());
2621   if (!UO)
2622     return false;
2623 
2624   const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr());
2625   if (!CE || CE->getCastKind() != CK_IntegralToPointer)
2626     return false;
2627 
2628   // The integer must be from an EnumConstantDecl.
2629   const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr());
2630   if (!DR)
2631     return false;
2632 
2633   const EnumConstantDecl *Enumerator =
2634       dyn_cast<EnumConstantDecl>(DR->getDecl());
2635   if (!Enumerator)
2636     return false;
2637 
2638   // The type must be EnumType.
2639   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2640   const auto *ET = Ty->getAs<EnumType>();
2641   if (!ET)
2642     return false;
2643 
2644   // The enum value must be supported.
2645   for (auto *EDI : ET->getDecl()->enumerators()) {
2646     if (EDI == Enumerator)
2647       return true;
2648   }
2649 
2650   return false;
2651 }
2652 
2653 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
2654                                        CallExpr *TheCall) {
2655   assert((BuiltinID == BPF::BI__builtin_preserve_field_info ||
2656           BuiltinID == BPF::BI__builtin_btf_type_id ||
2657           BuiltinID == BPF::BI__builtin_preserve_type_info ||
2658           BuiltinID == BPF::BI__builtin_preserve_enum_value) &&
2659          "unexpected BPF builtin");
2660 
2661   if (checkArgCount(*this, TheCall, 2))
2662     return true;
2663 
2664   // The second argument needs to be a constant int
2665   Expr *Arg = TheCall->getArg(1);
2666   Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context);
2667   diag::kind kind;
2668   if (!Value) {
2669     if (BuiltinID == BPF::BI__builtin_preserve_field_info)
2670       kind = diag::err_preserve_field_info_not_const;
2671     else if (BuiltinID == BPF::BI__builtin_btf_type_id)
2672       kind = diag::err_btf_type_id_not_const;
2673     else if (BuiltinID == BPF::BI__builtin_preserve_type_info)
2674       kind = diag::err_preserve_type_info_not_const;
2675     else
2676       kind = diag::err_preserve_enum_value_not_const;
2677     Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange();
2678     return true;
2679   }
2680 
2681   // The first argument
2682   Arg = TheCall->getArg(0);
2683   bool InvalidArg = false;
2684   bool ReturnUnsignedInt = true;
2685   if (BuiltinID == BPF::BI__builtin_preserve_field_info) {
2686     if (!isValidBPFPreserveFieldInfoArg(Arg)) {
2687       InvalidArg = true;
2688       kind = diag::err_preserve_field_info_not_field;
2689     }
2690   } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) {
2691     if (!isValidBPFPreserveTypeInfoArg(Arg)) {
2692       InvalidArg = true;
2693       kind = diag::err_preserve_type_info_invalid;
2694     }
2695   } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) {
2696     if (!isValidBPFPreserveEnumValueArg(Arg)) {
2697       InvalidArg = true;
2698       kind = diag::err_preserve_enum_value_invalid;
2699     }
2700     ReturnUnsignedInt = false;
2701   } else if (BuiltinID == BPF::BI__builtin_btf_type_id) {
2702     ReturnUnsignedInt = false;
2703   }
2704 
2705   if (InvalidArg) {
2706     Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange();
2707     return true;
2708   }
2709 
2710   if (ReturnUnsignedInt)
2711     TheCall->setType(Context.UnsignedIntTy);
2712   else
2713     TheCall->setType(Context.UnsignedLongTy);
2714   return false;
2715 }
2716 
2717 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2718   struct ArgInfo {
2719     uint8_t OpNum;
2720     bool IsSigned;
2721     uint8_t BitWidth;
2722     uint8_t Align;
2723   };
2724   struct BuiltinInfo {
2725     unsigned BuiltinID;
2726     ArgInfo Infos[2];
2727   };
2728 
2729   static BuiltinInfo Infos[] = {
2730     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
2731     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
2732     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
2733     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  1 }} },
2734     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
2735     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
2736     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
2737     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
2738     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
2739     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
2740     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
2741 
2742     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
2743     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
2744     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
2745     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
2746     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
2747     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
2748     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
2749     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
2750     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
2751     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
2752     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
2753 
2754     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
2755     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
2756     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
2757     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
2758     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
2759     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
2760     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
2761     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
2762     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
2763     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
2764     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
2765     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
2766     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
2767     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
2768     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
2769     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
2770     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
2771     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
2772     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
2773     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
2774     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
2775     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
2776     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
2777     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
2778     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
2779     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
2780     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
2781     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
2782     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
2783     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
2784     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
2785     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
2786     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
2787     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
2788     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
2789     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
2790     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
2791     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
2792     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
2793     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
2794     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
2795     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
2796     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
2797     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
2798     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
2799     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
2800     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
2801     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
2802     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
2803     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
2804     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
2805     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
2806                                                       {{ 1, false, 6,  0 }} },
2807     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
2808     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
2809     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
2810     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
2811     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
2812     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
2813     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
2814                                                       {{ 1, false, 5,  0 }} },
2815     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
2816     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
2817     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
2818     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
2819     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
2820     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
2821                                                        { 2, false, 5,  0 }} },
2822     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
2823                                                        { 2, false, 6,  0 }} },
2824     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
2825                                                        { 3, false, 5,  0 }} },
2826     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
2827                                                        { 3, false, 6,  0 }} },
2828     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
2829     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
2830     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
2831     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
2832     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
2833     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
2834     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
2835     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
2836     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
2837     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
2838     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
2839     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
2840     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
2841     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
2842     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
2843     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
2844                                                       {{ 2, false, 4,  0 },
2845                                                        { 3, false, 5,  0 }} },
2846     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
2847                                                       {{ 2, false, 4,  0 },
2848                                                        { 3, false, 5,  0 }} },
2849     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
2850                                                       {{ 2, false, 4,  0 },
2851                                                        { 3, false, 5,  0 }} },
2852     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
2853                                                       {{ 2, false, 4,  0 },
2854                                                        { 3, false, 5,  0 }} },
2855     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
2856     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
2857     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
2858     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
2859     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
2860     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
2861     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
2862     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
2863     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
2864     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
2865     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
2866                                                        { 2, false, 5,  0 }} },
2867     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
2868                                                        { 2, false, 6,  0 }} },
2869     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
2870     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
2871     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
2872     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
2873     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
2874     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
2875     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
2876     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
2877     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
2878                                                       {{ 1, false, 4,  0 }} },
2879     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
2880     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
2881                                                       {{ 1, false, 4,  0 }} },
2882     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
2883     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
2884     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
2885     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
2886     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
2887     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
2888     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
2889     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
2890     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
2891     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
2892     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
2893     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
2894     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
2895     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
2896     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
2897     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
2898     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
2899     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
2900     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
2901     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
2902                                                       {{ 3, false, 1,  0 }} },
2903     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
2904     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
2905     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
2906     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
2907                                                       {{ 3, false, 1,  0 }} },
2908     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
2909     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
2910     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
2911     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
2912                                                       {{ 3, false, 1,  0 }} },
2913   };
2914 
2915   // Use a dynamically initialized static to sort the table exactly once on
2916   // first run.
2917   static const bool SortOnce =
2918       (llvm::sort(Infos,
2919                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
2920                    return LHS.BuiltinID < RHS.BuiltinID;
2921                  }),
2922        true);
2923   (void)SortOnce;
2924 
2925   const BuiltinInfo *F = llvm::partition_point(
2926       Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
2927   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
2928     return false;
2929 
2930   bool Error = false;
2931 
2932   for (const ArgInfo &A : F->Infos) {
2933     // Ignore empty ArgInfo elements.
2934     if (A.BitWidth == 0)
2935       continue;
2936 
2937     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
2938     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
2939     if (!A.Align) {
2940       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
2941     } else {
2942       unsigned M = 1 << A.Align;
2943       Min *= M;
2944       Max *= M;
2945       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
2946                SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
2947     }
2948   }
2949   return Error;
2950 }
2951 
2952 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
2953                                            CallExpr *TheCall) {
2954   return CheckHexagonBuiltinArgument(BuiltinID, TheCall);
2955 }
2956 
2957 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI,
2958                                         unsigned BuiltinID, CallExpr *TheCall) {
2959   return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) ||
2960          CheckMipsBuiltinArgument(BuiltinID, TheCall);
2961 }
2962 
2963 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
2964                                CallExpr *TheCall) {
2965 
2966   if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
2967       BuiltinID <= Mips::BI__builtin_mips_lwx) {
2968     if (!TI.hasFeature("dsp"))
2969       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
2970   }
2971 
2972   if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
2973       BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
2974     if (!TI.hasFeature("dspr2"))
2975       return Diag(TheCall->getBeginLoc(),
2976                   diag::err_mips_builtin_requires_dspr2);
2977   }
2978 
2979   if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
2980       BuiltinID <= Mips::BI__builtin_msa_xori_b) {
2981     if (!TI.hasFeature("msa"))
2982       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
2983   }
2984 
2985   return false;
2986 }
2987 
2988 // CheckMipsBuiltinArgument - Checks the constant value passed to the
2989 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
2990 // ordering for DSP is unspecified. MSA is ordered by the data format used
2991 // by the underlying instruction i.e., df/m, df/n and then by size.
2992 //
2993 // FIXME: The size tests here should instead be tablegen'd along with the
2994 //        definitions from include/clang/Basic/BuiltinsMips.def.
2995 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
2996 //        be too.
2997 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2998   unsigned i = 0, l = 0, u = 0, m = 0;
2999   switch (BuiltinID) {
3000   default: return false;
3001   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
3002   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
3003   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
3004   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
3005   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
3006   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
3007   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
3008   // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
3009   // df/m field.
3010   // These intrinsics take an unsigned 3 bit immediate.
3011   case Mips::BI__builtin_msa_bclri_b:
3012   case Mips::BI__builtin_msa_bnegi_b:
3013   case Mips::BI__builtin_msa_bseti_b:
3014   case Mips::BI__builtin_msa_sat_s_b:
3015   case Mips::BI__builtin_msa_sat_u_b:
3016   case Mips::BI__builtin_msa_slli_b:
3017   case Mips::BI__builtin_msa_srai_b:
3018   case Mips::BI__builtin_msa_srari_b:
3019   case Mips::BI__builtin_msa_srli_b:
3020   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
3021   case Mips::BI__builtin_msa_binsli_b:
3022   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
3023   // These intrinsics take an unsigned 4 bit immediate.
3024   case Mips::BI__builtin_msa_bclri_h:
3025   case Mips::BI__builtin_msa_bnegi_h:
3026   case Mips::BI__builtin_msa_bseti_h:
3027   case Mips::BI__builtin_msa_sat_s_h:
3028   case Mips::BI__builtin_msa_sat_u_h:
3029   case Mips::BI__builtin_msa_slli_h:
3030   case Mips::BI__builtin_msa_srai_h:
3031   case Mips::BI__builtin_msa_srari_h:
3032   case Mips::BI__builtin_msa_srli_h:
3033   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
3034   case Mips::BI__builtin_msa_binsli_h:
3035   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
3036   // These intrinsics take an unsigned 5 bit immediate.
3037   // The first block of intrinsics actually have an unsigned 5 bit field,
3038   // not a df/n field.
3039   case Mips::BI__builtin_msa_cfcmsa:
3040   case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
3041   case Mips::BI__builtin_msa_clei_u_b:
3042   case Mips::BI__builtin_msa_clei_u_h:
3043   case Mips::BI__builtin_msa_clei_u_w:
3044   case Mips::BI__builtin_msa_clei_u_d:
3045   case Mips::BI__builtin_msa_clti_u_b:
3046   case Mips::BI__builtin_msa_clti_u_h:
3047   case Mips::BI__builtin_msa_clti_u_w:
3048   case Mips::BI__builtin_msa_clti_u_d:
3049   case Mips::BI__builtin_msa_maxi_u_b:
3050   case Mips::BI__builtin_msa_maxi_u_h:
3051   case Mips::BI__builtin_msa_maxi_u_w:
3052   case Mips::BI__builtin_msa_maxi_u_d:
3053   case Mips::BI__builtin_msa_mini_u_b:
3054   case Mips::BI__builtin_msa_mini_u_h:
3055   case Mips::BI__builtin_msa_mini_u_w:
3056   case Mips::BI__builtin_msa_mini_u_d:
3057   case Mips::BI__builtin_msa_addvi_b:
3058   case Mips::BI__builtin_msa_addvi_h:
3059   case Mips::BI__builtin_msa_addvi_w:
3060   case Mips::BI__builtin_msa_addvi_d:
3061   case Mips::BI__builtin_msa_bclri_w:
3062   case Mips::BI__builtin_msa_bnegi_w:
3063   case Mips::BI__builtin_msa_bseti_w:
3064   case Mips::BI__builtin_msa_sat_s_w:
3065   case Mips::BI__builtin_msa_sat_u_w:
3066   case Mips::BI__builtin_msa_slli_w:
3067   case Mips::BI__builtin_msa_srai_w:
3068   case Mips::BI__builtin_msa_srari_w:
3069   case Mips::BI__builtin_msa_srli_w:
3070   case Mips::BI__builtin_msa_srlri_w:
3071   case Mips::BI__builtin_msa_subvi_b:
3072   case Mips::BI__builtin_msa_subvi_h:
3073   case Mips::BI__builtin_msa_subvi_w:
3074   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
3075   case Mips::BI__builtin_msa_binsli_w:
3076   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
3077   // These intrinsics take an unsigned 6 bit immediate.
3078   case Mips::BI__builtin_msa_bclri_d:
3079   case Mips::BI__builtin_msa_bnegi_d:
3080   case Mips::BI__builtin_msa_bseti_d:
3081   case Mips::BI__builtin_msa_sat_s_d:
3082   case Mips::BI__builtin_msa_sat_u_d:
3083   case Mips::BI__builtin_msa_slli_d:
3084   case Mips::BI__builtin_msa_srai_d:
3085   case Mips::BI__builtin_msa_srari_d:
3086   case Mips::BI__builtin_msa_srli_d:
3087   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
3088   case Mips::BI__builtin_msa_binsli_d:
3089   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
3090   // These intrinsics take a signed 5 bit immediate.
3091   case Mips::BI__builtin_msa_ceqi_b:
3092   case Mips::BI__builtin_msa_ceqi_h:
3093   case Mips::BI__builtin_msa_ceqi_w:
3094   case Mips::BI__builtin_msa_ceqi_d:
3095   case Mips::BI__builtin_msa_clti_s_b:
3096   case Mips::BI__builtin_msa_clti_s_h:
3097   case Mips::BI__builtin_msa_clti_s_w:
3098   case Mips::BI__builtin_msa_clti_s_d:
3099   case Mips::BI__builtin_msa_clei_s_b:
3100   case Mips::BI__builtin_msa_clei_s_h:
3101   case Mips::BI__builtin_msa_clei_s_w:
3102   case Mips::BI__builtin_msa_clei_s_d:
3103   case Mips::BI__builtin_msa_maxi_s_b:
3104   case Mips::BI__builtin_msa_maxi_s_h:
3105   case Mips::BI__builtin_msa_maxi_s_w:
3106   case Mips::BI__builtin_msa_maxi_s_d:
3107   case Mips::BI__builtin_msa_mini_s_b:
3108   case Mips::BI__builtin_msa_mini_s_h:
3109   case Mips::BI__builtin_msa_mini_s_w:
3110   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
3111   // These intrinsics take an unsigned 8 bit immediate.
3112   case Mips::BI__builtin_msa_andi_b:
3113   case Mips::BI__builtin_msa_nori_b:
3114   case Mips::BI__builtin_msa_ori_b:
3115   case Mips::BI__builtin_msa_shf_b:
3116   case Mips::BI__builtin_msa_shf_h:
3117   case Mips::BI__builtin_msa_shf_w:
3118   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
3119   case Mips::BI__builtin_msa_bseli_b:
3120   case Mips::BI__builtin_msa_bmnzi_b:
3121   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
3122   // df/n format
3123   // These intrinsics take an unsigned 4 bit immediate.
3124   case Mips::BI__builtin_msa_copy_s_b:
3125   case Mips::BI__builtin_msa_copy_u_b:
3126   case Mips::BI__builtin_msa_insve_b:
3127   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
3128   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
3129   // These intrinsics take an unsigned 3 bit immediate.
3130   case Mips::BI__builtin_msa_copy_s_h:
3131   case Mips::BI__builtin_msa_copy_u_h:
3132   case Mips::BI__builtin_msa_insve_h:
3133   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
3134   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3135   // These intrinsics take an unsigned 2 bit immediate.
3136   case Mips::BI__builtin_msa_copy_s_w:
3137   case Mips::BI__builtin_msa_copy_u_w:
3138   case Mips::BI__builtin_msa_insve_w:
3139   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
3140   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3141   // These intrinsics take an unsigned 1 bit immediate.
3142   case Mips::BI__builtin_msa_copy_s_d:
3143   case Mips::BI__builtin_msa_copy_u_d:
3144   case Mips::BI__builtin_msa_insve_d:
3145   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
3146   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3147   // Memory offsets and immediate loads.
3148   // These intrinsics take a signed 10 bit immediate.
3149   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
3150   case Mips::BI__builtin_msa_ldi_h:
3151   case Mips::BI__builtin_msa_ldi_w:
3152   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
3153   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3154   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3155   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3156   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3157   case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break;
3158   case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break;
3159   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3160   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3161   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3162   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
3163   case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break;
3164   case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break;
3165   }
3166 
3167   if (!m)
3168     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3169 
3170   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3171          SemaBuiltinConstantArgMultiple(TheCall, i, m);
3172 }
3173 
3174 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str,
3175 /// advancing the pointer over the consumed characters. The decoded type is
3176 /// returned. If the decoded type represents a constant integer with a
3177 /// constraint on its value then Mask is set to that value. The type descriptors
3178 /// used in Str are specific to PPC MMA builtins and are documented in the file
3179 /// defining the PPC builtins.
3180 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str,
3181                                         unsigned &Mask) {
3182   bool RequireICE = false;
3183   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3184   switch (*Str++) {
3185   case 'V':
3186     return Context.getVectorType(Context.UnsignedCharTy, 16,
3187                                  VectorType::VectorKind::AltiVecVector);
3188   case 'i': {
3189     char *End;
3190     unsigned size = strtoul(Str, &End, 10);
3191     assert(End != Str && "Missing constant parameter constraint");
3192     Str = End;
3193     Mask = size;
3194     return Context.IntTy;
3195   }
3196   case 'W': {
3197     char *End;
3198     unsigned size = strtoul(Str, &End, 10);
3199     assert(End != Str && "Missing PowerPC MMA type size");
3200     Str = End;
3201     QualType Type;
3202     switch (size) {
3203   #define PPC_VECTOR_TYPE(typeName, Id, size) \
3204     case size: Type = Context.Id##Ty; break;
3205   #include "clang/Basic/PPCTypes.def"
3206     default: llvm_unreachable("Invalid PowerPC MMA vector type");
3207     }
3208     bool CheckVectorArgs = false;
3209     while (!CheckVectorArgs) {
3210       switch (*Str++) {
3211       case '*':
3212         Type = Context.getPointerType(Type);
3213         break;
3214       case 'C':
3215         Type = Type.withConst();
3216         break;
3217       default:
3218         CheckVectorArgs = true;
3219         --Str;
3220         break;
3221       }
3222     }
3223     return Type;
3224   }
3225   default:
3226     return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true);
3227   }
3228 }
3229 
3230 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3231                                        CallExpr *TheCall) {
3232   unsigned i = 0, l = 0, u = 0;
3233   bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
3234                       BuiltinID == PPC::BI__builtin_divdeu ||
3235                       BuiltinID == PPC::BI__builtin_bpermd;
3236   bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64;
3237   bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
3238                        BuiltinID == PPC::BI__builtin_divweu ||
3239                        BuiltinID == PPC::BI__builtin_divde ||
3240                        BuiltinID == PPC::BI__builtin_divdeu;
3241 
3242   if (Is64BitBltin && !IsTarget64Bit)
3243     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3244            << TheCall->getSourceRange();
3245 
3246   if ((IsBltinExtDiv && !TI.hasFeature("extdiv")) ||
3247       (BuiltinID == PPC::BI__builtin_bpermd && !TI.hasFeature("bpermd")))
3248     return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3249            << TheCall->getSourceRange();
3250 
3251   auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool {
3252     if (!TI.hasFeature("vsx"))
3253       return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3254              << TheCall->getSourceRange();
3255     return false;
3256   };
3257 
3258   switch (BuiltinID) {
3259   default: return false;
3260   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3261   case PPC::BI__builtin_altivec_crypto_vshasigmad:
3262     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3263            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3264   case PPC::BI__builtin_altivec_dss:
3265     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
3266   case PPC::BI__builtin_tbegin:
3267   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
3268   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
3269   case PPC::BI__builtin_tabortwc:
3270   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
3271   case PPC::BI__builtin_tabortwci:
3272   case PPC::BI__builtin_tabortdci:
3273     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3274            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
3275   case PPC::BI__builtin_altivec_dst:
3276   case PPC::BI__builtin_altivec_dstt:
3277   case PPC::BI__builtin_altivec_dstst:
3278   case PPC::BI__builtin_altivec_dststt:
3279     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
3280   case PPC::BI__builtin_vsx_xxpermdi:
3281   case PPC::BI__builtin_vsx_xxsldwi:
3282     return SemaBuiltinVSX(TheCall);
3283   case PPC::BI__builtin_unpack_vector_int128:
3284     return SemaVSXCheck(TheCall) ||
3285            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3286   case PPC::BI__builtin_pack_vector_int128:
3287     return SemaVSXCheck(TheCall);
3288   case PPC::BI__builtin_altivec_vgnb:
3289      return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7);
3290   case PPC::BI__builtin_altivec_vec_replace_elt:
3291   case PPC::BI__builtin_altivec_vec_replace_unaligned: {
3292     QualType VecTy = TheCall->getArg(0)->getType();
3293     QualType EltTy = TheCall->getArg(1)->getType();
3294     unsigned Width = Context.getIntWidth(EltTy);
3295     return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) ||
3296            !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy);
3297   }
3298   case PPC::BI__builtin_vsx_xxeval:
3299      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255);
3300   case PPC::BI__builtin_altivec_vsldbi:
3301      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3302   case PPC::BI__builtin_altivec_vsrdbi:
3303      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3304   case PPC::BI__builtin_vsx_xxpermx:
3305      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7);
3306 #define CUSTOM_BUILTIN(Name, Types, Acc) \
3307   case PPC::BI__builtin_##Name: \
3308     return SemaBuiltinPPCMMACall(TheCall, Types);
3309 #include "clang/Basic/BuiltinsPPC.def"
3310   }
3311   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3312 }
3313 
3314 // Check if the given type is a non-pointer PPC MMA type. This function is used
3315 // in Sema to prevent invalid uses of restricted PPC MMA types.
3316 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) {
3317   if (Type->isPointerType() || Type->isArrayType())
3318     return false;
3319 
3320   QualType CoreType = Type.getCanonicalType().getUnqualifiedType();
3321 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty
3322   if (false
3323 #include "clang/Basic/PPCTypes.def"
3324      ) {
3325     Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type);
3326     return true;
3327   }
3328   return false;
3329 }
3330 
3331 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID,
3332                                           CallExpr *TheCall) {
3333   // position of memory order and scope arguments in the builtin
3334   unsigned OrderIndex, ScopeIndex;
3335   switch (BuiltinID) {
3336   case AMDGPU::BI__builtin_amdgcn_atomic_inc32:
3337   case AMDGPU::BI__builtin_amdgcn_atomic_inc64:
3338   case AMDGPU::BI__builtin_amdgcn_atomic_dec32:
3339   case AMDGPU::BI__builtin_amdgcn_atomic_dec64:
3340     OrderIndex = 2;
3341     ScopeIndex = 3;
3342     break;
3343   case AMDGPU::BI__builtin_amdgcn_fence:
3344     OrderIndex = 0;
3345     ScopeIndex = 1;
3346     break;
3347   default:
3348     return false;
3349   }
3350 
3351   ExprResult Arg = TheCall->getArg(OrderIndex);
3352   auto ArgExpr = Arg.get();
3353   Expr::EvalResult ArgResult;
3354 
3355   if (!ArgExpr->EvaluateAsInt(ArgResult, Context))
3356     return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int)
3357            << ArgExpr->getType();
3358   int ord = ArgResult.Val.getInt().getZExtValue();
3359 
3360   // Check valididty of memory ordering as per C11 / C++11's memody model.
3361   switch (static_cast<llvm::AtomicOrderingCABI>(ord)) {
3362   case llvm::AtomicOrderingCABI::acquire:
3363   case llvm::AtomicOrderingCABI::release:
3364   case llvm::AtomicOrderingCABI::acq_rel:
3365   case llvm::AtomicOrderingCABI::seq_cst:
3366     break;
3367   default: {
3368     return Diag(ArgExpr->getBeginLoc(),
3369                 diag::warn_atomic_op_has_invalid_memory_order)
3370            << ArgExpr->getSourceRange();
3371   }
3372   }
3373 
3374   Arg = TheCall->getArg(ScopeIndex);
3375   ArgExpr = Arg.get();
3376   Expr::EvalResult ArgResult1;
3377   // Check that sync scope is a constant literal
3378   if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context))
3379     return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal)
3380            << ArgExpr->getType();
3381 
3382   return false;
3383 }
3384 
3385 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3386                                            CallExpr *TheCall) {
3387   if (BuiltinID == SystemZ::BI__builtin_tabort) {
3388     Expr *Arg = TheCall->getArg(0);
3389     if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context))
3390       if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256)
3391         return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
3392                << Arg->getSourceRange();
3393   }
3394 
3395   // For intrinsics which take an immediate value as part of the instruction,
3396   // range check them here.
3397   unsigned i = 0, l = 0, u = 0;
3398   switch (BuiltinID) {
3399   default: return false;
3400   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3401   case SystemZ::BI__builtin_s390_verimb:
3402   case SystemZ::BI__builtin_s390_verimh:
3403   case SystemZ::BI__builtin_s390_verimf:
3404   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
3405   case SystemZ::BI__builtin_s390_vfaeb:
3406   case SystemZ::BI__builtin_s390_vfaeh:
3407   case SystemZ::BI__builtin_s390_vfaef:
3408   case SystemZ::BI__builtin_s390_vfaebs:
3409   case SystemZ::BI__builtin_s390_vfaehs:
3410   case SystemZ::BI__builtin_s390_vfaefs:
3411   case SystemZ::BI__builtin_s390_vfaezb:
3412   case SystemZ::BI__builtin_s390_vfaezh:
3413   case SystemZ::BI__builtin_s390_vfaezf:
3414   case SystemZ::BI__builtin_s390_vfaezbs:
3415   case SystemZ::BI__builtin_s390_vfaezhs:
3416   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
3417   case SystemZ::BI__builtin_s390_vfisb:
3418   case SystemZ::BI__builtin_s390_vfidb:
3419     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3420            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3421   case SystemZ::BI__builtin_s390_vftcisb:
3422   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3423   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3424   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3425   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3426   case SystemZ::BI__builtin_s390_vstrcb:
3427   case SystemZ::BI__builtin_s390_vstrch:
3428   case SystemZ::BI__builtin_s390_vstrcf:
3429   case SystemZ::BI__builtin_s390_vstrczb:
3430   case SystemZ::BI__builtin_s390_vstrczh:
3431   case SystemZ::BI__builtin_s390_vstrczf:
3432   case SystemZ::BI__builtin_s390_vstrcbs:
3433   case SystemZ::BI__builtin_s390_vstrchs:
3434   case SystemZ::BI__builtin_s390_vstrcfs:
3435   case SystemZ::BI__builtin_s390_vstrczbs:
3436   case SystemZ::BI__builtin_s390_vstrczhs:
3437   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
3438   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3439   case SystemZ::BI__builtin_s390_vfminsb:
3440   case SystemZ::BI__builtin_s390_vfmaxsb:
3441   case SystemZ::BI__builtin_s390_vfmindb:
3442   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
3443   case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
3444   case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
3445   }
3446   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3447 }
3448 
3449 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3450 /// This checks that the target supports __builtin_cpu_supports and
3451 /// that the string argument is constant and valid.
3452 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI,
3453                                    CallExpr *TheCall) {
3454   Expr *Arg = TheCall->getArg(0);
3455 
3456   // Check if the argument is a string literal.
3457   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3458     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3459            << Arg->getSourceRange();
3460 
3461   // Check the contents of the string.
3462   StringRef Feature =
3463       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3464   if (!TI.validateCpuSupports(Feature))
3465     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
3466            << Arg->getSourceRange();
3467   return false;
3468 }
3469 
3470 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3471 /// This checks that the target supports __builtin_cpu_is and
3472 /// that the string argument is constant and valid.
3473 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) {
3474   Expr *Arg = TheCall->getArg(0);
3475 
3476   // Check if the argument is a string literal.
3477   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3478     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3479            << Arg->getSourceRange();
3480 
3481   // Check the contents of the string.
3482   StringRef Feature =
3483       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3484   if (!TI.validateCpuIs(Feature))
3485     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
3486            << Arg->getSourceRange();
3487   return false;
3488 }
3489 
3490 // Check if the rounding mode is legal.
3491 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3492   // Indicates if this instruction has rounding control or just SAE.
3493   bool HasRC = false;
3494 
3495   unsigned ArgNum = 0;
3496   switch (BuiltinID) {
3497   default:
3498     return false;
3499   case X86::BI__builtin_ia32_vcvttsd2si32:
3500   case X86::BI__builtin_ia32_vcvttsd2si64:
3501   case X86::BI__builtin_ia32_vcvttsd2usi32:
3502   case X86::BI__builtin_ia32_vcvttsd2usi64:
3503   case X86::BI__builtin_ia32_vcvttss2si32:
3504   case X86::BI__builtin_ia32_vcvttss2si64:
3505   case X86::BI__builtin_ia32_vcvttss2usi32:
3506   case X86::BI__builtin_ia32_vcvttss2usi64:
3507     ArgNum = 1;
3508     break;
3509   case X86::BI__builtin_ia32_maxpd512:
3510   case X86::BI__builtin_ia32_maxps512:
3511   case X86::BI__builtin_ia32_minpd512:
3512   case X86::BI__builtin_ia32_minps512:
3513     ArgNum = 2;
3514     break;
3515   case X86::BI__builtin_ia32_cvtps2pd512_mask:
3516   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
3517   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
3518   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
3519   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
3520   case X86::BI__builtin_ia32_cvttps2dq512_mask:
3521   case X86::BI__builtin_ia32_cvttps2qq512_mask:
3522   case X86::BI__builtin_ia32_cvttps2udq512_mask:
3523   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
3524   case X86::BI__builtin_ia32_exp2pd_mask:
3525   case X86::BI__builtin_ia32_exp2ps_mask:
3526   case X86::BI__builtin_ia32_getexppd512_mask:
3527   case X86::BI__builtin_ia32_getexpps512_mask:
3528   case X86::BI__builtin_ia32_rcp28pd_mask:
3529   case X86::BI__builtin_ia32_rcp28ps_mask:
3530   case X86::BI__builtin_ia32_rsqrt28pd_mask:
3531   case X86::BI__builtin_ia32_rsqrt28ps_mask:
3532   case X86::BI__builtin_ia32_vcomisd:
3533   case X86::BI__builtin_ia32_vcomiss:
3534   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
3535     ArgNum = 3;
3536     break;
3537   case X86::BI__builtin_ia32_cmppd512_mask:
3538   case X86::BI__builtin_ia32_cmpps512_mask:
3539   case X86::BI__builtin_ia32_cmpsd_mask:
3540   case X86::BI__builtin_ia32_cmpss_mask:
3541   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
3542   case X86::BI__builtin_ia32_getexpsd128_round_mask:
3543   case X86::BI__builtin_ia32_getexpss128_round_mask:
3544   case X86::BI__builtin_ia32_getmantpd512_mask:
3545   case X86::BI__builtin_ia32_getmantps512_mask:
3546   case X86::BI__builtin_ia32_maxsd_round_mask:
3547   case X86::BI__builtin_ia32_maxss_round_mask:
3548   case X86::BI__builtin_ia32_minsd_round_mask:
3549   case X86::BI__builtin_ia32_minss_round_mask:
3550   case X86::BI__builtin_ia32_rcp28sd_round_mask:
3551   case X86::BI__builtin_ia32_rcp28ss_round_mask:
3552   case X86::BI__builtin_ia32_reducepd512_mask:
3553   case X86::BI__builtin_ia32_reduceps512_mask:
3554   case X86::BI__builtin_ia32_rndscalepd_mask:
3555   case X86::BI__builtin_ia32_rndscaleps_mask:
3556   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
3557   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
3558     ArgNum = 4;
3559     break;
3560   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3561   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3562   case X86::BI__builtin_ia32_fixupimmps512_mask:
3563   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3564   case X86::BI__builtin_ia32_fixupimmsd_mask:
3565   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3566   case X86::BI__builtin_ia32_fixupimmss_mask:
3567   case X86::BI__builtin_ia32_fixupimmss_maskz:
3568   case X86::BI__builtin_ia32_getmantsd_round_mask:
3569   case X86::BI__builtin_ia32_getmantss_round_mask:
3570   case X86::BI__builtin_ia32_rangepd512_mask:
3571   case X86::BI__builtin_ia32_rangeps512_mask:
3572   case X86::BI__builtin_ia32_rangesd128_round_mask:
3573   case X86::BI__builtin_ia32_rangess128_round_mask:
3574   case X86::BI__builtin_ia32_reducesd_mask:
3575   case X86::BI__builtin_ia32_reducess_mask:
3576   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3577   case X86::BI__builtin_ia32_rndscaless_round_mask:
3578     ArgNum = 5;
3579     break;
3580   case X86::BI__builtin_ia32_vcvtsd2si64:
3581   case X86::BI__builtin_ia32_vcvtsd2si32:
3582   case X86::BI__builtin_ia32_vcvtsd2usi32:
3583   case X86::BI__builtin_ia32_vcvtsd2usi64:
3584   case X86::BI__builtin_ia32_vcvtss2si32:
3585   case X86::BI__builtin_ia32_vcvtss2si64:
3586   case X86::BI__builtin_ia32_vcvtss2usi32:
3587   case X86::BI__builtin_ia32_vcvtss2usi64:
3588   case X86::BI__builtin_ia32_sqrtpd512:
3589   case X86::BI__builtin_ia32_sqrtps512:
3590     ArgNum = 1;
3591     HasRC = true;
3592     break;
3593   case X86::BI__builtin_ia32_addpd512:
3594   case X86::BI__builtin_ia32_addps512:
3595   case X86::BI__builtin_ia32_divpd512:
3596   case X86::BI__builtin_ia32_divps512:
3597   case X86::BI__builtin_ia32_mulpd512:
3598   case X86::BI__builtin_ia32_mulps512:
3599   case X86::BI__builtin_ia32_subpd512:
3600   case X86::BI__builtin_ia32_subps512:
3601   case X86::BI__builtin_ia32_cvtsi2sd64:
3602   case X86::BI__builtin_ia32_cvtsi2ss32:
3603   case X86::BI__builtin_ia32_cvtsi2ss64:
3604   case X86::BI__builtin_ia32_cvtusi2sd64:
3605   case X86::BI__builtin_ia32_cvtusi2ss32:
3606   case X86::BI__builtin_ia32_cvtusi2ss64:
3607     ArgNum = 2;
3608     HasRC = true;
3609     break;
3610   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
3611   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
3612   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
3613   case X86::BI__builtin_ia32_cvtpd2dq512_mask:
3614   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
3615   case X86::BI__builtin_ia32_cvtpd2udq512_mask:
3616   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
3617   case X86::BI__builtin_ia32_cvtps2dq512_mask:
3618   case X86::BI__builtin_ia32_cvtps2qq512_mask:
3619   case X86::BI__builtin_ia32_cvtps2udq512_mask:
3620   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
3621   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
3622   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
3623   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
3624   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
3625     ArgNum = 3;
3626     HasRC = true;
3627     break;
3628   case X86::BI__builtin_ia32_addss_round_mask:
3629   case X86::BI__builtin_ia32_addsd_round_mask:
3630   case X86::BI__builtin_ia32_divss_round_mask:
3631   case X86::BI__builtin_ia32_divsd_round_mask:
3632   case X86::BI__builtin_ia32_mulss_round_mask:
3633   case X86::BI__builtin_ia32_mulsd_round_mask:
3634   case X86::BI__builtin_ia32_subss_round_mask:
3635   case X86::BI__builtin_ia32_subsd_round_mask:
3636   case X86::BI__builtin_ia32_scalefpd512_mask:
3637   case X86::BI__builtin_ia32_scalefps512_mask:
3638   case X86::BI__builtin_ia32_scalefsd_round_mask:
3639   case X86::BI__builtin_ia32_scalefss_round_mask:
3640   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
3641   case X86::BI__builtin_ia32_sqrtsd_round_mask:
3642   case X86::BI__builtin_ia32_sqrtss_round_mask:
3643   case X86::BI__builtin_ia32_vfmaddsd3_mask:
3644   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
3645   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
3646   case X86::BI__builtin_ia32_vfmaddss3_mask:
3647   case X86::BI__builtin_ia32_vfmaddss3_maskz:
3648   case X86::BI__builtin_ia32_vfmaddss3_mask3:
3649   case X86::BI__builtin_ia32_vfmaddpd512_mask:
3650   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
3651   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
3652   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
3653   case X86::BI__builtin_ia32_vfmaddps512_mask:
3654   case X86::BI__builtin_ia32_vfmaddps512_maskz:
3655   case X86::BI__builtin_ia32_vfmaddps512_mask3:
3656   case X86::BI__builtin_ia32_vfmsubps512_mask3:
3657   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
3658   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
3659   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
3660   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
3661   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
3662   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
3663   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
3664   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
3665     ArgNum = 4;
3666     HasRC = true;
3667     break;
3668   }
3669 
3670   llvm::APSInt Result;
3671 
3672   // We can't check the value of a dependent argument.
3673   Expr *Arg = TheCall->getArg(ArgNum);
3674   if (Arg->isTypeDependent() || Arg->isValueDependent())
3675     return false;
3676 
3677   // Check constant-ness first.
3678   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3679     return true;
3680 
3681   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
3682   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
3683   // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
3684   // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
3685   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
3686       Result == 8/*ROUND_NO_EXC*/ ||
3687       (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
3688       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
3689     return false;
3690 
3691   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
3692          << Arg->getSourceRange();
3693 }
3694 
3695 // Check if the gather/scatter scale is legal.
3696 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
3697                                              CallExpr *TheCall) {
3698   unsigned ArgNum = 0;
3699   switch (BuiltinID) {
3700   default:
3701     return false;
3702   case X86::BI__builtin_ia32_gatherpfdpd:
3703   case X86::BI__builtin_ia32_gatherpfdps:
3704   case X86::BI__builtin_ia32_gatherpfqpd:
3705   case X86::BI__builtin_ia32_gatherpfqps:
3706   case X86::BI__builtin_ia32_scatterpfdpd:
3707   case X86::BI__builtin_ia32_scatterpfdps:
3708   case X86::BI__builtin_ia32_scatterpfqpd:
3709   case X86::BI__builtin_ia32_scatterpfqps:
3710     ArgNum = 3;
3711     break;
3712   case X86::BI__builtin_ia32_gatherd_pd:
3713   case X86::BI__builtin_ia32_gatherd_pd256:
3714   case X86::BI__builtin_ia32_gatherq_pd:
3715   case X86::BI__builtin_ia32_gatherq_pd256:
3716   case X86::BI__builtin_ia32_gatherd_ps:
3717   case X86::BI__builtin_ia32_gatherd_ps256:
3718   case X86::BI__builtin_ia32_gatherq_ps:
3719   case X86::BI__builtin_ia32_gatherq_ps256:
3720   case X86::BI__builtin_ia32_gatherd_q:
3721   case X86::BI__builtin_ia32_gatherd_q256:
3722   case X86::BI__builtin_ia32_gatherq_q:
3723   case X86::BI__builtin_ia32_gatherq_q256:
3724   case X86::BI__builtin_ia32_gatherd_d:
3725   case X86::BI__builtin_ia32_gatherd_d256:
3726   case X86::BI__builtin_ia32_gatherq_d:
3727   case X86::BI__builtin_ia32_gatherq_d256:
3728   case X86::BI__builtin_ia32_gather3div2df:
3729   case X86::BI__builtin_ia32_gather3div2di:
3730   case X86::BI__builtin_ia32_gather3div4df:
3731   case X86::BI__builtin_ia32_gather3div4di:
3732   case X86::BI__builtin_ia32_gather3div4sf:
3733   case X86::BI__builtin_ia32_gather3div4si:
3734   case X86::BI__builtin_ia32_gather3div8sf:
3735   case X86::BI__builtin_ia32_gather3div8si:
3736   case X86::BI__builtin_ia32_gather3siv2df:
3737   case X86::BI__builtin_ia32_gather3siv2di:
3738   case X86::BI__builtin_ia32_gather3siv4df:
3739   case X86::BI__builtin_ia32_gather3siv4di:
3740   case X86::BI__builtin_ia32_gather3siv4sf:
3741   case X86::BI__builtin_ia32_gather3siv4si:
3742   case X86::BI__builtin_ia32_gather3siv8sf:
3743   case X86::BI__builtin_ia32_gather3siv8si:
3744   case X86::BI__builtin_ia32_gathersiv8df:
3745   case X86::BI__builtin_ia32_gathersiv16sf:
3746   case X86::BI__builtin_ia32_gatherdiv8df:
3747   case X86::BI__builtin_ia32_gatherdiv16sf:
3748   case X86::BI__builtin_ia32_gathersiv8di:
3749   case X86::BI__builtin_ia32_gathersiv16si:
3750   case X86::BI__builtin_ia32_gatherdiv8di:
3751   case X86::BI__builtin_ia32_gatherdiv16si:
3752   case X86::BI__builtin_ia32_scatterdiv2df:
3753   case X86::BI__builtin_ia32_scatterdiv2di:
3754   case X86::BI__builtin_ia32_scatterdiv4df:
3755   case X86::BI__builtin_ia32_scatterdiv4di:
3756   case X86::BI__builtin_ia32_scatterdiv4sf:
3757   case X86::BI__builtin_ia32_scatterdiv4si:
3758   case X86::BI__builtin_ia32_scatterdiv8sf:
3759   case X86::BI__builtin_ia32_scatterdiv8si:
3760   case X86::BI__builtin_ia32_scattersiv2df:
3761   case X86::BI__builtin_ia32_scattersiv2di:
3762   case X86::BI__builtin_ia32_scattersiv4df:
3763   case X86::BI__builtin_ia32_scattersiv4di:
3764   case X86::BI__builtin_ia32_scattersiv4sf:
3765   case X86::BI__builtin_ia32_scattersiv4si:
3766   case X86::BI__builtin_ia32_scattersiv8sf:
3767   case X86::BI__builtin_ia32_scattersiv8si:
3768   case X86::BI__builtin_ia32_scattersiv8df:
3769   case X86::BI__builtin_ia32_scattersiv16sf:
3770   case X86::BI__builtin_ia32_scatterdiv8df:
3771   case X86::BI__builtin_ia32_scatterdiv16sf:
3772   case X86::BI__builtin_ia32_scattersiv8di:
3773   case X86::BI__builtin_ia32_scattersiv16si:
3774   case X86::BI__builtin_ia32_scatterdiv8di:
3775   case X86::BI__builtin_ia32_scatterdiv16si:
3776     ArgNum = 4;
3777     break;
3778   }
3779 
3780   llvm::APSInt Result;
3781 
3782   // We can't check the value of a dependent argument.
3783   Expr *Arg = TheCall->getArg(ArgNum);
3784   if (Arg->isTypeDependent() || Arg->isValueDependent())
3785     return false;
3786 
3787   // Check constant-ness first.
3788   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3789     return true;
3790 
3791   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
3792     return false;
3793 
3794   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
3795          << Arg->getSourceRange();
3796 }
3797 
3798 enum { TileRegLow = 0, TileRegHigh = 7 };
3799 
3800 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
3801                                              ArrayRef<int> ArgNums) {
3802   for (int ArgNum : ArgNums) {
3803     if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh))
3804       return true;
3805   }
3806   return false;
3807 }
3808 
3809 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall,
3810                                         ArrayRef<int> ArgNums) {
3811   // Because the max number of tile register is TileRegHigh + 1, so here we use
3812   // each bit to represent the usage of them in bitset.
3813   std::bitset<TileRegHigh + 1> ArgValues;
3814   for (int ArgNum : ArgNums) {
3815     Expr *Arg = TheCall->getArg(ArgNum);
3816     if (Arg->isTypeDependent() || Arg->isValueDependent())
3817       continue;
3818 
3819     llvm::APSInt Result;
3820     if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3821       return true;
3822     int ArgExtValue = Result.getExtValue();
3823     assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) &&
3824            "Incorrect tile register num.");
3825     if (ArgValues.test(ArgExtValue))
3826       return Diag(TheCall->getBeginLoc(),
3827                   diag::err_x86_builtin_tile_arg_duplicate)
3828              << TheCall->getArg(ArgNum)->getSourceRange();
3829     ArgValues.set(ArgExtValue);
3830   }
3831   return false;
3832 }
3833 
3834 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
3835                                                 ArrayRef<int> ArgNums) {
3836   return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) ||
3837          CheckX86BuiltinTileDuplicate(TheCall, ArgNums);
3838 }
3839 
3840 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) {
3841   switch (BuiltinID) {
3842   default:
3843     return false;
3844   case X86::BI__builtin_ia32_tileloadd64:
3845   case X86::BI__builtin_ia32_tileloaddt164:
3846   case X86::BI__builtin_ia32_tilestored64:
3847   case X86::BI__builtin_ia32_tilezero:
3848     return CheckX86BuiltinTileArgumentsRange(TheCall, 0);
3849   case X86::BI__builtin_ia32_tdpbssd:
3850   case X86::BI__builtin_ia32_tdpbsud:
3851   case X86::BI__builtin_ia32_tdpbusd:
3852   case X86::BI__builtin_ia32_tdpbuud:
3853   case X86::BI__builtin_ia32_tdpbf16ps:
3854     return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2});
3855   }
3856 }
3857 static bool isX86_32Builtin(unsigned BuiltinID) {
3858   // These builtins only work on x86-32 targets.
3859   switch (BuiltinID) {
3860   case X86::BI__builtin_ia32_readeflags_u32:
3861   case X86::BI__builtin_ia32_writeeflags_u32:
3862     return true;
3863   }
3864 
3865   return false;
3866 }
3867 
3868 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3869                                        CallExpr *TheCall) {
3870   if (BuiltinID == X86::BI__builtin_cpu_supports)
3871     return SemaBuiltinCpuSupports(*this, TI, TheCall);
3872 
3873   if (BuiltinID == X86::BI__builtin_cpu_is)
3874     return SemaBuiltinCpuIs(*this, TI, TheCall);
3875 
3876   // Check for 32-bit only builtins on a 64-bit target.
3877   const llvm::Triple &TT = TI.getTriple();
3878   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
3879     return Diag(TheCall->getCallee()->getBeginLoc(),
3880                 diag::err_32_bit_builtin_64_bit_tgt);
3881 
3882   // If the intrinsic has rounding or SAE make sure its valid.
3883   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
3884     return true;
3885 
3886   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
3887   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
3888     return true;
3889 
3890   // If the intrinsic has a tile arguments, make sure they are valid.
3891   if (CheckX86BuiltinTileArguments(BuiltinID, TheCall))
3892     return true;
3893 
3894   // For intrinsics which take an immediate value as part of the instruction,
3895   // range check them here.
3896   int i = 0, l = 0, u = 0;
3897   switch (BuiltinID) {
3898   default:
3899     return false;
3900   case X86::BI__builtin_ia32_vec_ext_v2si:
3901   case X86::BI__builtin_ia32_vec_ext_v2di:
3902   case X86::BI__builtin_ia32_vextractf128_pd256:
3903   case X86::BI__builtin_ia32_vextractf128_ps256:
3904   case X86::BI__builtin_ia32_vextractf128_si256:
3905   case X86::BI__builtin_ia32_extract128i256:
3906   case X86::BI__builtin_ia32_extractf64x4_mask:
3907   case X86::BI__builtin_ia32_extracti64x4_mask:
3908   case X86::BI__builtin_ia32_extractf32x8_mask:
3909   case X86::BI__builtin_ia32_extracti32x8_mask:
3910   case X86::BI__builtin_ia32_extractf64x2_256_mask:
3911   case X86::BI__builtin_ia32_extracti64x2_256_mask:
3912   case X86::BI__builtin_ia32_extractf32x4_256_mask:
3913   case X86::BI__builtin_ia32_extracti32x4_256_mask:
3914     i = 1; l = 0; u = 1;
3915     break;
3916   case X86::BI__builtin_ia32_vec_set_v2di:
3917   case X86::BI__builtin_ia32_vinsertf128_pd256:
3918   case X86::BI__builtin_ia32_vinsertf128_ps256:
3919   case X86::BI__builtin_ia32_vinsertf128_si256:
3920   case X86::BI__builtin_ia32_insert128i256:
3921   case X86::BI__builtin_ia32_insertf32x8:
3922   case X86::BI__builtin_ia32_inserti32x8:
3923   case X86::BI__builtin_ia32_insertf64x4:
3924   case X86::BI__builtin_ia32_inserti64x4:
3925   case X86::BI__builtin_ia32_insertf64x2_256:
3926   case X86::BI__builtin_ia32_inserti64x2_256:
3927   case X86::BI__builtin_ia32_insertf32x4_256:
3928   case X86::BI__builtin_ia32_inserti32x4_256:
3929     i = 2; l = 0; u = 1;
3930     break;
3931   case X86::BI__builtin_ia32_vpermilpd:
3932   case X86::BI__builtin_ia32_vec_ext_v4hi:
3933   case X86::BI__builtin_ia32_vec_ext_v4si:
3934   case X86::BI__builtin_ia32_vec_ext_v4sf:
3935   case X86::BI__builtin_ia32_vec_ext_v4di:
3936   case X86::BI__builtin_ia32_extractf32x4_mask:
3937   case X86::BI__builtin_ia32_extracti32x4_mask:
3938   case X86::BI__builtin_ia32_extractf64x2_512_mask:
3939   case X86::BI__builtin_ia32_extracti64x2_512_mask:
3940     i = 1; l = 0; u = 3;
3941     break;
3942   case X86::BI_mm_prefetch:
3943   case X86::BI__builtin_ia32_vec_ext_v8hi:
3944   case X86::BI__builtin_ia32_vec_ext_v8si:
3945     i = 1; l = 0; u = 7;
3946     break;
3947   case X86::BI__builtin_ia32_sha1rnds4:
3948   case X86::BI__builtin_ia32_blendpd:
3949   case X86::BI__builtin_ia32_shufpd:
3950   case X86::BI__builtin_ia32_vec_set_v4hi:
3951   case X86::BI__builtin_ia32_vec_set_v4si:
3952   case X86::BI__builtin_ia32_vec_set_v4di:
3953   case X86::BI__builtin_ia32_shuf_f32x4_256:
3954   case X86::BI__builtin_ia32_shuf_f64x2_256:
3955   case X86::BI__builtin_ia32_shuf_i32x4_256:
3956   case X86::BI__builtin_ia32_shuf_i64x2_256:
3957   case X86::BI__builtin_ia32_insertf64x2_512:
3958   case X86::BI__builtin_ia32_inserti64x2_512:
3959   case X86::BI__builtin_ia32_insertf32x4:
3960   case X86::BI__builtin_ia32_inserti32x4:
3961     i = 2; l = 0; u = 3;
3962     break;
3963   case X86::BI__builtin_ia32_vpermil2pd:
3964   case X86::BI__builtin_ia32_vpermil2pd256:
3965   case X86::BI__builtin_ia32_vpermil2ps:
3966   case X86::BI__builtin_ia32_vpermil2ps256:
3967     i = 3; l = 0; u = 3;
3968     break;
3969   case X86::BI__builtin_ia32_cmpb128_mask:
3970   case X86::BI__builtin_ia32_cmpw128_mask:
3971   case X86::BI__builtin_ia32_cmpd128_mask:
3972   case X86::BI__builtin_ia32_cmpq128_mask:
3973   case X86::BI__builtin_ia32_cmpb256_mask:
3974   case X86::BI__builtin_ia32_cmpw256_mask:
3975   case X86::BI__builtin_ia32_cmpd256_mask:
3976   case X86::BI__builtin_ia32_cmpq256_mask:
3977   case X86::BI__builtin_ia32_cmpb512_mask:
3978   case X86::BI__builtin_ia32_cmpw512_mask:
3979   case X86::BI__builtin_ia32_cmpd512_mask:
3980   case X86::BI__builtin_ia32_cmpq512_mask:
3981   case X86::BI__builtin_ia32_ucmpb128_mask:
3982   case X86::BI__builtin_ia32_ucmpw128_mask:
3983   case X86::BI__builtin_ia32_ucmpd128_mask:
3984   case X86::BI__builtin_ia32_ucmpq128_mask:
3985   case X86::BI__builtin_ia32_ucmpb256_mask:
3986   case X86::BI__builtin_ia32_ucmpw256_mask:
3987   case X86::BI__builtin_ia32_ucmpd256_mask:
3988   case X86::BI__builtin_ia32_ucmpq256_mask:
3989   case X86::BI__builtin_ia32_ucmpb512_mask:
3990   case X86::BI__builtin_ia32_ucmpw512_mask:
3991   case X86::BI__builtin_ia32_ucmpd512_mask:
3992   case X86::BI__builtin_ia32_ucmpq512_mask:
3993   case X86::BI__builtin_ia32_vpcomub:
3994   case X86::BI__builtin_ia32_vpcomuw:
3995   case X86::BI__builtin_ia32_vpcomud:
3996   case X86::BI__builtin_ia32_vpcomuq:
3997   case X86::BI__builtin_ia32_vpcomb:
3998   case X86::BI__builtin_ia32_vpcomw:
3999   case X86::BI__builtin_ia32_vpcomd:
4000   case X86::BI__builtin_ia32_vpcomq:
4001   case X86::BI__builtin_ia32_vec_set_v8hi:
4002   case X86::BI__builtin_ia32_vec_set_v8si:
4003     i = 2; l = 0; u = 7;
4004     break;
4005   case X86::BI__builtin_ia32_vpermilpd256:
4006   case X86::BI__builtin_ia32_roundps:
4007   case X86::BI__builtin_ia32_roundpd:
4008   case X86::BI__builtin_ia32_roundps256:
4009   case X86::BI__builtin_ia32_roundpd256:
4010   case X86::BI__builtin_ia32_getmantpd128_mask:
4011   case X86::BI__builtin_ia32_getmantpd256_mask:
4012   case X86::BI__builtin_ia32_getmantps128_mask:
4013   case X86::BI__builtin_ia32_getmantps256_mask:
4014   case X86::BI__builtin_ia32_getmantpd512_mask:
4015   case X86::BI__builtin_ia32_getmantps512_mask:
4016   case X86::BI__builtin_ia32_vec_ext_v16qi:
4017   case X86::BI__builtin_ia32_vec_ext_v16hi:
4018     i = 1; l = 0; u = 15;
4019     break;
4020   case X86::BI__builtin_ia32_pblendd128:
4021   case X86::BI__builtin_ia32_blendps:
4022   case X86::BI__builtin_ia32_blendpd256:
4023   case X86::BI__builtin_ia32_shufpd256:
4024   case X86::BI__builtin_ia32_roundss:
4025   case X86::BI__builtin_ia32_roundsd:
4026   case X86::BI__builtin_ia32_rangepd128_mask:
4027   case X86::BI__builtin_ia32_rangepd256_mask:
4028   case X86::BI__builtin_ia32_rangepd512_mask:
4029   case X86::BI__builtin_ia32_rangeps128_mask:
4030   case X86::BI__builtin_ia32_rangeps256_mask:
4031   case X86::BI__builtin_ia32_rangeps512_mask:
4032   case X86::BI__builtin_ia32_getmantsd_round_mask:
4033   case X86::BI__builtin_ia32_getmantss_round_mask:
4034   case X86::BI__builtin_ia32_vec_set_v16qi:
4035   case X86::BI__builtin_ia32_vec_set_v16hi:
4036     i = 2; l = 0; u = 15;
4037     break;
4038   case X86::BI__builtin_ia32_vec_ext_v32qi:
4039     i = 1; l = 0; u = 31;
4040     break;
4041   case X86::BI__builtin_ia32_cmpps:
4042   case X86::BI__builtin_ia32_cmpss:
4043   case X86::BI__builtin_ia32_cmppd:
4044   case X86::BI__builtin_ia32_cmpsd:
4045   case X86::BI__builtin_ia32_cmpps256:
4046   case X86::BI__builtin_ia32_cmppd256:
4047   case X86::BI__builtin_ia32_cmpps128_mask:
4048   case X86::BI__builtin_ia32_cmppd128_mask:
4049   case X86::BI__builtin_ia32_cmpps256_mask:
4050   case X86::BI__builtin_ia32_cmppd256_mask:
4051   case X86::BI__builtin_ia32_cmpps512_mask:
4052   case X86::BI__builtin_ia32_cmppd512_mask:
4053   case X86::BI__builtin_ia32_cmpsd_mask:
4054   case X86::BI__builtin_ia32_cmpss_mask:
4055   case X86::BI__builtin_ia32_vec_set_v32qi:
4056     i = 2; l = 0; u = 31;
4057     break;
4058   case X86::BI__builtin_ia32_permdf256:
4059   case X86::BI__builtin_ia32_permdi256:
4060   case X86::BI__builtin_ia32_permdf512:
4061   case X86::BI__builtin_ia32_permdi512:
4062   case X86::BI__builtin_ia32_vpermilps:
4063   case X86::BI__builtin_ia32_vpermilps256:
4064   case X86::BI__builtin_ia32_vpermilpd512:
4065   case X86::BI__builtin_ia32_vpermilps512:
4066   case X86::BI__builtin_ia32_pshufd:
4067   case X86::BI__builtin_ia32_pshufd256:
4068   case X86::BI__builtin_ia32_pshufd512:
4069   case X86::BI__builtin_ia32_pshufhw:
4070   case X86::BI__builtin_ia32_pshufhw256:
4071   case X86::BI__builtin_ia32_pshufhw512:
4072   case X86::BI__builtin_ia32_pshuflw:
4073   case X86::BI__builtin_ia32_pshuflw256:
4074   case X86::BI__builtin_ia32_pshuflw512:
4075   case X86::BI__builtin_ia32_vcvtps2ph:
4076   case X86::BI__builtin_ia32_vcvtps2ph_mask:
4077   case X86::BI__builtin_ia32_vcvtps2ph256:
4078   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
4079   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
4080   case X86::BI__builtin_ia32_rndscaleps_128_mask:
4081   case X86::BI__builtin_ia32_rndscalepd_128_mask:
4082   case X86::BI__builtin_ia32_rndscaleps_256_mask:
4083   case X86::BI__builtin_ia32_rndscalepd_256_mask:
4084   case X86::BI__builtin_ia32_rndscaleps_mask:
4085   case X86::BI__builtin_ia32_rndscalepd_mask:
4086   case X86::BI__builtin_ia32_reducepd128_mask:
4087   case X86::BI__builtin_ia32_reducepd256_mask:
4088   case X86::BI__builtin_ia32_reducepd512_mask:
4089   case X86::BI__builtin_ia32_reduceps128_mask:
4090   case X86::BI__builtin_ia32_reduceps256_mask:
4091   case X86::BI__builtin_ia32_reduceps512_mask:
4092   case X86::BI__builtin_ia32_prold512:
4093   case X86::BI__builtin_ia32_prolq512:
4094   case X86::BI__builtin_ia32_prold128:
4095   case X86::BI__builtin_ia32_prold256:
4096   case X86::BI__builtin_ia32_prolq128:
4097   case X86::BI__builtin_ia32_prolq256:
4098   case X86::BI__builtin_ia32_prord512:
4099   case X86::BI__builtin_ia32_prorq512:
4100   case X86::BI__builtin_ia32_prord128:
4101   case X86::BI__builtin_ia32_prord256:
4102   case X86::BI__builtin_ia32_prorq128:
4103   case X86::BI__builtin_ia32_prorq256:
4104   case X86::BI__builtin_ia32_fpclasspd128_mask:
4105   case X86::BI__builtin_ia32_fpclasspd256_mask:
4106   case X86::BI__builtin_ia32_fpclassps128_mask:
4107   case X86::BI__builtin_ia32_fpclassps256_mask:
4108   case X86::BI__builtin_ia32_fpclassps512_mask:
4109   case X86::BI__builtin_ia32_fpclasspd512_mask:
4110   case X86::BI__builtin_ia32_fpclasssd_mask:
4111   case X86::BI__builtin_ia32_fpclassss_mask:
4112   case X86::BI__builtin_ia32_pslldqi128_byteshift:
4113   case X86::BI__builtin_ia32_pslldqi256_byteshift:
4114   case X86::BI__builtin_ia32_pslldqi512_byteshift:
4115   case X86::BI__builtin_ia32_psrldqi128_byteshift:
4116   case X86::BI__builtin_ia32_psrldqi256_byteshift:
4117   case X86::BI__builtin_ia32_psrldqi512_byteshift:
4118   case X86::BI__builtin_ia32_kshiftliqi:
4119   case X86::BI__builtin_ia32_kshiftlihi:
4120   case X86::BI__builtin_ia32_kshiftlisi:
4121   case X86::BI__builtin_ia32_kshiftlidi:
4122   case X86::BI__builtin_ia32_kshiftriqi:
4123   case X86::BI__builtin_ia32_kshiftrihi:
4124   case X86::BI__builtin_ia32_kshiftrisi:
4125   case X86::BI__builtin_ia32_kshiftridi:
4126     i = 1; l = 0; u = 255;
4127     break;
4128   case X86::BI__builtin_ia32_vperm2f128_pd256:
4129   case X86::BI__builtin_ia32_vperm2f128_ps256:
4130   case X86::BI__builtin_ia32_vperm2f128_si256:
4131   case X86::BI__builtin_ia32_permti256:
4132   case X86::BI__builtin_ia32_pblendw128:
4133   case X86::BI__builtin_ia32_pblendw256:
4134   case X86::BI__builtin_ia32_blendps256:
4135   case X86::BI__builtin_ia32_pblendd256:
4136   case X86::BI__builtin_ia32_palignr128:
4137   case X86::BI__builtin_ia32_palignr256:
4138   case X86::BI__builtin_ia32_palignr512:
4139   case X86::BI__builtin_ia32_alignq512:
4140   case X86::BI__builtin_ia32_alignd512:
4141   case X86::BI__builtin_ia32_alignd128:
4142   case X86::BI__builtin_ia32_alignd256:
4143   case X86::BI__builtin_ia32_alignq128:
4144   case X86::BI__builtin_ia32_alignq256:
4145   case X86::BI__builtin_ia32_vcomisd:
4146   case X86::BI__builtin_ia32_vcomiss:
4147   case X86::BI__builtin_ia32_shuf_f32x4:
4148   case X86::BI__builtin_ia32_shuf_f64x2:
4149   case X86::BI__builtin_ia32_shuf_i32x4:
4150   case X86::BI__builtin_ia32_shuf_i64x2:
4151   case X86::BI__builtin_ia32_shufpd512:
4152   case X86::BI__builtin_ia32_shufps:
4153   case X86::BI__builtin_ia32_shufps256:
4154   case X86::BI__builtin_ia32_shufps512:
4155   case X86::BI__builtin_ia32_dbpsadbw128:
4156   case X86::BI__builtin_ia32_dbpsadbw256:
4157   case X86::BI__builtin_ia32_dbpsadbw512:
4158   case X86::BI__builtin_ia32_vpshldd128:
4159   case X86::BI__builtin_ia32_vpshldd256:
4160   case X86::BI__builtin_ia32_vpshldd512:
4161   case X86::BI__builtin_ia32_vpshldq128:
4162   case X86::BI__builtin_ia32_vpshldq256:
4163   case X86::BI__builtin_ia32_vpshldq512:
4164   case X86::BI__builtin_ia32_vpshldw128:
4165   case X86::BI__builtin_ia32_vpshldw256:
4166   case X86::BI__builtin_ia32_vpshldw512:
4167   case X86::BI__builtin_ia32_vpshrdd128:
4168   case X86::BI__builtin_ia32_vpshrdd256:
4169   case X86::BI__builtin_ia32_vpshrdd512:
4170   case X86::BI__builtin_ia32_vpshrdq128:
4171   case X86::BI__builtin_ia32_vpshrdq256:
4172   case X86::BI__builtin_ia32_vpshrdq512:
4173   case X86::BI__builtin_ia32_vpshrdw128:
4174   case X86::BI__builtin_ia32_vpshrdw256:
4175   case X86::BI__builtin_ia32_vpshrdw512:
4176     i = 2; l = 0; u = 255;
4177     break;
4178   case X86::BI__builtin_ia32_fixupimmpd512_mask:
4179   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
4180   case X86::BI__builtin_ia32_fixupimmps512_mask:
4181   case X86::BI__builtin_ia32_fixupimmps512_maskz:
4182   case X86::BI__builtin_ia32_fixupimmsd_mask:
4183   case X86::BI__builtin_ia32_fixupimmsd_maskz:
4184   case X86::BI__builtin_ia32_fixupimmss_mask:
4185   case X86::BI__builtin_ia32_fixupimmss_maskz:
4186   case X86::BI__builtin_ia32_fixupimmpd128_mask:
4187   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
4188   case X86::BI__builtin_ia32_fixupimmpd256_mask:
4189   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
4190   case X86::BI__builtin_ia32_fixupimmps128_mask:
4191   case X86::BI__builtin_ia32_fixupimmps128_maskz:
4192   case X86::BI__builtin_ia32_fixupimmps256_mask:
4193   case X86::BI__builtin_ia32_fixupimmps256_maskz:
4194   case X86::BI__builtin_ia32_pternlogd512_mask:
4195   case X86::BI__builtin_ia32_pternlogd512_maskz:
4196   case X86::BI__builtin_ia32_pternlogq512_mask:
4197   case X86::BI__builtin_ia32_pternlogq512_maskz:
4198   case X86::BI__builtin_ia32_pternlogd128_mask:
4199   case X86::BI__builtin_ia32_pternlogd128_maskz:
4200   case X86::BI__builtin_ia32_pternlogd256_mask:
4201   case X86::BI__builtin_ia32_pternlogd256_maskz:
4202   case X86::BI__builtin_ia32_pternlogq128_mask:
4203   case X86::BI__builtin_ia32_pternlogq128_maskz:
4204   case X86::BI__builtin_ia32_pternlogq256_mask:
4205   case X86::BI__builtin_ia32_pternlogq256_maskz:
4206     i = 3; l = 0; u = 255;
4207     break;
4208   case X86::BI__builtin_ia32_gatherpfdpd:
4209   case X86::BI__builtin_ia32_gatherpfdps:
4210   case X86::BI__builtin_ia32_gatherpfqpd:
4211   case X86::BI__builtin_ia32_gatherpfqps:
4212   case X86::BI__builtin_ia32_scatterpfdpd:
4213   case X86::BI__builtin_ia32_scatterpfdps:
4214   case X86::BI__builtin_ia32_scatterpfqpd:
4215   case X86::BI__builtin_ia32_scatterpfqps:
4216     i = 4; l = 2; u = 3;
4217     break;
4218   case X86::BI__builtin_ia32_reducesd_mask:
4219   case X86::BI__builtin_ia32_reducess_mask:
4220   case X86::BI__builtin_ia32_rndscalesd_round_mask:
4221   case X86::BI__builtin_ia32_rndscaless_round_mask:
4222     i = 4; l = 0; u = 255;
4223     break;
4224   }
4225 
4226   // Note that we don't force a hard error on the range check here, allowing
4227   // template-generated or macro-generated dead code to potentially have out-of-
4228   // range values. These need to code generate, but don't need to necessarily
4229   // make any sense. We use a warning that defaults to an error.
4230   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
4231 }
4232 
4233 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
4234 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
4235 /// Returns true when the format fits the function and the FormatStringInfo has
4236 /// been populated.
4237 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
4238                                FormatStringInfo *FSI) {
4239   FSI->HasVAListArg = Format->getFirstArg() == 0;
4240   FSI->FormatIdx = Format->getFormatIdx() - 1;
4241   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
4242 
4243   // The way the format attribute works in GCC, the implicit this argument
4244   // of member functions is counted. However, it doesn't appear in our own
4245   // lists, so decrement format_idx in that case.
4246   if (IsCXXMember) {
4247     if(FSI->FormatIdx == 0)
4248       return false;
4249     --FSI->FormatIdx;
4250     if (FSI->FirstDataArg != 0)
4251       --FSI->FirstDataArg;
4252   }
4253   return true;
4254 }
4255 
4256 /// Checks if a the given expression evaluates to null.
4257 ///
4258 /// Returns true if the value evaluates to null.
4259 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4260   // If the expression has non-null type, it doesn't evaluate to null.
4261   if (auto nullability
4262         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
4263     if (*nullability == NullabilityKind::NonNull)
4264       return false;
4265   }
4266 
4267   // As a special case, transparent unions initialized with zero are
4268   // considered null for the purposes of the nonnull attribute.
4269   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
4270     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
4271       if (const CompoundLiteralExpr *CLE =
4272           dyn_cast<CompoundLiteralExpr>(Expr))
4273         if (const InitListExpr *ILE =
4274             dyn_cast<InitListExpr>(CLE->getInitializer()))
4275           Expr = ILE->getInit(0);
4276   }
4277 
4278   bool Result;
4279   return (!Expr->isValueDependent() &&
4280           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
4281           !Result);
4282 }
4283 
4284 static void CheckNonNullArgument(Sema &S,
4285                                  const Expr *ArgExpr,
4286                                  SourceLocation CallSiteLoc) {
4287   if (CheckNonNullExpr(S, ArgExpr))
4288     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
4289                           S.PDiag(diag::warn_null_arg)
4290                               << ArgExpr->getSourceRange());
4291 }
4292 
4293 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
4294   FormatStringInfo FSI;
4295   if ((GetFormatStringType(Format) == FST_NSString) &&
4296       getFormatStringInfo(Format, false, &FSI)) {
4297     Idx = FSI.FormatIdx;
4298     return true;
4299   }
4300   return false;
4301 }
4302 
4303 /// Diagnose use of %s directive in an NSString which is being passed
4304 /// as formatting string to formatting method.
4305 static void
4306 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
4307                                         const NamedDecl *FDecl,
4308                                         Expr **Args,
4309                                         unsigned NumArgs) {
4310   unsigned Idx = 0;
4311   bool Format = false;
4312   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
4313   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
4314     Idx = 2;
4315     Format = true;
4316   }
4317   else
4318     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4319       if (S.GetFormatNSStringIdx(I, Idx)) {
4320         Format = true;
4321         break;
4322       }
4323     }
4324   if (!Format || NumArgs <= Idx)
4325     return;
4326   const Expr *FormatExpr = Args[Idx];
4327   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
4328     FormatExpr = CSCE->getSubExpr();
4329   const StringLiteral *FormatString;
4330   if (const ObjCStringLiteral *OSL =
4331       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
4332     FormatString = OSL->getString();
4333   else
4334     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
4335   if (!FormatString)
4336     return;
4337   if (S.FormatStringHasSArg(FormatString)) {
4338     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
4339       << "%s" << 1 << 1;
4340     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
4341       << FDecl->getDeclName();
4342   }
4343 }
4344 
4345 /// Determine whether the given type has a non-null nullability annotation.
4346 static bool isNonNullType(ASTContext &ctx, QualType type) {
4347   if (auto nullability = type->getNullability(ctx))
4348     return *nullability == NullabilityKind::NonNull;
4349 
4350   return false;
4351 }
4352 
4353 static void CheckNonNullArguments(Sema &S,
4354                                   const NamedDecl *FDecl,
4355                                   const FunctionProtoType *Proto,
4356                                   ArrayRef<const Expr *> Args,
4357                                   SourceLocation CallSiteLoc) {
4358   assert((FDecl || Proto) && "Need a function declaration or prototype");
4359 
4360   // Already checked by by constant evaluator.
4361   if (S.isConstantEvaluated())
4362     return;
4363   // Check the attributes attached to the method/function itself.
4364   llvm::SmallBitVector NonNullArgs;
4365   if (FDecl) {
4366     // Handle the nonnull attribute on the function/method declaration itself.
4367     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4368       if (!NonNull->args_size()) {
4369         // Easy case: all pointer arguments are nonnull.
4370         for (const auto *Arg : Args)
4371           if (S.isValidPointerAttrType(Arg->getType()))
4372             CheckNonNullArgument(S, Arg, CallSiteLoc);
4373         return;
4374       }
4375 
4376       for (const ParamIdx &Idx : NonNull->args()) {
4377         unsigned IdxAST = Idx.getASTIndex();
4378         if (IdxAST >= Args.size())
4379           continue;
4380         if (NonNullArgs.empty())
4381           NonNullArgs.resize(Args.size());
4382         NonNullArgs.set(IdxAST);
4383       }
4384     }
4385   }
4386 
4387   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4388     // Handle the nonnull attribute on the parameters of the
4389     // function/method.
4390     ArrayRef<ParmVarDecl*> parms;
4391     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4392       parms = FD->parameters();
4393     else
4394       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4395 
4396     unsigned ParamIndex = 0;
4397     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4398          I != E; ++I, ++ParamIndex) {
4399       const ParmVarDecl *PVD = *I;
4400       if (PVD->hasAttr<NonNullAttr>() ||
4401           isNonNullType(S.Context, PVD->getType())) {
4402         if (NonNullArgs.empty())
4403           NonNullArgs.resize(Args.size());
4404 
4405         NonNullArgs.set(ParamIndex);
4406       }
4407     }
4408   } else {
4409     // If we have a non-function, non-method declaration but no
4410     // function prototype, try to dig out the function prototype.
4411     if (!Proto) {
4412       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4413         QualType type = VD->getType().getNonReferenceType();
4414         if (auto pointerType = type->getAs<PointerType>())
4415           type = pointerType->getPointeeType();
4416         else if (auto blockType = type->getAs<BlockPointerType>())
4417           type = blockType->getPointeeType();
4418         // FIXME: data member pointers?
4419 
4420         // Dig out the function prototype, if there is one.
4421         Proto = type->getAs<FunctionProtoType>();
4422       }
4423     }
4424 
4425     // Fill in non-null argument information from the nullability
4426     // information on the parameter types (if we have them).
4427     if (Proto) {
4428       unsigned Index = 0;
4429       for (auto paramType : Proto->getParamTypes()) {
4430         if (isNonNullType(S.Context, paramType)) {
4431           if (NonNullArgs.empty())
4432             NonNullArgs.resize(Args.size());
4433 
4434           NonNullArgs.set(Index);
4435         }
4436 
4437         ++Index;
4438       }
4439     }
4440   }
4441 
4442   // Check for non-null arguments.
4443   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4444        ArgIndex != ArgIndexEnd; ++ArgIndex) {
4445     if (NonNullArgs[ArgIndex])
4446       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
4447   }
4448 }
4449 
4450 /// Handles the checks for format strings, non-POD arguments to vararg
4451 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
4452 /// attributes.
4453 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
4454                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
4455                      bool IsMemberFunction, SourceLocation Loc,
4456                      SourceRange Range, VariadicCallType CallType) {
4457   // FIXME: We should check as much as we can in the template definition.
4458   if (CurContext->isDependentContext())
4459     return;
4460 
4461   // Printf and scanf checking.
4462   llvm::SmallBitVector CheckedVarArgs;
4463   if (FDecl) {
4464     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4465       // Only create vector if there are format attributes.
4466       CheckedVarArgs.resize(Args.size());
4467 
4468       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4469                            CheckedVarArgs);
4470     }
4471   }
4472 
4473   // Refuse POD arguments that weren't caught by the format string
4474   // checks above.
4475   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4476   if (CallType != VariadicDoesNotApply &&
4477       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4478     unsigned NumParams = Proto ? Proto->getNumParams()
4479                        : FDecl && isa<FunctionDecl>(FDecl)
4480                            ? cast<FunctionDecl>(FDecl)->getNumParams()
4481                        : FDecl && isa<ObjCMethodDecl>(FDecl)
4482                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
4483                        : 0;
4484 
4485     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4486       // Args[ArgIdx] can be null in malformed code.
4487       if (const Expr *Arg = Args[ArgIdx]) {
4488         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4489           checkVariadicArgument(Arg, CallType);
4490       }
4491     }
4492   }
4493 
4494   if (FDecl || Proto) {
4495     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4496 
4497     // Type safety checking.
4498     if (FDecl) {
4499       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4500         CheckArgumentWithTypeTag(I, Args, Loc);
4501     }
4502   }
4503 
4504   if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
4505     auto *AA = FDecl->getAttr<AllocAlignAttr>();
4506     const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
4507     if (!Arg->isValueDependent()) {
4508       Expr::EvalResult Align;
4509       if (Arg->EvaluateAsInt(Align, Context)) {
4510         const llvm::APSInt &I = Align.Val.getInt();
4511         if (!I.isPowerOf2())
4512           Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
4513               << Arg->getSourceRange();
4514 
4515         if (I > Sema::MaximumAlignment)
4516           Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
4517               << Arg->getSourceRange() << Sema::MaximumAlignment;
4518       }
4519     }
4520   }
4521 
4522   if (FD)
4523     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4524 }
4525 
4526 /// CheckConstructorCall - Check a constructor call for correctness and safety
4527 /// properties not enforced by the C type system.
4528 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
4529                                 ArrayRef<const Expr *> Args,
4530                                 const FunctionProtoType *Proto,
4531                                 SourceLocation Loc) {
4532   VariadicCallType CallType =
4533     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4534   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4535             Loc, SourceRange(), CallType);
4536 }
4537 
4538 /// CheckFunctionCall - Check a direct function call for various correctness
4539 /// and safety properties not strictly enforced by the C type system.
4540 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
4541                              const FunctionProtoType *Proto) {
4542   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4543                               isa<CXXMethodDecl>(FDecl);
4544   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4545                           IsMemberOperatorCall;
4546   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4547                                                   TheCall->getCallee());
4548   Expr** Args = TheCall->getArgs();
4549   unsigned NumArgs = TheCall->getNumArgs();
4550 
4551   Expr *ImplicitThis = nullptr;
4552   if (IsMemberOperatorCall) {
4553     // If this is a call to a member operator, hide the first argument
4554     // from checkCall.
4555     // FIXME: Our choice of AST representation here is less than ideal.
4556     ImplicitThis = Args[0];
4557     ++Args;
4558     --NumArgs;
4559   } else if (IsMemberFunction)
4560     ImplicitThis =
4561         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4562 
4563   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
4564             IsMemberFunction, TheCall->getRParenLoc(),
4565             TheCall->getCallee()->getSourceRange(), CallType);
4566 
4567   IdentifierInfo *FnInfo = FDecl->getIdentifier();
4568   // None of the checks below are needed for functions that don't have
4569   // simple names (e.g., C++ conversion functions).
4570   if (!FnInfo)
4571     return false;
4572 
4573   CheckTCBEnforcement(TheCall, FDecl);
4574 
4575   CheckAbsoluteValueFunction(TheCall, FDecl);
4576   CheckMaxUnsignedZero(TheCall, FDecl);
4577 
4578   if (getLangOpts().ObjC)
4579     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
4580 
4581   unsigned CMId = FDecl->getMemoryFunctionKind();
4582 
4583   // Handle memory setting and copying functions.
4584   switch (CMId) {
4585   case 0:
4586     return false;
4587   case Builtin::BIstrlcpy: // fallthrough
4588   case Builtin::BIstrlcat:
4589     CheckStrlcpycatArguments(TheCall, FnInfo);
4590     break;
4591   case Builtin::BIstrncat:
4592     CheckStrncatArguments(TheCall, FnInfo);
4593     break;
4594   case Builtin::BIfree:
4595     CheckFreeArguments(TheCall);
4596     break;
4597   default:
4598     CheckMemaccessArguments(TheCall, CMId, FnInfo);
4599   }
4600 
4601   return false;
4602 }
4603 
4604 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
4605                                ArrayRef<const Expr *> Args) {
4606   VariadicCallType CallType =
4607       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
4608 
4609   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
4610             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
4611             CallType);
4612 
4613   return false;
4614 }
4615 
4616 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4617                             const FunctionProtoType *Proto) {
4618   QualType Ty;
4619   if (const auto *V = dyn_cast<VarDecl>(NDecl))
4620     Ty = V->getType().getNonReferenceType();
4621   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4622     Ty = F->getType().getNonReferenceType();
4623   else
4624     return false;
4625 
4626   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4627       !Ty->isFunctionProtoType())
4628     return false;
4629 
4630   VariadicCallType CallType;
4631   if (!Proto || !Proto->isVariadic()) {
4632     CallType = VariadicDoesNotApply;
4633   } else if (Ty->isBlockPointerType()) {
4634     CallType = VariadicBlock;
4635   } else { // Ty->isFunctionPointerType()
4636     CallType = VariadicFunction;
4637   }
4638 
4639   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4640             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4641             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4642             TheCall->getCallee()->getSourceRange(), CallType);
4643 
4644   return false;
4645 }
4646 
4647 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
4648 /// such as function pointers returned from functions.
4649 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4650   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4651                                                   TheCall->getCallee());
4652   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4653             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4654             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4655             TheCall->getCallee()->getSourceRange(), CallType);
4656 
4657   return false;
4658 }
4659 
4660 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4661   if (!llvm::isValidAtomicOrderingCABI(Ordering))
4662     return false;
4663 
4664   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4665   switch (Op) {
4666   case AtomicExpr::AO__c11_atomic_init:
4667   case AtomicExpr::AO__opencl_atomic_init:
4668     llvm_unreachable("There is no ordering argument for an init");
4669 
4670   case AtomicExpr::AO__c11_atomic_load:
4671   case AtomicExpr::AO__opencl_atomic_load:
4672   case AtomicExpr::AO__atomic_load_n:
4673   case AtomicExpr::AO__atomic_load:
4674     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4675            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4676 
4677   case AtomicExpr::AO__c11_atomic_store:
4678   case AtomicExpr::AO__opencl_atomic_store:
4679   case AtomicExpr::AO__atomic_store:
4680   case AtomicExpr::AO__atomic_store_n:
4681     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4682            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4683            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4684 
4685   default:
4686     return true;
4687   }
4688 }
4689 
4690 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
4691                                          AtomicExpr::AtomicOp Op) {
4692   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4693   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4694   MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
4695   return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
4696                          DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
4697                          Op);
4698 }
4699 
4700 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
4701                                  SourceLocation RParenLoc, MultiExprArg Args,
4702                                  AtomicExpr::AtomicOp Op,
4703                                  AtomicArgumentOrder ArgOrder) {
4704   // All the non-OpenCL operations take one of the following forms.
4705   // The OpenCL operations take the __c11 forms with one extra argument for
4706   // synchronization scope.
4707   enum {
4708     // C    __c11_atomic_init(A *, C)
4709     Init,
4710 
4711     // C    __c11_atomic_load(A *, int)
4712     Load,
4713 
4714     // void __atomic_load(A *, CP, int)
4715     LoadCopy,
4716 
4717     // void __atomic_store(A *, CP, int)
4718     Copy,
4719 
4720     // C    __c11_atomic_add(A *, M, int)
4721     Arithmetic,
4722 
4723     // C    __atomic_exchange_n(A *, CP, int)
4724     Xchg,
4725 
4726     // void __atomic_exchange(A *, C *, CP, int)
4727     GNUXchg,
4728 
4729     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4730     C11CmpXchg,
4731 
4732     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4733     GNUCmpXchg
4734   } Form = Init;
4735 
4736   const unsigned NumForm = GNUCmpXchg + 1;
4737   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
4738   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
4739   // where:
4740   //   C is an appropriate type,
4741   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4742   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4743   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4744   //   the int parameters are for orderings.
4745 
4746   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4747       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4748       "need to update code for modified forms");
4749   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
4750                     AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
4751                         AtomicExpr::AO__atomic_load,
4752                 "need to update code for modified C11 atomics");
4753   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
4754                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
4755   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
4756                Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
4757                IsOpenCL;
4758   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4759              Op == AtomicExpr::AO__atomic_store_n ||
4760              Op == AtomicExpr::AO__atomic_exchange_n ||
4761              Op == AtomicExpr::AO__atomic_compare_exchange_n;
4762   bool IsAddSub = false;
4763 
4764   switch (Op) {
4765   case AtomicExpr::AO__c11_atomic_init:
4766   case AtomicExpr::AO__opencl_atomic_init:
4767     Form = Init;
4768     break;
4769 
4770   case AtomicExpr::AO__c11_atomic_load:
4771   case AtomicExpr::AO__opencl_atomic_load:
4772   case AtomicExpr::AO__atomic_load_n:
4773     Form = Load;
4774     break;
4775 
4776   case AtomicExpr::AO__atomic_load:
4777     Form = LoadCopy;
4778     break;
4779 
4780   case AtomicExpr::AO__c11_atomic_store:
4781   case AtomicExpr::AO__opencl_atomic_store:
4782   case AtomicExpr::AO__atomic_store:
4783   case AtomicExpr::AO__atomic_store_n:
4784     Form = Copy;
4785     break;
4786 
4787   case AtomicExpr::AO__c11_atomic_fetch_add:
4788   case AtomicExpr::AO__c11_atomic_fetch_sub:
4789   case AtomicExpr::AO__opencl_atomic_fetch_add:
4790   case AtomicExpr::AO__opencl_atomic_fetch_sub:
4791   case AtomicExpr::AO__atomic_fetch_add:
4792   case AtomicExpr::AO__atomic_fetch_sub:
4793   case AtomicExpr::AO__atomic_add_fetch:
4794   case AtomicExpr::AO__atomic_sub_fetch:
4795     IsAddSub = true;
4796     LLVM_FALLTHROUGH;
4797   case AtomicExpr::AO__c11_atomic_fetch_and:
4798   case AtomicExpr::AO__c11_atomic_fetch_or:
4799   case AtomicExpr::AO__c11_atomic_fetch_xor:
4800   case AtomicExpr::AO__opencl_atomic_fetch_and:
4801   case AtomicExpr::AO__opencl_atomic_fetch_or:
4802   case AtomicExpr::AO__opencl_atomic_fetch_xor:
4803   case AtomicExpr::AO__atomic_fetch_and:
4804   case AtomicExpr::AO__atomic_fetch_or:
4805   case AtomicExpr::AO__atomic_fetch_xor:
4806   case AtomicExpr::AO__atomic_fetch_nand:
4807   case AtomicExpr::AO__atomic_and_fetch:
4808   case AtomicExpr::AO__atomic_or_fetch:
4809   case AtomicExpr::AO__atomic_xor_fetch:
4810   case AtomicExpr::AO__atomic_nand_fetch:
4811   case AtomicExpr::AO__c11_atomic_fetch_min:
4812   case AtomicExpr::AO__c11_atomic_fetch_max:
4813   case AtomicExpr::AO__opencl_atomic_fetch_min:
4814   case AtomicExpr::AO__opencl_atomic_fetch_max:
4815   case AtomicExpr::AO__atomic_min_fetch:
4816   case AtomicExpr::AO__atomic_max_fetch:
4817   case AtomicExpr::AO__atomic_fetch_min:
4818   case AtomicExpr::AO__atomic_fetch_max:
4819     Form = Arithmetic;
4820     break;
4821 
4822   case AtomicExpr::AO__c11_atomic_exchange:
4823   case AtomicExpr::AO__opencl_atomic_exchange:
4824   case AtomicExpr::AO__atomic_exchange_n:
4825     Form = Xchg;
4826     break;
4827 
4828   case AtomicExpr::AO__atomic_exchange:
4829     Form = GNUXchg;
4830     break;
4831 
4832   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
4833   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
4834   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
4835   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
4836     Form = C11CmpXchg;
4837     break;
4838 
4839   case AtomicExpr::AO__atomic_compare_exchange:
4840   case AtomicExpr::AO__atomic_compare_exchange_n:
4841     Form = GNUCmpXchg;
4842     break;
4843   }
4844 
4845   unsigned AdjustedNumArgs = NumArgs[Form];
4846   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
4847     ++AdjustedNumArgs;
4848   // Check we have the right number of arguments.
4849   if (Args.size() < AdjustedNumArgs) {
4850     Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
4851         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4852         << ExprRange;
4853     return ExprError();
4854   } else if (Args.size() > AdjustedNumArgs) {
4855     Diag(Args[AdjustedNumArgs]->getBeginLoc(),
4856          diag::err_typecheck_call_too_many_args)
4857         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4858         << ExprRange;
4859     return ExprError();
4860   }
4861 
4862   // Inspect the first argument of the atomic operation.
4863   Expr *Ptr = Args[0];
4864   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
4865   if (ConvertedPtr.isInvalid())
4866     return ExprError();
4867 
4868   Ptr = ConvertedPtr.get();
4869   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
4870   if (!pointerType) {
4871     Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
4872         << Ptr->getType() << Ptr->getSourceRange();
4873     return ExprError();
4874   }
4875 
4876   // For a __c11 builtin, this should be a pointer to an _Atomic type.
4877   QualType AtomTy = pointerType->getPointeeType(); // 'A'
4878   QualType ValType = AtomTy; // 'C'
4879   if (IsC11) {
4880     if (!AtomTy->isAtomicType()) {
4881       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
4882           << Ptr->getType() << Ptr->getSourceRange();
4883       return ExprError();
4884     }
4885     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
4886         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
4887       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
4888           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
4889           << Ptr->getSourceRange();
4890       return ExprError();
4891     }
4892     ValType = AtomTy->castAs<AtomicType>()->getValueType();
4893   } else if (Form != Load && Form != LoadCopy) {
4894     if (ValType.isConstQualified()) {
4895       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
4896           << Ptr->getType() << Ptr->getSourceRange();
4897       return ExprError();
4898     }
4899   }
4900 
4901   // For an arithmetic operation, the implied arithmetic must be well-formed.
4902   if (Form == Arithmetic) {
4903     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
4904     if (IsAddSub && !ValType->isIntegerType()
4905         && !ValType->isPointerType()) {
4906       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4907           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4908       return ExprError();
4909     }
4910     if (!IsAddSub && !ValType->isIntegerType()) {
4911       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
4912           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4913       return ExprError();
4914     }
4915     if (IsC11 && ValType->isPointerType() &&
4916         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
4917                             diag::err_incomplete_type)) {
4918       return ExprError();
4919     }
4920   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
4921     // For __atomic_*_n operations, the value type must be a scalar integral or
4922     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
4923     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4924         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4925     return ExprError();
4926   }
4927 
4928   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
4929       !AtomTy->isScalarType()) {
4930     // For GNU atomics, require a trivially-copyable type. This is not part of
4931     // the GNU atomics specification, but we enforce it for sanity.
4932     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
4933         << Ptr->getType() << Ptr->getSourceRange();
4934     return ExprError();
4935   }
4936 
4937   switch (ValType.getObjCLifetime()) {
4938   case Qualifiers::OCL_None:
4939   case Qualifiers::OCL_ExplicitNone:
4940     // okay
4941     break;
4942 
4943   case Qualifiers::OCL_Weak:
4944   case Qualifiers::OCL_Strong:
4945   case Qualifiers::OCL_Autoreleasing:
4946     // FIXME: Can this happen? By this point, ValType should be known
4947     // to be trivially copyable.
4948     Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
4949         << ValType << Ptr->getSourceRange();
4950     return ExprError();
4951   }
4952 
4953   // All atomic operations have an overload which takes a pointer to a volatile
4954   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
4955   // into the result or the other operands. Similarly atomic_load takes a
4956   // pointer to a const 'A'.
4957   ValType.removeLocalVolatile();
4958   ValType.removeLocalConst();
4959   QualType ResultType = ValType;
4960   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
4961       Form == Init)
4962     ResultType = Context.VoidTy;
4963   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
4964     ResultType = Context.BoolTy;
4965 
4966   // The type of a parameter passed 'by value'. In the GNU atomics, such
4967   // arguments are actually passed as pointers.
4968   QualType ByValType = ValType; // 'CP'
4969   bool IsPassedByAddress = false;
4970   if (!IsC11 && !IsN) {
4971     ByValType = Ptr->getType();
4972     IsPassedByAddress = true;
4973   }
4974 
4975   SmallVector<Expr *, 5> APIOrderedArgs;
4976   if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
4977     APIOrderedArgs.push_back(Args[0]);
4978     switch (Form) {
4979     case Init:
4980     case Load:
4981       APIOrderedArgs.push_back(Args[1]); // Val1/Order
4982       break;
4983     case LoadCopy:
4984     case Copy:
4985     case Arithmetic:
4986     case Xchg:
4987       APIOrderedArgs.push_back(Args[2]); // Val1
4988       APIOrderedArgs.push_back(Args[1]); // Order
4989       break;
4990     case GNUXchg:
4991       APIOrderedArgs.push_back(Args[2]); // Val1
4992       APIOrderedArgs.push_back(Args[3]); // Val2
4993       APIOrderedArgs.push_back(Args[1]); // Order
4994       break;
4995     case C11CmpXchg:
4996       APIOrderedArgs.push_back(Args[2]); // Val1
4997       APIOrderedArgs.push_back(Args[4]); // Val2
4998       APIOrderedArgs.push_back(Args[1]); // Order
4999       APIOrderedArgs.push_back(Args[3]); // OrderFail
5000       break;
5001     case GNUCmpXchg:
5002       APIOrderedArgs.push_back(Args[2]); // Val1
5003       APIOrderedArgs.push_back(Args[4]); // Val2
5004       APIOrderedArgs.push_back(Args[5]); // Weak
5005       APIOrderedArgs.push_back(Args[1]); // Order
5006       APIOrderedArgs.push_back(Args[3]); // OrderFail
5007       break;
5008     }
5009   } else
5010     APIOrderedArgs.append(Args.begin(), Args.end());
5011 
5012   // The first argument's non-CV pointer type is used to deduce the type of
5013   // subsequent arguments, except for:
5014   //  - weak flag (always converted to bool)
5015   //  - memory order (always converted to int)
5016   //  - scope  (always converted to int)
5017   for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
5018     QualType Ty;
5019     if (i < NumVals[Form] + 1) {
5020       switch (i) {
5021       case 0:
5022         // The first argument is always a pointer. It has a fixed type.
5023         // It is always dereferenced, a nullptr is undefined.
5024         CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5025         // Nothing else to do: we already know all we want about this pointer.
5026         continue;
5027       case 1:
5028         // The second argument is the non-atomic operand. For arithmetic, this
5029         // is always passed by value, and for a compare_exchange it is always
5030         // passed by address. For the rest, GNU uses by-address and C11 uses
5031         // by-value.
5032         assert(Form != Load);
5033         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
5034           Ty = ValType;
5035         else if (Form == Copy || Form == Xchg) {
5036           if (IsPassedByAddress) {
5037             // The value pointer is always dereferenced, a nullptr is undefined.
5038             CheckNonNullArgument(*this, APIOrderedArgs[i],
5039                                  ExprRange.getBegin());
5040           }
5041           Ty = ByValType;
5042         } else if (Form == Arithmetic)
5043           Ty = Context.getPointerDiffType();
5044         else {
5045           Expr *ValArg = APIOrderedArgs[i];
5046           // The value pointer is always dereferenced, a nullptr is undefined.
5047           CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
5048           LangAS AS = LangAS::Default;
5049           // Keep address space of non-atomic pointer type.
5050           if (const PointerType *PtrTy =
5051                   ValArg->getType()->getAs<PointerType>()) {
5052             AS = PtrTy->getPointeeType().getAddressSpace();
5053           }
5054           Ty = Context.getPointerType(
5055               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
5056         }
5057         break;
5058       case 2:
5059         // The third argument to compare_exchange / GNU exchange is the desired
5060         // value, either by-value (for the C11 and *_n variant) or as a pointer.
5061         if (IsPassedByAddress)
5062           CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5063         Ty = ByValType;
5064         break;
5065       case 3:
5066         // The fourth argument to GNU compare_exchange is a 'weak' flag.
5067         Ty = Context.BoolTy;
5068         break;
5069       }
5070     } else {
5071       // The order(s) and scope are always converted to int.
5072       Ty = Context.IntTy;
5073     }
5074 
5075     InitializedEntity Entity =
5076         InitializedEntity::InitializeParameter(Context, Ty, false);
5077     ExprResult Arg = APIOrderedArgs[i];
5078     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5079     if (Arg.isInvalid())
5080       return true;
5081     APIOrderedArgs[i] = Arg.get();
5082   }
5083 
5084   // Permute the arguments into a 'consistent' order.
5085   SmallVector<Expr*, 5> SubExprs;
5086   SubExprs.push_back(Ptr);
5087   switch (Form) {
5088   case Init:
5089     // Note, AtomicExpr::getVal1() has a special case for this atomic.
5090     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5091     break;
5092   case Load:
5093     SubExprs.push_back(APIOrderedArgs[1]); // Order
5094     break;
5095   case LoadCopy:
5096   case Copy:
5097   case Arithmetic:
5098   case Xchg:
5099     SubExprs.push_back(APIOrderedArgs[2]); // Order
5100     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5101     break;
5102   case GNUXchg:
5103     // Note, AtomicExpr::getVal2() has a special case for this atomic.
5104     SubExprs.push_back(APIOrderedArgs[3]); // Order
5105     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5106     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5107     break;
5108   case C11CmpXchg:
5109     SubExprs.push_back(APIOrderedArgs[3]); // Order
5110     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5111     SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
5112     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5113     break;
5114   case GNUCmpXchg:
5115     SubExprs.push_back(APIOrderedArgs[4]); // Order
5116     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5117     SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
5118     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5119     SubExprs.push_back(APIOrderedArgs[3]); // Weak
5120     break;
5121   }
5122 
5123   if (SubExprs.size() >= 2 && Form != Init) {
5124     if (Optional<llvm::APSInt> Result =
5125             SubExprs[1]->getIntegerConstantExpr(Context))
5126       if (!isValidOrderingForOp(Result->getSExtValue(), Op))
5127         Diag(SubExprs[1]->getBeginLoc(),
5128              diag::warn_atomic_op_has_invalid_memory_order)
5129             << SubExprs[1]->getSourceRange();
5130   }
5131 
5132   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
5133     auto *Scope = Args[Args.size() - 1];
5134     if (Optional<llvm::APSInt> Result =
5135             Scope->getIntegerConstantExpr(Context)) {
5136       if (!ScopeModel->isValid(Result->getZExtValue()))
5137         Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
5138             << Scope->getSourceRange();
5139     }
5140     SubExprs.push_back(Scope);
5141   }
5142 
5143   AtomicExpr *AE = new (Context)
5144       AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
5145 
5146   if ((Op == AtomicExpr::AO__c11_atomic_load ||
5147        Op == AtomicExpr::AO__c11_atomic_store ||
5148        Op == AtomicExpr::AO__opencl_atomic_load ||
5149        Op == AtomicExpr::AO__opencl_atomic_store ) &&
5150       Context.AtomicUsesUnsupportedLibcall(AE))
5151     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
5152         << ((Op == AtomicExpr::AO__c11_atomic_load ||
5153              Op == AtomicExpr::AO__opencl_atomic_load)
5154                 ? 0
5155                 : 1);
5156 
5157   if (ValType->isExtIntType()) {
5158     Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_ext_int_prohibit);
5159     return ExprError();
5160   }
5161 
5162   return AE;
5163 }
5164 
5165 /// checkBuiltinArgument - Given a call to a builtin function, perform
5166 /// normal type-checking on the given argument, updating the call in
5167 /// place.  This is useful when a builtin function requires custom
5168 /// type-checking for some of its arguments but not necessarily all of
5169 /// them.
5170 ///
5171 /// Returns true on error.
5172 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
5173   FunctionDecl *Fn = E->getDirectCallee();
5174   assert(Fn && "builtin call without direct callee!");
5175 
5176   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
5177   InitializedEntity Entity =
5178     InitializedEntity::InitializeParameter(S.Context, Param);
5179 
5180   ExprResult Arg = E->getArg(0);
5181   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
5182   if (Arg.isInvalid())
5183     return true;
5184 
5185   E->setArg(ArgIndex, Arg.get());
5186   return false;
5187 }
5188 
5189 /// We have a call to a function like __sync_fetch_and_add, which is an
5190 /// overloaded function based on the pointer type of its first argument.
5191 /// The main BuildCallExpr routines have already promoted the types of
5192 /// arguments because all of these calls are prototyped as void(...).
5193 ///
5194 /// This function goes through and does final semantic checking for these
5195 /// builtins, as well as generating any warnings.
5196 ExprResult
5197 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
5198   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
5199   Expr *Callee = TheCall->getCallee();
5200   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
5201   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5202 
5203   // Ensure that we have at least one argument to do type inference from.
5204   if (TheCall->getNumArgs() < 1) {
5205     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5206         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
5207     return ExprError();
5208   }
5209 
5210   // Inspect the first argument of the atomic builtin.  This should always be
5211   // a pointer type, whose element is an integral scalar or pointer type.
5212   // Because it is a pointer type, we don't have to worry about any implicit
5213   // casts here.
5214   // FIXME: We don't allow floating point scalars as input.
5215   Expr *FirstArg = TheCall->getArg(0);
5216   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
5217   if (FirstArgResult.isInvalid())
5218     return ExprError();
5219   FirstArg = FirstArgResult.get();
5220   TheCall->setArg(0, FirstArg);
5221 
5222   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5223   if (!pointerType) {
5224     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
5225         << FirstArg->getType() << FirstArg->getSourceRange();
5226     return ExprError();
5227   }
5228 
5229   QualType ValType = pointerType->getPointeeType();
5230   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5231       !ValType->isBlockPointerType()) {
5232     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
5233         << FirstArg->getType() << FirstArg->getSourceRange();
5234     return ExprError();
5235   }
5236 
5237   if (ValType.isConstQualified()) {
5238     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
5239         << FirstArg->getType() << FirstArg->getSourceRange();
5240     return ExprError();
5241   }
5242 
5243   switch (ValType.getObjCLifetime()) {
5244   case Qualifiers::OCL_None:
5245   case Qualifiers::OCL_ExplicitNone:
5246     // okay
5247     break;
5248 
5249   case Qualifiers::OCL_Weak:
5250   case Qualifiers::OCL_Strong:
5251   case Qualifiers::OCL_Autoreleasing:
5252     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
5253         << ValType << FirstArg->getSourceRange();
5254     return ExprError();
5255   }
5256 
5257   // Strip any qualifiers off ValType.
5258   ValType = ValType.getUnqualifiedType();
5259 
5260   // The majority of builtins return a value, but a few have special return
5261   // types, so allow them to override appropriately below.
5262   QualType ResultType = ValType;
5263 
5264   // We need to figure out which concrete builtin this maps onto.  For example,
5265   // __sync_fetch_and_add with a 2 byte object turns into
5266   // __sync_fetch_and_add_2.
5267 #define BUILTIN_ROW(x) \
5268   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5269     Builtin::BI##x##_8, Builtin::BI##x##_16 }
5270 
5271   static const unsigned BuiltinIndices[][5] = {
5272     BUILTIN_ROW(__sync_fetch_and_add),
5273     BUILTIN_ROW(__sync_fetch_and_sub),
5274     BUILTIN_ROW(__sync_fetch_and_or),
5275     BUILTIN_ROW(__sync_fetch_and_and),
5276     BUILTIN_ROW(__sync_fetch_and_xor),
5277     BUILTIN_ROW(__sync_fetch_and_nand),
5278 
5279     BUILTIN_ROW(__sync_add_and_fetch),
5280     BUILTIN_ROW(__sync_sub_and_fetch),
5281     BUILTIN_ROW(__sync_and_and_fetch),
5282     BUILTIN_ROW(__sync_or_and_fetch),
5283     BUILTIN_ROW(__sync_xor_and_fetch),
5284     BUILTIN_ROW(__sync_nand_and_fetch),
5285 
5286     BUILTIN_ROW(__sync_val_compare_and_swap),
5287     BUILTIN_ROW(__sync_bool_compare_and_swap),
5288     BUILTIN_ROW(__sync_lock_test_and_set),
5289     BUILTIN_ROW(__sync_lock_release),
5290     BUILTIN_ROW(__sync_swap)
5291   };
5292 #undef BUILTIN_ROW
5293 
5294   // Determine the index of the size.
5295   unsigned SizeIndex;
5296   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
5297   case 1: SizeIndex = 0; break;
5298   case 2: SizeIndex = 1; break;
5299   case 4: SizeIndex = 2; break;
5300   case 8: SizeIndex = 3; break;
5301   case 16: SizeIndex = 4; break;
5302   default:
5303     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
5304         << FirstArg->getType() << FirstArg->getSourceRange();
5305     return ExprError();
5306   }
5307 
5308   // Each of these builtins has one pointer argument, followed by some number of
5309   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5310   // that we ignore.  Find out which row of BuiltinIndices to read from as well
5311   // as the number of fixed args.
5312   unsigned BuiltinID = FDecl->getBuiltinID();
5313   unsigned BuiltinIndex, NumFixed = 1;
5314   bool WarnAboutSemanticsChange = false;
5315   switch (BuiltinID) {
5316   default: llvm_unreachable("Unknown overloaded atomic builtin!");
5317   case Builtin::BI__sync_fetch_and_add:
5318   case Builtin::BI__sync_fetch_and_add_1:
5319   case Builtin::BI__sync_fetch_and_add_2:
5320   case Builtin::BI__sync_fetch_and_add_4:
5321   case Builtin::BI__sync_fetch_and_add_8:
5322   case Builtin::BI__sync_fetch_and_add_16:
5323     BuiltinIndex = 0;
5324     break;
5325 
5326   case Builtin::BI__sync_fetch_and_sub:
5327   case Builtin::BI__sync_fetch_and_sub_1:
5328   case Builtin::BI__sync_fetch_and_sub_2:
5329   case Builtin::BI__sync_fetch_and_sub_4:
5330   case Builtin::BI__sync_fetch_and_sub_8:
5331   case Builtin::BI__sync_fetch_and_sub_16:
5332     BuiltinIndex = 1;
5333     break;
5334 
5335   case Builtin::BI__sync_fetch_and_or:
5336   case Builtin::BI__sync_fetch_and_or_1:
5337   case Builtin::BI__sync_fetch_and_or_2:
5338   case Builtin::BI__sync_fetch_and_or_4:
5339   case Builtin::BI__sync_fetch_and_or_8:
5340   case Builtin::BI__sync_fetch_and_or_16:
5341     BuiltinIndex = 2;
5342     break;
5343 
5344   case Builtin::BI__sync_fetch_and_and:
5345   case Builtin::BI__sync_fetch_and_and_1:
5346   case Builtin::BI__sync_fetch_and_and_2:
5347   case Builtin::BI__sync_fetch_and_and_4:
5348   case Builtin::BI__sync_fetch_and_and_8:
5349   case Builtin::BI__sync_fetch_and_and_16:
5350     BuiltinIndex = 3;
5351     break;
5352 
5353   case Builtin::BI__sync_fetch_and_xor:
5354   case Builtin::BI__sync_fetch_and_xor_1:
5355   case Builtin::BI__sync_fetch_and_xor_2:
5356   case Builtin::BI__sync_fetch_and_xor_4:
5357   case Builtin::BI__sync_fetch_and_xor_8:
5358   case Builtin::BI__sync_fetch_and_xor_16:
5359     BuiltinIndex = 4;
5360     break;
5361 
5362   case Builtin::BI__sync_fetch_and_nand:
5363   case Builtin::BI__sync_fetch_and_nand_1:
5364   case Builtin::BI__sync_fetch_and_nand_2:
5365   case Builtin::BI__sync_fetch_and_nand_4:
5366   case Builtin::BI__sync_fetch_and_nand_8:
5367   case Builtin::BI__sync_fetch_and_nand_16:
5368     BuiltinIndex = 5;
5369     WarnAboutSemanticsChange = true;
5370     break;
5371 
5372   case Builtin::BI__sync_add_and_fetch:
5373   case Builtin::BI__sync_add_and_fetch_1:
5374   case Builtin::BI__sync_add_and_fetch_2:
5375   case Builtin::BI__sync_add_and_fetch_4:
5376   case Builtin::BI__sync_add_and_fetch_8:
5377   case Builtin::BI__sync_add_and_fetch_16:
5378     BuiltinIndex = 6;
5379     break;
5380 
5381   case Builtin::BI__sync_sub_and_fetch:
5382   case Builtin::BI__sync_sub_and_fetch_1:
5383   case Builtin::BI__sync_sub_and_fetch_2:
5384   case Builtin::BI__sync_sub_and_fetch_4:
5385   case Builtin::BI__sync_sub_and_fetch_8:
5386   case Builtin::BI__sync_sub_and_fetch_16:
5387     BuiltinIndex = 7;
5388     break;
5389 
5390   case Builtin::BI__sync_and_and_fetch:
5391   case Builtin::BI__sync_and_and_fetch_1:
5392   case Builtin::BI__sync_and_and_fetch_2:
5393   case Builtin::BI__sync_and_and_fetch_4:
5394   case Builtin::BI__sync_and_and_fetch_8:
5395   case Builtin::BI__sync_and_and_fetch_16:
5396     BuiltinIndex = 8;
5397     break;
5398 
5399   case Builtin::BI__sync_or_and_fetch:
5400   case Builtin::BI__sync_or_and_fetch_1:
5401   case Builtin::BI__sync_or_and_fetch_2:
5402   case Builtin::BI__sync_or_and_fetch_4:
5403   case Builtin::BI__sync_or_and_fetch_8:
5404   case Builtin::BI__sync_or_and_fetch_16:
5405     BuiltinIndex = 9;
5406     break;
5407 
5408   case Builtin::BI__sync_xor_and_fetch:
5409   case Builtin::BI__sync_xor_and_fetch_1:
5410   case Builtin::BI__sync_xor_and_fetch_2:
5411   case Builtin::BI__sync_xor_and_fetch_4:
5412   case Builtin::BI__sync_xor_and_fetch_8:
5413   case Builtin::BI__sync_xor_and_fetch_16:
5414     BuiltinIndex = 10;
5415     break;
5416 
5417   case Builtin::BI__sync_nand_and_fetch:
5418   case Builtin::BI__sync_nand_and_fetch_1:
5419   case Builtin::BI__sync_nand_and_fetch_2:
5420   case Builtin::BI__sync_nand_and_fetch_4:
5421   case Builtin::BI__sync_nand_and_fetch_8:
5422   case Builtin::BI__sync_nand_and_fetch_16:
5423     BuiltinIndex = 11;
5424     WarnAboutSemanticsChange = true;
5425     break;
5426 
5427   case Builtin::BI__sync_val_compare_and_swap:
5428   case Builtin::BI__sync_val_compare_and_swap_1:
5429   case Builtin::BI__sync_val_compare_and_swap_2:
5430   case Builtin::BI__sync_val_compare_and_swap_4:
5431   case Builtin::BI__sync_val_compare_and_swap_8:
5432   case Builtin::BI__sync_val_compare_and_swap_16:
5433     BuiltinIndex = 12;
5434     NumFixed = 2;
5435     break;
5436 
5437   case Builtin::BI__sync_bool_compare_and_swap:
5438   case Builtin::BI__sync_bool_compare_and_swap_1:
5439   case Builtin::BI__sync_bool_compare_and_swap_2:
5440   case Builtin::BI__sync_bool_compare_and_swap_4:
5441   case Builtin::BI__sync_bool_compare_and_swap_8:
5442   case Builtin::BI__sync_bool_compare_and_swap_16:
5443     BuiltinIndex = 13;
5444     NumFixed = 2;
5445     ResultType = Context.BoolTy;
5446     break;
5447 
5448   case Builtin::BI__sync_lock_test_and_set:
5449   case Builtin::BI__sync_lock_test_and_set_1:
5450   case Builtin::BI__sync_lock_test_and_set_2:
5451   case Builtin::BI__sync_lock_test_and_set_4:
5452   case Builtin::BI__sync_lock_test_and_set_8:
5453   case Builtin::BI__sync_lock_test_and_set_16:
5454     BuiltinIndex = 14;
5455     break;
5456 
5457   case Builtin::BI__sync_lock_release:
5458   case Builtin::BI__sync_lock_release_1:
5459   case Builtin::BI__sync_lock_release_2:
5460   case Builtin::BI__sync_lock_release_4:
5461   case Builtin::BI__sync_lock_release_8:
5462   case Builtin::BI__sync_lock_release_16:
5463     BuiltinIndex = 15;
5464     NumFixed = 0;
5465     ResultType = Context.VoidTy;
5466     break;
5467 
5468   case Builtin::BI__sync_swap:
5469   case Builtin::BI__sync_swap_1:
5470   case Builtin::BI__sync_swap_2:
5471   case Builtin::BI__sync_swap_4:
5472   case Builtin::BI__sync_swap_8:
5473   case Builtin::BI__sync_swap_16:
5474     BuiltinIndex = 16;
5475     break;
5476   }
5477 
5478   // Now that we know how many fixed arguments we expect, first check that we
5479   // have at least that many.
5480   if (TheCall->getNumArgs() < 1+NumFixed) {
5481     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5482         << 0 << 1 + NumFixed << TheCall->getNumArgs()
5483         << Callee->getSourceRange();
5484     return ExprError();
5485   }
5486 
5487   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5488       << Callee->getSourceRange();
5489 
5490   if (WarnAboutSemanticsChange) {
5491     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
5492         << Callee->getSourceRange();
5493   }
5494 
5495   // Get the decl for the concrete builtin from this, we can tell what the
5496   // concrete integer type we should convert to is.
5497   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5498   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
5499   FunctionDecl *NewBuiltinDecl;
5500   if (NewBuiltinID == BuiltinID)
5501     NewBuiltinDecl = FDecl;
5502   else {
5503     // Perform builtin lookup to avoid redeclaring it.
5504     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
5505     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5506     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5507     assert(Res.getFoundDecl());
5508     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
5509     if (!NewBuiltinDecl)
5510       return ExprError();
5511   }
5512 
5513   // The first argument --- the pointer --- has a fixed type; we
5514   // deduce the types of the rest of the arguments accordingly.  Walk
5515   // the remaining arguments, converting them to the deduced value type.
5516   for (unsigned i = 0; i != NumFixed; ++i) {
5517     ExprResult Arg = TheCall->getArg(i+1);
5518 
5519     // GCC does an implicit conversion to the pointer or integer ValType.  This
5520     // can fail in some cases (1i -> int**), check for this error case now.
5521     // Initialize the argument.
5522     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5523                                                    ValType, /*consume*/ false);
5524     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5525     if (Arg.isInvalid())
5526       return ExprError();
5527 
5528     // Okay, we have something that *can* be converted to the right type.  Check
5529     // to see if there is a potentially weird extension going on here.  This can
5530     // happen when you do an atomic operation on something like an char* and
5531     // pass in 42.  The 42 gets converted to char.  This is even more strange
5532     // for things like 45.123 -> char, etc.
5533     // FIXME: Do this check.
5534     TheCall->setArg(i+1, Arg.get());
5535   }
5536 
5537   // Create a new DeclRefExpr to refer to the new decl.
5538   DeclRefExpr *NewDRE = DeclRefExpr::Create(
5539       Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
5540       /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
5541       DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
5542 
5543   // Set the callee in the CallExpr.
5544   // FIXME: This loses syntactic information.
5545   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5546   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5547                                               CK_BuiltinFnToFnPtr);
5548   TheCall->setCallee(PromotedCall.get());
5549 
5550   // Change the result type of the call to match the original value type. This
5551   // is arbitrary, but the codegen for these builtins ins design to handle it
5552   // gracefully.
5553   TheCall->setType(ResultType);
5554 
5555   // Prohibit use of _ExtInt with atomic builtins.
5556   // The arguments would have already been converted to the first argument's
5557   // type, so only need to check the first argument.
5558   const auto *ExtIntValType = ValType->getAs<ExtIntType>();
5559   if (ExtIntValType && !llvm::isPowerOf2_64(ExtIntValType->getNumBits())) {
5560     Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
5561     return ExprError();
5562   }
5563 
5564   return TheCallResult;
5565 }
5566 
5567 /// SemaBuiltinNontemporalOverloaded - We have a call to
5568 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
5569 /// overloaded function based on the pointer type of its last argument.
5570 ///
5571 /// This function goes through and does final semantic checking for these
5572 /// builtins.
5573 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5574   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5575   DeclRefExpr *DRE =
5576       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5577   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5578   unsigned BuiltinID = FDecl->getBuiltinID();
5579   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5580           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5581          "Unexpected nontemporal load/store builtin!");
5582   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5583   unsigned numArgs = isStore ? 2 : 1;
5584 
5585   // Ensure that we have the proper number of arguments.
5586   if (checkArgCount(*this, TheCall, numArgs))
5587     return ExprError();
5588 
5589   // Inspect the last argument of the nontemporal builtin.  This should always
5590   // be a pointer type, from which we imply the type of the memory access.
5591   // Because it is a pointer type, we don't have to worry about any implicit
5592   // casts here.
5593   Expr *PointerArg = TheCall->getArg(numArgs - 1);
5594   ExprResult PointerArgResult =
5595       DefaultFunctionArrayLvalueConversion(PointerArg);
5596 
5597   if (PointerArgResult.isInvalid())
5598     return ExprError();
5599   PointerArg = PointerArgResult.get();
5600   TheCall->setArg(numArgs - 1, PointerArg);
5601 
5602   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5603   if (!pointerType) {
5604     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
5605         << PointerArg->getType() << PointerArg->getSourceRange();
5606     return ExprError();
5607   }
5608 
5609   QualType ValType = pointerType->getPointeeType();
5610 
5611   // Strip any qualifiers off ValType.
5612   ValType = ValType.getUnqualifiedType();
5613   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5614       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5615       !ValType->isVectorType()) {
5616     Diag(DRE->getBeginLoc(),
5617          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5618         << PointerArg->getType() << PointerArg->getSourceRange();
5619     return ExprError();
5620   }
5621 
5622   if (!isStore) {
5623     TheCall->setType(ValType);
5624     return TheCallResult;
5625   }
5626 
5627   ExprResult ValArg = TheCall->getArg(0);
5628   InitializedEntity Entity = InitializedEntity::InitializeParameter(
5629       Context, ValType, /*consume*/ false);
5630   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
5631   if (ValArg.isInvalid())
5632     return ExprError();
5633 
5634   TheCall->setArg(0, ValArg.get());
5635   TheCall->setType(Context.VoidTy);
5636   return TheCallResult;
5637 }
5638 
5639 /// CheckObjCString - Checks that the argument to the builtin
5640 /// CFString constructor is correct
5641 /// Note: It might also make sense to do the UTF-16 conversion here (would
5642 /// simplify the backend).
5643 bool Sema::CheckObjCString(Expr *Arg) {
5644   Arg = Arg->IgnoreParenCasts();
5645   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
5646 
5647   if (!Literal || !Literal->isAscii()) {
5648     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
5649         << Arg->getSourceRange();
5650     return true;
5651   }
5652 
5653   if (Literal->containsNonAsciiOrNull()) {
5654     StringRef String = Literal->getString();
5655     unsigned NumBytes = String.size();
5656     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
5657     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
5658     llvm::UTF16 *ToPtr = &ToBuf[0];
5659 
5660     llvm::ConversionResult Result =
5661         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
5662                                  ToPtr + NumBytes, llvm::strictConversion);
5663     // Check for conversion failure.
5664     if (Result != llvm::conversionOK)
5665       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
5666           << Arg->getSourceRange();
5667   }
5668   return false;
5669 }
5670 
5671 /// CheckObjCString - Checks that the format string argument to the os_log()
5672 /// and os_trace() functions is correct, and converts it to const char *.
5673 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5674   Arg = Arg->IgnoreParenCasts();
5675   auto *Literal = dyn_cast<StringLiteral>(Arg);
5676   if (!Literal) {
5677     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
5678       Literal = ObjcLiteral->getString();
5679     }
5680   }
5681 
5682   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
5683     return ExprError(
5684         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
5685         << Arg->getSourceRange());
5686   }
5687 
5688   ExprResult Result(Literal);
5689   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
5690   InitializedEntity Entity =
5691       InitializedEntity::InitializeParameter(Context, ResultTy, false);
5692   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
5693   return Result;
5694 }
5695 
5696 /// Check that the user is calling the appropriate va_start builtin for the
5697 /// target and calling convention.
5698 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5699   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5700   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
5701   bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
5702                     TT.getArch() == llvm::Triple::aarch64_32);
5703   bool IsWindows = TT.isOSWindows();
5704   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5705   if (IsX64 || IsAArch64) {
5706     CallingConv CC = CC_C;
5707     if (const FunctionDecl *FD = S.getCurFunctionDecl())
5708       CC = FD->getType()->castAs<FunctionType>()->getCallConv();
5709     if (IsMSVAStart) {
5710       // Don't allow this in System V ABI functions.
5711       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
5712         return S.Diag(Fn->getBeginLoc(),
5713                       diag::err_ms_va_start_used_in_sysv_function);
5714     } else {
5715       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
5716       // On x64 Windows, don't allow this in System V ABI functions.
5717       // (Yes, that means there's no corresponding way to support variadic
5718       // System V ABI functions on Windows.)
5719       if ((IsWindows && CC == CC_X86_64SysV) ||
5720           (!IsWindows && CC == CC_Win64))
5721         return S.Diag(Fn->getBeginLoc(),
5722                       diag::err_va_start_used_in_wrong_abi_function)
5723                << !IsWindows;
5724     }
5725     return false;
5726   }
5727 
5728   if (IsMSVAStart)
5729     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
5730   return false;
5731 }
5732 
5733 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
5734                                              ParmVarDecl **LastParam = nullptr) {
5735   // Determine whether the current function, block, or obj-c method is variadic
5736   // and get its parameter list.
5737   bool IsVariadic = false;
5738   ArrayRef<ParmVarDecl *> Params;
5739   DeclContext *Caller = S.CurContext;
5740   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
5741     IsVariadic = Block->isVariadic();
5742     Params = Block->parameters();
5743   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
5744     IsVariadic = FD->isVariadic();
5745     Params = FD->parameters();
5746   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
5747     IsVariadic = MD->isVariadic();
5748     // FIXME: This isn't correct for methods (results in bogus warning).
5749     Params = MD->parameters();
5750   } else if (isa<CapturedDecl>(Caller)) {
5751     // We don't support va_start in a CapturedDecl.
5752     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
5753     return true;
5754   } else {
5755     // This must be some other declcontext that parses exprs.
5756     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
5757     return true;
5758   }
5759 
5760   if (!IsVariadic) {
5761     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
5762     return true;
5763   }
5764 
5765   if (LastParam)
5766     *LastParam = Params.empty() ? nullptr : Params.back();
5767 
5768   return false;
5769 }
5770 
5771 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
5772 /// for validity.  Emit an error and return true on failure; return false
5773 /// on success.
5774 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5775   Expr *Fn = TheCall->getCallee();
5776 
5777   if (checkVAStartABI(*this, BuiltinID, Fn))
5778     return true;
5779 
5780   if (checkArgCount(*this, TheCall, 2))
5781     return true;
5782 
5783   // Type-check the first argument normally.
5784   if (checkBuiltinArgument(*this, TheCall, 0))
5785     return true;
5786 
5787   // Check that the current function is variadic, and get its last parameter.
5788   ParmVarDecl *LastParam;
5789   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
5790     return true;
5791 
5792   // Verify that the second argument to the builtin is the last argument of the
5793   // current function or method.
5794   bool SecondArgIsLastNamedArgument = false;
5795   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
5796 
5797   // These are valid if SecondArgIsLastNamedArgument is false after the next
5798   // block.
5799   QualType Type;
5800   SourceLocation ParamLoc;
5801   bool IsCRegister = false;
5802 
5803   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
5804     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
5805       SecondArgIsLastNamedArgument = PV == LastParam;
5806 
5807       Type = PV->getType();
5808       ParamLoc = PV->getLocation();
5809       IsCRegister =
5810           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
5811     }
5812   }
5813 
5814   if (!SecondArgIsLastNamedArgument)
5815     Diag(TheCall->getArg(1)->getBeginLoc(),
5816          diag::warn_second_arg_of_va_start_not_last_named_param);
5817   else if (IsCRegister || Type->isReferenceType() ||
5818            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
5819              // Promotable integers are UB, but enumerations need a bit of
5820              // extra checking to see what their promotable type actually is.
5821              if (!Type->isPromotableIntegerType())
5822                return false;
5823              if (!Type->isEnumeralType())
5824                return true;
5825              const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
5826              return !(ED &&
5827                       Context.typesAreCompatible(ED->getPromotionType(), Type));
5828            }()) {
5829     unsigned Reason = 0;
5830     if (Type->isReferenceType())  Reason = 1;
5831     else if (IsCRegister)         Reason = 2;
5832     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
5833     Diag(ParamLoc, diag::note_parameter_type) << Type;
5834   }
5835 
5836   TheCall->setType(Context.VoidTy);
5837   return false;
5838 }
5839 
5840 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
5841   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
5842   //                 const char *named_addr);
5843 
5844   Expr *Func = Call->getCallee();
5845 
5846   if (Call->getNumArgs() < 3)
5847     return Diag(Call->getEndLoc(),
5848                 diag::err_typecheck_call_too_few_args_at_least)
5849            << 0 /*function call*/ << 3 << Call->getNumArgs();
5850 
5851   // Type-check the first argument normally.
5852   if (checkBuiltinArgument(*this, Call, 0))
5853     return true;
5854 
5855   // Check that the current function is variadic.
5856   if (checkVAStartIsInVariadicFunction(*this, Func))
5857     return true;
5858 
5859   // __va_start on Windows does not validate the parameter qualifiers
5860 
5861   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
5862   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
5863 
5864   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
5865   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
5866 
5867   const QualType &ConstCharPtrTy =
5868       Context.getPointerType(Context.CharTy.withConst());
5869   if (!Arg1Ty->isPointerType() ||
5870       Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
5871     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5872         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
5873         << 0                                      /* qualifier difference */
5874         << 3                                      /* parameter mismatch */
5875         << 2 << Arg1->getType() << ConstCharPtrTy;
5876 
5877   const QualType SizeTy = Context.getSizeType();
5878   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
5879     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5880         << Arg2->getType() << SizeTy << 1 /* different class */
5881         << 0                              /* qualifier difference */
5882         << 3                              /* parameter mismatch */
5883         << 3 << Arg2->getType() << SizeTy;
5884 
5885   return false;
5886 }
5887 
5888 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
5889 /// friends.  This is declared to take (...), so we have to check everything.
5890 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
5891   if (checkArgCount(*this, TheCall, 2))
5892     return true;
5893 
5894   ExprResult OrigArg0 = TheCall->getArg(0);
5895   ExprResult OrigArg1 = TheCall->getArg(1);
5896 
5897   // Do standard promotions between the two arguments, returning their common
5898   // type.
5899   QualType Res = UsualArithmeticConversions(
5900       OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
5901   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
5902     return true;
5903 
5904   // Make sure any conversions are pushed back into the call; this is
5905   // type safe since unordered compare builtins are declared as "_Bool
5906   // foo(...)".
5907   TheCall->setArg(0, OrigArg0.get());
5908   TheCall->setArg(1, OrigArg1.get());
5909 
5910   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
5911     return false;
5912 
5913   // If the common type isn't a real floating type, then the arguments were
5914   // invalid for this operation.
5915   if (Res.isNull() || !Res->isRealFloatingType())
5916     return Diag(OrigArg0.get()->getBeginLoc(),
5917                 diag::err_typecheck_call_invalid_ordered_compare)
5918            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
5919            << SourceRange(OrigArg0.get()->getBeginLoc(),
5920                           OrigArg1.get()->getEndLoc());
5921 
5922   return false;
5923 }
5924 
5925 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
5926 /// __builtin_isnan and friends.  This is declared to take (...), so we have
5927 /// to check everything. We expect the last argument to be a floating point
5928 /// value.
5929 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
5930   if (checkArgCount(*this, TheCall, NumArgs))
5931     return true;
5932 
5933   // __builtin_fpclassify is the only case where NumArgs != 1, so we can count
5934   // on all preceding parameters just being int.  Try all of those.
5935   for (unsigned i = 0; i < NumArgs - 1; ++i) {
5936     Expr *Arg = TheCall->getArg(i);
5937 
5938     if (Arg->isTypeDependent())
5939       return false;
5940 
5941     ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);
5942 
5943     if (Res.isInvalid())
5944       return true;
5945     TheCall->setArg(i, Res.get());
5946   }
5947 
5948   Expr *OrigArg = TheCall->getArg(NumArgs-1);
5949 
5950   if (OrigArg->isTypeDependent())
5951     return false;
5952 
5953   // Usual Unary Conversions will convert half to float, which we want for
5954   // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
5955   // type how it is, but do normal L->Rvalue conversions.
5956   if (Context.getTargetInfo().useFP16ConversionIntrinsics())
5957     OrigArg = UsualUnaryConversions(OrigArg).get();
5958   else
5959     OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
5960   TheCall->setArg(NumArgs - 1, OrigArg);
5961 
5962   // This operation requires a non-_Complex floating-point number.
5963   if (!OrigArg->getType()->isRealFloatingType())
5964     return Diag(OrigArg->getBeginLoc(),
5965                 diag::err_typecheck_call_invalid_unary_fp)
5966            << OrigArg->getType() << OrigArg->getSourceRange();
5967 
5968   return false;
5969 }
5970 
5971 /// Perform semantic analysis for a call to __builtin_complex.
5972 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) {
5973   if (checkArgCount(*this, TheCall, 2))
5974     return true;
5975 
5976   bool Dependent = false;
5977   for (unsigned I = 0; I != 2; ++I) {
5978     Expr *Arg = TheCall->getArg(I);
5979     QualType T = Arg->getType();
5980     if (T->isDependentType()) {
5981       Dependent = true;
5982       continue;
5983     }
5984 
5985     // Despite supporting _Complex int, GCC requires a real floating point type
5986     // for the operands of __builtin_complex.
5987     if (!T->isRealFloatingType()) {
5988       return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
5989              << Arg->getType() << Arg->getSourceRange();
5990     }
5991 
5992     ExprResult Converted = DefaultLvalueConversion(Arg);
5993     if (Converted.isInvalid())
5994       return true;
5995     TheCall->setArg(I, Converted.get());
5996   }
5997 
5998   if (Dependent) {
5999     TheCall->setType(Context.DependentTy);
6000     return false;
6001   }
6002 
6003   Expr *Real = TheCall->getArg(0);
6004   Expr *Imag = TheCall->getArg(1);
6005   if (!Context.hasSameType(Real->getType(), Imag->getType())) {
6006     return Diag(Real->getBeginLoc(),
6007                 diag::err_typecheck_call_different_arg_types)
6008            << Real->getType() << Imag->getType()
6009            << Real->getSourceRange() << Imag->getSourceRange();
6010   }
6011 
6012   // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers;
6013   // don't allow this builtin to form those types either.
6014   // FIXME: Should we allow these types?
6015   if (Real->getType()->isFloat16Type())
6016     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6017            << "_Float16";
6018   if (Real->getType()->isHalfType())
6019     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6020            << "half";
6021 
6022   TheCall->setType(Context.getComplexType(Real->getType()));
6023   return false;
6024 }
6025 
6026 // Customized Sema Checking for VSX builtins that have the following signature:
6027 // vector [...] builtinName(vector [...], vector [...], const int);
6028 // Which takes the same type of vectors (any legal vector type) for the first
6029 // two arguments and takes compile time constant for the third argument.
6030 // Example builtins are :
6031 // vector double vec_xxpermdi(vector double, vector double, int);
6032 // vector short vec_xxsldwi(vector short, vector short, int);
6033 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
6034   unsigned ExpectedNumArgs = 3;
6035   if (checkArgCount(*this, TheCall, ExpectedNumArgs))
6036     return true;
6037 
6038   // Check the third argument is a compile time constant
6039   if (!TheCall->getArg(2)->isIntegerConstantExpr(Context))
6040     return Diag(TheCall->getBeginLoc(),
6041                 diag::err_vsx_builtin_nonconstant_argument)
6042            << 3 /* argument index */ << TheCall->getDirectCallee()
6043            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
6044                           TheCall->getArg(2)->getEndLoc());
6045 
6046   QualType Arg1Ty = TheCall->getArg(0)->getType();
6047   QualType Arg2Ty = TheCall->getArg(1)->getType();
6048 
6049   // Check the type of argument 1 and argument 2 are vectors.
6050   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
6051   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
6052       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
6053     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
6054            << TheCall->getDirectCallee()
6055            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6056                           TheCall->getArg(1)->getEndLoc());
6057   }
6058 
6059   // Check the first two arguments are the same type.
6060   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
6061     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
6062            << TheCall->getDirectCallee()
6063            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6064                           TheCall->getArg(1)->getEndLoc());
6065   }
6066 
6067   // When default clang type checking is turned off and the customized type
6068   // checking is used, the returning type of the function must be explicitly
6069   // set. Otherwise it is _Bool by default.
6070   TheCall->setType(Arg1Ty);
6071 
6072   return false;
6073 }
6074 
6075 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
6076 // This is declared to take (...), so we have to check everything.
6077 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
6078   if (TheCall->getNumArgs() < 2)
6079     return ExprError(Diag(TheCall->getEndLoc(),
6080                           diag::err_typecheck_call_too_few_args_at_least)
6081                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
6082                      << TheCall->getSourceRange());
6083 
6084   // Determine which of the following types of shufflevector we're checking:
6085   // 1) unary, vector mask: (lhs, mask)
6086   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
6087   QualType resType = TheCall->getArg(0)->getType();
6088   unsigned numElements = 0;
6089 
6090   if (!TheCall->getArg(0)->isTypeDependent() &&
6091       !TheCall->getArg(1)->isTypeDependent()) {
6092     QualType LHSType = TheCall->getArg(0)->getType();
6093     QualType RHSType = TheCall->getArg(1)->getType();
6094 
6095     if (!LHSType->isVectorType() || !RHSType->isVectorType())
6096       return ExprError(
6097           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
6098           << TheCall->getDirectCallee()
6099           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6100                          TheCall->getArg(1)->getEndLoc()));
6101 
6102     numElements = LHSType->castAs<VectorType>()->getNumElements();
6103     unsigned numResElements = TheCall->getNumArgs() - 2;
6104 
6105     // Check to see if we have a call with 2 vector arguments, the unary shuffle
6106     // with mask.  If so, verify that RHS is an integer vector type with the
6107     // same number of elts as lhs.
6108     if (TheCall->getNumArgs() == 2) {
6109       if (!RHSType->hasIntegerRepresentation() ||
6110           RHSType->castAs<VectorType>()->getNumElements() != numElements)
6111         return ExprError(Diag(TheCall->getBeginLoc(),
6112                               diag::err_vec_builtin_incompatible_vector)
6113                          << TheCall->getDirectCallee()
6114                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
6115                                         TheCall->getArg(1)->getEndLoc()));
6116     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
6117       return ExprError(Diag(TheCall->getBeginLoc(),
6118                             diag::err_vec_builtin_incompatible_vector)
6119                        << TheCall->getDirectCallee()
6120                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6121                                       TheCall->getArg(1)->getEndLoc()));
6122     } else if (numElements != numResElements) {
6123       QualType eltType = LHSType->castAs<VectorType>()->getElementType();
6124       resType = Context.getVectorType(eltType, numResElements,
6125                                       VectorType::GenericVector);
6126     }
6127   }
6128 
6129   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
6130     if (TheCall->getArg(i)->isTypeDependent() ||
6131         TheCall->getArg(i)->isValueDependent())
6132       continue;
6133 
6134     Optional<llvm::APSInt> Result;
6135     if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context)))
6136       return ExprError(Diag(TheCall->getBeginLoc(),
6137                             diag::err_shufflevector_nonconstant_argument)
6138                        << TheCall->getArg(i)->getSourceRange());
6139 
6140     // Allow -1 which will be translated to undef in the IR.
6141     if (Result->isSigned() && Result->isAllOnesValue())
6142       continue;
6143 
6144     if (Result->getActiveBits() > 64 ||
6145         Result->getZExtValue() >= numElements * 2)
6146       return ExprError(Diag(TheCall->getBeginLoc(),
6147                             diag::err_shufflevector_argument_too_large)
6148                        << TheCall->getArg(i)->getSourceRange());
6149   }
6150 
6151   SmallVector<Expr*, 32> exprs;
6152 
6153   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
6154     exprs.push_back(TheCall->getArg(i));
6155     TheCall->setArg(i, nullptr);
6156   }
6157 
6158   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
6159                                          TheCall->getCallee()->getBeginLoc(),
6160                                          TheCall->getRParenLoc());
6161 }
6162 
6163 /// SemaConvertVectorExpr - Handle __builtin_convertvector
6164 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
6165                                        SourceLocation BuiltinLoc,
6166                                        SourceLocation RParenLoc) {
6167   ExprValueKind VK = VK_RValue;
6168   ExprObjectKind OK = OK_Ordinary;
6169   QualType DstTy = TInfo->getType();
6170   QualType SrcTy = E->getType();
6171 
6172   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
6173     return ExprError(Diag(BuiltinLoc,
6174                           diag::err_convertvector_non_vector)
6175                      << E->getSourceRange());
6176   if (!DstTy->isVectorType() && !DstTy->isDependentType())
6177     return ExprError(Diag(BuiltinLoc,
6178                           diag::err_convertvector_non_vector_type));
6179 
6180   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
6181     unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
6182     unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
6183     if (SrcElts != DstElts)
6184       return ExprError(Diag(BuiltinLoc,
6185                             diag::err_convertvector_incompatible_vector)
6186                        << E->getSourceRange());
6187   }
6188 
6189   return new (Context)
6190       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
6191 }
6192 
6193 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
6194 // This is declared to take (const void*, ...) and can take two
6195 // optional constant int args.
6196 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
6197   unsigned NumArgs = TheCall->getNumArgs();
6198 
6199   if (NumArgs > 3)
6200     return Diag(TheCall->getEndLoc(),
6201                 diag::err_typecheck_call_too_many_args_at_most)
6202            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6203 
6204   // Argument 0 is checked for us and the remaining arguments must be
6205   // constant integers.
6206   for (unsigned i = 1; i != NumArgs; ++i)
6207     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
6208       return true;
6209 
6210   return false;
6211 }
6212 
6213 /// SemaBuiltinAssume - Handle __assume (MS Extension).
6214 // __assume does not evaluate its arguments, and should warn if its argument
6215 // has side effects.
6216 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
6217   Expr *Arg = TheCall->getArg(0);
6218   if (Arg->isInstantiationDependent()) return false;
6219 
6220   if (Arg->HasSideEffects(Context))
6221     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
6222         << Arg->getSourceRange()
6223         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
6224 
6225   return false;
6226 }
6227 
6228 /// Handle __builtin_alloca_with_align. This is declared
6229 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
6230 /// than 8.
6231 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
6232   // The alignment must be a constant integer.
6233   Expr *Arg = TheCall->getArg(1);
6234 
6235   // We can't check the value of a dependent argument.
6236   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6237     if (const auto *UE =
6238             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
6239       if (UE->getKind() == UETT_AlignOf ||
6240           UE->getKind() == UETT_PreferredAlignOf)
6241         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
6242             << Arg->getSourceRange();
6243 
6244     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
6245 
6246     if (!Result.isPowerOf2())
6247       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6248              << Arg->getSourceRange();
6249 
6250     if (Result < Context.getCharWidth())
6251       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
6252              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6253 
6254     if (Result > std::numeric_limits<int32_t>::max())
6255       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
6256              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6257   }
6258 
6259   return false;
6260 }
6261 
6262 /// Handle __builtin_assume_aligned. This is declared
6263 /// as (const void*, size_t, ...) and can take one optional constant int arg.
6264 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
6265   unsigned NumArgs = TheCall->getNumArgs();
6266 
6267   if (NumArgs > 3)
6268     return Diag(TheCall->getEndLoc(),
6269                 diag::err_typecheck_call_too_many_args_at_most)
6270            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6271 
6272   // The alignment must be a constant integer.
6273   Expr *Arg = TheCall->getArg(1);
6274 
6275   // We can't check the value of a dependent argument.
6276   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6277     llvm::APSInt Result;
6278     if (SemaBuiltinConstantArg(TheCall, 1, Result))
6279       return true;
6280 
6281     if (!Result.isPowerOf2())
6282       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6283              << Arg->getSourceRange();
6284 
6285     if (Result > Sema::MaximumAlignment)
6286       Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
6287           << Arg->getSourceRange() << Sema::MaximumAlignment;
6288   }
6289 
6290   if (NumArgs > 2) {
6291     ExprResult Arg(TheCall->getArg(2));
6292     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6293       Context.getSizeType(), false);
6294     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6295     if (Arg.isInvalid()) return true;
6296     TheCall->setArg(2, Arg.get());
6297   }
6298 
6299   return false;
6300 }
6301 
6302 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
6303   unsigned BuiltinID =
6304       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
6305   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6306 
6307   unsigned NumArgs = TheCall->getNumArgs();
6308   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6309   if (NumArgs < NumRequiredArgs) {
6310     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
6311            << 0 /* function call */ << NumRequiredArgs << NumArgs
6312            << TheCall->getSourceRange();
6313   }
6314   if (NumArgs >= NumRequiredArgs + 0x100) {
6315     return Diag(TheCall->getEndLoc(),
6316                 diag::err_typecheck_call_too_many_args_at_most)
6317            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6318            << TheCall->getSourceRange();
6319   }
6320   unsigned i = 0;
6321 
6322   // For formatting call, check buffer arg.
6323   if (!IsSizeCall) {
6324     ExprResult Arg(TheCall->getArg(i));
6325     InitializedEntity Entity = InitializedEntity::InitializeParameter(
6326         Context, Context.VoidPtrTy, false);
6327     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6328     if (Arg.isInvalid())
6329       return true;
6330     TheCall->setArg(i, Arg.get());
6331     i++;
6332   }
6333 
6334   // Check string literal arg.
6335   unsigned FormatIdx = i;
6336   {
6337     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
6338     if (Arg.isInvalid())
6339       return true;
6340     TheCall->setArg(i, Arg.get());
6341     i++;
6342   }
6343 
6344   // Make sure variadic args are scalar.
6345   unsigned FirstDataArg = i;
6346   while (i < NumArgs) {
6347     ExprResult Arg = DefaultVariadicArgumentPromotion(
6348         TheCall->getArg(i), VariadicFunction, nullptr);
6349     if (Arg.isInvalid())
6350       return true;
6351     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
6352     if (ArgSize.getQuantity() >= 0x100) {
6353       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
6354              << i << (int)ArgSize.getQuantity() << 0xff
6355              << TheCall->getSourceRange();
6356     }
6357     TheCall->setArg(i, Arg.get());
6358     i++;
6359   }
6360 
6361   // Check formatting specifiers. NOTE: We're only doing this for the non-size
6362   // call to avoid duplicate diagnostics.
6363   if (!IsSizeCall) {
6364     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6365     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6366     bool Success = CheckFormatArguments(
6367         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
6368         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
6369         CheckedVarArgs);
6370     if (!Success)
6371       return true;
6372   }
6373 
6374   if (IsSizeCall) {
6375     TheCall->setType(Context.getSizeType());
6376   } else {
6377     TheCall->setType(Context.VoidPtrTy);
6378   }
6379   return false;
6380 }
6381 
6382 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
6383 /// TheCall is a constant expression.
6384 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
6385                                   llvm::APSInt &Result) {
6386   Expr *Arg = TheCall->getArg(ArgNum);
6387   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6388   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6389 
6390   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
6391 
6392   Optional<llvm::APSInt> R;
6393   if (!(R = Arg->getIntegerConstantExpr(Context)))
6394     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6395            << FDecl->getDeclName() << Arg->getSourceRange();
6396   Result = *R;
6397   return false;
6398 }
6399 
6400 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
6401 /// TheCall is a constant expression in the range [Low, High].
6402 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
6403                                        int Low, int High, bool RangeIsError) {
6404   if (isConstantEvaluated())
6405     return false;
6406   llvm::APSInt Result;
6407 
6408   // We can't check the value of a dependent argument.
6409   Expr *Arg = TheCall->getArg(ArgNum);
6410   if (Arg->isTypeDependent() || Arg->isValueDependent())
6411     return false;
6412 
6413   // Check constant-ness first.
6414   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6415     return true;
6416 
6417   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6418     if (RangeIsError)
6419       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
6420              << Result.toString(10) << Low << High << Arg->getSourceRange();
6421     else
6422       // Defer the warning until we know if the code will be emitted so that
6423       // dead code can ignore this.
6424       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6425                           PDiag(diag::warn_argument_invalid_range)
6426                               << Result.toString(10) << Low << High
6427                               << Arg->getSourceRange());
6428   }
6429 
6430   return false;
6431 }
6432 
6433 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
6434 /// TheCall is a constant expression is a multiple of Num..
6435 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
6436                                           unsigned Num) {
6437   llvm::APSInt Result;
6438 
6439   // We can't check the value of a dependent argument.
6440   Expr *Arg = TheCall->getArg(ArgNum);
6441   if (Arg->isTypeDependent() || Arg->isValueDependent())
6442     return false;
6443 
6444   // Check constant-ness first.
6445   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6446     return true;
6447 
6448   if (Result.getSExtValue() % Num != 0)
6449     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6450            << Num << Arg->getSourceRange();
6451 
6452   return false;
6453 }
6454 
6455 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
6456 /// constant expression representing a power of 2.
6457 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
6458   llvm::APSInt Result;
6459 
6460   // We can't check the value of a dependent argument.
6461   Expr *Arg = TheCall->getArg(ArgNum);
6462   if (Arg->isTypeDependent() || Arg->isValueDependent())
6463     return false;
6464 
6465   // Check constant-ness first.
6466   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6467     return true;
6468 
6469   // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
6470   // and only if x is a power of 2.
6471   if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
6472     return false;
6473 
6474   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
6475          << Arg->getSourceRange();
6476 }
6477 
6478 static bool IsShiftedByte(llvm::APSInt Value) {
6479   if (Value.isNegative())
6480     return false;
6481 
6482   // Check if it's a shifted byte, by shifting it down
6483   while (true) {
6484     // If the value fits in the bottom byte, the check passes.
6485     if (Value < 0x100)
6486       return true;
6487 
6488     // Otherwise, if the value has _any_ bits in the bottom byte, the check
6489     // fails.
6490     if ((Value & 0xFF) != 0)
6491       return false;
6492 
6493     // If the bottom 8 bits are all 0, but something above that is nonzero,
6494     // then shifting the value right by 8 bits won't affect whether it's a
6495     // shifted byte or not. So do that, and go round again.
6496     Value >>= 8;
6497   }
6498 }
6499 
6500 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
6501 /// a constant expression representing an arbitrary byte value shifted left by
6502 /// a multiple of 8 bits.
6503 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
6504                                              unsigned ArgBits) {
6505   llvm::APSInt Result;
6506 
6507   // We can't check the value of a dependent argument.
6508   Expr *Arg = TheCall->getArg(ArgNum);
6509   if (Arg->isTypeDependent() || Arg->isValueDependent())
6510     return false;
6511 
6512   // Check constant-ness first.
6513   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6514     return true;
6515 
6516   // Truncate to the given size.
6517   Result = Result.getLoBits(ArgBits);
6518   Result.setIsUnsigned(true);
6519 
6520   if (IsShiftedByte(Result))
6521     return false;
6522 
6523   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
6524          << Arg->getSourceRange();
6525 }
6526 
6527 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
6528 /// TheCall is a constant expression representing either a shifted byte value,
6529 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
6530 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
6531 /// Arm MVE intrinsics.
6532 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
6533                                                    int ArgNum,
6534                                                    unsigned ArgBits) {
6535   llvm::APSInt Result;
6536 
6537   // We can't check the value of a dependent argument.
6538   Expr *Arg = TheCall->getArg(ArgNum);
6539   if (Arg->isTypeDependent() || Arg->isValueDependent())
6540     return false;
6541 
6542   // Check constant-ness first.
6543   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6544     return true;
6545 
6546   // Truncate to the given size.
6547   Result = Result.getLoBits(ArgBits);
6548   Result.setIsUnsigned(true);
6549 
6550   // Check to see if it's in either of the required forms.
6551   if (IsShiftedByte(Result) ||
6552       (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
6553     return false;
6554 
6555   return Diag(TheCall->getBeginLoc(),
6556               diag::err_argument_not_shifted_byte_or_xxff)
6557          << Arg->getSourceRange();
6558 }
6559 
6560 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
6561 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
6562   if (BuiltinID == AArch64::BI__builtin_arm_irg) {
6563     if (checkArgCount(*this, TheCall, 2))
6564       return true;
6565     Expr *Arg0 = TheCall->getArg(0);
6566     Expr *Arg1 = TheCall->getArg(1);
6567 
6568     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6569     if (FirstArg.isInvalid())
6570       return true;
6571     QualType FirstArgType = FirstArg.get()->getType();
6572     if (!FirstArgType->isAnyPointerType())
6573       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6574                << "first" << FirstArgType << Arg0->getSourceRange();
6575     TheCall->setArg(0, FirstArg.get());
6576 
6577     ExprResult SecArg = DefaultLvalueConversion(Arg1);
6578     if (SecArg.isInvalid())
6579       return true;
6580     QualType SecArgType = SecArg.get()->getType();
6581     if (!SecArgType->isIntegerType())
6582       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6583                << "second" << SecArgType << Arg1->getSourceRange();
6584 
6585     // Derive the return type from the pointer argument.
6586     TheCall->setType(FirstArgType);
6587     return false;
6588   }
6589 
6590   if (BuiltinID == AArch64::BI__builtin_arm_addg) {
6591     if (checkArgCount(*this, TheCall, 2))
6592       return true;
6593 
6594     Expr *Arg0 = TheCall->getArg(0);
6595     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6596     if (FirstArg.isInvalid())
6597       return true;
6598     QualType FirstArgType = FirstArg.get()->getType();
6599     if (!FirstArgType->isAnyPointerType())
6600       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6601                << "first" << FirstArgType << Arg0->getSourceRange();
6602     TheCall->setArg(0, FirstArg.get());
6603 
6604     // Derive the return type from the pointer argument.
6605     TheCall->setType(FirstArgType);
6606 
6607     // Second arg must be an constant in range [0,15]
6608     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6609   }
6610 
6611   if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
6612     if (checkArgCount(*this, TheCall, 2))
6613       return true;
6614     Expr *Arg0 = TheCall->getArg(0);
6615     Expr *Arg1 = TheCall->getArg(1);
6616 
6617     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6618     if (FirstArg.isInvalid())
6619       return true;
6620     QualType FirstArgType = FirstArg.get()->getType();
6621     if (!FirstArgType->isAnyPointerType())
6622       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6623                << "first" << FirstArgType << Arg0->getSourceRange();
6624 
6625     QualType SecArgType = Arg1->getType();
6626     if (!SecArgType->isIntegerType())
6627       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6628                << "second" << SecArgType << Arg1->getSourceRange();
6629     TheCall->setType(Context.IntTy);
6630     return false;
6631   }
6632 
6633   if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
6634       BuiltinID == AArch64::BI__builtin_arm_stg) {
6635     if (checkArgCount(*this, TheCall, 1))
6636       return true;
6637     Expr *Arg0 = TheCall->getArg(0);
6638     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6639     if (FirstArg.isInvalid())
6640       return true;
6641 
6642     QualType FirstArgType = FirstArg.get()->getType();
6643     if (!FirstArgType->isAnyPointerType())
6644       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6645                << "first" << FirstArgType << Arg0->getSourceRange();
6646     TheCall->setArg(0, FirstArg.get());
6647 
6648     // Derive the return type from the pointer argument.
6649     if (BuiltinID == AArch64::BI__builtin_arm_ldg)
6650       TheCall->setType(FirstArgType);
6651     return false;
6652   }
6653 
6654   if (BuiltinID == AArch64::BI__builtin_arm_subp) {
6655     Expr *ArgA = TheCall->getArg(0);
6656     Expr *ArgB = TheCall->getArg(1);
6657 
6658     ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
6659     ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
6660 
6661     if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
6662       return true;
6663 
6664     QualType ArgTypeA = ArgExprA.get()->getType();
6665     QualType ArgTypeB = ArgExprB.get()->getType();
6666 
6667     auto isNull = [&] (Expr *E) -> bool {
6668       return E->isNullPointerConstant(
6669                         Context, Expr::NPC_ValueDependentIsNotNull); };
6670 
6671     // argument should be either a pointer or null
6672     if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
6673       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6674         << "first" << ArgTypeA << ArgA->getSourceRange();
6675 
6676     if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
6677       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6678         << "second" << ArgTypeB << ArgB->getSourceRange();
6679 
6680     // Ensure Pointee types are compatible
6681     if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
6682         ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
6683       QualType pointeeA = ArgTypeA->getPointeeType();
6684       QualType pointeeB = ArgTypeB->getPointeeType();
6685       if (!Context.typesAreCompatible(
6686              Context.getCanonicalType(pointeeA).getUnqualifiedType(),
6687              Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
6688         return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
6689           << ArgTypeA <<  ArgTypeB << ArgA->getSourceRange()
6690           << ArgB->getSourceRange();
6691       }
6692     }
6693 
6694     // at least one argument should be pointer type
6695     if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
6696       return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
6697         <<  ArgTypeA << ArgTypeB << ArgA->getSourceRange();
6698 
6699     if (isNull(ArgA)) // adopt type of the other pointer
6700       ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
6701 
6702     if (isNull(ArgB))
6703       ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
6704 
6705     TheCall->setArg(0, ArgExprA.get());
6706     TheCall->setArg(1, ArgExprB.get());
6707     TheCall->setType(Context.LongLongTy);
6708     return false;
6709   }
6710   assert(false && "Unhandled ARM MTE intrinsic");
6711   return true;
6712 }
6713 
6714 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
6715 /// TheCall is an ARM/AArch64 special register string literal.
6716 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
6717                                     int ArgNum, unsigned ExpectedFieldNum,
6718                                     bool AllowName) {
6719   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
6720                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
6721                       BuiltinID == ARM::BI__builtin_arm_rsr ||
6722                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
6723                       BuiltinID == ARM::BI__builtin_arm_wsr ||
6724                       BuiltinID == ARM::BI__builtin_arm_wsrp;
6725   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
6726                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
6727                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
6728                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
6729                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
6730                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
6731   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
6732 
6733   // We can't check the value of a dependent argument.
6734   Expr *Arg = TheCall->getArg(ArgNum);
6735   if (Arg->isTypeDependent() || Arg->isValueDependent())
6736     return false;
6737 
6738   // Check if the argument is a string literal.
6739   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
6740     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
6741            << Arg->getSourceRange();
6742 
6743   // Check the type of special register given.
6744   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
6745   SmallVector<StringRef, 6> Fields;
6746   Reg.split(Fields, ":");
6747 
6748   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
6749     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6750            << Arg->getSourceRange();
6751 
6752   // If the string is the name of a register then we cannot check that it is
6753   // valid here but if the string is of one the forms described in ACLE then we
6754   // can check that the supplied fields are integers and within the valid
6755   // ranges.
6756   if (Fields.size() > 1) {
6757     bool FiveFields = Fields.size() == 5;
6758 
6759     bool ValidString = true;
6760     if (IsARMBuiltin) {
6761       ValidString &= Fields[0].startswith_lower("cp") ||
6762                      Fields[0].startswith_lower("p");
6763       if (ValidString)
6764         Fields[0] =
6765           Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
6766 
6767       ValidString &= Fields[2].startswith_lower("c");
6768       if (ValidString)
6769         Fields[2] = Fields[2].drop_front(1);
6770 
6771       if (FiveFields) {
6772         ValidString &= Fields[3].startswith_lower("c");
6773         if (ValidString)
6774           Fields[3] = Fields[3].drop_front(1);
6775       }
6776     }
6777 
6778     SmallVector<int, 5> Ranges;
6779     if (FiveFields)
6780       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
6781     else
6782       Ranges.append({15, 7, 15});
6783 
6784     for (unsigned i=0; i<Fields.size(); ++i) {
6785       int IntField;
6786       ValidString &= !Fields[i].getAsInteger(10, IntField);
6787       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
6788     }
6789 
6790     if (!ValidString)
6791       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6792              << Arg->getSourceRange();
6793   } else if (IsAArch64Builtin && Fields.size() == 1) {
6794     // If the register name is one of those that appear in the condition below
6795     // and the special register builtin being used is one of the write builtins,
6796     // then we require that the argument provided for writing to the register
6797     // is an integer constant expression. This is because it will be lowered to
6798     // an MSR (immediate) instruction, so we need to know the immediate at
6799     // compile time.
6800     if (TheCall->getNumArgs() != 2)
6801       return false;
6802 
6803     std::string RegLower = Reg.lower();
6804     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
6805         RegLower != "pan" && RegLower != "uao")
6806       return false;
6807 
6808     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6809   }
6810 
6811   return false;
6812 }
6813 
6814 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity.
6815 /// Emit an error and return true on failure; return false on success.
6816 /// TypeStr is a string containing the type descriptor of the value returned by
6817 /// the builtin and the descriptors of the expected type of the arguments.
6818 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, const char *TypeStr) {
6819 
6820   assert((TypeStr[0] != '\0') &&
6821          "Invalid types in PPC MMA builtin declaration");
6822 
6823   unsigned Mask = 0;
6824   unsigned ArgNum = 0;
6825 
6826   // The first type in TypeStr is the type of the value returned by the
6827   // builtin. So we first read that type and change the type of TheCall.
6828   QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
6829   TheCall->setType(type);
6830 
6831   while (*TypeStr != '\0') {
6832     Mask = 0;
6833     QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
6834     if (ArgNum >= TheCall->getNumArgs()) {
6835       ArgNum++;
6836       break;
6837     }
6838 
6839     Expr *Arg = TheCall->getArg(ArgNum);
6840     QualType ArgType = Arg->getType();
6841 
6842     if ((ExpectedType->isVoidPointerType() && !ArgType->isPointerType()) ||
6843         (!ExpectedType->isVoidPointerType() &&
6844            ArgType.getCanonicalType() != ExpectedType))
6845       return Diag(Arg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6846              << ArgType << ExpectedType << 1 << 0 << 0;
6847 
6848     // If the value of the Mask is not 0, we have a constraint in the size of
6849     // the integer argument so here we ensure the argument is a constant that
6850     // is in the valid range.
6851     if (Mask != 0 &&
6852         SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true))
6853       return true;
6854 
6855     ArgNum++;
6856   }
6857 
6858   // In case we exited early from the previous loop, there are other types to
6859   // read from TypeStr. So we need to read them all to ensure we have the right
6860   // number of arguments in TheCall and if it is not the case, to display a
6861   // better error message.
6862   while (*TypeStr != '\0') {
6863     (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
6864     ArgNum++;
6865   }
6866   if (checkArgCount(*this, TheCall, ArgNum))
6867     return true;
6868 
6869   return false;
6870 }
6871 
6872 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
6873 /// This checks that the target supports __builtin_longjmp and
6874 /// that val is a constant 1.
6875 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
6876   if (!Context.getTargetInfo().hasSjLjLowering())
6877     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
6878            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6879 
6880   Expr *Arg = TheCall->getArg(1);
6881   llvm::APSInt Result;
6882 
6883   // TODO: This is less than ideal. Overload this to take a value.
6884   if (SemaBuiltinConstantArg(TheCall, 1, Result))
6885     return true;
6886 
6887   if (Result != 1)
6888     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
6889            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
6890 
6891   return false;
6892 }
6893 
6894 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
6895 /// This checks that the target supports __builtin_setjmp.
6896 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
6897   if (!Context.getTargetInfo().hasSjLjLowering())
6898     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
6899            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6900   return false;
6901 }
6902 
6903 namespace {
6904 
6905 class UncoveredArgHandler {
6906   enum { Unknown = -1, AllCovered = -2 };
6907 
6908   signed FirstUncoveredArg = Unknown;
6909   SmallVector<const Expr *, 4> DiagnosticExprs;
6910 
6911 public:
6912   UncoveredArgHandler() = default;
6913 
6914   bool hasUncoveredArg() const {
6915     return (FirstUncoveredArg >= 0);
6916   }
6917 
6918   unsigned getUncoveredArg() const {
6919     assert(hasUncoveredArg() && "no uncovered argument");
6920     return FirstUncoveredArg;
6921   }
6922 
6923   void setAllCovered() {
6924     // A string has been found with all arguments covered, so clear out
6925     // the diagnostics.
6926     DiagnosticExprs.clear();
6927     FirstUncoveredArg = AllCovered;
6928   }
6929 
6930   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
6931     assert(NewFirstUncoveredArg >= 0 && "Outside range");
6932 
6933     // Don't update if a previous string covers all arguments.
6934     if (FirstUncoveredArg == AllCovered)
6935       return;
6936 
6937     // UncoveredArgHandler tracks the highest uncovered argument index
6938     // and with it all the strings that match this index.
6939     if (NewFirstUncoveredArg == FirstUncoveredArg)
6940       DiagnosticExprs.push_back(StrExpr);
6941     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
6942       DiagnosticExprs.clear();
6943       DiagnosticExprs.push_back(StrExpr);
6944       FirstUncoveredArg = NewFirstUncoveredArg;
6945     }
6946   }
6947 
6948   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
6949 };
6950 
6951 enum StringLiteralCheckType {
6952   SLCT_NotALiteral,
6953   SLCT_UncheckedLiteral,
6954   SLCT_CheckedLiteral
6955 };
6956 
6957 } // namespace
6958 
6959 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
6960                                      BinaryOperatorKind BinOpKind,
6961                                      bool AddendIsRight) {
6962   unsigned BitWidth = Offset.getBitWidth();
6963   unsigned AddendBitWidth = Addend.getBitWidth();
6964   // There might be negative interim results.
6965   if (Addend.isUnsigned()) {
6966     Addend = Addend.zext(++AddendBitWidth);
6967     Addend.setIsSigned(true);
6968   }
6969   // Adjust the bit width of the APSInts.
6970   if (AddendBitWidth > BitWidth) {
6971     Offset = Offset.sext(AddendBitWidth);
6972     BitWidth = AddendBitWidth;
6973   } else if (BitWidth > AddendBitWidth) {
6974     Addend = Addend.sext(BitWidth);
6975   }
6976 
6977   bool Ov = false;
6978   llvm::APSInt ResOffset = Offset;
6979   if (BinOpKind == BO_Add)
6980     ResOffset = Offset.sadd_ov(Addend, Ov);
6981   else {
6982     assert(AddendIsRight && BinOpKind == BO_Sub &&
6983            "operator must be add or sub with addend on the right");
6984     ResOffset = Offset.ssub_ov(Addend, Ov);
6985   }
6986 
6987   // We add an offset to a pointer here so we should support an offset as big as
6988   // possible.
6989   if (Ov) {
6990     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
6991            "index (intermediate) result too big");
6992     Offset = Offset.sext(2 * BitWidth);
6993     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
6994     return;
6995   }
6996 
6997   Offset = ResOffset;
6998 }
6999 
7000 namespace {
7001 
7002 // This is a wrapper class around StringLiteral to support offsetted string
7003 // literals as format strings. It takes the offset into account when returning
7004 // the string and its length or the source locations to display notes correctly.
7005 class FormatStringLiteral {
7006   const StringLiteral *FExpr;
7007   int64_t Offset;
7008 
7009  public:
7010   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
7011       : FExpr(fexpr), Offset(Offset) {}
7012 
7013   StringRef getString() const {
7014     return FExpr->getString().drop_front(Offset);
7015   }
7016 
7017   unsigned getByteLength() const {
7018     return FExpr->getByteLength() - getCharByteWidth() * Offset;
7019   }
7020 
7021   unsigned getLength() const { return FExpr->getLength() - Offset; }
7022   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
7023 
7024   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
7025 
7026   QualType getType() const { return FExpr->getType(); }
7027 
7028   bool isAscii() const { return FExpr->isAscii(); }
7029   bool isWide() const { return FExpr->isWide(); }
7030   bool isUTF8() const { return FExpr->isUTF8(); }
7031   bool isUTF16() const { return FExpr->isUTF16(); }
7032   bool isUTF32() const { return FExpr->isUTF32(); }
7033   bool isPascal() const { return FExpr->isPascal(); }
7034 
7035   SourceLocation getLocationOfByte(
7036       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
7037       const TargetInfo &Target, unsigned *StartToken = nullptr,
7038       unsigned *StartTokenByteOffset = nullptr) const {
7039     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
7040                                     StartToken, StartTokenByteOffset);
7041   }
7042 
7043   SourceLocation getBeginLoc() const LLVM_READONLY {
7044     return FExpr->getBeginLoc().getLocWithOffset(Offset);
7045   }
7046 
7047   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
7048 };
7049 
7050 }  // namespace
7051 
7052 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
7053                               const Expr *OrigFormatExpr,
7054                               ArrayRef<const Expr *> Args,
7055                               bool HasVAListArg, unsigned format_idx,
7056                               unsigned firstDataArg,
7057                               Sema::FormatStringType Type,
7058                               bool inFunctionCall,
7059                               Sema::VariadicCallType CallType,
7060                               llvm::SmallBitVector &CheckedVarArgs,
7061                               UncoveredArgHandler &UncoveredArg,
7062                               bool IgnoreStringsWithoutSpecifiers);
7063 
7064 // Determine if an expression is a string literal or constant string.
7065 // If this function returns false on the arguments to a function expecting a
7066 // format string, we will usually need to emit a warning.
7067 // True string literals are then checked by CheckFormatString.
7068 static StringLiteralCheckType
7069 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
7070                       bool HasVAListArg, unsigned format_idx,
7071                       unsigned firstDataArg, Sema::FormatStringType Type,
7072                       Sema::VariadicCallType CallType, bool InFunctionCall,
7073                       llvm::SmallBitVector &CheckedVarArgs,
7074                       UncoveredArgHandler &UncoveredArg,
7075                       llvm::APSInt Offset,
7076                       bool IgnoreStringsWithoutSpecifiers = false) {
7077   if (S.isConstantEvaluated())
7078     return SLCT_NotALiteral;
7079  tryAgain:
7080   assert(Offset.isSigned() && "invalid offset");
7081 
7082   if (E->isTypeDependent() || E->isValueDependent())
7083     return SLCT_NotALiteral;
7084 
7085   E = E->IgnoreParenCasts();
7086 
7087   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
7088     // Technically -Wformat-nonliteral does not warn about this case.
7089     // The behavior of printf and friends in this case is implementation
7090     // dependent.  Ideally if the format string cannot be null then
7091     // it should have a 'nonnull' attribute in the function prototype.
7092     return SLCT_UncheckedLiteral;
7093 
7094   switch (E->getStmtClass()) {
7095   case Stmt::BinaryConditionalOperatorClass:
7096   case Stmt::ConditionalOperatorClass: {
7097     // The expression is a literal if both sub-expressions were, and it was
7098     // completely checked only if both sub-expressions were checked.
7099     const AbstractConditionalOperator *C =
7100         cast<AbstractConditionalOperator>(E);
7101 
7102     // Determine whether it is necessary to check both sub-expressions, for
7103     // example, because the condition expression is a constant that can be
7104     // evaluated at compile time.
7105     bool CheckLeft = true, CheckRight = true;
7106 
7107     bool Cond;
7108     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
7109                                                  S.isConstantEvaluated())) {
7110       if (Cond)
7111         CheckRight = false;
7112       else
7113         CheckLeft = false;
7114     }
7115 
7116     // We need to maintain the offsets for the right and the left hand side
7117     // separately to check if every possible indexed expression is a valid
7118     // string literal. They might have different offsets for different string
7119     // literals in the end.
7120     StringLiteralCheckType Left;
7121     if (!CheckLeft)
7122       Left = SLCT_UncheckedLiteral;
7123     else {
7124       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
7125                                    HasVAListArg, format_idx, firstDataArg,
7126                                    Type, CallType, InFunctionCall,
7127                                    CheckedVarArgs, UncoveredArg, Offset,
7128                                    IgnoreStringsWithoutSpecifiers);
7129       if (Left == SLCT_NotALiteral || !CheckRight) {
7130         return Left;
7131       }
7132     }
7133 
7134     StringLiteralCheckType Right = checkFormatStringExpr(
7135         S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
7136         Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7137         IgnoreStringsWithoutSpecifiers);
7138 
7139     return (CheckLeft && Left < Right) ? Left : Right;
7140   }
7141 
7142   case Stmt::ImplicitCastExprClass:
7143     E = cast<ImplicitCastExpr>(E)->getSubExpr();
7144     goto tryAgain;
7145 
7146   case Stmt::OpaqueValueExprClass:
7147     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
7148       E = src;
7149       goto tryAgain;
7150     }
7151     return SLCT_NotALiteral;
7152 
7153   case Stmt::PredefinedExprClass:
7154     // While __func__, etc., are technically not string literals, they
7155     // cannot contain format specifiers and thus are not a security
7156     // liability.
7157     return SLCT_UncheckedLiteral;
7158 
7159   case Stmt::DeclRefExprClass: {
7160     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7161 
7162     // As an exception, do not flag errors for variables binding to
7163     // const string literals.
7164     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
7165       bool isConstant = false;
7166       QualType T = DR->getType();
7167 
7168       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
7169         isConstant = AT->getElementType().isConstant(S.Context);
7170       } else if (const PointerType *PT = T->getAs<PointerType>()) {
7171         isConstant = T.isConstant(S.Context) &&
7172                      PT->getPointeeType().isConstant(S.Context);
7173       } else if (T->isObjCObjectPointerType()) {
7174         // In ObjC, there is usually no "const ObjectPointer" type,
7175         // so don't check if the pointee type is constant.
7176         isConstant = T.isConstant(S.Context);
7177       }
7178 
7179       if (isConstant) {
7180         if (const Expr *Init = VD->getAnyInitializer()) {
7181           // Look through initializers like const char c[] = { "foo" }
7182           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
7183             if (InitList->isStringLiteralInit())
7184               Init = InitList->getInit(0)->IgnoreParenImpCasts();
7185           }
7186           return checkFormatStringExpr(S, Init, Args,
7187                                        HasVAListArg, format_idx,
7188                                        firstDataArg, Type, CallType,
7189                                        /*InFunctionCall*/ false, CheckedVarArgs,
7190                                        UncoveredArg, Offset);
7191         }
7192       }
7193 
7194       // For vprintf* functions (i.e., HasVAListArg==true), we add a
7195       // special check to see if the format string is a function parameter
7196       // of the function calling the printf function.  If the function
7197       // has an attribute indicating it is a printf-like function, then we
7198       // should suppress warnings concerning non-literals being used in a call
7199       // to a vprintf function.  For example:
7200       //
7201       // void
7202       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
7203       //      va_list ap;
7204       //      va_start(ap, fmt);
7205       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
7206       //      ...
7207       // }
7208       if (HasVAListArg) {
7209         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
7210           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
7211             int PVIndex = PV->getFunctionScopeIndex() + 1;
7212             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
7213               // adjust for implicit parameter
7214               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
7215                 if (MD->isInstance())
7216                   ++PVIndex;
7217               // We also check if the formats are compatible.
7218               // We can't pass a 'scanf' string to a 'printf' function.
7219               if (PVIndex == PVFormat->getFormatIdx() &&
7220                   Type == S.GetFormatStringType(PVFormat))
7221                 return SLCT_UncheckedLiteral;
7222             }
7223           }
7224         }
7225       }
7226     }
7227 
7228     return SLCT_NotALiteral;
7229   }
7230 
7231   case Stmt::CallExprClass:
7232   case Stmt::CXXMemberCallExprClass: {
7233     const CallExpr *CE = cast<CallExpr>(E);
7234     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
7235       bool IsFirst = true;
7236       StringLiteralCheckType CommonResult;
7237       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
7238         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
7239         StringLiteralCheckType Result = checkFormatStringExpr(
7240             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7241             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7242             IgnoreStringsWithoutSpecifiers);
7243         if (IsFirst) {
7244           CommonResult = Result;
7245           IsFirst = false;
7246         }
7247       }
7248       if (!IsFirst)
7249         return CommonResult;
7250 
7251       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
7252         unsigned BuiltinID = FD->getBuiltinID();
7253         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
7254             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
7255           const Expr *Arg = CE->getArg(0);
7256           return checkFormatStringExpr(S, Arg, Args,
7257                                        HasVAListArg, format_idx,
7258                                        firstDataArg, Type, CallType,
7259                                        InFunctionCall, CheckedVarArgs,
7260                                        UncoveredArg, Offset,
7261                                        IgnoreStringsWithoutSpecifiers);
7262         }
7263       }
7264     }
7265 
7266     return SLCT_NotALiteral;
7267   }
7268   case Stmt::ObjCMessageExprClass: {
7269     const auto *ME = cast<ObjCMessageExpr>(E);
7270     if (const auto *MD = ME->getMethodDecl()) {
7271       if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
7272         // As a special case heuristic, if we're using the method -[NSBundle
7273         // localizedStringForKey:value:table:], ignore any key strings that lack
7274         // format specifiers. The idea is that if the key doesn't have any
7275         // format specifiers then its probably just a key to map to the
7276         // localized strings. If it does have format specifiers though, then its
7277         // likely that the text of the key is the format string in the
7278         // programmer's language, and should be checked.
7279         const ObjCInterfaceDecl *IFace;
7280         if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
7281             IFace->getIdentifier()->isStr("NSBundle") &&
7282             MD->getSelector().isKeywordSelector(
7283                 {"localizedStringForKey", "value", "table"})) {
7284           IgnoreStringsWithoutSpecifiers = true;
7285         }
7286 
7287         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
7288         return checkFormatStringExpr(
7289             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7290             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7291             IgnoreStringsWithoutSpecifiers);
7292       }
7293     }
7294 
7295     return SLCT_NotALiteral;
7296   }
7297   case Stmt::ObjCStringLiteralClass:
7298   case Stmt::StringLiteralClass: {
7299     const StringLiteral *StrE = nullptr;
7300 
7301     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
7302       StrE = ObjCFExpr->getString();
7303     else
7304       StrE = cast<StringLiteral>(E);
7305 
7306     if (StrE) {
7307       if (Offset.isNegative() || Offset > StrE->getLength()) {
7308         // TODO: It would be better to have an explicit warning for out of
7309         // bounds literals.
7310         return SLCT_NotALiteral;
7311       }
7312       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
7313       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
7314                         firstDataArg, Type, InFunctionCall, CallType,
7315                         CheckedVarArgs, UncoveredArg,
7316                         IgnoreStringsWithoutSpecifiers);
7317       return SLCT_CheckedLiteral;
7318     }
7319 
7320     return SLCT_NotALiteral;
7321   }
7322   case Stmt::BinaryOperatorClass: {
7323     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
7324 
7325     // A string literal + an int offset is still a string literal.
7326     if (BinOp->isAdditiveOp()) {
7327       Expr::EvalResult LResult, RResult;
7328 
7329       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
7330           LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7331       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
7332           RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7333 
7334       if (LIsInt != RIsInt) {
7335         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
7336 
7337         if (LIsInt) {
7338           if (BinOpKind == BO_Add) {
7339             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
7340             E = BinOp->getRHS();
7341             goto tryAgain;
7342           }
7343         } else {
7344           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
7345           E = BinOp->getLHS();
7346           goto tryAgain;
7347         }
7348       }
7349     }
7350 
7351     return SLCT_NotALiteral;
7352   }
7353   case Stmt::UnaryOperatorClass: {
7354     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
7355     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
7356     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
7357       Expr::EvalResult IndexResult;
7358       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
7359                                        Expr::SE_NoSideEffects,
7360                                        S.isConstantEvaluated())) {
7361         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
7362                    /*RHS is int*/ true);
7363         E = ASE->getBase();
7364         goto tryAgain;
7365       }
7366     }
7367 
7368     return SLCT_NotALiteral;
7369   }
7370 
7371   default:
7372     return SLCT_NotALiteral;
7373   }
7374 }
7375 
7376 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
7377   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
7378       .Case("scanf", FST_Scanf)
7379       .Cases("printf", "printf0", FST_Printf)
7380       .Cases("NSString", "CFString", FST_NSString)
7381       .Case("strftime", FST_Strftime)
7382       .Case("strfmon", FST_Strfmon)
7383       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
7384       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
7385       .Case("os_trace", FST_OSLog)
7386       .Case("os_log", FST_OSLog)
7387       .Default(FST_Unknown);
7388 }
7389 
7390 /// CheckFormatArguments - Check calls to printf and scanf (and similar
7391 /// functions) for correct use of format strings.
7392 /// Returns true if a format string has been fully checked.
7393 bool Sema::CheckFormatArguments(const FormatAttr *Format,
7394                                 ArrayRef<const Expr *> Args,
7395                                 bool IsCXXMember,
7396                                 VariadicCallType CallType,
7397                                 SourceLocation Loc, SourceRange Range,
7398                                 llvm::SmallBitVector &CheckedVarArgs) {
7399   FormatStringInfo FSI;
7400   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
7401     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
7402                                 FSI.FirstDataArg, GetFormatStringType(Format),
7403                                 CallType, Loc, Range, CheckedVarArgs);
7404   return false;
7405 }
7406 
7407 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
7408                                 bool HasVAListArg, unsigned format_idx,
7409                                 unsigned firstDataArg, FormatStringType Type,
7410                                 VariadicCallType CallType,
7411                                 SourceLocation Loc, SourceRange Range,
7412                                 llvm::SmallBitVector &CheckedVarArgs) {
7413   // CHECK: printf/scanf-like function is called with no format string.
7414   if (format_idx >= Args.size()) {
7415     Diag(Loc, diag::warn_missing_format_string) << Range;
7416     return false;
7417   }
7418 
7419   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
7420 
7421   // CHECK: format string is not a string literal.
7422   //
7423   // Dynamically generated format strings are difficult to
7424   // automatically vet at compile time.  Requiring that format strings
7425   // are string literals: (1) permits the checking of format strings by
7426   // the compiler and thereby (2) can practically remove the source of
7427   // many format string exploits.
7428 
7429   // Format string can be either ObjC string (e.g. @"%d") or
7430   // C string (e.g. "%d")
7431   // ObjC string uses the same format specifiers as C string, so we can use
7432   // the same format string checking logic for both ObjC and C strings.
7433   UncoveredArgHandler UncoveredArg;
7434   StringLiteralCheckType CT =
7435       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
7436                             format_idx, firstDataArg, Type, CallType,
7437                             /*IsFunctionCall*/ true, CheckedVarArgs,
7438                             UncoveredArg,
7439                             /*no string offset*/ llvm::APSInt(64, false) = 0);
7440 
7441   // Generate a diagnostic where an uncovered argument is detected.
7442   if (UncoveredArg.hasUncoveredArg()) {
7443     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
7444     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
7445     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
7446   }
7447 
7448   if (CT != SLCT_NotALiteral)
7449     // Literal format string found, check done!
7450     return CT == SLCT_CheckedLiteral;
7451 
7452   // Strftime is particular as it always uses a single 'time' argument,
7453   // so it is safe to pass a non-literal string.
7454   if (Type == FST_Strftime)
7455     return false;
7456 
7457   // Do not emit diag when the string param is a macro expansion and the
7458   // format is either NSString or CFString. This is a hack to prevent
7459   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
7460   // which are usually used in place of NS and CF string literals.
7461   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
7462   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
7463     return false;
7464 
7465   // If there are no arguments specified, warn with -Wformat-security, otherwise
7466   // warn only with -Wformat-nonliteral.
7467   if (Args.size() == firstDataArg) {
7468     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
7469       << OrigFormatExpr->getSourceRange();
7470     switch (Type) {
7471     default:
7472       break;
7473     case FST_Kprintf:
7474     case FST_FreeBSDKPrintf:
7475     case FST_Printf:
7476       Diag(FormatLoc, diag::note_format_security_fixit)
7477         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
7478       break;
7479     case FST_NSString:
7480       Diag(FormatLoc, diag::note_format_security_fixit)
7481         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
7482       break;
7483     }
7484   } else {
7485     Diag(FormatLoc, diag::warn_format_nonliteral)
7486       << OrigFormatExpr->getSourceRange();
7487   }
7488   return false;
7489 }
7490 
7491 namespace {
7492 
7493 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
7494 protected:
7495   Sema &S;
7496   const FormatStringLiteral *FExpr;
7497   const Expr *OrigFormatExpr;
7498   const Sema::FormatStringType FSType;
7499   const unsigned FirstDataArg;
7500   const unsigned NumDataArgs;
7501   const char *Beg; // Start of format string.
7502   const bool HasVAListArg;
7503   ArrayRef<const Expr *> Args;
7504   unsigned FormatIdx;
7505   llvm::SmallBitVector CoveredArgs;
7506   bool usesPositionalArgs = false;
7507   bool atFirstArg = true;
7508   bool inFunctionCall;
7509   Sema::VariadicCallType CallType;
7510   llvm::SmallBitVector &CheckedVarArgs;
7511   UncoveredArgHandler &UncoveredArg;
7512 
7513 public:
7514   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
7515                      const Expr *origFormatExpr,
7516                      const Sema::FormatStringType type, unsigned firstDataArg,
7517                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
7518                      ArrayRef<const Expr *> Args, unsigned formatIdx,
7519                      bool inFunctionCall, Sema::VariadicCallType callType,
7520                      llvm::SmallBitVector &CheckedVarArgs,
7521                      UncoveredArgHandler &UncoveredArg)
7522       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
7523         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
7524         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
7525         inFunctionCall(inFunctionCall), CallType(callType),
7526         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
7527     CoveredArgs.resize(numDataArgs);
7528     CoveredArgs.reset();
7529   }
7530 
7531   void DoneProcessing();
7532 
7533   void HandleIncompleteSpecifier(const char *startSpecifier,
7534                                  unsigned specifierLen) override;
7535 
7536   void HandleInvalidLengthModifier(
7537                            const analyze_format_string::FormatSpecifier &FS,
7538                            const analyze_format_string::ConversionSpecifier &CS,
7539                            const char *startSpecifier, unsigned specifierLen,
7540                            unsigned DiagID);
7541 
7542   void HandleNonStandardLengthModifier(
7543                     const analyze_format_string::FormatSpecifier &FS,
7544                     const char *startSpecifier, unsigned specifierLen);
7545 
7546   void HandleNonStandardConversionSpecifier(
7547                     const analyze_format_string::ConversionSpecifier &CS,
7548                     const char *startSpecifier, unsigned specifierLen);
7549 
7550   void HandlePosition(const char *startPos, unsigned posLen) override;
7551 
7552   void HandleInvalidPosition(const char *startSpecifier,
7553                              unsigned specifierLen,
7554                              analyze_format_string::PositionContext p) override;
7555 
7556   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
7557 
7558   void HandleNullChar(const char *nullCharacter) override;
7559 
7560   template <typename Range>
7561   static void
7562   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
7563                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
7564                        bool IsStringLocation, Range StringRange,
7565                        ArrayRef<FixItHint> Fixit = None);
7566 
7567 protected:
7568   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
7569                                         const char *startSpec,
7570                                         unsigned specifierLen,
7571                                         const char *csStart, unsigned csLen);
7572 
7573   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
7574                                          const char *startSpec,
7575                                          unsigned specifierLen);
7576 
7577   SourceRange getFormatStringRange();
7578   CharSourceRange getSpecifierRange(const char *startSpecifier,
7579                                     unsigned specifierLen);
7580   SourceLocation getLocationOfByte(const char *x);
7581 
7582   const Expr *getDataArg(unsigned i) const;
7583 
7584   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
7585                     const analyze_format_string::ConversionSpecifier &CS,
7586                     const char *startSpecifier, unsigned specifierLen,
7587                     unsigned argIndex);
7588 
7589   template <typename Range>
7590   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
7591                             bool IsStringLocation, Range StringRange,
7592                             ArrayRef<FixItHint> Fixit = None);
7593 };
7594 
7595 } // namespace
7596 
7597 SourceRange CheckFormatHandler::getFormatStringRange() {
7598   return OrigFormatExpr->getSourceRange();
7599 }
7600 
7601 CharSourceRange CheckFormatHandler::
7602 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
7603   SourceLocation Start = getLocationOfByte(startSpecifier);
7604   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
7605 
7606   // Advance the end SourceLocation by one due to half-open ranges.
7607   End = End.getLocWithOffset(1);
7608 
7609   return CharSourceRange::getCharRange(Start, End);
7610 }
7611 
7612 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
7613   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
7614                                   S.getLangOpts(), S.Context.getTargetInfo());
7615 }
7616 
7617 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
7618                                                    unsigned specifierLen){
7619   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
7620                        getLocationOfByte(startSpecifier),
7621                        /*IsStringLocation*/true,
7622                        getSpecifierRange(startSpecifier, specifierLen));
7623 }
7624 
7625 void CheckFormatHandler::HandleInvalidLengthModifier(
7626     const analyze_format_string::FormatSpecifier &FS,
7627     const analyze_format_string::ConversionSpecifier &CS,
7628     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
7629   using namespace analyze_format_string;
7630 
7631   const LengthModifier &LM = FS.getLengthModifier();
7632   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7633 
7634   // See if we know how to fix this length modifier.
7635   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7636   if (FixedLM) {
7637     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7638                          getLocationOfByte(LM.getStart()),
7639                          /*IsStringLocation*/true,
7640                          getSpecifierRange(startSpecifier, specifierLen));
7641 
7642     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7643       << FixedLM->toString()
7644       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7645 
7646   } else {
7647     FixItHint Hint;
7648     if (DiagID == diag::warn_format_nonsensical_length)
7649       Hint = FixItHint::CreateRemoval(LMRange);
7650 
7651     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7652                          getLocationOfByte(LM.getStart()),
7653                          /*IsStringLocation*/true,
7654                          getSpecifierRange(startSpecifier, specifierLen),
7655                          Hint);
7656   }
7657 }
7658 
7659 void CheckFormatHandler::HandleNonStandardLengthModifier(
7660     const analyze_format_string::FormatSpecifier &FS,
7661     const char *startSpecifier, unsigned specifierLen) {
7662   using namespace analyze_format_string;
7663 
7664   const LengthModifier &LM = FS.getLengthModifier();
7665   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7666 
7667   // See if we know how to fix this length modifier.
7668   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7669   if (FixedLM) {
7670     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7671                            << LM.toString() << 0,
7672                          getLocationOfByte(LM.getStart()),
7673                          /*IsStringLocation*/true,
7674                          getSpecifierRange(startSpecifier, specifierLen));
7675 
7676     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7677       << FixedLM->toString()
7678       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7679 
7680   } else {
7681     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7682                            << LM.toString() << 0,
7683                          getLocationOfByte(LM.getStart()),
7684                          /*IsStringLocation*/true,
7685                          getSpecifierRange(startSpecifier, specifierLen));
7686   }
7687 }
7688 
7689 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
7690     const analyze_format_string::ConversionSpecifier &CS,
7691     const char *startSpecifier, unsigned specifierLen) {
7692   using namespace analyze_format_string;
7693 
7694   // See if we know how to fix this conversion specifier.
7695   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
7696   if (FixedCS) {
7697     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7698                           << CS.toString() << /*conversion specifier*/1,
7699                          getLocationOfByte(CS.getStart()),
7700                          /*IsStringLocation*/true,
7701                          getSpecifierRange(startSpecifier, specifierLen));
7702 
7703     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
7704     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
7705       << FixedCS->toString()
7706       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
7707   } else {
7708     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7709                           << CS.toString() << /*conversion specifier*/1,
7710                          getLocationOfByte(CS.getStart()),
7711                          /*IsStringLocation*/true,
7712                          getSpecifierRange(startSpecifier, specifierLen));
7713   }
7714 }
7715 
7716 void CheckFormatHandler::HandlePosition(const char *startPos,
7717                                         unsigned posLen) {
7718   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
7719                                getLocationOfByte(startPos),
7720                                /*IsStringLocation*/true,
7721                                getSpecifierRange(startPos, posLen));
7722 }
7723 
7724 void
7725 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
7726                                      analyze_format_string::PositionContext p) {
7727   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
7728                          << (unsigned) p,
7729                        getLocationOfByte(startPos), /*IsStringLocation*/true,
7730                        getSpecifierRange(startPos, posLen));
7731 }
7732 
7733 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
7734                                             unsigned posLen) {
7735   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
7736                                getLocationOfByte(startPos),
7737                                /*IsStringLocation*/true,
7738                                getSpecifierRange(startPos, posLen));
7739 }
7740 
7741 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
7742   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
7743     // The presence of a null character is likely an error.
7744     EmitFormatDiagnostic(
7745       S.PDiag(diag::warn_printf_format_string_contains_null_char),
7746       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
7747       getFormatStringRange());
7748   }
7749 }
7750 
7751 // Note that this may return NULL if there was an error parsing or building
7752 // one of the argument expressions.
7753 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
7754   return Args[FirstDataArg + i];
7755 }
7756 
7757 void CheckFormatHandler::DoneProcessing() {
7758   // Does the number of data arguments exceed the number of
7759   // format conversions in the format string?
7760   if (!HasVAListArg) {
7761       // Find any arguments that weren't covered.
7762     CoveredArgs.flip();
7763     signed notCoveredArg = CoveredArgs.find_first();
7764     if (notCoveredArg >= 0) {
7765       assert((unsigned)notCoveredArg < NumDataArgs);
7766       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
7767     } else {
7768       UncoveredArg.setAllCovered();
7769     }
7770   }
7771 }
7772 
7773 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
7774                                    const Expr *ArgExpr) {
7775   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
7776          "Invalid state");
7777 
7778   if (!ArgExpr)
7779     return;
7780 
7781   SourceLocation Loc = ArgExpr->getBeginLoc();
7782 
7783   if (S.getSourceManager().isInSystemMacro(Loc))
7784     return;
7785 
7786   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
7787   for (auto E : DiagnosticExprs)
7788     PDiag << E->getSourceRange();
7789 
7790   CheckFormatHandler::EmitFormatDiagnostic(
7791                                   S, IsFunctionCall, DiagnosticExprs[0],
7792                                   PDiag, Loc, /*IsStringLocation*/false,
7793                                   DiagnosticExprs[0]->getSourceRange());
7794 }
7795 
7796 bool
7797 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
7798                                                      SourceLocation Loc,
7799                                                      const char *startSpec,
7800                                                      unsigned specifierLen,
7801                                                      const char *csStart,
7802                                                      unsigned csLen) {
7803   bool keepGoing = true;
7804   if (argIndex < NumDataArgs) {
7805     // Consider the argument coverered, even though the specifier doesn't
7806     // make sense.
7807     CoveredArgs.set(argIndex);
7808   }
7809   else {
7810     // If argIndex exceeds the number of data arguments we
7811     // don't issue a warning because that is just a cascade of warnings (and
7812     // they may have intended '%%' anyway). We don't want to continue processing
7813     // the format string after this point, however, as we will like just get
7814     // gibberish when trying to match arguments.
7815     keepGoing = false;
7816   }
7817 
7818   StringRef Specifier(csStart, csLen);
7819 
7820   // If the specifier in non-printable, it could be the first byte of a UTF-8
7821   // sequence. In that case, print the UTF-8 code point. If not, print the byte
7822   // hex value.
7823   std::string CodePointStr;
7824   if (!llvm::sys::locale::isPrint(*csStart)) {
7825     llvm::UTF32 CodePoint;
7826     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
7827     const llvm::UTF8 *E =
7828         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
7829     llvm::ConversionResult Result =
7830         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
7831 
7832     if (Result != llvm::conversionOK) {
7833       unsigned char FirstChar = *csStart;
7834       CodePoint = (llvm::UTF32)FirstChar;
7835     }
7836 
7837     llvm::raw_string_ostream OS(CodePointStr);
7838     if (CodePoint < 256)
7839       OS << "\\x" << llvm::format("%02x", CodePoint);
7840     else if (CodePoint <= 0xFFFF)
7841       OS << "\\u" << llvm::format("%04x", CodePoint);
7842     else
7843       OS << "\\U" << llvm::format("%08x", CodePoint);
7844     OS.flush();
7845     Specifier = CodePointStr;
7846   }
7847 
7848   EmitFormatDiagnostic(
7849       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
7850       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
7851 
7852   return keepGoing;
7853 }
7854 
7855 void
7856 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
7857                                                       const char *startSpec,
7858                                                       unsigned specifierLen) {
7859   EmitFormatDiagnostic(
7860     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
7861     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
7862 }
7863 
7864 bool
7865 CheckFormatHandler::CheckNumArgs(
7866   const analyze_format_string::FormatSpecifier &FS,
7867   const analyze_format_string::ConversionSpecifier &CS,
7868   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
7869 
7870   if (argIndex >= NumDataArgs) {
7871     PartialDiagnostic PDiag = FS.usesPositionalArg()
7872       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
7873            << (argIndex+1) << NumDataArgs)
7874       : S.PDiag(diag::warn_printf_insufficient_data_args);
7875     EmitFormatDiagnostic(
7876       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
7877       getSpecifierRange(startSpecifier, specifierLen));
7878 
7879     // Since more arguments than conversion tokens are given, by extension
7880     // all arguments are covered, so mark this as so.
7881     UncoveredArg.setAllCovered();
7882     return false;
7883   }
7884   return true;
7885 }
7886 
7887 template<typename Range>
7888 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
7889                                               SourceLocation Loc,
7890                                               bool IsStringLocation,
7891                                               Range StringRange,
7892                                               ArrayRef<FixItHint> FixIt) {
7893   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
7894                        Loc, IsStringLocation, StringRange, FixIt);
7895 }
7896 
7897 /// If the format string is not within the function call, emit a note
7898 /// so that the function call and string are in diagnostic messages.
7899 ///
7900 /// \param InFunctionCall if true, the format string is within the function
7901 /// call and only one diagnostic message will be produced.  Otherwise, an
7902 /// extra note will be emitted pointing to location of the format string.
7903 ///
7904 /// \param ArgumentExpr the expression that is passed as the format string
7905 /// argument in the function call.  Used for getting locations when two
7906 /// diagnostics are emitted.
7907 ///
7908 /// \param PDiag the callee should already have provided any strings for the
7909 /// diagnostic message.  This function only adds locations and fixits
7910 /// to diagnostics.
7911 ///
7912 /// \param Loc primary location for diagnostic.  If two diagnostics are
7913 /// required, one will be at Loc and a new SourceLocation will be created for
7914 /// the other one.
7915 ///
7916 /// \param IsStringLocation if true, Loc points to the format string should be
7917 /// used for the note.  Otherwise, Loc points to the argument list and will
7918 /// be used with PDiag.
7919 ///
7920 /// \param StringRange some or all of the string to highlight.  This is
7921 /// templated so it can accept either a CharSourceRange or a SourceRange.
7922 ///
7923 /// \param FixIt optional fix it hint for the format string.
7924 template <typename Range>
7925 void CheckFormatHandler::EmitFormatDiagnostic(
7926     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
7927     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
7928     Range StringRange, ArrayRef<FixItHint> FixIt) {
7929   if (InFunctionCall) {
7930     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
7931     D << StringRange;
7932     D << FixIt;
7933   } else {
7934     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
7935       << ArgumentExpr->getSourceRange();
7936 
7937     const Sema::SemaDiagnosticBuilder &Note =
7938       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
7939              diag::note_format_string_defined);
7940 
7941     Note << StringRange;
7942     Note << FixIt;
7943   }
7944 }
7945 
7946 //===--- CHECK: Printf format string checking ------------------------------===//
7947 
7948 namespace {
7949 
7950 class CheckPrintfHandler : public CheckFormatHandler {
7951 public:
7952   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
7953                      const Expr *origFormatExpr,
7954                      const Sema::FormatStringType type, unsigned firstDataArg,
7955                      unsigned numDataArgs, bool isObjC, const char *beg,
7956                      bool hasVAListArg, ArrayRef<const Expr *> Args,
7957                      unsigned formatIdx, bool inFunctionCall,
7958                      Sema::VariadicCallType CallType,
7959                      llvm::SmallBitVector &CheckedVarArgs,
7960                      UncoveredArgHandler &UncoveredArg)
7961       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7962                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
7963                            inFunctionCall, CallType, CheckedVarArgs,
7964                            UncoveredArg) {}
7965 
7966   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
7967 
7968   /// Returns true if '%@' specifiers are allowed in the format string.
7969   bool allowsObjCArg() const {
7970     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
7971            FSType == Sema::FST_OSTrace;
7972   }
7973 
7974   bool HandleInvalidPrintfConversionSpecifier(
7975                                       const analyze_printf::PrintfSpecifier &FS,
7976                                       const char *startSpecifier,
7977                                       unsigned specifierLen) override;
7978 
7979   void handleInvalidMaskType(StringRef MaskType) override;
7980 
7981   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
7982                              const char *startSpecifier,
7983                              unsigned specifierLen) override;
7984   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7985                        const char *StartSpecifier,
7986                        unsigned SpecifierLen,
7987                        const Expr *E);
7988 
7989   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
7990                     const char *startSpecifier, unsigned specifierLen);
7991   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
7992                            const analyze_printf::OptionalAmount &Amt,
7993                            unsigned type,
7994                            const char *startSpecifier, unsigned specifierLen);
7995   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7996                   const analyze_printf::OptionalFlag &flag,
7997                   const char *startSpecifier, unsigned specifierLen);
7998   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
7999                          const analyze_printf::OptionalFlag &ignoredFlag,
8000                          const analyze_printf::OptionalFlag &flag,
8001                          const char *startSpecifier, unsigned specifierLen);
8002   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
8003                            const Expr *E);
8004 
8005   void HandleEmptyObjCModifierFlag(const char *startFlag,
8006                                    unsigned flagLen) override;
8007 
8008   void HandleInvalidObjCModifierFlag(const char *startFlag,
8009                                             unsigned flagLen) override;
8010 
8011   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
8012                                            const char *flagsEnd,
8013                                            const char *conversionPosition)
8014                                              override;
8015 };
8016 
8017 } // namespace
8018 
8019 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
8020                                       const analyze_printf::PrintfSpecifier &FS,
8021                                       const char *startSpecifier,
8022                                       unsigned specifierLen) {
8023   const analyze_printf::PrintfConversionSpecifier &CS =
8024     FS.getConversionSpecifier();
8025 
8026   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8027                                           getLocationOfByte(CS.getStart()),
8028                                           startSpecifier, specifierLen,
8029                                           CS.getStart(), CS.getLength());
8030 }
8031 
8032 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
8033   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
8034 }
8035 
8036 bool CheckPrintfHandler::HandleAmount(
8037                                const analyze_format_string::OptionalAmount &Amt,
8038                                unsigned k, const char *startSpecifier,
8039                                unsigned specifierLen) {
8040   if (Amt.hasDataArgument()) {
8041     if (!HasVAListArg) {
8042       unsigned argIndex = Amt.getArgIndex();
8043       if (argIndex >= NumDataArgs) {
8044         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
8045                                << k,
8046                              getLocationOfByte(Amt.getStart()),
8047                              /*IsStringLocation*/true,
8048                              getSpecifierRange(startSpecifier, specifierLen));
8049         // Don't do any more checking.  We will just emit
8050         // spurious errors.
8051         return false;
8052       }
8053 
8054       // Type check the data argument.  It should be an 'int'.
8055       // Although not in conformance with C99, we also allow the argument to be
8056       // an 'unsigned int' as that is a reasonably safe case.  GCC also
8057       // doesn't emit a warning for that case.
8058       CoveredArgs.set(argIndex);
8059       const Expr *Arg = getDataArg(argIndex);
8060       if (!Arg)
8061         return false;
8062 
8063       QualType T = Arg->getType();
8064 
8065       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
8066       assert(AT.isValid());
8067 
8068       if (!AT.matchesType(S.Context, T)) {
8069         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
8070                                << k << AT.getRepresentativeTypeName(S.Context)
8071                                << T << Arg->getSourceRange(),
8072                              getLocationOfByte(Amt.getStart()),
8073                              /*IsStringLocation*/true,
8074                              getSpecifierRange(startSpecifier, specifierLen));
8075         // Don't do any more checking.  We will just emit
8076         // spurious errors.
8077         return false;
8078       }
8079     }
8080   }
8081   return true;
8082 }
8083 
8084 void CheckPrintfHandler::HandleInvalidAmount(
8085                                       const analyze_printf::PrintfSpecifier &FS,
8086                                       const analyze_printf::OptionalAmount &Amt,
8087                                       unsigned type,
8088                                       const char *startSpecifier,
8089                                       unsigned specifierLen) {
8090   const analyze_printf::PrintfConversionSpecifier &CS =
8091     FS.getConversionSpecifier();
8092 
8093   FixItHint fixit =
8094     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
8095       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
8096                                  Amt.getConstantLength()))
8097       : FixItHint();
8098 
8099   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
8100                          << type << CS.toString(),
8101                        getLocationOfByte(Amt.getStart()),
8102                        /*IsStringLocation*/true,
8103                        getSpecifierRange(startSpecifier, specifierLen),
8104                        fixit);
8105 }
8106 
8107 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8108                                     const analyze_printf::OptionalFlag &flag,
8109                                     const char *startSpecifier,
8110                                     unsigned specifierLen) {
8111   // Warn about pointless flag with a fixit removal.
8112   const analyze_printf::PrintfConversionSpecifier &CS =
8113     FS.getConversionSpecifier();
8114   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
8115                          << flag.toString() << CS.toString(),
8116                        getLocationOfByte(flag.getPosition()),
8117                        /*IsStringLocation*/true,
8118                        getSpecifierRange(startSpecifier, specifierLen),
8119                        FixItHint::CreateRemoval(
8120                          getSpecifierRange(flag.getPosition(), 1)));
8121 }
8122 
8123 void CheckPrintfHandler::HandleIgnoredFlag(
8124                                 const analyze_printf::PrintfSpecifier &FS,
8125                                 const analyze_printf::OptionalFlag &ignoredFlag,
8126                                 const analyze_printf::OptionalFlag &flag,
8127                                 const char *startSpecifier,
8128                                 unsigned specifierLen) {
8129   // Warn about ignored flag with a fixit removal.
8130   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
8131                          << ignoredFlag.toString() << flag.toString(),
8132                        getLocationOfByte(ignoredFlag.getPosition()),
8133                        /*IsStringLocation*/true,
8134                        getSpecifierRange(startSpecifier, specifierLen),
8135                        FixItHint::CreateRemoval(
8136                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
8137 }
8138 
8139 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
8140                                                      unsigned flagLen) {
8141   // Warn about an empty flag.
8142   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
8143                        getLocationOfByte(startFlag),
8144                        /*IsStringLocation*/true,
8145                        getSpecifierRange(startFlag, flagLen));
8146 }
8147 
8148 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
8149                                                        unsigned flagLen) {
8150   // Warn about an invalid flag.
8151   auto Range = getSpecifierRange(startFlag, flagLen);
8152   StringRef flag(startFlag, flagLen);
8153   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
8154                       getLocationOfByte(startFlag),
8155                       /*IsStringLocation*/true,
8156                       Range, FixItHint::CreateRemoval(Range));
8157 }
8158 
8159 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
8160     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
8161     // Warn about using '[...]' without a '@' conversion.
8162     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
8163     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
8164     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
8165                          getLocationOfByte(conversionPosition),
8166                          /*IsStringLocation*/true,
8167                          Range, FixItHint::CreateRemoval(Range));
8168 }
8169 
8170 // Determines if the specified is a C++ class or struct containing
8171 // a member with the specified name and kind (e.g. a CXXMethodDecl named
8172 // "c_str()").
8173 template<typename MemberKind>
8174 static llvm::SmallPtrSet<MemberKind*, 1>
8175 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
8176   const RecordType *RT = Ty->getAs<RecordType>();
8177   llvm::SmallPtrSet<MemberKind*, 1> Results;
8178 
8179   if (!RT)
8180     return Results;
8181   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
8182   if (!RD || !RD->getDefinition())
8183     return Results;
8184 
8185   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
8186                  Sema::LookupMemberName);
8187   R.suppressDiagnostics();
8188 
8189   // We just need to include all members of the right kind turned up by the
8190   // filter, at this point.
8191   if (S.LookupQualifiedName(R, RT->getDecl()))
8192     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8193       NamedDecl *decl = (*I)->getUnderlyingDecl();
8194       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
8195         Results.insert(FK);
8196     }
8197   return Results;
8198 }
8199 
8200 /// Check if we could call '.c_str()' on an object.
8201 ///
8202 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
8203 /// allow the call, or if it would be ambiguous).
8204 bool Sema::hasCStrMethod(const Expr *E) {
8205   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8206 
8207   MethodSet Results =
8208       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
8209   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8210        MI != ME; ++MI)
8211     if ((*MI)->getMinRequiredArguments() == 0)
8212       return true;
8213   return false;
8214 }
8215 
8216 // Check if a (w)string was passed when a (w)char* was needed, and offer a
8217 // better diagnostic if so. AT is assumed to be valid.
8218 // Returns true when a c_str() conversion method is found.
8219 bool CheckPrintfHandler::checkForCStrMembers(
8220     const analyze_printf::ArgType &AT, const Expr *E) {
8221   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8222 
8223   MethodSet Results =
8224       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
8225 
8226   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8227        MI != ME; ++MI) {
8228     const CXXMethodDecl *Method = *MI;
8229     if (Method->getMinRequiredArguments() == 0 &&
8230         AT.matchesType(S.Context, Method->getReturnType())) {
8231       // FIXME: Suggest parens if the expression needs them.
8232       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
8233       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
8234           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
8235       return true;
8236     }
8237   }
8238 
8239   return false;
8240 }
8241 
8242 bool
8243 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
8244                                             &FS,
8245                                           const char *startSpecifier,
8246                                           unsigned specifierLen) {
8247   using namespace analyze_format_string;
8248   using namespace analyze_printf;
8249 
8250   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
8251 
8252   if (FS.consumesDataArgument()) {
8253     if (atFirstArg) {
8254         atFirstArg = false;
8255         usesPositionalArgs = FS.usesPositionalArg();
8256     }
8257     else if (usesPositionalArgs != FS.usesPositionalArg()) {
8258       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8259                                         startSpecifier, specifierLen);
8260       return false;
8261     }
8262   }
8263 
8264   // First check if the field width, precision, and conversion specifier
8265   // have matching data arguments.
8266   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
8267                     startSpecifier, specifierLen)) {
8268     return false;
8269   }
8270 
8271   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
8272                     startSpecifier, specifierLen)) {
8273     return false;
8274   }
8275 
8276   if (!CS.consumesDataArgument()) {
8277     // FIXME: Technically specifying a precision or field width here
8278     // makes no sense.  Worth issuing a warning at some point.
8279     return true;
8280   }
8281 
8282   // Consume the argument.
8283   unsigned argIndex = FS.getArgIndex();
8284   if (argIndex < NumDataArgs) {
8285     // The check to see if the argIndex is valid will come later.
8286     // We set the bit here because we may exit early from this
8287     // function if we encounter some other error.
8288     CoveredArgs.set(argIndex);
8289   }
8290 
8291   // FreeBSD kernel extensions.
8292   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
8293       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
8294     // We need at least two arguments.
8295     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
8296       return false;
8297 
8298     // Claim the second argument.
8299     CoveredArgs.set(argIndex + 1);
8300 
8301     // Type check the first argument (int for %b, pointer for %D)
8302     const Expr *Ex = getDataArg(argIndex);
8303     const analyze_printf::ArgType &AT =
8304       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
8305         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
8306     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
8307       EmitFormatDiagnostic(
8308           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8309               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
8310               << false << Ex->getSourceRange(),
8311           Ex->getBeginLoc(), /*IsStringLocation*/ false,
8312           getSpecifierRange(startSpecifier, specifierLen));
8313 
8314     // Type check the second argument (char * for both %b and %D)
8315     Ex = getDataArg(argIndex + 1);
8316     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
8317     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
8318       EmitFormatDiagnostic(
8319           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8320               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
8321               << false << Ex->getSourceRange(),
8322           Ex->getBeginLoc(), /*IsStringLocation*/ false,
8323           getSpecifierRange(startSpecifier, specifierLen));
8324 
8325      return true;
8326   }
8327 
8328   // Check for using an Objective-C specific conversion specifier
8329   // in a non-ObjC literal.
8330   if (!allowsObjCArg() && CS.isObjCArg()) {
8331     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8332                                                   specifierLen);
8333   }
8334 
8335   // %P can only be used with os_log.
8336   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
8337     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8338                                                   specifierLen);
8339   }
8340 
8341   // %n is not allowed with os_log.
8342   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
8343     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
8344                          getLocationOfByte(CS.getStart()),
8345                          /*IsStringLocation*/ false,
8346                          getSpecifierRange(startSpecifier, specifierLen));
8347 
8348     return true;
8349   }
8350 
8351   // Only scalars are allowed for os_trace.
8352   if (FSType == Sema::FST_OSTrace &&
8353       (CS.getKind() == ConversionSpecifier::PArg ||
8354        CS.getKind() == ConversionSpecifier::sArg ||
8355        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
8356     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8357                                                   specifierLen);
8358   }
8359 
8360   // Check for use of public/private annotation outside of os_log().
8361   if (FSType != Sema::FST_OSLog) {
8362     if (FS.isPublic().isSet()) {
8363       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8364                                << "public",
8365                            getLocationOfByte(FS.isPublic().getPosition()),
8366                            /*IsStringLocation*/ false,
8367                            getSpecifierRange(startSpecifier, specifierLen));
8368     }
8369     if (FS.isPrivate().isSet()) {
8370       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8371                                << "private",
8372                            getLocationOfByte(FS.isPrivate().getPosition()),
8373                            /*IsStringLocation*/ false,
8374                            getSpecifierRange(startSpecifier, specifierLen));
8375     }
8376   }
8377 
8378   // Check for invalid use of field width
8379   if (!FS.hasValidFieldWidth()) {
8380     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
8381         startSpecifier, specifierLen);
8382   }
8383 
8384   // Check for invalid use of precision
8385   if (!FS.hasValidPrecision()) {
8386     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
8387         startSpecifier, specifierLen);
8388   }
8389 
8390   // Precision is mandatory for %P specifier.
8391   if (CS.getKind() == ConversionSpecifier::PArg &&
8392       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
8393     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
8394                          getLocationOfByte(startSpecifier),
8395                          /*IsStringLocation*/ false,
8396                          getSpecifierRange(startSpecifier, specifierLen));
8397   }
8398 
8399   // Check each flag does not conflict with any other component.
8400   if (!FS.hasValidThousandsGroupingPrefix())
8401     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
8402   if (!FS.hasValidLeadingZeros())
8403     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
8404   if (!FS.hasValidPlusPrefix())
8405     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
8406   if (!FS.hasValidSpacePrefix())
8407     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
8408   if (!FS.hasValidAlternativeForm())
8409     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
8410   if (!FS.hasValidLeftJustified())
8411     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
8412 
8413   // Check that flags are not ignored by another flag
8414   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
8415     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
8416         startSpecifier, specifierLen);
8417   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
8418     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
8419             startSpecifier, specifierLen);
8420 
8421   // Check the length modifier is valid with the given conversion specifier.
8422   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8423                                  S.getLangOpts()))
8424     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8425                                 diag::warn_format_nonsensical_length);
8426   else if (!FS.hasStandardLengthModifier())
8427     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8428   else if (!FS.hasStandardLengthConversionCombination())
8429     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8430                                 diag::warn_format_non_standard_conversion_spec);
8431 
8432   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8433     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8434 
8435   // The remaining checks depend on the data arguments.
8436   if (HasVAListArg)
8437     return true;
8438 
8439   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8440     return false;
8441 
8442   const Expr *Arg = getDataArg(argIndex);
8443   if (!Arg)
8444     return true;
8445 
8446   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
8447 }
8448 
8449 static bool requiresParensToAddCast(const Expr *E) {
8450   // FIXME: We should have a general way to reason about operator
8451   // precedence and whether parens are actually needed here.
8452   // Take care of a few common cases where they aren't.
8453   const Expr *Inside = E->IgnoreImpCasts();
8454   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
8455     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
8456 
8457   switch (Inside->getStmtClass()) {
8458   case Stmt::ArraySubscriptExprClass:
8459   case Stmt::CallExprClass:
8460   case Stmt::CharacterLiteralClass:
8461   case Stmt::CXXBoolLiteralExprClass:
8462   case Stmt::DeclRefExprClass:
8463   case Stmt::FloatingLiteralClass:
8464   case Stmt::IntegerLiteralClass:
8465   case Stmt::MemberExprClass:
8466   case Stmt::ObjCArrayLiteralClass:
8467   case Stmt::ObjCBoolLiteralExprClass:
8468   case Stmt::ObjCBoxedExprClass:
8469   case Stmt::ObjCDictionaryLiteralClass:
8470   case Stmt::ObjCEncodeExprClass:
8471   case Stmt::ObjCIvarRefExprClass:
8472   case Stmt::ObjCMessageExprClass:
8473   case Stmt::ObjCPropertyRefExprClass:
8474   case Stmt::ObjCStringLiteralClass:
8475   case Stmt::ObjCSubscriptRefExprClass:
8476   case Stmt::ParenExprClass:
8477   case Stmt::StringLiteralClass:
8478   case Stmt::UnaryOperatorClass:
8479     return false;
8480   default:
8481     return true;
8482   }
8483 }
8484 
8485 static std::pair<QualType, StringRef>
8486 shouldNotPrintDirectly(const ASTContext &Context,
8487                        QualType IntendedTy,
8488                        const Expr *E) {
8489   // Use a 'while' to peel off layers of typedefs.
8490   QualType TyTy = IntendedTy;
8491   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
8492     StringRef Name = UserTy->getDecl()->getName();
8493     QualType CastTy = llvm::StringSwitch<QualType>(Name)
8494       .Case("CFIndex", Context.getNSIntegerType())
8495       .Case("NSInteger", Context.getNSIntegerType())
8496       .Case("NSUInteger", Context.getNSUIntegerType())
8497       .Case("SInt32", Context.IntTy)
8498       .Case("UInt32", Context.UnsignedIntTy)
8499       .Default(QualType());
8500 
8501     if (!CastTy.isNull())
8502       return std::make_pair(CastTy, Name);
8503 
8504     TyTy = UserTy->desugar();
8505   }
8506 
8507   // Strip parens if necessary.
8508   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
8509     return shouldNotPrintDirectly(Context,
8510                                   PE->getSubExpr()->getType(),
8511                                   PE->getSubExpr());
8512 
8513   // If this is a conditional expression, then its result type is constructed
8514   // via usual arithmetic conversions and thus there might be no necessary
8515   // typedef sugar there.  Recurse to operands to check for NSInteger &
8516   // Co. usage condition.
8517   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8518     QualType TrueTy, FalseTy;
8519     StringRef TrueName, FalseName;
8520 
8521     std::tie(TrueTy, TrueName) =
8522       shouldNotPrintDirectly(Context,
8523                              CO->getTrueExpr()->getType(),
8524                              CO->getTrueExpr());
8525     std::tie(FalseTy, FalseName) =
8526       shouldNotPrintDirectly(Context,
8527                              CO->getFalseExpr()->getType(),
8528                              CO->getFalseExpr());
8529 
8530     if (TrueTy == FalseTy)
8531       return std::make_pair(TrueTy, TrueName);
8532     else if (TrueTy.isNull())
8533       return std::make_pair(FalseTy, FalseName);
8534     else if (FalseTy.isNull())
8535       return std::make_pair(TrueTy, TrueName);
8536   }
8537 
8538   return std::make_pair(QualType(), StringRef());
8539 }
8540 
8541 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
8542 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
8543 /// type do not count.
8544 static bool
8545 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
8546   QualType From = ICE->getSubExpr()->getType();
8547   QualType To = ICE->getType();
8548   // It's an integer promotion if the destination type is the promoted
8549   // source type.
8550   if (ICE->getCastKind() == CK_IntegralCast &&
8551       From->isPromotableIntegerType() &&
8552       S.Context.getPromotedIntegerType(From) == To)
8553     return true;
8554   // Look through vector types, since we do default argument promotion for
8555   // those in OpenCL.
8556   if (const auto *VecTy = From->getAs<ExtVectorType>())
8557     From = VecTy->getElementType();
8558   if (const auto *VecTy = To->getAs<ExtVectorType>())
8559     To = VecTy->getElementType();
8560   // It's a floating promotion if the source type is a lower rank.
8561   return ICE->getCastKind() == CK_FloatingCast &&
8562          S.Context.getFloatingTypeOrder(From, To) < 0;
8563 }
8564 
8565 bool
8566 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8567                                     const char *StartSpecifier,
8568                                     unsigned SpecifierLen,
8569                                     const Expr *E) {
8570   using namespace analyze_format_string;
8571   using namespace analyze_printf;
8572 
8573   // Now type check the data expression that matches the
8574   // format specifier.
8575   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
8576   if (!AT.isValid())
8577     return true;
8578 
8579   QualType ExprTy = E->getType();
8580   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
8581     ExprTy = TET->getUnderlyingExpr()->getType();
8582   }
8583 
8584   // Diagnose attempts to print a boolean value as a character. Unlike other
8585   // -Wformat diagnostics, this is fine from a type perspective, but it still
8586   // doesn't make sense.
8587   if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
8588       E->isKnownToHaveBooleanValue()) {
8589     const CharSourceRange &CSR =
8590         getSpecifierRange(StartSpecifier, SpecifierLen);
8591     SmallString<4> FSString;
8592     llvm::raw_svector_ostream os(FSString);
8593     FS.toString(os);
8594     EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
8595                              << FSString,
8596                          E->getExprLoc(), false, CSR);
8597     return true;
8598   }
8599 
8600   analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
8601   if (Match == analyze_printf::ArgType::Match)
8602     return true;
8603 
8604   // Look through argument promotions for our error message's reported type.
8605   // This includes the integral and floating promotions, but excludes array
8606   // and function pointer decay (seeing that an argument intended to be a
8607   // string has type 'char [6]' is probably more confusing than 'char *') and
8608   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
8609   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8610     if (isArithmeticArgumentPromotion(S, ICE)) {
8611       E = ICE->getSubExpr();
8612       ExprTy = E->getType();
8613 
8614       // Check if we didn't match because of an implicit cast from a 'char'
8615       // or 'short' to an 'int'.  This is done because printf is a varargs
8616       // function.
8617       if (ICE->getType() == S.Context.IntTy ||
8618           ICE->getType() == S.Context.UnsignedIntTy) {
8619         // All further checking is done on the subexpression
8620         const analyze_printf::ArgType::MatchKind ImplicitMatch =
8621             AT.matchesType(S.Context, ExprTy);
8622         if (ImplicitMatch == analyze_printf::ArgType::Match)
8623           return true;
8624         if (ImplicitMatch == ArgType::NoMatchPedantic ||
8625             ImplicitMatch == ArgType::NoMatchTypeConfusion)
8626           Match = ImplicitMatch;
8627       }
8628     }
8629   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
8630     // Special case for 'a', which has type 'int' in C.
8631     // Note, however, that we do /not/ want to treat multibyte constants like
8632     // 'MooV' as characters! This form is deprecated but still exists.
8633     if (ExprTy == S.Context.IntTy)
8634       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
8635         ExprTy = S.Context.CharTy;
8636   }
8637 
8638   // Look through enums to their underlying type.
8639   bool IsEnum = false;
8640   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
8641     ExprTy = EnumTy->getDecl()->getIntegerType();
8642     IsEnum = true;
8643   }
8644 
8645   // %C in an Objective-C context prints a unichar, not a wchar_t.
8646   // If the argument is an integer of some kind, believe the %C and suggest
8647   // a cast instead of changing the conversion specifier.
8648   QualType IntendedTy = ExprTy;
8649   if (isObjCContext() &&
8650       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
8651     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
8652         !ExprTy->isCharType()) {
8653       // 'unichar' is defined as a typedef of unsigned short, but we should
8654       // prefer using the typedef if it is visible.
8655       IntendedTy = S.Context.UnsignedShortTy;
8656 
8657       // While we are here, check if the value is an IntegerLiteral that happens
8658       // to be within the valid range.
8659       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
8660         const llvm::APInt &V = IL->getValue();
8661         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
8662           return true;
8663       }
8664 
8665       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
8666                           Sema::LookupOrdinaryName);
8667       if (S.LookupName(Result, S.getCurScope())) {
8668         NamedDecl *ND = Result.getFoundDecl();
8669         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
8670           if (TD->getUnderlyingType() == IntendedTy)
8671             IntendedTy = S.Context.getTypedefType(TD);
8672       }
8673     }
8674   }
8675 
8676   // Special-case some of Darwin's platform-independence types by suggesting
8677   // casts to primitive types that are known to be large enough.
8678   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
8679   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
8680     QualType CastTy;
8681     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
8682     if (!CastTy.isNull()) {
8683       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
8684       // (long in ASTContext). Only complain to pedants.
8685       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
8686           (AT.isSizeT() || AT.isPtrdiffT()) &&
8687           AT.matchesType(S.Context, CastTy))
8688         Match = ArgType::NoMatchPedantic;
8689       IntendedTy = CastTy;
8690       ShouldNotPrintDirectly = true;
8691     }
8692   }
8693 
8694   // We may be able to offer a FixItHint if it is a supported type.
8695   PrintfSpecifier fixedFS = FS;
8696   bool Success =
8697       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
8698 
8699   if (Success) {
8700     // Get the fix string from the fixed format specifier
8701     SmallString<16> buf;
8702     llvm::raw_svector_ostream os(buf);
8703     fixedFS.toString(os);
8704 
8705     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
8706 
8707     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
8708       unsigned Diag;
8709       switch (Match) {
8710       case ArgType::Match: llvm_unreachable("expected non-matching");
8711       case ArgType::NoMatchPedantic:
8712         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8713         break;
8714       case ArgType::NoMatchTypeConfusion:
8715         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8716         break;
8717       case ArgType::NoMatch:
8718         Diag = diag::warn_format_conversion_argument_type_mismatch;
8719         break;
8720       }
8721 
8722       // In this case, the specifier is wrong and should be changed to match
8723       // the argument.
8724       EmitFormatDiagnostic(S.PDiag(Diag)
8725                                << AT.getRepresentativeTypeName(S.Context)
8726                                << IntendedTy << IsEnum << E->getSourceRange(),
8727                            E->getBeginLoc(),
8728                            /*IsStringLocation*/ false, SpecRange,
8729                            FixItHint::CreateReplacement(SpecRange, os.str()));
8730     } else {
8731       // The canonical type for formatting this value is different from the
8732       // actual type of the expression. (This occurs, for example, with Darwin's
8733       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
8734       // should be printed as 'long' for 64-bit compatibility.)
8735       // Rather than emitting a normal format/argument mismatch, we want to
8736       // add a cast to the recommended type (and correct the format string
8737       // if necessary).
8738       SmallString<16> CastBuf;
8739       llvm::raw_svector_ostream CastFix(CastBuf);
8740       CastFix << "(";
8741       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
8742       CastFix << ")";
8743 
8744       SmallVector<FixItHint,4> Hints;
8745       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
8746         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
8747 
8748       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
8749         // If there's already a cast present, just replace it.
8750         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
8751         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
8752 
8753       } else if (!requiresParensToAddCast(E)) {
8754         // If the expression has high enough precedence,
8755         // just write the C-style cast.
8756         Hints.push_back(
8757             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8758       } else {
8759         // Otherwise, add parens around the expression as well as the cast.
8760         CastFix << "(";
8761         Hints.push_back(
8762             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8763 
8764         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
8765         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
8766       }
8767 
8768       if (ShouldNotPrintDirectly) {
8769         // The expression has a type that should not be printed directly.
8770         // We extract the name from the typedef because we don't want to show
8771         // the underlying type in the diagnostic.
8772         StringRef Name;
8773         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
8774           Name = TypedefTy->getDecl()->getName();
8775         else
8776           Name = CastTyName;
8777         unsigned Diag = Match == ArgType::NoMatchPedantic
8778                             ? diag::warn_format_argument_needs_cast_pedantic
8779                             : diag::warn_format_argument_needs_cast;
8780         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
8781                                            << E->getSourceRange(),
8782                              E->getBeginLoc(), /*IsStringLocation=*/false,
8783                              SpecRange, Hints);
8784       } else {
8785         // In this case, the expression could be printed using a different
8786         // specifier, but we've decided that the specifier is probably correct
8787         // and we should cast instead. Just use the normal warning message.
8788         EmitFormatDiagnostic(
8789             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8790                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
8791                 << E->getSourceRange(),
8792             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
8793       }
8794     }
8795   } else {
8796     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
8797                                                    SpecifierLen);
8798     // Since the warning for passing non-POD types to variadic functions
8799     // was deferred until now, we emit a warning for non-POD
8800     // arguments here.
8801     switch (S.isValidVarArgType(ExprTy)) {
8802     case Sema::VAK_Valid:
8803     case Sema::VAK_ValidInCXX11: {
8804       unsigned Diag;
8805       switch (Match) {
8806       case ArgType::Match: llvm_unreachable("expected non-matching");
8807       case ArgType::NoMatchPedantic:
8808         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8809         break;
8810       case ArgType::NoMatchTypeConfusion:
8811         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8812         break;
8813       case ArgType::NoMatch:
8814         Diag = diag::warn_format_conversion_argument_type_mismatch;
8815         break;
8816       }
8817 
8818       EmitFormatDiagnostic(
8819           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
8820                         << IsEnum << CSR << E->getSourceRange(),
8821           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8822       break;
8823     }
8824     case Sema::VAK_Undefined:
8825     case Sema::VAK_MSVCUndefined:
8826       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
8827                                << S.getLangOpts().CPlusPlus11 << ExprTy
8828                                << CallType
8829                                << AT.getRepresentativeTypeName(S.Context) << CSR
8830                                << E->getSourceRange(),
8831                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8832       checkForCStrMembers(AT, E);
8833       break;
8834 
8835     case Sema::VAK_Invalid:
8836       if (ExprTy->isObjCObjectType())
8837         EmitFormatDiagnostic(
8838             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
8839                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
8840                 << AT.getRepresentativeTypeName(S.Context) << CSR
8841                 << E->getSourceRange(),
8842             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8843       else
8844         // FIXME: If this is an initializer list, suggest removing the braces
8845         // or inserting a cast to the target type.
8846         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
8847             << isa<InitListExpr>(E) << ExprTy << CallType
8848             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
8849       break;
8850     }
8851 
8852     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
8853            "format string specifier index out of range");
8854     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
8855   }
8856 
8857   return true;
8858 }
8859 
8860 //===--- CHECK: Scanf format string checking ------------------------------===//
8861 
8862 namespace {
8863 
8864 class CheckScanfHandler : public CheckFormatHandler {
8865 public:
8866   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
8867                     const Expr *origFormatExpr, Sema::FormatStringType type,
8868                     unsigned firstDataArg, unsigned numDataArgs,
8869                     const char *beg, bool hasVAListArg,
8870                     ArrayRef<const Expr *> Args, unsigned formatIdx,
8871                     bool inFunctionCall, Sema::VariadicCallType CallType,
8872                     llvm::SmallBitVector &CheckedVarArgs,
8873                     UncoveredArgHandler &UncoveredArg)
8874       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8875                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
8876                            inFunctionCall, CallType, CheckedVarArgs,
8877                            UncoveredArg) {}
8878 
8879   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
8880                             const char *startSpecifier,
8881                             unsigned specifierLen) override;
8882 
8883   bool HandleInvalidScanfConversionSpecifier(
8884           const analyze_scanf::ScanfSpecifier &FS,
8885           const char *startSpecifier,
8886           unsigned specifierLen) override;
8887 
8888   void HandleIncompleteScanList(const char *start, const char *end) override;
8889 };
8890 
8891 } // namespace
8892 
8893 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
8894                                                  const char *end) {
8895   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
8896                        getLocationOfByte(end), /*IsStringLocation*/true,
8897                        getSpecifierRange(start, end - start));
8898 }
8899 
8900 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
8901                                         const analyze_scanf::ScanfSpecifier &FS,
8902                                         const char *startSpecifier,
8903                                         unsigned specifierLen) {
8904   const analyze_scanf::ScanfConversionSpecifier &CS =
8905     FS.getConversionSpecifier();
8906 
8907   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8908                                           getLocationOfByte(CS.getStart()),
8909                                           startSpecifier, specifierLen,
8910                                           CS.getStart(), CS.getLength());
8911 }
8912 
8913 bool CheckScanfHandler::HandleScanfSpecifier(
8914                                        const analyze_scanf::ScanfSpecifier &FS,
8915                                        const char *startSpecifier,
8916                                        unsigned specifierLen) {
8917   using namespace analyze_scanf;
8918   using namespace analyze_format_string;
8919 
8920   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
8921 
8922   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
8923   // be used to decide if we are using positional arguments consistently.
8924   if (FS.consumesDataArgument()) {
8925     if (atFirstArg) {
8926       atFirstArg = false;
8927       usesPositionalArgs = FS.usesPositionalArg();
8928     }
8929     else if (usesPositionalArgs != FS.usesPositionalArg()) {
8930       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8931                                         startSpecifier, specifierLen);
8932       return false;
8933     }
8934   }
8935 
8936   // Check if the field with is non-zero.
8937   const OptionalAmount &Amt = FS.getFieldWidth();
8938   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
8939     if (Amt.getConstantAmount() == 0) {
8940       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
8941                                                    Amt.getConstantLength());
8942       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
8943                            getLocationOfByte(Amt.getStart()),
8944                            /*IsStringLocation*/true, R,
8945                            FixItHint::CreateRemoval(R));
8946     }
8947   }
8948 
8949   if (!FS.consumesDataArgument()) {
8950     // FIXME: Technically specifying a precision or field width here
8951     // makes no sense.  Worth issuing a warning at some point.
8952     return true;
8953   }
8954 
8955   // Consume the argument.
8956   unsigned argIndex = FS.getArgIndex();
8957   if (argIndex < NumDataArgs) {
8958       // The check to see if the argIndex is valid will come later.
8959       // We set the bit here because we may exit early from this
8960       // function if we encounter some other error.
8961     CoveredArgs.set(argIndex);
8962   }
8963 
8964   // Check the length modifier is valid with the given conversion specifier.
8965   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8966                                  S.getLangOpts()))
8967     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8968                                 diag::warn_format_nonsensical_length);
8969   else if (!FS.hasStandardLengthModifier())
8970     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8971   else if (!FS.hasStandardLengthConversionCombination())
8972     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8973                                 diag::warn_format_non_standard_conversion_spec);
8974 
8975   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8976     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8977 
8978   // The remaining checks depend on the data arguments.
8979   if (HasVAListArg)
8980     return true;
8981 
8982   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8983     return false;
8984 
8985   // Check that the argument type matches the format specifier.
8986   const Expr *Ex = getDataArg(argIndex);
8987   if (!Ex)
8988     return true;
8989 
8990   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
8991 
8992   if (!AT.isValid()) {
8993     return true;
8994   }
8995 
8996   analyze_format_string::ArgType::MatchKind Match =
8997       AT.matchesType(S.Context, Ex->getType());
8998   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
8999   if (Match == analyze_format_string::ArgType::Match)
9000     return true;
9001 
9002   ScanfSpecifier fixedFS = FS;
9003   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
9004                                  S.getLangOpts(), S.Context);
9005 
9006   unsigned Diag =
9007       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9008                : diag::warn_format_conversion_argument_type_mismatch;
9009 
9010   if (Success) {
9011     // Get the fix string from the fixed format specifier.
9012     SmallString<128> buf;
9013     llvm::raw_svector_ostream os(buf);
9014     fixedFS.toString(os);
9015 
9016     EmitFormatDiagnostic(
9017         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
9018                       << Ex->getType() << false << Ex->getSourceRange(),
9019         Ex->getBeginLoc(),
9020         /*IsStringLocation*/ false,
9021         getSpecifierRange(startSpecifier, specifierLen),
9022         FixItHint::CreateReplacement(
9023             getSpecifierRange(startSpecifier, specifierLen), os.str()));
9024   } else {
9025     EmitFormatDiagnostic(S.PDiag(Diag)
9026                              << AT.getRepresentativeTypeName(S.Context)
9027                              << Ex->getType() << false << Ex->getSourceRange(),
9028                          Ex->getBeginLoc(),
9029                          /*IsStringLocation*/ false,
9030                          getSpecifierRange(startSpecifier, specifierLen));
9031   }
9032 
9033   return true;
9034 }
9035 
9036 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
9037                               const Expr *OrigFormatExpr,
9038                               ArrayRef<const Expr *> Args,
9039                               bool HasVAListArg, unsigned format_idx,
9040                               unsigned firstDataArg,
9041                               Sema::FormatStringType Type,
9042                               bool inFunctionCall,
9043                               Sema::VariadicCallType CallType,
9044                               llvm::SmallBitVector &CheckedVarArgs,
9045                               UncoveredArgHandler &UncoveredArg,
9046                               bool IgnoreStringsWithoutSpecifiers) {
9047   // CHECK: is the format string a wide literal?
9048   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
9049     CheckFormatHandler::EmitFormatDiagnostic(
9050         S, inFunctionCall, Args[format_idx],
9051         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
9052         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9053     return;
9054   }
9055 
9056   // Str - The format string.  NOTE: this is NOT null-terminated!
9057   StringRef StrRef = FExpr->getString();
9058   const char *Str = StrRef.data();
9059   // Account for cases where the string literal is truncated in a declaration.
9060   const ConstantArrayType *T =
9061     S.Context.getAsConstantArrayType(FExpr->getType());
9062   assert(T && "String literal not of constant array type!");
9063   size_t TypeSize = T->getSize().getZExtValue();
9064   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9065   const unsigned numDataArgs = Args.size() - firstDataArg;
9066 
9067   if (IgnoreStringsWithoutSpecifiers &&
9068       !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
9069           Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
9070     return;
9071 
9072   // Emit a warning if the string literal is truncated and does not contain an
9073   // embedded null character.
9074   if (TypeSize <= StrRef.size() &&
9075       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
9076     CheckFormatHandler::EmitFormatDiagnostic(
9077         S, inFunctionCall, Args[format_idx],
9078         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
9079         FExpr->getBeginLoc(),
9080         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
9081     return;
9082   }
9083 
9084   // CHECK: empty format string?
9085   if (StrLen == 0 && numDataArgs > 0) {
9086     CheckFormatHandler::EmitFormatDiagnostic(
9087         S, inFunctionCall, Args[format_idx],
9088         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
9089         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9090     return;
9091   }
9092 
9093   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
9094       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
9095       Type == Sema::FST_OSTrace) {
9096     CheckPrintfHandler H(
9097         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
9098         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
9099         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
9100         CheckedVarArgs, UncoveredArg);
9101 
9102     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
9103                                                   S.getLangOpts(),
9104                                                   S.Context.getTargetInfo(),
9105                                             Type == Sema::FST_FreeBSDKPrintf))
9106       H.DoneProcessing();
9107   } else if (Type == Sema::FST_Scanf) {
9108     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9109                         numDataArgs, Str, HasVAListArg, Args, format_idx,
9110                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
9111 
9112     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
9113                                                  S.getLangOpts(),
9114                                                  S.Context.getTargetInfo()))
9115       H.DoneProcessing();
9116   } // TODO: handle other formats
9117 }
9118 
9119 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
9120   // Str - The format string.  NOTE: this is NOT null-terminated!
9121   StringRef StrRef = FExpr->getString();
9122   const char *Str = StrRef.data();
9123   // Account for cases where the string literal is truncated in a declaration.
9124   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
9125   assert(T && "String literal not of constant array type!");
9126   size_t TypeSize = T->getSize().getZExtValue();
9127   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9128   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
9129                                                          getLangOpts(),
9130                                                          Context.getTargetInfo());
9131 }
9132 
9133 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
9134 
9135 // Returns the related absolute value function that is larger, of 0 if one
9136 // does not exist.
9137 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
9138   switch (AbsFunction) {
9139   default:
9140     return 0;
9141 
9142   case Builtin::BI__builtin_abs:
9143     return Builtin::BI__builtin_labs;
9144   case Builtin::BI__builtin_labs:
9145     return Builtin::BI__builtin_llabs;
9146   case Builtin::BI__builtin_llabs:
9147     return 0;
9148 
9149   case Builtin::BI__builtin_fabsf:
9150     return Builtin::BI__builtin_fabs;
9151   case Builtin::BI__builtin_fabs:
9152     return Builtin::BI__builtin_fabsl;
9153   case Builtin::BI__builtin_fabsl:
9154     return 0;
9155 
9156   case Builtin::BI__builtin_cabsf:
9157     return Builtin::BI__builtin_cabs;
9158   case Builtin::BI__builtin_cabs:
9159     return Builtin::BI__builtin_cabsl;
9160   case Builtin::BI__builtin_cabsl:
9161     return 0;
9162 
9163   case Builtin::BIabs:
9164     return Builtin::BIlabs;
9165   case Builtin::BIlabs:
9166     return Builtin::BIllabs;
9167   case Builtin::BIllabs:
9168     return 0;
9169 
9170   case Builtin::BIfabsf:
9171     return Builtin::BIfabs;
9172   case Builtin::BIfabs:
9173     return Builtin::BIfabsl;
9174   case Builtin::BIfabsl:
9175     return 0;
9176 
9177   case Builtin::BIcabsf:
9178    return Builtin::BIcabs;
9179   case Builtin::BIcabs:
9180     return Builtin::BIcabsl;
9181   case Builtin::BIcabsl:
9182     return 0;
9183   }
9184 }
9185 
9186 // Returns the argument type of the absolute value function.
9187 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
9188                                              unsigned AbsType) {
9189   if (AbsType == 0)
9190     return QualType();
9191 
9192   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
9193   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
9194   if (Error != ASTContext::GE_None)
9195     return QualType();
9196 
9197   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
9198   if (!FT)
9199     return QualType();
9200 
9201   if (FT->getNumParams() != 1)
9202     return QualType();
9203 
9204   return FT->getParamType(0);
9205 }
9206 
9207 // Returns the best absolute value function, or zero, based on type and
9208 // current absolute value function.
9209 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
9210                                    unsigned AbsFunctionKind) {
9211   unsigned BestKind = 0;
9212   uint64_t ArgSize = Context.getTypeSize(ArgType);
9213   for (unsigned Kind = AbsFunctionKind; Kind != 0;
9214        Kind = getLargerAbsoluteValueFunction(Kind)) {
9215     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
9216     if (Context.getTypeSize(ParamType) >= ArgSize) {
9217       if (BestKind == 0)
9218         BestKind = Kind;
9219       else if (Context.hasSameType(ParamType, ArgType)) {
9220         BestKind = Kind;
9221         break;
9222       }
9223     }
9224   }
9225   return BestKind;
9226 }
9227 
9228 enum AbsoluteValueKind {
9229   AVK_Integer,
9230   AVK_Floating,
9231   AVK_Complex
9232 };
9233 
9234 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
9235   if (T->isIntegralOrEnumerationType())
9236     return AVK_Integer;
9237   if (T->isRealFloatingType())
9238     return AVK_Floating;
9239   if (T->isAnyComplexType())
9240     return AVK_Complex;
9241 
9242   llvm_unreachable("Type not integer, floating, or complex");
9243 }
9244 
9245 // Changes the absolute value function to a different type.  Preserves whether
9246 // the function is a builtin.
9247 static unsigned changeAbsFunction(unsigned AbsKind,
9248                                   AbsoluteValueKind ValueKind) {
9249   switch (ValueKind) {
9250   case AVK_Integer:
9251     switch (AbsKind) {
9252     default:
9253       return 0;
9254     case Builtin::BI__builtin_fabsf:
9255     case Builtin::BI__builtin_fabs:
9256     case Builtin::BI__builtin_fabsl:
9257     case Builtin::BI__builtin_cabsf:
9258     case Builtin::BI__builtin_cabs:
9259     case Builtin::BI__builtin_cabsl:
9260       return Builtin::BI__builtin_abs;
9261     case Builtin::BIfabsf:
9262     case Builtin::BIfabs:
9263     case Builtin::BIfabsl:
9264     case Builtin::BIcabsf:
9265     case Builtin::BIcabs:
9266     case Builtin::BIcabsl:
9267       return Builtin::BIabs;
9268     }
9269   case AVK_Floating:
9270     switch (AbsKind) {
9271     default:
9272       return 0;
9273     case Builtin::BI__builtin_abs:
9274     case Builtin::BI__builtin_labs:
9275     case Builtin::BI__builtin_llabs:
9276     case Builtin::BI__builtin_cabsf:
9277     case Builtin::BI__builtin_cabs:
9278     case Builtin::BI__builtin_cabsl:
9279       return Builtin::BI__builtin_fabsf;
9280     case Builtin::BIabs:
9281     case Builtin::BIlabs:
9282     case Builtin::BIllabs:
9283     case Builtin::BIcabsf:
9284     case Builtin::BIcabs:
9285     case Builtin::BIcabsl:
9286       return Builtin::BIfabsf;
9287     }
9288   case AVK_Complex:
9289     switch (AbsKind) {
9290     default:
9291       return 0;
9292     case Builtin::BI__builtin_abs:
9293     case Builtin::BI__builtin_labs:
9294     case Builtin::BI__builtin_llabs:
9295     case Builtin::BI__builtin_fabsf:
9296     case Builtin::BI__builtin_fabs:
9297     case Builtin::BI__builtin_fabsl:
9298       return Builtin::BI__builtin_cabsf;
9299     case Builtin::BIabs:
9300     case Builtin::BIlabs:
9301     case Builtin::BIllabs:
9302     case Builtin::BIfabsf:
9303     case Builtin::BIfabs:
9304     case Builtin::BIfabsl:
9305       return Builtin::BIcabsf;
9306     }
9307   }
9308   llvm_unreachable("Unable to convert function");
9309 }
9310 
9311 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
9312   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
9313   if (!FnInfo)
9314     return 0;
9315 
9316   switch (FDecl->getBuiltinID()) {
9317   default:
9318     return 0;
9319   case Builtin::BI__builtin_abs:
9320   case Builtin::BI__builtin_fabs:
9321   case Builtin::BI__builtin_fabsf:
9322   case Builtin::BI__builtin_fabsl:
9323   case Builtin::BI__builtin_labs:
9324   case Builtin::BI__builtin_llabs:
9325   case Builtin::BI__builtin_cabs:
9326   case Builtin::BI__builtin_cabsf:
9327   case Builtin::BI__builtin_cabsl:
9328   case Builtin::BIabs:
9329   case Builtin::BIlabs:
9330   case Builtin::BIllabs:
9331   case Builtin::BIfabs:
9332   case Builtin::BIfabsf:
9333   case Builtin::BIfabsl:
9334   case Builtin::BIcabs:
9335   case Builtin::BIcabsf:
9336   case Builtin::BIcabsl:
9337     return FDecl->getBuiltinID();
9338   }
9339   llvm_unreachable("Unknown Builtin type");
9340 }
9341 
9342 // If the replacement is valid, emit a note with replacement function.
9343 // Additionally, suggest including the proper header if not already included.
9344 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
9345                             unsigned AbsKind, QualType ArgType) {
9346   bool EmitHeaderHint = true;
9347   const char *HeaderName = nullptr;
9348   const char *FunctionName = nullptr;
9349   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
9350     FunctionName = "std::abs";
9351     if (ArgType->isIntegralOrEnumerationType()) {
9352       HeaderName = "cstdlib";
9353     } else if (ArgType->isRealFloatingType()) {
9354       HeaderName = "cmath";
9355     } else {
9356       llvm_unreachable("Invalid Type");
9357     }
9358 
9359     // Lookup all std::abs
9360     if (NamespaceDecl *Std = S.getStdNamespace()) {
9361       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
9362       R.suppressDiagnostics();
9363       S.LookupQualifiedName(R, Std);
9364 
9365       for (const auto *I : R) {
9366         const FunctionDecl *FDecl = nullptr;
9367         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
9368           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
9369         } else {
9370           FDecl = dyn_cast<FunctionDecl>(I);
9371         }
9372         if (!FDecl)
9373           continue;
9374 
9375         // Found std::abs(), check that they are the right ones.
9376         if (FDecl->getNumParams() != 1)
9377           continue;
9378 
9379         // Check that the parameter type can handle the argument.
9380         QualType ParamType = FDecl->getParamDecl(0)->getType();
9381         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
9382             S.Context.getTypeSize(ArgType) <=
9383                 S.Context.getTypeSize(ParamType)) {
9384           // Found a function, don't need the header hint.
9385           EmitHeaderHint = false;
9386           break;
9387         }
9388       }
9389     }
9390   } else {
9391     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
9392     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
9393 
9394     if (HeaderName) {
9395       DeclarationName DN(&S.Context.Idents.get(FunctionName));
9396       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
9397       R.suppressDiagnostics();
9398       S.LookupName(R, S.getCurScope());
9399 
9400       if (R.isSingleResult()) {
9401         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
9402         if (FD && FD->getBuiltinID() == AbsKind) {
9403           EmitHeaderHint = false;
9404         } else {
9405           return;
9406         }
9407       } else if (!R.empty()) {
9408         return;
9409       }
9410     }
9411   }
9412 
9413   S.Diag(Loc, diag::note_replace_abs_function)
9414       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
9415 
9416   if (!HeaderName)
9417     return;
9418 
9419   if (!EmitHeaderHint)
9420     return;
9421 
9422   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
9423                                                     << FunctionName;
9424 }
9425 
9426 template <std::size_t StrLen>
9427 static bool IsStdFunction(const FunctionDecl *FDecl,
9428                           const char (&Str)[StrLen]) {
9429   if (!FDecl)
9430     return false;
9431   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
9432     return false;
9433   if (!FDecl->isInStdNamespace())
9434     return false;
9435 
9436   return true;
9437 }
9438 
9439 // Warn when using the wrong abs() function.
9440 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
9441                                       const FunctionDecl *FDecl) {
9442   if (Call->getNumArgs() != 1)
9443     return;
9444 
9445   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
9446   bool IsStdAbs = IsStdFunction(FDecl, "abs");
9447   if (AbsKind == 0 && !IsStdAbs)
9448     return;
9449 
9450   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9451   QualType ParamType = Call->getArg(0)->getType();
9452 
9453   // Unsigned types cannot be negative.  Suggest removing the absolute value
9454   // function call.
9455   if (ArgType->isUnsignedIntegerType()) {
9456     const char *FunctionName =
9457         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
9458     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
9459     Diag(Call->getExprLoc(), diag::note_remove_abs)
9460         << FunctionName
9461         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
9462     return;
9463   }
9464 
9465   // Taking the absolute value of a pointer is very suspicious, they probably
9466   // wanted to index into an array, dereference a pointer, call a function, etc.
9467   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
9468     unsigned DiagType = 0;
9469     if (ArgType->isFunctionType())
9470       DiagType = 1;
9471     else if (ArgType->isArrayType())
9472       DiagType = 2;
9473 
9474     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
9475     return;
9476   }
9477 
9478   // std::abs has overloads which prevent most of the absolute value problems
9479   // from occurring.
9480   if (IsStdAbs)
9481     return;
9482 
9483   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
9484   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
9485 
9486   // The argument and parameter are the same kind.  Check if they are the right
9487   // size.
9488   if (ArgValueKind == ParamValueKind) {
9489     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
9490       return;
9491 
9492     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
9493     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
9494         << FDecl << ArgType << ParamType;
9495 
9496     if (NewAbsKind == 0)
9497       return;
9498 
9499     emitReplacement(*this, Call->getExprLoc(),
9500                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9501     return;
9502   }
9503 
9504   // ArgValueKind != ParamValueKind
9505   // The wrong type of absolute value function was used.  Attempt to find the
9506   // proper one.
9507   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
9508   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
9509   if (NewAbsKind == 0)
9510     return;
9511 
9512   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
9513       << FDecl << ParamValueKind << ArgValueKind;
9514 
9515   emitReplacement(*this, Call->getExprLoc(),
9516                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9517 }
9518 
9519 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
9520 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
9521                                 const FunctionDecl *FDecl) {
9522   if (!Call || !FDecl) return;
9523 
9524   // Ignore template specializations and macros.
9525   if (inTemplateInstantiation()) return;
9526   if (Call->getExprLoc().isMacroID()) return;
9527 
9528   // Only care about the one template argument, two function parameter std::max
9529   if (Call->getNumArgs() != 2) return;
9530   if (!IsStdFunction(FDecl, "max")) return;
9531   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
9532   if (!ArgList) return;
9533   if (ArgList->size() != 1) return;
9534 
9535   // Check that template type argument is unsigned integer.
9536   const auto& TA = ArgList->get(0);
9537   if (TA.getKind() != TemplateArgument::Type) return;
9538   QualType ArgType = TA.getAsType();
9539   if (!ArgType->isUnsignedIntegerType()) return;
9540 
9541   // See if either argument is a literal zero.
9542   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
9543     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
9544     if (!MTE) return false;
9545     const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
9546     if (!Num) return false;
9547     if (Num->getValue() != 0) return false;
9548     return true;
9549   };
9550 
9551   const Expr *FirstArg = Call->getArg(0);
9552   const Expr *SecondArg = Call->getArg(1);
9553   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
9554   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
9555 
9556   // Only warn when exactly one argument is zero.
9557   if (IsFirstArgZero == IsSecondArgZero) return;
9558 
9559   SourceRange FirstRange = FirstArg->getSourceRange();
9560   SourceRange SecondRange = SecondArg->getSourceRange();
9561 
9562   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
9563 
9564   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
9565       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
9566 
9567   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
9568   SourceRange RemovalRange;
9569   if (IsFirstArgZero) {
9570     RemovalRange = SourceRange(FirstRange.getBegin(),
9571                                SecondRange.getBegin().getLocWithOffset(-1));
9572   } else {
9573     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
9574                                SecondRange.getEnd());
9575   }
9576 
9577   Diag(Call->getExprLoc(), diag::note_remove_max_call)
9578         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
9579         << FixItHint::CreateRemoval(RemovalRange);
9580 }
9581 
9582 //===--- CHECK: Standard memory functions ---------------------------------===//
9583 
9584 /// Takes the expression passed to the size_t parameter of functions
9585 /// such as memcmp, strncat, etc and warns if it's a comparison.
9586 ///
9587 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
9588 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
9589                                            IdentifierInfo *FnName,
9590                                            SourceLocation FnLoc,
9591                                            SourceLocation RParenLoc) {
9592   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
9593   if (!Size)
9594     return false;
9595 
9596   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
9597   if (!Size->isComparisonOp() && !Size->isLogicalOp())
9598     return false;
9599 
9600   SourceRange SizeRange = Size->getSourceRange();
9601   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
9602       << SizeRange << FnName;
9603   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
9604       << FnName
9605       << FixItHint::CreateInsertion(
9606              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
9607       << FixItHint::CreateRemoval(RParenLoc);
9608   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
9609       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
9610       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
9611                                     ")");
9612 
9613   return true;
9614 }
9615 
9616 /// Determine whether the given type is or contains a dynamic class type
9617 /// (e.g., whether it has a vtable).
9618 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
9619                                                      bool &IsContained) {
9620   // Look through array types while ignoring qualifiers.
9621   const Type *Ty = T->getBaseElementTypeUnsafe();
9622   IsContained = false;
9623 
9624   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
9625   RD = RD ? RD->getDefinition() : nullptr;
9626   if (!RD || RD->isInvalidDecl())
9627     return nullptr;
9628 
9629   if (RD->isDynamicClass())
9630     return RD;
9631 
9632   // Check all the fields.  If any bases were dynamic, the class is dynamic.
9633   // It's impossible for a class to transitively contain itself by value, so
9634   // infinite recursion is impossible.
9635   for (auto *FD : RD->fields()) {
9636     bool SubContained;
9637     if (const CXXRecordDecl *ContainedRD =
9638             getContainedDynamicClass(FD->getType(), SubContained)) {
9639       IsContained = true;
9640       return ContainedRD;
9641     }
9642   }
9643 
9644   return nullptr;
9645 }
9646 
9647 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
9648   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
9649     if (Unary->getKind() == UETT_SizeOf)
9650       return Unary;
9651   return nullptr;
9652 }
9653 
9654 /// If E is a sizeof expression, returns its argument expression,
9655 /// otherwise returns NULL.
9656 static const Expr *getSizeOfExprArg(const Expr *E) {
9657   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9658     if (!SizeOf->isArgumentType())
9659       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
9660   return nullptr;
9661 }
9662 
9663 /// If E is a sizeof expression, returns its argument type.
9664 static QualType getSizeOfArgType(const Expr *E) {
9665   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9666     return SizeOf->getTypeOfArgument();
9667   return QualType();
9668 }
9669 
9670 namespace {
9671 
9672 struct SearchNonTrivialToInitializeField
9673     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
9674   using Super =
9675       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
9676 
9677   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
9678 
9679   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
9680                      SourceLocation SL) {
9681     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9682       asDerived().visitArray(PDIK, AT, SL);
9683       return;
9684     }
9685 
9686     Super::visitWithKind(PDIK, FT, SL);
9687   }
9688 
9689   void visitARCStrong(QualType FT, SourceLocation SL) {
9690     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9691   }
9692   void visitARCWeak(QualType FT, SourceLocation SL) {
9693     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9694   }
9695   void visitStruct(QualType FT, SourceLocation SL) {
9696     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9697       visit(FD->getType(), FD->getLocation());
9698   }
9699   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
9700                   const ArrayType *AT, SourceLocation SL) {
9701     visit(getContext().getBaseElementType(AT), SL);
9702   }
9703   void visitTrivial(QualType FT, SourceLocation SL) {}
9704 
9705   static void diag(QualType RT, const Expr *E, Sema &S) {
9706     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
9707   }
9708 
9709   ASTContext &getContext() { return S.getASTContext(); }
9710 
9711   const Expr *E;
9712   Sema &S;
9713 };
9714 
9715 struct SearchNonTrivialToCopyField
9716     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
9717   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
9718 
9719   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
9720 
9721   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
9722                      SourceLocation SL) {
9723     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9724       asDerived().visitArray(PCK, AT, SL);
9725       return;
9726     }
9727 
9728     Super::visitWithKind(PCK, FT, SL);
9729   }
9730 
9731   void visitARCStrong(QualType FT, SourceLocation SL) {
9732     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9733   }
9734   void visitARCWeak(QualType FT, SourceLocation SL) {
9735     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9736   }
9737   void visitStruct(QualType FT, SourceLocation SL) {
9738     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9739       visit(FD->getType(), FD->getLocation());
9740   }
9741   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
9742                   SourceLocation SL) {
9743     visit(getContext().getBaseElementType(AT), SL);
9744   }
9745   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
9746                 SourceLocation SL) {}
9747   void visitTrivial(QualType FT, SourceLocation SL) {}
9748   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
9749 
9750   static void diag(QualType RT, const Expr *E, Sema &S) {
9751     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
9752   }
9753 
9754   ASTContext &getContext() { return S.getASTContext(); }
9755 
9756   const Expr *E;
9757   Sema &S;
9758 };
9759 
9760 }
9761 
9762 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
9763 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
9764   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
9765 
9766   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
9767     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
9768       return false;
9769 
9770     return doesExprLikelyComputeSize(BO->getLHS()) ||
9771            doesExprLikelyComputeSize(BO->getRHS());
9772   }
9773 
9774   return getAsSizeOfExpr(SizeofExpr) != nullptr;
9775 }
9776 
9777 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
9778 ///
9779 /// \code
9780 ///   #define MACRO 0
9781 ///   foo(MACRO);
9782 ///   foo(0);
9783 /// \endcode
9784 ///
9785 /// This should return true for the first call to foo, but not for the second
9786 /// (regardless of whether foo is a macro or function).
9787 static bool isArgumentExpandedFromMacro(SourceManager &SM,
9788                                         SourceLocation CallLoc,
9789                                         SourceLocation ArgLoc) {
9790   if (!CallLoc.isMacroID())
9791     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
9792 
9793   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
9794          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
9795 }
9796 
9797 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
9798 /// last two arguments transposed.
9799 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
9800   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
9801     return;
9802 
9803   const Expr *SizeArg =
9804     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
9805 
9806   auto isLiteralZero = [](const Expr *E) {
9807     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
9808   };
9809 
9810   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
9811   SourceLocation CallLoc = Call->getRParenLoc();
9812   SourceManager &SM = S.getSourceManager();
9813   if (isLiteralZero(SizeArg) &&
9814       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
9815 
9816     SourceLocation DiagLoc = SizeArg->getExprLoc();
9817 
9818     // Some platforms #define bzero to __builtin_memset. See if this is the
9819     // case, and if so, emit a better diagnostic.
9820     if (BId == Builtin::BIbzero ||
9821         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
9822                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
9823       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
9824       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
9825     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
9826       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
9827       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
9828     }
9829     return;
9830   }
9831 
9832   // If the second argument to a memset is a sizeof expression and the third
9833   // isn't, this is also likely an error. This should catch
9834   // 'memset(buf, sizeof(buf), 0xff)'.
9835   if (BId == Builtin::BImemset &&
9836       doesExprLikelyComputeSize(Call->getArg(1)) &&
9837       !doesExprLikelyComputeSize(Call->getArg(2))) {
9838     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
9839     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
9840     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
9841     return;
9842   }
9843 }
9844 
9845 /// Check for dangerous or invalid arguments to memset().
9846 ///
9847 /// This issues warnings on known problematic, dangerous or unspecified
9848 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
9849 /// function calls.
9850 ///
9851 /// \param Call The call expression to diagnose.
9852 void Sema::CheckMemaccessArguments(const CallExpr *Call,
9853                                    unsigned BId,
9854                                    IdentifierInfo *FnName) {
9855   assert(BId != 0);
9856 
9857   // It is possible to have a non-standard definition of memset.  Validate
9858   // we have enough arguments, and if not, abort further checking.
9859   unsigned ExpectedNumArgs =
9860       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
9861   if (Call->getNumArgs() < ExpectedNumArgs)
9862     return;
9863 
9864   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
9865                       BId == Builtin::BIstrndup ? 1 : 2);
9866   unsigned LenArg =
9867       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
9868   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
9869 
9870   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
9871                                      Call->getBeginLoc(), Call->getRParenLoc()))
9872     return;
9873 
9874   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
9875   CheckMemaccessSize(*this, BId, Call);
9876 
9877   // We have special checking when the length is a sizeof expression.
9878   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
9879   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
9880   llvm::FoldingSetNodeID SizeOfArgID;
9881 
9882   // Although widely used, 'bzero' is not a standard function. Be more strict
9883   // with the argument types before allowing diagnostics and only allow the
9884   // form bzero(ptr, sizeof(...)).
9885   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9886   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
9887     return;
9888 
9889   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
9890     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
9891     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
9892 
9893     QualType DestTy = Dest->getType();
9894     QualType PointeeTy;
9895     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
9896       PointeeTy = DestPtrTy->getPointeeType();
9897 
9898       // Never warn about void type pointers. This can be used to suppress
9899       // false positives.
9900       if (PointeeTy->isVoidType())
9901         continue;
9902 
9903       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
9904       // actually comparing the expressions for equality. Because computing the
9905       // expression IDs can be expensive, we only do this if the diagnostic is
9906       // enabled.
9907       if (SizeOfArg &&
9908           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
9909                            SizeOfArg->getExprLoc())) {
9910         // We only compute IDs for expressions if the warning is enabled, and
9911         // cache the sizeof arg's ID.
9912         if (SizeOfArgID == llvm::FoldingSetNodeID())
9913           SizeOfArg->Profile(SizeOfArgID, Context, true);
9914         llvm::FoldingSetNodeID DestID;
9915         Dest->Profile(DestID, Context, true);
9916         if (DestID == SizeOfArgID) {
9917           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
9918           //       over sizeof(src) as well.
9919           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
9920           StringRef ReadableName = FnName->getName();
9921 
9922           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
9923             if (UnaryOp->getOpcode() == UO_AddrOf)
9924               ActionIdx = 1; // If its an address-of operator, just remove it.
9925           if (!PointeeTy->isIncompleteType() &&
9926               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
9927             ActionIdx = 2; // If the pointee's size is sizeof(char),
9928                            // suggest an explicit length.
9929 
9930           // If the function is defined as a builtin macro, do not show macro
9931           // expansion.
9932           SourceLocation SL = SizeOfArg->getExprLoc();
9933           SourceRange DSR = Dest->getSourceRange();
9934           SourceRange SSR = SizeOfArg->getSourceRange();
9935           SourceManager &SM = getSourceManager();
9936 
9937           if (SM.isMacroArgExpansion(SL)) {
9938             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
9939             SL = SM.getSpellingLoc(SL);
9940             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
9941                              SM.getSpellingLoc(DSR.getEnd()));
9942             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
9943                              SM.getSpellingLoc(SSR.getEnd()));
9944           }
9945 
9946           DiagRuntimeBehavior(SL, SizeOfArg,
9947                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
9948                                 << ReadableName
9949                                 << PointeeTy
9950                                 << DestTy
9951                                 << DSR
9952                                 << SSR);
9953           DiagRuntimeBehavior(SL, SizeOfArg,
9954                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
9955                                 << ActionIdx
9956                                 << SSR);
9957 
9958           break;
9959         }
9960       }
9961 
9962       // Also check for cases where the sizeof argument is the exact same
9963       // type as the memory argument, and where it points to a user-defined
9964       // record type.
9965       if (SizeOfArgTy != QualType()) {
9966         if (PointeeTy->isRecordType() &&
9967             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
9968           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
9969                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
9970                                 << FnName << SizeOfArgTy << ArgIdx
9971                                 << PointeeTy << Dest->getSourceRange()
9972                                 << LenExpr->getSourceRange());
9973           break;
9974         }
9975       }
9976     } else if (DestTy->isArrayType()) {
9977       PointeeTy = DestTy;
9978     }
9979 
9980     if (PointeeTy == QualType())
9981       continue;
9982 
9983     // Always complain about dynamic classes.
9984     bool IsContained;
9985     if (const CXXRecordDecl *ContainedRD =
9986             getContainedDynamicClass(PointeeTy, IsContained)) {
9987 
9988       unsigned OperationType = 0;
9989       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
9990       // "overwritten" if we're warning about the destination for any call
9991       // but memcmp; otherwise a verb appropriate to the call.
9992       if (ArgIdx != 0 || IsCmp) {
9993         if (BId == Builtin::BImemcpy)
9994           OperationType = 1;
9995         else if(BId == Builtin::BImemmove)
9996           OperationType = 2;
9997         else if (IsCmp)
9998           OperationType = 3;
9999       }
10000 
10001       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10002                           PDiag(diag::warn_dyn_class_memaccess)
10003                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
10004                               << IsContained << ContainedRD << OperationType
10005                               << Call->getCallee()->getSourceRange());
10006     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
10007              BId != Builtin::BImemset)
10008       DiagRuntimeBehavior(
10009         Dest->getExprLoc(), Dest,
10010         PDiag(diag::warn_arc_object_memaccess)
10011           << ArgIdx << FnName << PointeeTy
10012           << Call->getCallee()->getSourceRange());
10013     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
10014       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10015           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
10016         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10017                             PDiag(diag::warn_cstruct_memaccess)
10018                                 << ArgIdx << FnName << PointeeTy << 0);
10019         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
10020       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10021                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
10022         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10023                             PDiag(diag::warn_cstruct_memaccess)
10024                                 << ArgIdx << FnName << PointeeTy << 1);
10025         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
10026       } else {
10027         continue;
10028       }
10029     } else
10030       continue;
10031 
10032     DiagRuntimeBehavior(
10033       Dest->getExprLoc(), Dest,
10034       PDiag(diag::note_bad_memaccess_silence)
10035         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
10036     break;
10037   }
10038 }
10039 
10040 // A little helper routine: ignore addition and subtraction of integer literals.
10041 // This intentionally does not ignore all integer constant expressions because
10042 // we don't want to remove sizeof().
10043 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
10044   Ex = Ex->IgnoreParenCasts();
10045 
10046   while (true) {
10047     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
10048     if (!BO || !BO->isAdditiveOp())
10049       break;
10050 
10051     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
10052     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
10053 
10054     if (isa<IntegerLiteral>(RHS))
10055       Ex = LHS;
10056     else if (isa<IntegerLiteral>(LHS))
10057       Ex = RHS;
10058     else
10059       break;
10060   }
10061 
10062   return Ex;
10063 }
10064 
10065 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
10066                                                       ASTContext &Context) {
10067   // Only handle constant-sized or VLAs, but not flexible members.
10068   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
10069     // Only issue the FIXIT for arrays of size > 1.
10070     if (CAT->getSize().getSExtValue() <= 1)
10071       return false;
10072   } else if (!Ty->isVariableArrayType()) {
10073     return false;
10074   }
10075   return true;
10076 }
10077 
10078 // Warn if the user has made the 'size' argument to strlcpy or strlcat
10079 // be the size of the source, instead of the destination.
10080 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
10081                                     IdentifierInfo *FnName) {
10082 
10083   // Don't crash if the user has the wrong number of arguments
10084   unsigned NumArgs = Call->getNumArgs();
10085   if ((NumArgs != 3) && (NumArgs != 4))
10086     return;
10087 
10088   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
10089   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
10090   const Expr *CompareWithSrc = nullptr;
10091 
10092   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
10093                                      Call->getBeginLoc(), Call->getRParenLoc()))
10094     return;
10095 
10096   // Look for 'strlcpy(dst, x, sizeof(x))'
10097   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
10098     CompareWithSrc = Ex;
10099   else {
10100     // Look for 'strlcpy(dst, x, strlen(x))'
10101     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
10102       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
10103           SizeCall->getNumArgs() == 1)
10104         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
10105     }
10106   }
10107 
10108   if (!CompareWithSrc)
10109     return;
10110 
10111   // Determine if the argument to sizeof/strlen is equal to the source
10112   // argument.  In principle there's all kinds of things you could do
10113   // here, for instance creating an == expression and evaluating it with
10114   // EvaluateAsBooleanCondition, but this uses a more direct technique:
10115   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
10116   if (!SrcArgDRE)
10117     return;
10118 
10119   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
10120   if (!CompareWithSrcDRE ||
10121       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
10122     return;
10123 
10124   const Expr *OriginalSizeArg = Call->getArg(2);
10125   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
10126       << OriginalSizeArg->getSourceRange() << FnName;
10127 
10128   // Output a FIXIT hint if the destination is an array (rather than a
10129   // pointer to an array).  This could be enhanced to handle some
10130   // pointers if we know the actual size, like if DstArg is 'array+2'
10131   // we could say 'sizeof(array)-2'.
10132   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
10133   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
10134     return;
10135 
10136   SmallString<128> sizeString;
10137   llvm::raw_svector_ostream OS(sizeString);
10138   OS << "sizeof(";
10139   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10140   OS << ")";
10141 
10142   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
10143       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
10144                                       OS.str());
10145 }
10146 
10147 /// Check if two expressions refer to the same declaration.
10148 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
10149   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
10150     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
10151       return D1->getDecl() == D2->getDecl();
10152   return false;
10153 }
10154 
10155 static const Expr *getStrlenExprArg(const Expr *E) {
10156   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10157     const FunctionDecl *FD = CE->getDirectCallee();
10158     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
10159       return nullptr;
10160     return CE->getArg(0)->IgnoreParenCasts();
10161   }
10162   return nullptr;
10163 }
10164 
10165 // Warn on anti-patterns as the 'size' argument to strncat.
10166 // The correct size argument should look like following:
10167 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
10168 void Sema::CheckStrncatArguments(const CallExpr *CE,
10169                                  IdentifierInfo *FnName) {
10170   // Don't crash if the user has the wrong number of arguments.
10171   if (CE->getNumArgs() < 3)
10172     return;
10173   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
10174   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
10175   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
10176 
10177   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
10178                                      CE->getRParenLoc()))
10179     return;
10180 
10181   // Identify common expressions, which are wrongly used as the size argument
10182   // to strncat and may lead to buffer overflows.
10183   unsigned PatternType = 0;
10184   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
10185     // - sizeof(dst)
10186     if (referToTheSameDecl(SizeOfArg, DstArg))
10187       PatternType = 1;
10188     // - sizeof(src)
10189     else if (referToTheSameDecl(SizeOfArg, SrcArg))
10190       PatternType = 2;
10191   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
10192     if (BE->getOpcode() == BO_Sub) {
10193       const Expr *L = BE->getLHS()->IgnoreParenCasts();
10194       const Expr *R = BE->getRHS()->IgnoreParenCasts();
10195       // - sizeof(dst) - strlen(dst)
10196       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
10197           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
10198         PatternType = 1;
10199       // - sizeof(src) - (anything)
10200       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
10201         PatternType = 2;
10202     }
10203   }
10204 
10205   if (PatternType == 0)
10206     return;
10207 
10208   // Generate the diagnostic.
10209   SourceLocation SL = LenArg->getBeginLoc();
10210   SourceRange SR = LenArg->getSourceRange();
10211   SourceManager &SM = getSourceManager();
10212 
10213   // If the function is defined as a builtin macro, do not show macro expansion.
10214   if (SM.isMacroArgExpansion(SL)) {
10215     SL = SM.getSpellingLoc(SL);
10216     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
10217                      SM.getSpellingLoc(SR.getEnd()));
10218   }
10219 
10220   // Check if the destination is an array (rather than a pointer to an array).
10221   QualType DstTy = DstArg->getType();
10222   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
10223                                                                     Context);
10224   if (!isKnownSizeArray) {
10225     if (PatternType == 1)
10226       Diag(SL, diag::warn_strncat_wrong_size) << SR;
10227     else
10228       Diag(SL, diag::warn_strncat_src_size) << SR;
10229     return;
10230   }
10231 
10232   if (PatternType == 1)
10233     Diag(SL, diag::warn_strncat_large_size) << SR;
10234   else
10235     Diag(SL, diag::warn_strncat_src_size) << SR;
10236 
10237   SmallString<128> sizeString;
10238   llvm::raw_svector_ostream OS(sizeString);
10239   OS << "sizeof(";
10240   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10241   OS << ") - ";
10242   OS << "strlen(";
10243   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10244   OS << ") - 1";
10245 
10246   Diag(SL, diag::note_strncat_wrong_size)
10247     << FixItHint::CreateReplacement(SR, OS.str());
10248 }
10249 
10250 namespace {
10251 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
10252                                 const UnaryOperator *UnaryExpr,
10253                                 const VarDecl *Var) {
10254   StorageClass Class = Var->getStorageClass();
10255   if (Class == StorageClass::SC_Extern ||
10256       Class == StorageClass::SC_PrivateExtern ||
10257       Var->getType()->isReferenceType())
10258     return;
10259 
10260   S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
10261       << CalleeName << Var;
10262 }
10263 
10264 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
10265                                 const UnaryOperator *UnaryExpr, const Decl *D) {
10266   if (const auto *Field = dyn_cast<FieldDecl>(D))
10267     S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
10268         << CalleeName << Field;
10269 }
10270 
10271 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
10272                                  const UnaryOperator *UnaryExpr) {
10273   if (UnaryExpr->getOpcode() != UnaryOperator::Opcode::UO_AddrOf)
10274     return;
10275 
10276   if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr()))
10277     if (const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl()))
10278       return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, Var);
10279 
10280   if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
10281     return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
10282                                       Lvalue->getMemberDecl());
10283 }
10284 
10285 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
10286                                   const DeclRefExpr *Lvalue) {
10287   if (!Lvalue->getType()->isArrayType())
10288     return;
10289 
10290   const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
10291   if (Var == nullptr)
10292     return;
10293 
10294   S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
10295       << CalleeName << Var;
10296 }
10297 } // namespace
10298 
10299 /// Alerts the user that they are attempting to free a non-malloc'd object.
10300 void Sema::CheckFreeArguments(const CallExpr *E) {
10301   const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
10302   const std::string CalleeName =
10303       dyn_cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
10304 
10305   if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
10306     return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
10307 
10308   if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
10309     return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
10310 }
10311 
10312 void
10313 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
10314                          SourceLocation ReturnLoc,
10315                          bool isObjCMethod,
10316                          const AttrVec *Attrs,
10317                          const FunctionDecl *FD) {
10318   // Check if the return value is null but should not be.
10319   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
10320        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
10321       CheckNonNullExpr(*this, RetValExp))
10322     Diag(ReturnLoc, diag::warn_null_ret)
10323       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
10324 
10325   // C++11 [basic.stc.dynamic.allocation]p4:
10326   //   If an allocation function declared with a non-throwing
10327   //   exception-specification fails to allocate storage, it shall return
10328   //   a null pointer. Any other allocation function that fails to allocate
10329   //   storage shall indicate failure only by throwing an exception [...]
10330   if (FD) {
10331     OverloadedOperatorKind Op = FD->getOverloadedOperator();
10332     if (Op == OO_New || Op == OO_Array_New) {
10333       const FunctionProtoType *Proto
10334         = FD->getType()->castAs<FunctionProtoType>();
10335       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
10336           CheckNonNullExpr(*this, RetValExp))
10337         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
10338           << FD << getLangOpts().CPlusPlus11;
10339     }
10340   }
10341 
10342   // PPC MMA non-pointer types are not allowed as return type. Checking the type
10343   // here prevent the user from using a PPC MMA type as trailing return type.
10344   if (Context.getTargetInfo().getTriple().isPPC64())
10345     CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
10346 }
10347 
10348 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
10349 
10350 /// Check for comparisons of floating point operands using != and ==.
10351 /// Issue a warning if these are no self-comparisons, as they are not likely
10352 /// to do what the programmer intended.
10353 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
10354   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
10355   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
10356 
10357   // Special case: check for x == x (which is OK).
10358   // Do not emit warnings for such cases.
10359   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
10360     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
10361       if (DRL->getDecl() == DRR->getDecl())
10362         return;
10363 
10364   // Special case: check for comparisons against literals that can be exactly
10365   //  represented by APFloat.  In such cases, do not emit a warning.  This
10366   //  is a heuristic: often comparison against such literals are used to
10367   //  detect if a value in a variable has not changed.  This clearly can
10368   //  lead to false negatives.
10369   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
10370     if (FLL->isExact())
10371       return;
10372   } else
10373     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
10374       if (FLR->isExact())
10375         return;
10376 
10377   // Check for comparisons with builtin types.
10378   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
10379     if (CL->getBuiltinCallee())
10380       return;
10381 
10382   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
10383     if (CR->getBuiltinCallee())
10384       return;
10385 
10386   // Emit the diagnostic.
10387   Diag(Loc, diag::warn_floatingpoint_eq)
10388     << LHS->getSourceRange() << RHS->getSourceRange();
10389 }
10390 
10391 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
10392 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
10393 
10394 namespace {
10395 
10396 /// Structure recording the 'active' range of an integer-valued
10397 /// expression.
10398 struct IntRange {
10399   /// The number of bits active in the int. Note that this includes exactly one
10400   /// sign bit if !NonNegative.
10401   unsigned Width;
10402 
10403   /// True if the int is known not to have negative values. If so, all leading
10404   /// bits before Width are known zero, otherwise they are known to be the
10405   /// same as the MSB within Width.
10406   bool NonNegative;
10407 
10408   IntRange(unsigned Width, bool NonNegative)
10409       : Width(Width), NonNegative(NonNegative) {}
10410 
10411   /// Number of bits excluding the sign bit.
10412   unsigned valueBits() const {
10413     return NonNegative ? Width : Width - 1;
10414   }
10415 
10416   /// Returns the range of the bool type.
10417   static IntRange forBoolType() {
10418     return IntRange(1, true);
10419   }
10420 
10421   /// Returns the range of an opaque value of the given integral type.
10422   static IntRange forValueOfType(ASTContext &C, QualType T) {
10423     return forValueOfCanonicalType(C,
10424                           T->getCanonicalTypeInternal().getTypePtr());
10425   }
10426 
10427   /// Returns the range of an opaque value of a canonical integral type.
10428   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
10429     assert(T->isCanonicalUnqualified());
10430 
10431     if (const VectorType *VT = dyn_cast<VectorType>(T))
10432       T = VT->getElementType().getTypePtr();
10433     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
10434       T = CT->getElementType().getTypePtr();
10435     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
10436       T = AT->getValueType().getTypePtr();
10437 
10438     if (!C.getLangOpts().CPlusPlus) {
10439       // For enum types in C code, use the underlying datatype.
10440       if (const EnumType *ET = dyn_cast<EnumType>(T))
10441         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
10442     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
10443       // For enum types in C++, use the known bit width of the enumerators.
10444       EnumDecl *Enum = ET->getDecl();
10445       // In C++11, enums can have a fixed underlying type. Use this type to
10446       // compute the range.
10447       if (Enum->isFixed()) {
10448         return IntRange(C.getIntWidth(QualType(T, 0)),
10449                         !ET->isSignedIntegerOrEnumerationType());
10450       }
10451 
10452       unsigned NumPositive = Enum->getNumPositiveBits();
10453       unsigned NumNegative = Enum->getNumNegativeBits();
10454 
10455       if (NumNegative == 0)
10456         return IntRange(NumPositive, true/*NonNegative*/);
10457       else
10458         return IntRange(std::max(NumPositive + 1, NumNegative),
10459                         false/*NonNegative*/);
10460     }
10461 
10462     if (const auto *EIT = dyn_cast<ExtIntType>(T))
10463       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
10464 
10465     const BuiltinType *BT = cast<BuiltinType>(T);
10466     assert(BT->isInteger());
10467 
10468     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10469   }
10470 
10471   /// Returns the "target" range of a canonical integral type, i.e.
10472   /// the range of values expressible in the type.
10473   ///
10474   /// This matches forValueOfCanonicalType except that enums have the
10475   /// full range of their type, not the range of their enumerators.
10476   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
10477     assert(T->isCanonicalUnqualified());
10478 
10479     if (const VectorType *VT = dyn_cast<VectorType>(T))
10480       T = VT->getElementType().getTypePtr();
10481     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
10482       T = CT->getElementType().getTypePtr();
10483     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
10484       T = AT->getValueType().getTypePtr();
10485     if (const EnumType *ET = dyn_cast<EnumType>(T))
10486       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
10487 
10488     if (const auto *EIT = dyn_cast<ExtIntType>(T))
10489       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
10490 
10491     const BuiltinType *BT = cast<BuiltinType>(T);
10492     assert(BT->isInteger());
10493 
10494     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10495   }
10496 
10497   /// Returns the supremum of two ranges: i.e. their conservative merge.
10498   static IntRange join(IntRange L, IntRange R) {
10499     bool Unsigned = L.NonNegative && R.NonNegative;
10500     return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
10501                     L.NonNegative && R.NonNegative);
10502   }
10503 
10504   /// Return the range of a bitwise-AND of the two ranges.
10505   static IntRange bit_and(IntRange L, IntRange R) {
10506     unsigned Bits = std::max(L.Width, R.Width);
10507     bool NonNegative = false;
10508     if (L.NonNegative) {
10509       Bits = std::min(Bits, L.Width);
10510       NonNegative = true;
10511     }
10512     if (R.NonNegative) {
10513       Bits = std::min(Bits, R.Width);
10514       NonNegative = true;
10515     }
10516     return IntRange(Bits, NonNegative);
10517   }
10518 
10519   /// Return the range of a sum of the two ranges.
10520   static IntRange sum(IntRange L, IntRange R) {
10521     bool Unsigned = L.NonNegative && R.NonNegative;
10522     return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
10523                     Unsigned);
10524   }
10525 
10526   /// Return the range of a difference of the two ranges.
10527   static IntRange difference(IntRange L, IntRange R) {
10528     // We need a 1-bit-wider range if:
10529     //   1) LHS can be negative: least value can be reduced.
10530     //   2) RHS can be negative: greatest value can be increased.
10531     bool CanWiden = !L.NonNegative || !R.NonNegative;
10532     bool Unsigned = L.NonNegative && R.Width == 0;
10533     return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
10534                         !Unsigned,
10535                     Unsigned);
10536   }
10537 
10538   /// Return the range of a product of the two ranges.
10539   static IntRange product(IntRange L, IntRange R) {
10540     // If both LHS and RHS can be negative, we can form
10541     //   -2^L * -2^R = 2^(L + R)
10542     // which requires L + R + 1 value bits to represent.
10543     bool CanWiden = !L.NonNegative && !R.NonNegative;
10544     bool Unsigned = L.NonNegative && R.NonNegative;
10545     return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
10546                     Unsigned);
10547   }
10548 
10549   /// Return the range of a remainder operation between the two ranges.
10550   static IntRange rem(IntRange L, IntRange R) {
10551     // The result of a remainder can't be larger than the result of
10552     // either side. The sign of the result is the sign of the LHS.
10553     bool Unsigned = L.NonNegative;
10554     return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
10555                     Unsigned);
10556   }
10557 };
10558 
10559 } // namespace
10560 
10561 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
10562                               unsigned MaxWidth) {
10563   if (value.isSigned() && value.isNegative())
10564     return IntRange(value.getMinSignedBits(), false);
10565 
10566   if (value.getBitWidth() > MaxWidth)
10567     value = value.trunc(MaxWidth);
10568 
10569   // isNonNegative() just checks the sign bit without considering
10570   // signedness.
10571   return IntRange(value.getActiveBits(), true);
10572 }
10573 
10574 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
10575                               unsigned MaxWidth) {
10576   if (result.isInt())
10577     return GetValueRange(C, result.getInt(), MaxWidth);
10578 
10579   if (result.isVector()) {
10580     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
10581     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
10582       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
10583       R = IntRange::join(R, El);
10584     }
10585     return R;
10586   }
10587 
10588   if (result.isComplexInt()) {
10589     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
10590     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
10591     return IntRange::join(R, I);
10592   }
10593 
10594   // This can happen with lossless casts to intptr_t of "based" lvalues.
10595   // Assume it might use arbitrary bits.
10596   // FIXME: The only reason we need to pass the type in here is to get
10597   // the sign right on this one case.  It would be nice if APValue
10598   // preserved this.
10599   assert(result.isLValue() || result.isAddrLabelDiff());
10600   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
10601 }
10602 
10603 static QualType GetExprType(const Expr *E) {
10604   QualType Ty = E->getType();
10605   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
10606     Ty = AtomicRHS->getValueType();
10607   return Ty;
10608 }
10609 
10610 /// Pseudo-evaluate the given integer expression, estimating the
10611 /// range of values it might take.
10612 ///
10613 /// \param MaxWidth The width to which the value will be truncated.
10614 /// \param Approximate If \c true, return a likely range for the result: in
10615 ///        particular, assume that aritmetic on narrower types doesn't leave
10616 ///        those types. If \c false, return a range including all possible
10617 ///        result values.
10618 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
10619                              bool InConstantContext, bool Approximate) {
10620   E = E->IgnoreParens();
10621 
10622   // Try a full evaluation first.
10623   Expr::EvalResult result;
10624   if (E->EvaluateAsRValue(result, C, InConstantContext))
10625     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
10626 
10627   // I think we only want to look through implicit casts here; if the
10628   // user has an explicit widening cast, we should treat the value as
10629   // being of the new, wider type.
10630   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
10631     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
10632       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
10633                           Approximate);
10634 
10635     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
10636 
10637     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
10638                          CE->getCastKind() == CK_BooleanToSignedIntegral;
10639 
10640     // Assume that non-integer casts can span the full range of the type.
10641     if (!isIntegerCast)
10642       return OutputTypeRange;
10643 
10644     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
10645                                      std::min(MaxWidth, OutputTypeRange.Width),
10646                                      InConstantContext, Approximate);
10647 
10648     // Bail out if the subexpr's range is as wide as the cast type.
10649     if (SubRange.Width >= OutputTypeRange.Width)
10650       return OutputTypeRange;
10651 
10652     // Otherwise, we take the smaller width, and we're non-negative if
10653     // either the output type or the subexpr is.
10654     return IntRange(SubRange.Width,
10655                     SubRange.NonNegative || OutputTypeRange.NonNegative);
10656   }
10657 
10658   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
10659     // If we can fold the condition, just take that operand.
10660     bool CondResult;
10661     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
10662       return GetExprRange(C,
10663                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
10664                           MaxWidth, InConstantContext, Approximate);
10665 
10666     // Otherwise, conservatively merge.
10667     // GetExprRange requires an integer expression, but a throw expression
10668     // results in a void type.
10669     Expr *E = CO->getTrueExpr();
10670     IntRange L = E->getType()->isVoidType()
10671                      ? IntRange{0, true}
10672                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
10673     E = CO->getFalseExpr();
10674     IntRange R = E->getType()->isVoidType()
10675                      ? IntRange{0, true}
10676                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
10677     return IntRange::join(L, R);
10678   }
10679 
10680   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
10681     IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
10682 
10683     switch (BO->getOpcode()) {
10684     case BO_Cmp:
10685       llvm_unreachable("builtin <=> should have class type");
10686 
10687     // Boolean-valued operations are single-bit and positive.
10688     case BO_LAnd:
10689     case BO_LOr:
10690     case BO_LT:
10691     case BO_GT:
10692     case BO_LE:
10693     case BO_GE:
10694     case BO_EQ:
10695     case BO_NE:
10696       return IntRange::forBoolType();
10697 
10698     // The type of the assignments is the type of the LHS, so the RHS
10699     // is not necessarily the same type.
10700     case BO_MulAssign:
10701     case BO_DivAssign:
10702     case BO_RemAssign:
10703     case BO_AddAssign:
10704     case BO_SubAssign:
10705     case BO_XorAssign:
10706     case BO_OrAssign:
10707       // TODO: bitfields?
10708       return IntRange::forValueOfType(C, GetExprType(E));
10709 
10710     // Simple assignments just pass through the RHS, which will have
10711     // been coerced to the LHS type.
10712     case BO_Assign:
10713       // TODO: bitfields?
10714       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
10715                           Approximate);
10716 
10717     // Operations with opaque sources are black-listed.
10718     case BO_PtrMemD:
10719     case BO_PtrMemI:
10720       return IntRange::forValueOfType(C, GetExprType(E));
10721 
10722     // Bitwise-and uses the *infinum* of the two source ranges.
10723     case BO_And:
10724     case BO_AndAssign:
10725       Combine = IntRange::bit_and;
10726       break;
10727 
10728     // Left shift gets black-listed based on a judgement call.
10729     case BO_Shl:
10730       // ...except that we want to treat '1 << (blah)' as logically
10731       // positive.  It's an important idiom.
10732       if (IntegerLiteral *I
10733             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
10734         if (I->getValue() == 1) {
10735           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
10736           return IntRange(R.Width, /*NonNegative*/ true);
10737         }
10738       }
10739       LLVM_FALLTHROUGH;
10740 
10741     case BO_ShlAssign:
10742       return IntRange::forValueOfType(C, GetExprType(E));
10743 
10744     // Right shift by a constant can narrow its left argument.
10745     case BO_Shr:
10746     case BO_ShrAssign: {
10747       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext,
10748                                 Approximate);
10749 
10750       // If the shift amount is a positive constant, drop the width by
10751       // that much.
10752       if (Optional<llvm::APSInt> shift =
10753               BO->getRHS()->getIntegerConstantExpr(C)) {
10754         if (shift->isNonNegative()) {
10755           unsigned zext = shift->getZExtValue();
10756           if (zext >= L.Width)
10757             L.Width = (L.NonNegative ? 0 : 1);
10758           else
10759             L.Width -= zext;
10760         }
10761       }
10762 
10763       return L;
10764     }
10765 
10766     // Comma acts as its right operand.
10767     case BO_Comma:
10768       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
10769                           Approximate);
10770 
10771     case BO_Add:
10772       if (!Approximate)
10773         Combine = IntRange::sum;
10774       break;
10775 
10776     case BO_Sub:
10777       if (BO->getLHS()->getType()->isPointerType())
10778         return IntRange::forValueOfType(C, GetExprType(E));
10779       if (!Approximate)
10780         Combine = IntRange::difference;
10781       break;
10782 
10783     case BO_Mul:
10784       if (!Approximate)
10785         Combine = IntRange::product;
10786       break;
10787 
10788     // The width of a division result is mostly determined by the size
10789     // of the LHS.
10790     case BO_Div: {
10791       // Don't 'pre-truncate' the operands.
10792       unsigned opWidth = C.getIntWidth(GetExprType(E));
10793       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext,
10794                                 Approximate);
10795 
10796       // If the divisor is constant, use that.
10797       if (Optional<llvm::APSInt> divisor =
10798               BO->getRHS()->getIntegerConstantExpr(C)) {
10799         unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
10800         if (log2 >= L.Width)
10801           L.Width = (L.NonNegative ? 0 : 1);
10802         else
10803           L.Width = std::min(L.Width - log2, MaxWidth);
10804         return L;
10805       }
10806 
10807       // Otherwise, just use the LHS's width.
10808       // FIXME: This is wrong if the LHS could be its minimal value and the RHS
10809       // could be -1.
10810       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext,
10811                                 Approximate);
10812       return IntRange(L.Width, L.NonNegative && R.NonNegative);
10813     }
10814 
10815     case BO_Rem:
10816       Combine = IntRange::rem;
10817       break;
10818 
10819     // The default behavior is okay for these.
10820     case BO_Xor:
10821     case BO_Or:
10822       break;
10823     }
10824 
10825     // Combine the two ranges, but limit the result to the type in which we
10826     // performed the computation.
10827     QualType T = GetExprType(E);
10828     unsigned opWidth = C.getIntWidth(T);
10829     IntRange L =
10830         GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate);
10831     IntRange R =
10832         GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate);
10833     IntRange C = Combine(L, R);
10834     C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
10835     C.Width = std::min(C.Width, MaxWidth);
10836     return C;
10837   }
10838 
10839   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
10840     switch (UO->getOpcode()) {
10841     // Boolean-valued operations are white-listed.
10842     case UO_LNot:
10843       return IntRange::forBoolType();
10844 
10845     // Operations with opaque sources are black-listed.
10846     case UO_Deref:
10847     case UO_AddrOf: // should be impossible
10848       return IntRange::forValueOfType(C, GetExprType(E));
10849 
10850     default:
10851       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
10852                           Approximate);
10853     }
10854   }
10855 
10856   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
10857     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
10858                         Approximate);
10859 
10860   if (const auto *BitField = E->getSourceBitField())
10861     return IntRange(BitField->getBitWidthValue(C),
10862                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
10863 
10864   return IntRange::forValueOfType(C, GetExprType(E));
10865 }
10866 
10867 static IntRange GetExprRange(ASTContext &C, const Expr *E,
10868                              bool InConstantContext, bool Approximate) {
10869   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
10870                       Approximate);
10871 }
10872 
10873 /// Checks whether the given value, which currently has the given
10874 /// source semantics, has the same value when coerced through the
10875 /// target semantics.
10876 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
10877                                  const llvm::fltSemantics &Src,
10878                                  const llvm::fltSemantics &Tgt) {
10879   llvm::APFloat truncated = value;
10880 
10881   bool ignored;
10882   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
10883   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
10884 
10885   return truncated.bitwiseIsEqual(value);
10886 }
10887 
10888 /// Checks whether the given value, which currently has the given
10889 /// source semantics, has the same value when coerced through the
10890 /// target semantics.
10891 ///
10892 /// The value might be a vector of floats (or a complex number).
10893 static bool IsSameFloatAfterCast(const APValue &value,
10894                                  const llvm::fltSemantics &Src,
10895                                  const llvm::fltSemantics &Tgt) {
10896   if (value.isFloat())
10897     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
10898 
10899   if (value.isVector()) {
10900     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
10901       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
10902         return false;
10903     return true;
10904   }
10905 
10906   assert(value.isComplexFloat());
10907   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
10908           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
10909 }
10910 
10911 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
10912                                        bool IsListInit = false);
10913 
10914 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
10915   // Suppress cases where we are comparing against an enum constant.
10916   if (const DeclRefExpr *DR =
10917       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
10918     if (isa<EnumConstantDecl>(DR->getDecl()))
10919       return true;
10920 
10921   // Suppress cases where the value is expanded from a macro, unless that macro
10922   // is how a language represents a boolean literal. This is the case in both C
10923   // and Objective-C.
10924   SourceLocation BeginLoc = E->getBeginLoc();
10925   if (BeginLoc.isMacroID()) {
10926     StringRef MacroName = Lexer::getImmediateMacroName(
10927         BeginLoc, S.getSourceManager(), S.getLangOpts());
10928     return MacroName != "YES" && MacroName != "NO" &&
10929            MacroName != "true" && MacroName != "false";
10930   }
10931 
10932   return false;
10933 }
10934 
10935 static bool isKnownToHaveUnsignedValue(Expr *E) {
10936   return E->getType()->isIntegerType() &&
10937          (!E->getType()->isSignedIntegerType() ||
10938           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
10939 }
10940 
10941 namespace {
10942 /// The promoted range of values of a type. In general this has the
10943 /// following structure:
10944 ///
10945 ///     |-----------| . . . |-----------|
10946 ///     ^           ^       ^           ^
10947 ///    Min       HoleMin  HoleMax      Max
10948 ///
10949 /// ... where there is only a hole if a signed type is promoted to unsigned
10950 /// (in which case Min and Max are the smallest and largest representable
10951 /// values).
10952 struct PromotedRange {
10953   // Min, or HoleMax if there is a hole.
10954   llvm::APSInt PromotedMin;
10955   // Max, or HoleMin if there is a hole.
10956   llvm::APSInt PromotedMax;
10957 
10958   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
10959     if (R.Width == 0)
10960       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
10961     else if (R.Width >= BitWidth && !Unsigned) {
10962       // Promotion made the type *narrower*. This happens when promoting
10963       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
10964       // Treat all values of 'signed int' as being in range for now.
10965       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
10966       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
10967     } else {
10968       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
10969                         .extOrTrunc(BitWidth);
10970       PromotedMin.setIsUnsigned(Unsigned);
10971 
10972       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
10973                         .extOrTrunc(BitWidth);
10974       PromotedMax.setIsUnsigned(Unsigned);
10975     }
10976   }
10977 
10978   // Determine whether this range is contiguous (has no hole).
10979   bool isContiguous() const { return PromotedMin <= PromotedMax; }
10980 
10981   // Where a constant value is within the range.
10982   enum ComparisonResult {
10983     LT = 0x1,
10984     LE = 0x2,
10985     GT = 0x4,
10986     GE = 0x8,
10987     EQ = 0x10,
10988     NE = 0x20,
10989     InRangeFlag = 0x40,
10990 
10991     Less = LE | LT | NE,
10992     Min = LE | InRangeFlag,
10993     InRange = InRangeFlag,
10994     Max = GE | InRangeFlag,
10995     Greater = GE | GT | NE,
10996 
10997     OnlyValue = LE | GE | EQ | InRangeFlag,
10998     InHole = NE
10999   };
11000 
11001   ComparisonResult compare(const llvm::APSInt &Value) const {
11002     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
11003            Value.isUnsigned() == PromotedMin.isUnsigned());
11004     if (!isContiguous()) {
11005       assert(Value.isUnsigned() && "discontiguous range for signed compare");
11006       if (Value.isMinValue()) return Min;
11007       if (Value.isMaxValue()) return Max;
11008       if (Value >= PromotedMin) return InRange;
11009       if (Value <= PromotedMax) return InRange;
11010       return InHole;
11011     }
11012 
11013     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
11014     case -1: return Less;
11015     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
11016     case 1:
11017       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
11018       case -1: return InRange;
11019       case 0: return Max;
11020       case 1: return Greater;
11021       }
11022     }
11023 
11024     llvm_unreachable("impossible compare result");
11025   }
11026 
11027   static llvm::Optional<StringRef>
11028   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
11029     if (Op == BO_Cmp) {
11030       ComparisonResult LTFlag = LT, GTFlag = GT;
11031       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
11032 
11033       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
11034       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
11035       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
11036       return llvm::None;
11037     }
11038 
11039     ComparisonResult TrueFlag, FalseFlag;
11040     if (Op == BO_EQ) {
11041       TrueFlag = EQ;
11042       FalseFlag = NE;
11043     } else if (Op == BO_NE) {
11044       TrueFlag = NE;
11045       FalseFlag = EQ;
11046     } else {
11047       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
11048         TrueFlag = LT;
11049         FalseFlag = GE;
11050       } else {
11051         TrueFlag = GT;
11052         FalseFlag = LE;
11053       }
11054       if (Op == BO_GE || Op == BO_LE)
11055         std::swap(TrueFlag, FalseFlag);
11056     }
11057     if (R & TrueFlag)
11058       return StringRef("true");
11059     if (R & FalseFlag)
11060       return StringRef("false");
11061     return llvm::None;
11062   }
11063 };
11064 }
11065 
11066 static bool HasEnumType(Expr *E) {
11067   // Strip off implicit integral promotions.
11068   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
11069     if (ICE->getCastKind() != CK_IntegralCast &&
11070         ICE->getCastKind() != CK_NoOp)
11071       break;
11072     E = ICE->getSubExpr();
11073   }
11074 
11075   return E->getType()->isEnumeralType();
11076 }
11077 
11078 static int classifyConstantValue(Expr *Constant) {
11079   // The values of this enumeration are used in the diagnostics
11080   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
11081   enum ConstantValueKind {
11082     Miscellaneous = 0,
11083     LiteralTrue,
11084     LiteralFalse
11085   };
11086   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
11087     return BL->getValue() ? ConstantValueKind::LiteralTrue
11088                           : ConstantValueKind::LiteralFalse;
11089   return ConstantValueKind::Miscellaneous;
11090 }
11091 
11092 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
11093                                         Expr *Constant, Expr *Other,
11094                                         const llvm::APSInt &Value,
11095                                         bool RhsConstant) {
11096   if (S.inTemplateInstantiation())
11097     return false;
11098 
11099   Expr *OriginalOther = Other;
11100 
11101   Constant = Constant->IgnoreParenImpCasts();
11102   Other = Other->IgnoreParenImpCasts();
11103 
11104   // Suppress warnings on tautological comparisons between values of the same
11105   // enumeration type. There are only two ways we could warn on this:
11106   //  - If the constant is outside the range of representable values of
11107   //    the enumeration. In such a case, we should warn about the cast
11108   //    to enumeration type, not about the comparison.
11109   //  - If the constant is the maximum / minimum in-range value. For an
11110   //    enumeratin type, such comparisons can be meaningful and useful.
11111   if (Constant->getType()->isEnumeralType() &&
11112       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
11113     return false;
11114 
11115   IntRange OtherValueRange = GetExprRange(
11116       S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false);
11117 
11118   QualType OtherT = Other->getType();
11119   if (const auto *AT = OtherT->getAs<AtomicType>())
11120     OtherT = AT->getValueType();
11121   IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
11122 
11123   // Special case for ObjC BOOL on targets where its a typedef for a signed char
11124   // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
11125   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
11126                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
11127                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
11128 
11129   // Whether we're treating Other as being a bool because of the form of
11130   // expression despite it having another type (typically 'int' in C).
11131   bool OtherIsBooleanDespiteType =
11132       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
11133   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
11134     OtherTypeRange = OtherValueRange = IntRange::forBoolType();
11135 
11136   // Check if all values in the range of possible values of this expression
11137   // lead to the same comparison outcome.
11138   PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(),
11139                                         Value.isUnsigned());
11140   auto Cmp = OtherPromotedValueRange.compare(Value);
11141   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
11142   if (!Result)
11143     return false;
11144 
11145   // Also consider the range determined by the type alone. This allows us to
11146   // classify the warning under the proper diagnostic group.
11147   bool TautologicalTypeCompare = false;
11148   {
11149     PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
11150                                          Value.isUnsigned());
11151     auto TypeCmp = OtherPromotedTypeRange.compare(Value);
11152     if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
11153                                                        RhsConstant)) {
11154       TautologicalTypeCompare = true;
11155       Cmp = TypeCmp;
11156       Result = TypeResult;
11157     }
11158   }
11159 
11160   // Don't warn if the non-constant operand actually always evaluates to the
11161   // same value.
11162   if (!TautologicalTypeCompare && OtherValueRange.Width == 0)
11163     return false;
11164 
11165   // Suppress the diagnostic for an in-range comparison if the constant comes
11166   // from a macro or enumerator. We don't want to diagnose
11167   //
11168   //   some_long_value <= INT_MAX
11169   //
11170   // when sizeof(int) == sizeof(long).
11171   bool InRange = Cmp & PromotedRange::InRangeFlag;
11172   if (InRange && IsEnumConstOrFromMacro(S, Constant))
11173     return false;
11174 
11175   // A comparison of an unsigned bit-field against 0 is really a type problem,
11176   // even though at the type level the bit-field might promote to 'signed int'.
11177   if (Other->refersToBitField() && InRange && Value == 0 &&
11178       Other->getType()->isUnsignedIntegerOrEnumerationType())
11179     TautologicalTypeCompare = true;
11180 
11181   // If this is a comparison to an enum constant, include that
11182   // constant in the diagnostic.
11183   const EnumConstantDecl *ED = nullptr;
11184   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
11185     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
11186 
11187   // Should be enough for uint128 (39 decimal digits)
11188   SmallString<64> PrettySourceValue;
11189   llvm::raw_svector_ostream OS(PrettySourceValue);
11190   if (ED) {
11191     OS << '\'' << *ED << "' (" << Value << ")";
11192   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
11193                Constant->IgnoreParenImpCasts())) {
11194     OS << (BL->getValue() ? "YES" : "NO");
11195   } else {
11196     OS << Value;
11197   }
11198 
11199   if (!TautologicalTypeCompare) {
11200     S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
11201         << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative
11202         << E->getOpcodeStr() << OS.str() << *Result
11203         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11204     return true;
11205   }
11206 
11207   if (IsObjCSignedCharBool) {
11208     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
11209                           S.PDiag(diag::warn_tautological_compare_objc_bool)
11210                               << OS.str() << *Result);
11211     return true;
11212   }
11213 
11214   // FIXME: We use a somewhat different formatting for the in-range cases and
11215   // cases involving boolean values for historical reasons. We should pick a
11216   // consistent way of presenting these diagnostics.
11217   if (!InRange || Other->isKnownToHaveBooleanValue()) {
11218 
11219     S.DiagRuntimeBehavior(
11220         E->getOperatorLoc(), E,
11221         S.PDiag(!InRange ? diag::warn_out_of_range_compare
11222                          : diag::warn_tautological_bool_compare)
11223             << OS.str() << classifyConstantValue(Constant) << OtherT
11224             << OtherIsBooleanDespiteType << *Result
11225             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
11226   } else {
11227     unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
11228                         ? (HasEnumType(OriginalOther)
11229                                ? diag::warn_unsigned_enum_always_true_comparison
11230                                : diag::warn_unsigned_always_true_comparison)
11231                         : diag::warn_tautological_constant_compare;
11232 
11233     S.Diag(E->getOperatorLoc(), Diag)
11234         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
11235         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11236   }
11237 
11238   return true;
11239 }
11240 
11241 /// Analyze the operands of the given comparison.  Implements the
11242 /// fallback case from AnalyzeComparison.
11243 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
11244   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11245   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11246 }
11247 
11248 /// Implements -Wsign-compare.
11249 ///
11250 /// \param E the binary operator to check for warnings
11251 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
11252   // The type the comparison is being performed in.
11253   QualType T = E->getLHS()->getType();
11254 
11255   // Only analyze comparison operators where both sides have been converted to
11256   // the same type.
11257   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
11258     return AnalyzeImpConvsInComparison(S, E);
11259 
11260   // Don't analyze value-dependent comparisons directly.
11261   if (E->isValueDependent())
11262     return AnalyzeImpConvsInComparison(S, E);
11263 
11264   Expr *LHS = E->getLHS();
11265   Expr *RHS = E->getRHS();
11266 
11267   if (T->isIntegralType(S.Context)) {
11268     Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context);
11269     Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context);
11270 
11271     // We don't care about expressions whose result is a constant.
11272     if (RHSValue && LHSValue)
11273       return AnalyzeImpConvsInComparison(S, E);
11274 
11275     // We only care about expressions where just one side is literal
11276     if ((bool)RHSValue ^ (bool)LHSValue) {
11277       // Is the constant on the RHS or LHS?
11278       const bool RhsConstant = (bool)RHSValue;
11279       Expr *Const = RhsConstant ? RHS : LHS;
11280       Expr *Other = RhsConstant ? LHS : RHS;
11281       const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
11282 
11283       // Check whether an integer constant comparison results in a value
11284       // of 'true' or 'false'.
11285       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
11286         return AnalyzeImpConvsInComparison(S, E);
11287     }
11288   }
11289 
11290   if (!T->hasUnsignedIntegerRepresentation()) {
11291     // We don't do anything special if this isn't an unsigned integral
11292     // comparison:  we're only interested in integral comparisons, and
11293     // signed comparisons only happen in cases we don't care to warn about.
11294     return AnalyzeImpConvsInComparison(S, E);
11295   }
11296 
11297   LHS = LHS->IgnoreParenImpCasts();
11298   RHS = RHS->IgnoreParenImpCasts();
11299 
11300   if (!S.getLangOpts().CPlusPlus) {
11301     // Avoid warning about comparison of integers with different signs when
11302     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
11303     // the type of `E`.
11304     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
11305       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11306     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
11307       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11308   }
11309 
11310   // Check to see if one of the (unmodified) operands is of different
11311   // signedness.
11312   Expr *signedOperand, *unsignedOperand;
11313   if (LHS->getType()->hasSignedIntegerRepresentation()) {
11314     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
11315            "unsigned comparison between two signed integer expressions?");
11316     signedOperand = LHS;
11317     unsignedOperand = RHS;
11318   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
11319     signedOperand = RHS;
11320     unsignedOperand = LHS;
11321   } else {
11322     return AnalyzeImpConvsInComparison(S, E);
11323   }
11324 
11325   // Otherwise, calculate the effective range of the signed operand.
11326   IntRange signedRange = GetExprRange(
11327       S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true);
11328 
11329   // Go ahead and analyze implicit conversions in the operands.  Note
11330   // that we skip the implicit conversions on both sides.
11331   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
11332   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
11333 
11334   // If the signed range is non-negative, -Wsign-compare won't fire.
11335   if (signedRange.NonNegative)
11336     return;
11337 
11338   // For (in)equality comparisons, if the unsigned operand is a
11339   // constant which cannot collide with a overflowed signed operand,
11340   // then reinterpreting the signed operand as unsigned will not
11341   // change the result of the comparison.
11342   if (E->isEqualityOp()) {
11343     unsigned comparisonWidth = S.Context.getIntWidth(T);
11344     IntRange unsignedRange =
11345         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(),
11346                      /*Approximate*/ true);
11347 
11348     // We should never be unable to prove that the unsigned operand is
11349     // non-negative.
11350     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
11351 
11352     if (unsignedRange.Width < comparisonWidth)
11353       return;
11354   }
11355 
11356   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
11357                         S.PDiag(diag::warn_mixed_sign_comparison)
11358                             << LHS->getType() << RHS->getType()
11359                             << LHS->getSourceRange() << RHS->getSourceRange());
11360 }
11361 
11362 /// Analyzes an attempt to assign the given value to a bitfield.
11363 ///
11364 /// Returns true if there was something fishy about the attempt.
11365 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
11366                                       SourceLocation InitLoc) {
11367   assert(Bitfield->isBitField());
11368   if (Bitfield->isInvalidDecl())
11369     return false;
11370 
11371   // White-list bool bitfields.
11372   QualType BitfieldType = Bitfield->getType();
11373   if (BitfieldType->isBooleanType())
11374      return false;
11375 
11376   if (BitfieldType->isEnumeralType()) {
11377     EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
11378     // If the underlying enum type was not explicitly specified as an unsigned
11379     // type and the enum contain only positive values, MSVC++ will cause an
11380     // inconsistency by storing this as a signed type.
11381     if (S.getLangOpts().CPlusPlus11 &&
11382         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
11383         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
11384         BitfieldEnumDecl->getNumNegativeBits() == 0) {
11385       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
11386           << BitfieldEnumDecl;
11387     }
11388   }
11389 
11390   if (Bitfield->getType()->isBooleanType())
11391     return false;
11392 
11393   // Ignore value- or type-dependent expressions.
11394   if (Bitfield->getBitWidth()->isValueDependent() ||
11395       Bitfield->getBitWidth()->isTypeDependent() ||
11396       Init->isValueDependent() ||
11397       Init->isTypeDependent())
11398     return false;
11399 
11400   Expr *OriginalInit = Init->IgnoreParenImpCasts();
11401   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
11402 
11403   Expr::EvalResult Result;
11404   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
11405                                    Expr::SE_AllowSideEffects)) {
11406     // The RHS is not constant.  If the RHS has an enum type, make sure the
11407     // bitfield is wide enough to hold all the values of the enum without
11408     // truncation.
11409     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
11410       EnumDecl *ED = EnumTy->getDecl();
11411       bool SignedBitfield = BitfieldType->isSignedIntegerType();
11412 
11413       // Enum types are implicitly signed on Windows, so check if there are any
11414       // negative enumerators to see if the enum was intended to be signed or
11415       // not.
11416       bool SignedEnum = ED->getNumNegativeBits() > 0;
11417 
11418       // Check for surprising sign changes when assigning enum values to a
11419       // bitfield of different signedness.  If the bitfield is signed and we
11420       // have exactly the right number of bits to store this unsigned enum,
11421       // suggest changing the enum to an unsigned type. This typically happens
11422       // on Windows where unfixed enums always use an underlying type of 'int'.
11423       unsigned DiagID = 0;
11424       if (SignedEnum && !SignedBitfield) {
11425         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
11426       } else if (SignedBitfield && !SignedEnum &&
11427                  ED->getNumPositiveBits() == FieldWidth) {
11428         DiagID = diag::warn_signed_bitfield_enum_conversion;
11429       }
11430 
11431       if (DiagID) {
11432         S.Diag(InitLoc, DiagID) << Bitfield << ED;
11433         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
11434         SourceRange TypeRange =
11435             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
11436         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
11437             << SignedEnum << TypeRange;
11438       }
11439 
11440       // Compute the required bitwidth. If the enum has negative values, we need
11441       // one more bit than the normal number of positive bits to represent the
11442       // sign bit.
11443       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
11444                                                   ED->getNumNegativeBits())
11445                                        : ED->getNumPositiveBits();
11446 
11447       // Check the bitwidth.
11448       if (BitsNeeded > FieldWidth) {
11449         Expr *WidthExpr = Bitfield->getBitWidth();
11450         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
11451             << Bitfield << ED;
11452         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
11453             << BitsNeeded << ED << WidthExpr->getSourceRange();
11454       }
11455     }
11456 
11457     return false;
11458   }
11459 
11460   llvm::APSInt Value = Result.Val.getInt();
11461 
11462   unsigned OriginalWidth = Value.getBitWidth();
11463 
11464   if (!Value.isSigned() || Value.isNegative())
11465     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
11466       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
11467         OriginalWidth = Value.getMinSignedBits();
11468 
11469   if (OriginalWidth <= FieldWidth)
11470     return false;
11471 
11472   // Compute the value which the bitfield will contain.
11473   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
11474   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
11475 
11476   // Check whether the stored value is equal to the original value.
11477   TruncatedValue = TruncatedValue.extend(OriginalWidth);
11478   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
11479     return false;
11480 
11481   // Special-case bitfields of width 1: booleans are naturally 0/1, and
11482   // therefore don't strictly fit into a signed bitfield of width 1.
11483   if (FieldWidth == 1 && Value == 1)
11484     return false;
11485 
11486   std::string PrettyValue = Value.toString(10);
11487   std::string PrettyTrunc = TruncatedValue.toString(10);
11488 
11489   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
11490     << PrettyValue << PrettyTrunc << OriginalInit->getType()
11491     << Init->getSourceRange();
11492 
11493   return true;
11494 }
11495 
11496 /// Analyze the given simple or compound assignment for warning-worthy
11497 /// operations.
11498 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
11499   // Just recurse on the LHS.
11500   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11501 
11502   // We want to recurse on the RHS as normal unless we're assigning to
11503   // a bitfield.
11504   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
11505     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
11506                                   E->getOperatorLoc())) {
11507       // Recurse, ignoring any implicit conversions on the RHS.
11508       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
11509                                         E->getOperatorLoc());
11510     }
11511   }
11512 
11513   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11514 
11515   // Diagnose implicitly sequentially-consistent atomic assignment.
11516   if (E->getLHS()->getType()->isAtomicType())
11517     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
11518 }
11519 
11520 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
11521 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
11522                             SourceLocation CContext, unsigned diag,
11523                             bool pruneControlFlow = false) {
11524   if (pruneControlFlow) {
11525     S.DiagRuntimeBehavior(E->getExprLoc(), E,
11526                           S.PDiag(diag)
11527                               << SourceType << T << E->getSourceRange()
11528                               << SourceRange(CContext));
11529     return;
11530   }
11531   S.Diag(E->getExprLoc(), diag)
11532     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
11533 }
11534 
11535 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
11536 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
11537                             SourceLocation CContext,
11538                             unsigned diag, bool pruneControlFlow = false) {
11539   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
11540 }
11541 
11542 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
11543   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
11544       S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
11545 }
11546 
11547 static void adornObjCBoolConversionDiagWithTernaryFixit(
11548     Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
11549   Expr *Ignored = SourceExpr->IgnoreImplicit();
11550   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
11551     Ignored = OVE->getSourceExpr();
11552   bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
11553                      isa<BinaryOperator>(Ignored) ||
11554                      isa<CXXOperatorCallExpr>(Ignored);
11555   SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
11556   if (NeedsParens)
11557     Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
11558             << FixItHint::CreateInsertion(EndLoc, ")");
11559   Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
11560 }
11561 
11562 /// Diagnose an implicit cast from a floating point value to an integer value.
11563 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
11564                                     SourceLocation CContext) {
11565   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
11566   const bool PruneWarnings = S.inTemplateInstantiation();
11567 
11568   Expr *InnerE = E->IgnoreParenImpCasts();
11569   // We also want to warn on, e.g., "int i = -1.234"
11570   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
11571     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
11572       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
11573 
11574   const bool IsLiteral =
11575       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
11576 
11577   llvm::APFloat Value(0.0);
11578   bool IsConstant =
11579     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
11580   if (!IsConstant) {
11581     if (isObjCSignedCharBool(S, T)) {
11582       return adornObjCBoolConversionDiagWithTernaryFixit(
11583           S, E,
11584           S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
11585               << E->getType());
11586     }
11587 
11588     return DiagnoseImpCast(S, E, T, CContext,
11589                            diag::warn_impcast_float_integer, PruneWarnings);
11590   }
11591 
11592   bool isExact = false;
11593 
11594   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
11595                             T->hasUnsignedIntegerRepresentation());
11596   llvm::APFloat::opStatus Result = Value.convertToInteger(
11597       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
11598 
11599   // FIXME: Force the precision of the source value down so we don't print
11600   // digits which are usually useless (we don't really care here if we
11601   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
11602   // would automatically print the shortest representation, but it's a bit
11603   // tricky to implement.
11604   SmallString<16> PrettySourceValue;
11605   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
11606   precision = (precision * 59 + 195) / 196;
11607   Value.toString(PrettySourceValue, precision);
11608 
11609   if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
11610     return adornObjCBoolConversionDiagWithTernaryFixit(
11611         S, E,
11612         S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
11613             << PrettySourceValue);
11614   }
11615 
11616   if (Result == llvm::APFloat::opOK && isExact) {
11617     if (IsLiteral) return;
11618     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
11619                            PruneWarnings);
11620   }
11621 
11622   // Conversion of a floating-point value to a non-bool integer where the
11623   // integral part cannot be represented by the integer type is undefined.
11624   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
11625     return DiagnoseImpCast(
11626         S, E, T, CContext,
11627         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
11628                   : diag::warn_impcast_float_to_integer_out_of_range,
11629         PruneWarnings);
11630 
11631   unsigned DiagID = 0;
11632   if (IsLiteral) {
11633     // Warn on floating point literal to integer.
11634     DiagID = diag::warn_impcast_literal_float_to_integer;
11635   } else if (IntegerValue == 0) {
11636     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
11637       return DiagnoseImpCast(S, E, T, CContext,
11638                              diag::warn_impcast_float_integer, PruneWarnings);
11639     }
11640     // Warn on non-zero to zero conversion.
11641     DiagID = diag::warn_impcast_float_to_integer_zero;
11642   } else {
11643     if (IntegerValue.isUnsigned()) {
11644       if (!IntegerValue.isMaxValue()) {
11645         return DiagnoseImpCast(S, E, T, CContext,
11646                                diag::warn_impcast_float_integer, PruneWarnings);
11647       }
11648     } else {  // IntegerValue.isSigned()
11649       if (!IntegerValue.isMaxSignedValue() &&
11650           !IntegerValue.isMinSignedValue()) {
11651         return DiagnoseImpCast(S, E, T, CContext,
11652                                diag::warn_impcast_float_integer, PruneWarnings);
11653       }
11654     }
11655     // Warn on evaluatable floating point expression to integer conversion.
11656     DiagID = diag::warn_impcast_float_to_integer;
11657   }
11658 
11659   SmallString<16> PrettyTargetValue;
11660   if (IsBool)
11661     PrettyTargetValue = Value.isZero() ? "false" : "true";
11662   else
11663     IntegerValue.toString(PrettyTargetValue);
11664 
11665   if (PruneWarnings) {
11666     S.DiagRuntimeBehavior(E->getExprLoc(), E,
11667                           S.PDiag(DiagID)
11668                               << E->getType() << T.getUnqualifiedType()
11669                               << PrettySourceValue << PrettyTargetValue
11670                               << E->getSourceRange() << SourceRange(CContext));
11671   } else {
11672     S.Diag(E->getExprLoc(), DiagID)
11673         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
11674         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
11675   }
11676 }
11677 
11678 /// Analyze the given compound assignment for the possible losing of
11679 /// floating-point precision.
11680 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
11681   assert(isa<CompoundAssignOperator>(E) &&
11682          "Must be compound assignment operation");
11683   // Recurse on the LHS and RHS in here
11684   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11685   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11686 
11687   if (E->getLHS()->getType()->isAtomicType())
11688     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
11689 
11690   // Now check the outermost expression
11691   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
11692   const auto *RBT = cast<CompoundAssignOperator>(E)
11693                         ->getComputationResultType()
11694                         ->getAs<BuiltinType>();
11695 
11696   // The below checks assume source is floating point.
11697   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
11698 
11699   // If source is floating point but target is an integer.
11700   if (ResultBT->isInteger())
11701     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
11702                            E->getExprLoc(), diag::warn_impcast_float_integer);
11703 
11704   if (!ResultBT->isFloatingPoint())
11705     return;
11706 
11707   // If both source and target are floating points, warn about losing precision.
11708   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
11709       QualType(ResultBT, 0), QualType(RBT, 0));
11710   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
11711     // warn about dropping FP rank.
11712     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
11713                     diag::warn_impcast_float_result_precision);
11714 }
11715 
11716 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
11717                                       IntRange Range) {
11718   if (!Range.Width) return "0";
11719 
11720   llvm::APSInt ValueInRange = Value;
11721   ValueInRange.setIsSigned(!Range.NonNegative);
11722   ValueInRange = ValueInRange.trunc(Range.Width);
11723   return ValueInRange.toString(10);
11724 }
11725 
11726 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
11727   if (!isa<ImplicitCastExpr>(Ex))
11728     return false;
11729 
11730   Expr *InnerE = Ex->IgnoreParenImpCasts();
11731   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
11732   const Type *Source =
11733     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
11734   if (Target->isDependentType())
11735     return false;
11736 
11737   const BuiltinType *FloatCandidateBT =
11738     dyn_cast<BuiltinType>(ToBool ? Source : Target);
11739   const Type *BoolCandidateType = ToBool ? Target : Source;
11740 
11741   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
11742           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
11743 }
11744 
11745 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
11746                                              SourceLocation CC) {
11747   unsigned NumArgs = TheCall->getNumArgs();
11748   for (unsigned i = 0; i < NumArgs; ++i) {
11749     Expr *CurrA = TheCall->getArg(i);
11750     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
11751       continue;
11752 
11753     bool IsSwapped = ((i > 0) &&
11754         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
11755     IsSwapped |= ((i < (NumArgs - 1)) &&
11756         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
11757     if (IsSwapped) {
11758       // Warn on this floating-point to bool conversion.
11759       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
11760                       CurrA->getType(), CC,
11761                       diag::warn_impcast_floating_point_to_bool);
11762     }
11763   }
11764 }
11765 
11766 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
11767                                    SourceLocation CC) {
11768   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
11769                         E->getExprLoc()))
11770     return;
11771 
11772   // Don't warn on functions which have return type nullptr_t.
11773   if (isa<CallExpr>(E))
11774     return;
11775 
11776   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
11777   const Expr::NullPointerConstantKind NullKind =
11778       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
11779   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
11780     return;
11781 
11782   // Return if target type is a safe conversion.
11783   if (T->isAnyPointerType() || T->isBlockPointerType() ||
11784       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
11785     return;
11786 
11787   SourceLocation Loc = E->getSourceRange().getBegin();
11788 
11789   // Venture through the macro stacks to get to the source of macro arguments.
11790   // The new location is a better location than the complete location that was
11791   // passed in.
11792   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
11793   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
11794 
11795   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
11796   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
11797     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
11798         Loc, S.SourceMgr, S.getLangOpts());
11799     if (MacroName == "NULL")
11800       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
11801   }
11802 
11803   // Only warn if the null and context location are in the same macro expansion.
11804   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
11805     return;
11806 
11807   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
11808       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
11809       << FixItHint::CreateReplacement(Loc,
11810                                       S.getFixItZeroLiteralForType(T, Loc));
11811 }
11812 
11813 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
11814                                   ObjCArrayLiteral *ArrayLiteral);
11815 
11816 static void
11817 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
11818                            ObjCDictionaryLiteral *DictionaryLiteral);
11819 
11820 /// Check a single element within a collection literal against the
11821 /// target element type.
11822 static void checkObjCCollectionLiteralElement(Sema &S,
11823                                               QualType TargetElementType,
11824                                               Expr *Element,
11825                                               unsigned ElementKind) {
11826   // Skip a bitcast to 'id' or qualified 'id'.
11827   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
11828     if (ICE->getCastKind() == CK_BitCast &&
11829         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
11830       Element = ICE->getSubExpr();
11831   }
11832 
11833   QualType ElementType = Element->getType();
11834   ExprResult ElementResult(Element);
11835   if (ElementType->getAs<ObjCObjectPointerType>() &&
11836       S.CheckSingleAssignmentConstraints(TargetElementType,
11837                                          ElementResult,
11838                                          false, false)
11839         != Sema::Compatible) {
11840     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
11841         << ElementType << ElementKind << TargetElementType
11842         << Element->getSourceRange();
11843   }
11844 
11845   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
11846     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
11847   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
11848     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
11849 }
11850 
11851 /// Check an Objective-C array literal being converted to the given
11852 /// target type.
11853 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
11854                                   ObjCArrayLiteral *ArrayLiteral) {
11855   if (!S.NSArrayDecl)
11856     return;
11857 
11858   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
11859   if (!TargetObjCPtr)
11860     return;
11861 
11862   if (TargetObjCPtr->isUnspecialized() ||
11863       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
11864         != S.NSArrayDecl->getCanonicalDecl())
11865     return;
11866 
11867   auto TypeArgs = TargetObjCPtr->getTypeArgs();
11868   if (TypeArgs.size() != 1)
11869     return;
11870 
11871   QualType TargetElementType = TypeArgs[0];
11872   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
11873     checkObjCCollectionLiteralElement(S, TargetElementType,
11874                                       ArrayLiteral->getElement(I),
11875                                       0);
11876   }
11877 }
11878 
11879 /// Check an Objective-C dictionary literal being converted to the given
11880 /// target type.
11881 static void
11882 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
11883                            ObjCDictionaryLiteral *DictionaryLiteral) {
11884   if (!S.NSDictionaryDecl)
11885     return;
11886 
11887   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
11888   if (!TargetObjCPtr)
11889     return;
11890 
11891   if (TargetObjCPtr->isUnspecialized() ||
11892       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
11893         != S.NSDictionaryDecl->getCanonicalDecl())
11894     return;
11895 
11896   auto TypeArgs = TargetObjCPtr->getTypeArgs();
11897   if (TypeArgs.size() != 2)
11898     return;
11899 
11900   QualType TargetKeyType = TypeArgs[0];
11901   QualType TargetObjectType = TypeArgs[1];
11902   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
11903     auto Element = DictionaryLiteral->getKeyValueElement(I);
11904     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
11905     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
11906   }
11907 }
11908 
11909 // Helper function to filter out cases for constant width constant conversion.
11910 // Don't warn on char array initialization or for non-decimal values.
11911 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
11912                                           SourceLocation CC) {
11913   // If initializing from a constant, and the constant starts with '0',
11914   // then it is a binary, octal, or hexadecimal.  Allow these constants
11915   // to fill all the bits, even if there is a sign change.
11916   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
11917     const char FirstLiteralCharacter =
11918         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
11919     if (FirstLiteralCharacter == '0')
11920       return false;
11921   }
11922 
11923   // If the CC location points to a '{', and the type is char, then assume
11924   // assume it is an array initialization.
11925   if (CC.isValid() && T->isCharType()) {
11926     const char FirstContextCharacter =
11927         S.getSourceManager().getCharacterData(CC)[0];
11928     if (FirstContextCharacter == '{')
11929       return false;
11930   }
11931 
11932   return true;
11933 }
11934 
11935 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
11936   const auto *IL = dyn_cast<IntegerLiteral>(E);
11937   if (!IL) {
11938     if (auto *UO = dyn_cast<UnaryOperator>(E)) {
11939       if (UO->getOpcode() == UO_Minus)
11940         return dyn_cast<IntegerLiteral>(UO->getSubExpr());
11941     }
11942   }
11943 
11944   return IL;
11945 }
11946 
11947 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
11948   E = E->IgnoreParenImpCasts();
11949   SourceLocation ExprLoc = E->getExprLoc();
11950 
11951   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11952     BinaryOperator::Opcode Opc = BO->getOpcode();
11953     Expr::EvalResult Result;
11954     // Do not diagnose unsigned shifts.
11955     if (Opc == BO_Shl) {
11956       const auto *LHS = getIntegerLiteral(BO->getLHS());
11957       const auto *RHS = getIntegerLiteral(BO->getRHS());
11958       if (LHS && LHS->getValue() == 0)
11959         S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
11960       else if (!E->isValueDependent() && LHS && RHS &&
11961                RHS->getValue().isNonNegative() &&
11962                E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
11963         S.Diag(ExprLoc, diag::warn_left_shift_always)
11964             << (Result.Val.getInt() != 0);
11965       else if (E->getType()->isSignedIntegerType())
11966         S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
11967     }
11968   }
11969 
11970   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11971     const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
11972     const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
11973     if (!LHS || !RHS)
11974       return;
11975     if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
11976         (RHS->getValue() == 0 || RHS->getValue() == 1))
11977       // Do not diagnose common idioms.
11978       return;
11979     if (LHS->getValue() != 0 && RHS->getValue() != 0)
11980       S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
11981   }
11982 }
11983 
11984 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
11985                                     SourceLocation CC,
11986                                     bool *ICContext = nullptr,
11987                                     bool IsListInit = false) {
11988   if (E->isTypeDependent() || E->isValueDependent()) return;
11989 
11990   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
11991   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
11992   if (Source == Target) return;
11993   if (Target->isDependentType()) return;
11994 
11995   // If the conversion context location is invalid don't complain. We also
11996   // don't want to emit a warning if the issue occurs from the expansion of
11997   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
11998   // delay this check as long as possible. Once we detect we are in that
11999   // scenario, we just return.
12000   if (CC.isInvalid())
12001     return;
12002 
12003   if (Source->isAtomicType())
12004     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
12005 
12006   // Diagnose implicit casts to bool.
12007   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
12008     if (isa<StringLiteral>(E))
12009       // Warn on string literal to bool.  Checks for string literals in logical
12010       // and expressions, for instance, assert(0 && "error here"), are
12011       // prevented by a check in AnalyzeImplicitConversions().
12012       return DiagnoseImpCast(S, E, T, CC,
12013                              diag::warn_impcast_string_literal_to_bool);
12014     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
12015         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
12016       // This covers the literal expressions that evaluate to Objective-C
12017       // objects.
12018       return DiagnoseImpCast(S, E, T, CC,
12019                              diag::warn_impcast_objective_c_literal_to_bool);
12020     }
12021     if (Source->isPointerType() || Source->canDecayToPointerType()) {
12022       // Warn on pointer to bool conversion that is always true.
12023       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
12024                                      SourceRange(CC));
12025     }
12026   }
12027 
12028   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
12029   // is a typedef for signed char (macOS), then that constant value has to be 1
12030   // or 0.
12031   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
12032     Expr::EvalResult Result;
12033     if (E->EvaluateAsInt(Result, S.getASTContext(),
12034                          Expr::SE_AllowSideEffects)) {
12035       if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
12036         adornObjCBoolConversionDiagWithTernaryFixit(
12037             S, E,
12038             S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
12039                 << Result.Val.getInt().toString(10));
12040       }
12041       return;
12042     }
12043   }
12044 
12045   // Check implicit casts from Objective-C collection literals to specialized
12046   // collection types, e.g., NSArray<NSString *> *.
12047   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
12048     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
12049   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
12050     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
12051 
12052   // Strip vector types.
12053   if (isa<VectorType>(Source)) {
12054     if (!isa<VectorType>(Target)) {
12055       if (S.SourceMgr.isInSystemMacro(CC))
12056         return;
12057       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
12058     }
12059 
12060     // If the vector cast is cast between two vectors of the same size, it is
12061     // a bitcast, not a conversion.
12062     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
12063       return;
12064 
12065     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
12066     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
12067   }
12068   if (auto VecTy = dyn_cast<VectorType>(Target))
12069     Target = VecTy->getElementType().getTypePtr();
12070 
12071   // Strip complex types.
12072   if (isa<ComplexType>(Source)) {
12073     if (!isa<ComplexType>(Target)) {
12074       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
12075         return;
12076 
12077       return DiagnoseImpCast(S, E, T, CC,
12078                              S.getLangOpts().CPlusPlus
12079                                  ? diag::err_impcast_complex_scalar
12080                                  : diag::warn_impcast_complex_scalar);
12081     }
12082 
12083     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
12084     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
12085   }
12086 
12087   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
12088   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
12089 
12090   // If the source is floating point...
12091   if (SourceBT && SourceBT->isFloatingPoint()) {
12092     // ...and the target is floating point...
12093     if (TargetBT && TargetBT->isFloatingPoint()) {
12094       // ...then warn if we're dropping FP rank.
12095 
12096       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12097           QualType(SourceBT, 0), QualType(TargetBT, 0));
12098       if (Order > 0) {
12099         // Don't warn about float constants that are precisely
12100         // representable in the target type.
12101         Expr::EvalResult result;
12102         if (E->EvaluateAsRValue(result, S.Context)) {
12103           // Value might be a float, a float vector, or a float complex.
12104           if (IsSameFloatAfterCast(result.Val,
12105                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
12106                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
12107             return;
12108         }
12109 
12110         if (S.SourceMgr.isInSystemMacro(CC))
12111           return;
12112 
12113         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
12114       }
12115       // ... or possibly if we're increasing rank, too
12116       else if (Order < 0) {
12117         if (S.SourceMgr.isInSystemMacro(CC))
12118           return;
12119 
12120         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
12121       }
12122       return;
12123     }
12124 
12125     // If the target is integral, always warn.
12126     if (TargetBT && TargetBT->isInteger()) {
12127       if (S.SourceMgr.isInSystemMacro(CC))
12128         return;
12129 
12130       DiagnoseFloatingImpCast(S, E, T, CC);
12131     }
12132 
12133     // Detect the case where a call result is converted from floating-point to
12134     // to bool, and the final argument to the call is converted from bool, to
12135     // discover this typo:
12136     //
12137     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
12138     //
12139     // FIXME: This is an incredibly special case; is there some more general
12140     // way to detect this class of misplaced-parentheses bug?
12141     if (Target->isBooleanType() && isa<CallExpr>(E)) {
12142       // Check last argument of function call to see if it is an
12143       // implicit cast from a type matching the type the result
12144       // is being cast to.
12145       CallExpr *CEx = cast<CallExpr>(E);
12146       if (unsigned NumArgs = CEx->getNumArgs()) {
12147         Expr *LastA = CEx->getArg(NumArgs - 1);
12148         Expr *InnerE = LastA->IgnoreParenImpCasts();
12149         if (isa<ImplicitCastExpr>(LastA) &&
12150             InnerE->getType()->isBooleanType()) {
12151           // Warn on this floating-point to bool conversion
12152           DiagnoseImpCast(S, E, T, CC,
12153                           diag::warn_impcast_floating_point_to_bool);
12154         }
12155       }
12156     }
12157     return;
12158   }
12159 
12160   // Valid casts involving fixed point types should be accounted for here.
12161   if (Source->isFixedPointType()) {
12162     if (Target->isUnsaturatedFixedPointType()) {
12163       Expr::EvalResult Result;
12164       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
12165                                   S.isConstantEvaluated())) {
12166         llvm::APFixedPoint Value = Result.Val.getFixedPoint();
12167         llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
12168         llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T);
12169         if (Value > MaxVal || Value < MinVal) {
12170           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12171                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12172                                     << Value.toString() << T
12173                                     << E->getSourceRange()
12174                                     << clang::SourceRange(CC));
12175           return;
12176         }
12177       }
12178     } else if (Target->isIntegerType()) {
12179       Expr::EvalResult Result;
12180       if (!S.isConstantEvaluated() &&
12181           E->EvaluateAsFixedPoint(Result, S.Context,
12182                                   Expr::SE_AllowSideEffects)) {
12183         llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
12184 
12185         bool Overflowed;
12186         llvm::APSInt IntResult = FXResult.convertToInt(
12187             S.Context.getIntWidth(T),
12188             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
12189 
12190         if (Overflowed) {
12191           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12192                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12193                                     << FXResult.toString() << T
12194                                     << E->getSourceRange()
12195                                     << clang::SourceRange(CC));
12196           return;
12197         }
12198       }
12199     }
12200   } else if (Target->isUnsaturatedFixedPointType()) {
12201     if (Source->isIntegerType()) {
12202       Expr::EvalResult Result;
12203       if (!S.isConstantEvaluated() &&
12204           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
12205         llvm::APSInt Value = Result.Val.getInt();
12206 
12207         bool Overflowed;
12208         llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
12209             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
12210 
12211         if (Overflowed) {
12212           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12213                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12214                                     << Value.toString(/*Radix=*/10) << T
12215                                     << E->getSourceRange()
12216                                     << clang::SourceRange(CC));
12217           return;
12218         }
12219       }
12220     }
12221   }
12222 
12223   // If we are casting an integer type to a floating point type without
12224   // initialization-list syntax, we might lose accuracy if the floating
12225   // point type has a narrower significand than the integer type.
12226   if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
12227       TargetBT->isFloatingType() && !IsListInit) {
12228     // Determine the number of precision bits in the source integer type.
12229     IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(),
12230                                         /*Approximate*/ true);
12231     unsigned int SourcePrecision = SourceRange.Width;
12232 
12233     // Determine the number of precision bits in the
12234     // target floating point type.
12235     unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
12236         S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12237 
12238     if (SourcePrecision > 0 && TargetPrecision > 0 &&
12239         SourcePrecision > TargetPrecision) {
12240 
12241       if (Optional<llvm::APSInt> SourceInt =
12242               E->getIntegerConstantExpr(S.Context)) {
12243         // If the source integer is a constant, convert it to the target
12244         // floating point type. Issue a warning if the value changes
12245         // during the whole conversion.
12246         llvm::APFloat TargetFloatValue(
12247             S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12248         llvm::APFloat::opStatus ConversionStatus =
12249             TargetFloatValue.convertFromAPInt(
12250                 *SourceInt, SourceBT->isSignedInteger(),
12251                 llvm::APFloat::rmNearestTiesToEven);
12252 
12253         if (ConversionStatus != llvm::APFloat::opOK) {
12254           std::string PrettySourceValue = SourceInt->toString(10);
12255           SmallString<32> PrettyTargetValue;
12256           TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
12257 
12258           S.DiagRuntimeBehavior(
12259               E->getExprLoc(), E,
12260               S.PDiag(diag::warn_impcast_integer_float_precision_constant)
12261                   << PrettySourceValue << PrettyTargetValue << E->getType() << T
12262                   << E->getSourceRange() << clang::SourceRange(CC));
12263         }
12264       } else {
12265         // Otherwise, the implicit conversion may lose precision.
12266         DiagnoseImpCast(S, E, T, CC,
12267                         diag::warn_impcast_integer_float_precision);
12268       }
12269     }
12270   }
12271 
12272   DiagnoseNullConversion(S, E, T, CC);
12273 
12274   S.DiscardMisalignedMemberAddress(Target, E);
12275 
12276   if (Target->isBooleanType())
12277     DiagnoseIntInBoolContext(S, E);
12278 
12279   if (!Source->isIntegerType() || !Target->isIntegerType())
12280     return;
12281 
12282   // TODO: remove this early return once the false positives for constant->bool
12283   // in templates, macros, etc, are reduced or removed.
12284   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
12285     return;
12286 
12287   if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
12288       !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
12289     return adornObjCBoolConversionDiagWithTernaryFixit(
12290         S, E,
12291         S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
12292             << E->getType());
12293   }
12294 
12295   IntRange SourceTypeRange =
12296       IntRange::forTargetOfCanonicalType(S.Context, Source);
12297   IntRange LikelySourceRange =
12298       GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true);
12299   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
12300 
12301   if (LikelySourceRange.Width > TargetRange.Width) {
12302     // If the source is a constant, use a default-on diagnostic.
12303     // TODO: this should happen for bitfield stores, too.
12304     Expr::EvalResult Result;
12305     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
12306                          S.isConstantEvaluated())) {
12307       llvm::APSInt Value(32);
12308       Value = Result.Val.getInt();
12309 
12310       if (S.SourceMgr.isInSystemMacro(CC))
12311         return;
12312 
12313       std::string PrettySourceValue = Value.toString(10);
12314       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
12315 
12316       S.DiagRuntimeBehavior(
12317           E->getExprLoc(), E,
12318           S.PDiag(diag::warn_impcast_integer_precision_constant)
12319               << PrettySourceValue << PrettyTargetValue << E->getType() << T
12320               << E->getSourceRange() << SourceRange(CC));
12321       return;
12322     }
12323 
12324     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
12325     if (S.SourceMgr.isInSystemMacro(CC))
12326       return;
12327 
12328     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
12329       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
12330                              /* pruneControlFlow */ true);
12331     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
12332   }
12333 
12334   if (TargetRange.Width > SourceTypeRange.Width) {
12335     if (auto *UO = dyn_cast<UnaryOperator>(E))
12336       if (UO->getOpcode() == UO_Minus)
12337         if (Source->isUnsignedIntegerType()) {
12338           if (Target->isUnsignedIntegerType())
12339             return DiagnoseImpCast(S, E, T, CC,
12340                                    diag::warn_impcast_high_order_zero_bits);
12341           if (Target->isSignedIntegerType())
12342             return DiagnoseImpCast(S, E, T, CC,
12343                                    diag::warn_impcast_nonnegative_result);
12344         }
12345   }
12346 
12347   if (TargetRange.Width == LikelySourceRange.Width &&
12348       !TargetRange.NonNegative && LikelySourceRange.NonNegative &&
12349       Source->isSignedIntegerType()) {
12350     // Warn when doing a signed to signed conversion, warn if the positive
12351     // source value is exactly the width of the target type, which will
12352     // cause a negative value to be stored.
12353 
12354     Expr::EvalResult Result;
12355     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
12356         !S.SourceMgr.isInSystemMacro(CC)) {
12357       llvm::APSInt Value = Result.Val.getInt();
12358       if (isSameWidthConstantConversion(S, E, T, CC)) {
12359         std::string PrettySourceValue = Value.toString(10);
12360         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
12361 
12362         S.DiagRuntimeBehavior(
12363             E->getExprLoc(), E,
12364             S.PDiag(diag::warn_impcast_integer_precision_constant)
12365                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
12366                 << E->getSourceRange() << SourceRange(CC));
12367         return;
12368       }
12369     }
12370 
12371     // Fall through for non-constants to give a sign conversion warning.
12372   }
12373 
12374   if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) ||
12375       (!TargetRange.NonNegative && LikelySourceRange.NonNegative &&
12376        LikelySourceRange.Width == TargetRange.Width)) {
12377     if (S.SourceMgr.isInSystemMacro(CC))
12378       return;
12379 
12380     unsigned DiagID = diag::warn_impcast_integer_sign;
12381 
12382     // Traditionally, gcc has warned about this under -Wsign-compare.
12383     // We also want to warn about it in -Wconversion.
12384     // So if -Wconversion is off, use a completely identical diagnostic
12385     // in the sign-compare group.
12386     // The conditional-checking code will
12387     if (ICContext) {
12388       DiagID = diag::warn_impcast_integer_sign_conditional;
12389       *ICContext = true;
12390     }
12391 
12392     return DiagnoseImpCast(S, E, T, CC, DiagID);
12393   }
12394 
12395   // Diagnose conversions between different enumeration types.
12396   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
12397   // type, to give us better diagnostics.
12398   QualType SourceType = E->getType();
12399   if (!S.getLangOpts().CPlusPlus) {
12400     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12401       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
12402         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
12403         SourceType = S.Context.getTypeDeclType(Enum);
12404         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
12405       }
12406   }
12407 
12408   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
12409     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
12410       if (SourceEnum->getDecl()->hasNameForLinkage() &&
12411           TargetEnum->getDecl()->hasNameForLinkage() &&
12412           SourceEnum != TargetEnum) {
12413         if (S.SourceMgr.isInSystemMacro(CC))
12414           return;
12415 
12416         return DiagnoseImpCast(S, E, SourceType, T, CC,
12417                                diag::warn_impcast_different_enum_types);
12418       }
12419 }
12420 
12421 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
12422                                      SourceLocation CC, QualType T);
12423 
12424 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
12425                                     SourceLocation CC, bool &ICContext) {
12426   E = E->IgnoreParenImpCasts();
12427 
12428   if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
12429     return CheckConditionalOperator(S, CO, CC, T);
12430 
12431   AnalyzeImplicitConversions(S, E, CC);
12432   if (E->getType() != T)
12433     return CheckImplicitConversion(S, E, T, CC, &ICContext);
12434 }
12435 
12436 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
12437                                      SourceLocation CC, QualType T) {
12438   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
12439 
12440   Expr *TrueExpr = E->getTrueExpr();
12441   if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
12442     TrueExpr = BCO->getCommon();
12443 
12444   bool Suspicious = false;
12445   CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
12446   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
12447 
12448   if (T->isBooleanType())
12449     DiagnoseIntInBoolContext(S, E);
12450 
12451   // If -Wconversion would have warned about either of the candidates
12452   // for a signedness conversion to the context type...
12453   if (!Suspicious) return;
12454 
12455   // ...but it's currently ignored...
12456   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
12457     return;
12458 
12459   // ...then check whether it would have warned about either of the
12460   // candidates for a signedness conversion to the condition type.
12461   if (E->getType() == T) return;
12462 
12463   Suspicious = false;
12464   CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(),
12465                           E->getType(), CC, &Suspicious);
12466   if (!Suspicious)
12467     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
12468                             E->getType(), CC, &Suspicious);
12469 }
12470 
12471 /// Check conversion of given expression to boolean.
12472 /// Input argument E is a logical expression.
12473 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
12474   if (S.getLangOpts().Bool)
12475     return;
12476   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
12477     return;
12478   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
12479 }
12480 
12481 namespace {
12482 struct AnalyzeImplicitConversionsWorkItem {
12483   Expr *E;
12484   SourceLocation CC;
12485   bool IsListInit;
12486 };
12487 }
12488 
12489 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
12490 /// that should be visited are added to WorkList.
12491 static void AnalyzeImplicitConversions(
12492     Sema &S, AnalyzeImplicitConversionsWorkItem Item,
12493     llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
12494   Expr *OrigE = Item.E;
12495   SourceLocation CC = Item.CC;
12496 
12497   QualType T = OrigE->getType();
12498   Expr *E = OrigE->IgnoreParenImpCasts();
12499 
12500   // Propagate whether we are in a C++ list initialization expression.
12501   // If so, we do not issue warnings for implicit int-float conversion
12502   // precision loss, because C++11 narrowing already handles it.
12503   bool IsListInit = Item.IsListInit ||
12504                     (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
12505 
12506   if (E->isTypeDependent() || E->isValueDependent())
12507     return;
12508 
12509   Expr *SourceExpr = E;
12510   // Examine, but don't traverse into the source expression of an
12511   // OpaqueValueExpr, since it may have multiple parents and we don't want to
12512   // emit duplicate diagnostics. Its fine to examine the form or attempt to
12513   // evaluate it in the context of checking the specific conversion to T though.
12514   if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
12515     if (auto *Src = OVE->getSourceExpr())
12516       SourceExpr = Src;
12517 
12518   if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
12519     if (UO->getOpcode() == UO_Not &&
12520         UO->getSubExpr()->isKnownToHaveBooleanValue())
12521       S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
12522           << OrigE->getSourceRange() << T->isBooleanType()
12523           << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
12524 
12525   // For conditional operators, we analyze the arguments as if they
12526   // were being fed directly into the output.
12527   if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
12528     CheckConditionalOperator(S, CO, CC, T);
12529     return;
12530   }
12531 
12532   // Check implicit argument conversions for function calls.
12533   if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
12534     CheckImplicitArgumentConversions(S, Call, CC);
12535 
12536   // Go ahead and check any implicit conversions we might have skipped.
12537   // The non-canonical typecheck is just an optimization;
12538   // CheckImplicitConversion will filter out dead implicit conversions.
12539   if (SourceExpr->getType() != T)
12540     CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit);
12541 
12542   // Now continue drilling into this expression.
12543 
12544   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
12545     // The bound subexpressions in a PseudoObjectExpr are not reachable
12546     // as transitive children.
12547     // FIXME: Use a more uniform representation for this.
12548     for (auto *SE : POE->semantics())
12549       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
12550         WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
12551   }
12552 
12553   // Skip past explicit casts.
12554   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
12555     E = CE->getSubExpr()->IgnoreParenImpCasts();
12556     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
12557       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12558     WorkList.push_back({E, CC, IsListInit});
12559     return;
12560   }
12561 
12562   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12563     // Do a somewhat different check with comparison operators.
12564     if (BO->isComparisonOp())
12565       return AnalyzeComparison(S, BO);
12566 
12567     // And with simple assignments.
12568     if (BO->getOpcode() == BO_Assign)
12569       return AnalyzeAssignment(S, BO);
12570     // And with compound assignments.
12571     if (BO->isAssignmentOp())
12572       return AnalyzeCompoundAssignment(S, BO);
12573   }
12574 
12575   // These break the otherwise-useful invariant below.  Fortunately,
12576   // we don't really need to recurse into them, because any internal
12577   // expressions should have been analyzed already when they were
12578   // built into statements.
12579   if (isa<StmtExpr>(E)) return;
12580 
12581   // Don't descend into unevaluated contexts.
12582   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
12583 
12584   // Now just recurse over the expression's children.
12585   CC = E->getExprLoc();
12586   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
12587   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
12588   for (Stmt *SubStmt : E->children()) {
12589     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
12590     if (!ChildExpr)
12591       continue;
12592 
12593     if (IsLogicalAndOperator &&
12594         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
12595       // Ignore checking string literals that are in logical and operators.
12596       // This is a common pattern for asserts.
12597       continue;
12598     WorkList.push_back({ChildExpr, CC, IsListInit});
12599   }
12600 
12601   if (BO && BO->isLogicalOp()) {
12602     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
12603     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
12604       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
12605 
12606     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
12607     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
12608       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
12609   }
12610 
12611   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
12612     if (U->getOpcode() == UO_LNot) {
12613       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
12614     } else if (U->getOpcode() != UO_AddrOf) {
12615       if (U->getSubExpr()->getType()->isAtomicType())
12616         S.Diag(U->getSubExpr()->getBeginLoc(),
12617                diag::warn_atomic_implicit_seq_cst);
12618     }
12619   }
12620 }
12621 
12622 /// AnalyzeImplicitConversions - Find and report any interesting
12623 /// implicit conversions in the given expression.  There are a couple
12624 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
12625 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
12626                                        bool IsListInit/*= false*/) {
12627   llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
12628   WorkList.push_back({OrigE, CC, IsListInit});
12629   while (!WorkList.empty())
12630     AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
12631 }
12632 
12633 /// Diagnose integer type and any valid implicit conversion to it.
12634 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
12635   // Taking into account implicit conversions,
12636   // allow any integer.
12637   if (!E->getType()->isIntegerType()) {
12638     S.Diag(E->getBeginLoc(),
12639            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
12640     return true;
12641   }
12642   // Potentially emit standard warnings for implicit conversions if enabled
12643   // using -Wconversion.
12644   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
12645   return false;
12646 }
12647 
12648 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
12649 // Returns true when emitting a warning about taking the address of a reference.
12650 static bool CheckForReference(Sema &SemaRef, const Expr *E,
12651                               const PartialDiagnostic &PD) {
12652   E = E->IgnoreParenImpCasts();
12653 
12654   const FunctionDecl *FD = nullptr;
12655 
12656   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12657     if (!DRE->getDecl()->getType()->isReferenceType())
12658       return false;
12659   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
12660     if (!M->getMemberDecl()->getType()->isReferenceType())
12661       return false;
12662   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
12663     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
12664       return false;
12665     FD = Call->getDirectCallee();
12666   } else {
12667     return false;
12668   }
12669 
12670   SemaRef.Diag(E->getExprLoc(), PD);
12671 
12672   // If possible, point to location of function.
12673   if (FD) {
12674     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
12675   }
12676 
12677   return true;
12678 }
12679 
12680 // Returns true if the SourceLocation is expanded from any macro body.
12681 // Returns false if the SourceLocation is invalid, is from not in a macro
12682 // expansion, or is from expanded from a top-level macro argument.
12683 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
12684   if (Loc.isInvalid())
12685     return false;
12686 
12687   while (Loc.isMacroID()) {
12688     if (SM.isMacroBodyExpansion(Loc))
12689       return true;
12690     Loc = SM.getImmediateMacroCallerLoc(Loc);
12691   }
12692 
12693   return false;
12694 }
12695 
12696 /// Diagnose pointers that are always non-null.
12697 /// \param E the expression containing the pointer
12698 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
12699 /// compared to a null pointer
12700 /// \param IsEqual True when the comparison is equal to a null pointer
12701 /// \param Range Extra SourceRange to highlight in the diagnostic
12702 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
12703                                         Expr::NullPointerConstantKind NullKind,
12704                                         bool IsEqual, SourceRange Range) {
12705   if (!E)
12706     return;
12707 
12708   // Don't warn inside macros.
12709   if (E->getExprLoc().isMacroID()) {
12710     const SourceManager &SM = getSourceManager();
12711     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
12712         IsInAnyMacroBody(SM, Range.getBegin()))
12713       return;
12714   }
12715   E = E->IgnoreImpCasts();
12716 
12717   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
12718 
12719   if (isa<CXXThisExpr>(E)) {
12720     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
12721                                 : diag::warn_this_bool_conversion;
12722     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
12723     return;
12724   }
12725 
12726   bool IsAddressOf = false;
12727 
12728   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
12729     if (UO->getOpcode() != UO_AddrOf)
12730       return;
12731     IsAddressOf = true;
12732     E = UO->getSubExpr();
12733   }
12734 
12735   if (IsAddressOf) {
12736     unsigned DiagID = IsCompare
12737                           ? diag::warn_address_of_reference_null_compare
12738                           : diag::warn_address_of_reference_bool_conversion;
12739     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
12740                                          << IsEqual;
12741     if (CheckForReference(*this, E, PD)) {
12742       return;
12743     }
12744   }
12745 
12746   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
12747     bool IsParam = isa<NonNullAttr>(NonnullAttr);
12748     std::string Str;
12749     llvm::raw_string_ostream S(Str);
12750     E->printPretty(S, nullptr, getPrintingPolicy());
12751     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
12752                                 : diag::warn_cast_nonnull_to_bool;
12753     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
12754       << E->getSourceRange() << Range << IsEqual;
12755     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
12756   };
12757 
12758   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
12759   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
12760     if (auto *Callee = Call->getDirectCallee()) {
12761       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
12762         ComplainAboutNonnullParamOrCall(A);
12763         return;
12764       }
12765     }
12766   }
12767 
12768   // Expect to find a single Decl.  Skip anything more complicated.
12769   ValueDecl *D = nullptr;
12770   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
12771     D = R->getDecl();
12772   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
12773     D = M->getMemberDecl();
12774   }
12775 
12776   // Weak Decls can be null.
12777   if (!D || D->isWeak())
12778     return;
12779 
12780   // Check for parameter decl with nonnull attribute
12781   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
12782     if (getCurFunction() &&
12783         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
12784       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
12785         ComplainAboutNonnullParamOrCall(A);
12786         return;
12787       }
12788 
12789       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
12790         // Skip function template not specialized yet.
12791         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
12792           return;
12793         auto ParamIter = llvm::find(FD->parameters(), PV);
12794         assert(ParamIter != FD->param_end());
12795         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
12796 
12797         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
12798           if (!NonNull->args_size()) {
12799               ComplainAboutNonnullParamOrCall(NonNull);
12800               return;
12801           }
12802 
12803           for (const ParamIdx &ArgNo : NonNull->args()) {
12804             if (ArgNo.getASTIndex() == ParamNo) {
12805               ComplainAboutNonnullParamOrCall(NonNull);
12806               return;
12807             }
12808           }
12809         }
12810       }
12811     }
12812   }
12813 
12814   QualType T = D->getType();
12815   const bool IsArray = T->isArrayType();
12816   const bool IsFunction = T->isFunctionType();
12817 
12818   // Address of function is used to silence the function warning.
12819   if (IsAddressOf && IsFunction) {
12820     return;
12821   }
12822 
12823   // Found nothing.
12824   if (!IsAddressOf && !IsFunction && !IsArray)
12825     return;
12826 
12827   // Pretty print the expression for the diagnostic.
12828   std::string Str;
12829   llvm::raw_string_ostream S(Str);
12830   E->printPretty(S, nullptr, getPrintingPolicy());
12831 
12832   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
12833                               : diag::warn_impcast_pointer_to_bool;
12834   enum {
12835     AddressOf,
12836     FunctionPointer,
12837     ArrayPointer
12838   } DiagType;
12839   if (IsAddressOf)
12840     DiagType = AddressOf;
12841   else if (IsFunction)
12842     DiagType = FunctionPointer;
12843   else if (IsArray)
12844     DiagType = ArrayPointer;
12845   else
12846     llvm_unreachable("Could not determine diagnostic.");
12847   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
12848                                 << Range << IsEqual;
12849 
12850   if (!IsFunction)
12851     return;
12852 
12853   // Suggest '&' to silence the function warning.
12854   Diag(E->getExprLoc(), diag::note_function_warning_silence)
12855       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
12856 
12857   // Check to see if '()' fixit should be emitted.
12858   QualType ReturnType;
12859   UnresolvedSet<4> NonTemplateOverloads;
12860   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
12861   if (ReturnType.isNull())
12862     return;
12863 
12864   if (IsCompare) {
12865     // There are two cases here.  If there is null constant, the only suggest
12866     // for a pointer return type.  If the null is 0, then suggest if the return
12867     // type is a pointer or an integer type.
12868     if (!ReturnType->isPointerType()) {
12869       if (NullKind == Expr::NPCK_ZeroExpression ||
12870           NullKind == Expr::NPCK_ZeroLiteral) {
12871         if (!ReturnType->isIntegerType())
12872           return;
12873       } else {
12874         return;
12875       }
12876     }
12877   } else { // !IsCompare
12878     // For function to bool, only suggest if the function pointer has bool
12879     // return type.
12880     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
12881       return;
12882   }
12883   Diag(E->getExprLoc(), diag::note_function_to_function_call)
12884       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
12885 }
12886 
12887 /// Diagnoses "dangerous" implicit conversions within the given
12888 /// expression (which is a full expression).  Implements -Wconversion
12889 /// and -Wsign-compare.
12890 ///
12891 /// \param CC the "context" location of the implicit conversion, i.e.
12892 ///   the most location of the syntactic entity requiring the implicit
12893 ///   conversion
12894 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
12895   // Don't diagnose in unevaluated contexts.
12896   if (isUnevaluatedContext())
12897     return;
12898 
12899   // Don't diagnose for value- or type-dependent expressions.
12900   if (E->isTypeDependent() || E->isValueDependent())
12901     return;
12902 
12903   // Check for array bounds violations in cases where the check isn't triggered
12904   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
12905   // ArraySubscriptExpr is on the RHS of a variable initialization.
12906   CheckArrayAccess(E);
12907 
12908   // This is not the right CC for (e.g.) a variable initialization.
12909   AnalyzeImplicitConversions(*this, E, CC);
12910 }
12911 
12912 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
12913 /// Input argument E is a logical expression.
12914 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
12915   ::CheckBoolLikeConversion(*this, E, CC);
12916 }
12917 
12918 /// Diagnose when expression is an integer constant expression and its evaluation
12919 /// results in integer overflow
12920 void Sema::CheckForIntOverflow (Expr *E) {
12921   // Use a work list to deal with nested struct initializers.
12922   SmallVector<Expr *, 2> Exprs(1, E);
12923 
12924   do {
12925     Expr *OriginalE = Exprs.pop_back_val();
12926     Expr *E = OriginalE->IgnoreParenCasts();
12927 
12928     if (isa<BinaryOperator>(E)) {
12929       E->EvaluateForOverflow(Context);
12930       continue;
12931     }
12932 
12933     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
12934       Exprs.append(InitList->inits().begin(), InitList->inits().end());
12935     else if (isa<ObjCBoxedExpr>(OriginalE))
12936       E->EvaluateForOverflow(Context);
12937     else if (auto Call = dyn_cast<CallExpr>(E))
12938       Exprs.append(Call->arg_begin(), Call->arg_end());
12939     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
12940       Exprs.append(Message->arg_begin(), Message->arg_end());
12941   } while (!Exprs.empty());
12942 }
12943 
12944 namespace {
12945 
12946 /// Visitor for expressions which looks for unsequenced operations on the
12947 /// same object.
12948 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
12949   using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
12950 
12951   /// A tree of sequenced regions within an expression. Two regions are
12952   /// unsequenced if one is an ancestor or a descendent of the other. When we
12953   /// finish processing an expression with sequencing, such as a comma
12954   /// expression, we fold its tree nodes into its parent, since they are
12955   /// unsequenced with respect to nodes we will visit later.
12956   class SequenceTree {
12957     struct Value {
12958       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
12959       unsigned Parent : 31;
12960       unsigned Merged : 1;
12961     };
12962     SmallVector<Value, 8> Values;
12963 
12964   public:
12965     /// A region within an expression which may be sequenced with respect
12966     /// to some other region.
12967     class Seq {
12968       friend class SequenceTree;
12969 
12970       unsigned Index;
12971 
12972       explicit Seq(unsigned N) : Index(N) {}
12973 
12974     public:
12975       Seq() : Index(0) {}
12976     };
12977 
12978     SequenceTree() { Values.push_back(Value(0)); }
12979     Seq root() const { return Seq(0); }
12980 
12981     /// Create a new sequence of operations, which is an unsequenced
12982     /// subset of \p Parent. This sequence of operations is sequenced with
12983     /// respect to other children of \p Parent.
12984     Seq allocate(Seq Parent) {
12985       Values.push_back(Value(Parent.Index));
12986       return Seq(Values.size() - 1);
12987     }
12988 
12989     /// Merge a sequence of operations into its parent.
12990     void merge(Seq S) {
12991       Values[S.Index].Merged = true;
12992     }
12993 
12994     /// Determine whether two operations are unsequenced. This operation
12995     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
12996     /// should have been merged into its parent as appropriate.
12997     bool isUnsequenced(Seq Cur, Seq Old) {
12998       unsigned C = representative(Cur.Index);
12999       unsigned Target = representative(Old.Index);
13000       while (C >= Target) {
13001         if (C == Target)
13002           return true;
13003         C = Values[C].Parent;
13004       }
13005       return false;
13006     }
13007 
13008   private:
13009     /// Pick a representative for a sequence.
13010     unsigned representative(unsigned K) {
13011       if (Values[K].Merged)
13012         // Perform path compression as we go.
13013         return Values[K].Parent = representative(Values[K].Parent);
13014       return K;
13015     }
13016   };
13017 
13018   /// An object for which we can track unsequenced uses.
13019   using Object = const NamedDecl *;
13020 
13021   /// Different flavors of object usage which we track. We only track the
13022   /// least-sequenced usage of each kind.
13023   enum UsageKind {
13024     /// A read of an object. Multiple unsequenced reads are OK.
13025     UK_Use,
13026 
13027     /// A modification of an object which is sequenced before the value
13028     /// computation of the expression, such as ++n in C++.
13029     UK_ModAsValue,
13030 
13031     /// A modification of an object which is not sequenced before the value
13032     /// computation of the expression, such as n++.
13033     UK_ModAsSideEffect,
13034 
13035     UK_Count = UK_ModAsSideEffect + 1
13036   };
13037 
13038   /// Bundle together a sequencing region and the expression corresponding
13039   /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
13040   struct Usage {
13041     const Expr *UsageExpr;
13042     SequenceTree::Seq Seq;
13043 
13044     Usage() : UsageExpr(nullptr), Seq() {}
13045   };
13046 
13047   struct UsageInfo {
13048     Usage Uses[UK_Count];
13049 
13050     /// Have we issued a diagnostic for this object already?
13051     bool Diagnosed;
13052 
13053     UsageInfo() : Uses(), Diagnosed(false) {}
13054   };
13055   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
13056 
13057   Sema &SemaRef;
13058 
13059   /// Sequenced regions within the expression.
13060   SequenceTree Tree;
13061 
13062   /// Declaration modifications and references which we have seen.
13063   UsageInfoMap UsageMap;
13064 
13065   /// The region we are currently within.
13066   SequenceTree::Seq Region;
13067 
13068   /// Filled in with declarations which were modified as a side-effect
13069   /// (that is, post-increment operations).
13070   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
13071 
13072   /// Expressions to check later. We defer checking these to reduce
13073   /// stack usage.
13074   SmallVectorImpl<const Expr *> &WorkList;
13075 
13076   /// RAII object wrapping the visitation of a sequenced subexpression of an
13077   /// expression. At the end of this process, the side-effects of the evaluation
13078   /// become sequenced with respect to the value computation of the result, so
13079   /// we downgrade any UK_ModAsSideEffect within the evaluation to
13080   /// UK_ModAsValue.
13081   struct SequencedSubexpression {
13082     SequencedSubexpression(SequenceChecker &Self)
13083       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
13084       Self.ModAsSideEffect = &ModAsSideEffect;
13085     }
13086 
13087     ~SequencedSubexpression() {
13088       for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
13089         // Add a new usage with usage kind UK_ModAsValue, and then restore
13090         // the previous usage with UK_ModAsSideEffect (thus clearing it if
13091         // the previous one was empty).
13092         UsageInfo &UI = Self.UsageMap[M.first];
13093         auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
13094         Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
13095         SideEffectUsage = M.second;
13096       }
13097       Self.ModAsSideEffect = OldModAsSideEffect;
13098     }
13099 
13100     SequenceChecker &Self;
13101     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
13102     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
13103   };
13104 
13105   /// RAII object wrapping the visitation of a subexpression which we might
13106   /// choose to evaluate as a constant. If any subexpression is evaluated and
13107   /// found to be non-constant, this allows us to suppress the evaluation of
13108   /// the outer expression.
13109   class EvaluationTracker {
13110   public:
13111     EvaluationTracker(SequenceChecker &Self)
13112         : Self(Self), Prev(Self.EvalTracker) {
13113       Self.EvalTracker = this;
13114     }
13115 
13116     ~EvaluationTracker() {
13117       Self.EvalTracker = Prev;
13118       if (Prev)
13119         Prev->EvalOK &= EvalOK;
13120     }
13121 
13122     bool evaluate(const Expr *E, bool &Result) {
13123       if (!EvalOK || E->isValueDependent())
13124         return false;
13125       EvalOK = E->EvaluateAsBooleanCondition(
13126           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
13127       return EvalOK;
13128     }
13129 
13130   private:
13131     SequenceChecker &Self;
13132     EvaluationTracker *Prev;
13133     bool EvalOK = true;
13134   } *EvalTracker = nullptr;
13135 
13136   /// Find the object which is produced by the specified expression,
13137   /// if any.
13138   Object getObject(const Expr *E, bool Mod) const {
13139     E = E->IgnoreParenCasts();
13140     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13141       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
13142         return getObject(UO->getSubExpr(), Mod);
13143     } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13144       if (BO->getOpcode() == BO_Comma)
13145         return getObject(BO->getRHS(), Mod);
13146       if (Mod && BO->isAssignmentOp())
13147         return getObject(BO->getLHS(), Mod);
13148     } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13149       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
13150       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
13151         return ME->getMemberDecl();
13152     } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13153       // FIXME: If this is a reference, map through to its value.
13154       return DRE->getDecl();
13155     return nullptr;
13156   }
13157 
13158   /// Note that an object \p O was modified or used by an expression
13159   /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
13160   /// the object \p O as obtained via the \p UsageMap.
13161   void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
13162     // Get the old usage for the given object and usage kind.
13163     Usage &U = UI.Uses[UK];
13164     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
13165       // If we have a modification as side effect and are in a sequenced
13166       // subexpression, save the old Usage so that we can restore it later
13167       // in SequencedSubexpression::~SequencedSubexpression.
13168       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
13169         ModAsSideEffect->push_back(std::make_pair(O, U));
13170       // Then record the new usage with the current sequencing region.
13171       U.UsageExpr = UsageExpr;
13172       U.Seq = Region;
13173     }
13174   }
13175 
13176   /// Check whether a modification or use of an object \p O in an expression
13177   /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
13178   /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
13179   /// \p IsModMod is true when we are checking for a mod-mod unsequenced
13180   /// usage and false we are checking for a mod-use unsequenced usage.
13181   void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
13182                   UsageKind OtherKind, bool IsModMod) {
13183     if (UI.Diagnosed)
13184       return;
13185 
13186     const Usage &U = UI.Uses[OtherKind];
13187     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
13188       return;
13189 
13190     const Expr *Mod = U.UsageExpr;
13191     const Expr *ModOrUse = UsageExpr;
13192     if (OtherKind == UK_Use)
13193       std::swap(Mod, ModOrUse);
13194 
13195     SemaRef.DiagRuntimeBehavior(
13196         Mod->getExprLoc(), {Mod, ModOrUse},
13197         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
13198                                : diag::warn_unsequenced_mod_use)
13199             << O << SourceRange(ModOrUse->getExprLoc()));
13200     UI.Diagnosed = true;
13201   }
13202 
13203   // A note on note{Pre, Post}{Use, Mod}:
13204   //
13205   // (It helps to follow the algorithm with an expression such as
13206   //  "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
13207   //  operations before C++17 and both are well-defined in C++17).
13208   //
13209   // When visiting a node which uses/modify an object we first call notePreUse
13210   // or notePreMod before visiting its sub-expression(s). At this point the
13211   // children of the current node have not yet been visited and so the eventual
13212   // uses/modifications resulting from the children of the current node have not
13213   // been recorded yet.
13214   //
13215   // We then visit the children of the current node. After that notePostUse or
13216   // notePostMod is called. These will 1) detect an unsequenced modification
13217   // as side effect (as in "k++ + k") and 2) add a new usage with the
13218   // appropriate usage kind.
13219   //
13220   // We also have to be careful that some operation sequences modification as
13221   // side effect as well (for example: || or ,). To account for this we wrap
13222   // the visitation of such a sub-expression (for example: the LHS of || or ,)
13223   // with SequencedSubexpression. SequencedSubexpression is an RAII object
13224   // which record usages which are modifications as side effect, and then
13225   // downgrade them (or more accurately restore the previous usage which was a
13226   // modification as side effect) when exiting the scope of the sequenced
13227   // subexpression.
13228 
13229   void notePreUse(Object O, const Expr *UseExpr) {
13230     UsageInfo &UI = UsageMap[O];
13231     // Uses conflict with other modifications.
13232     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
13233   }
13234 
13235   void notePostUse(Object O, const Expr *UseExpr) {
13236     UsageInfo &UI = UsageMap[O];
13237     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
13238                /*IsModMod=*/false);
13239     addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
13240   }
13241 
13242   void notePreMod(Object O, const Expr *ModExpr) {
13243     UsageInfo &UI = UsageMap[O];
13244     // Modifications conflict with other modifications and with uses.
13245     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
13246     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
13247   }
13248 
13249   void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
13250     UsageInfo &UI = UsageMap[O];
13251     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
13252                /*IsModMod=*/true);
13253     addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
13254   }
13255 
13256 public:
13257   SequenceChecker(Sema &S, const Expr *E,
13258                   SmallVectorImpl<const Expr *> &WorkList)
13259       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
13260     Visit(E);
13261     // Silence a -Wunused-private-field since WorkList is now unused.
13262     // TODO: Evaluate if it can be used, and if not remove it.
13263     (void)this->WorkList;
13264   }
13265 
13266   void VisitStmt(const Stmt *S) {
13267     // Skip all statements which aren't expressions for now.
13268   }
13269 
13270   void VisitExpr(const Expr *E) {
13271     // By default, just recurse to evaluated subexpressions.
13272     Base::VisitStmt(E);
13273   }
13274 
13275   void VisitCastExpr(const CastExpr *E) {
13276     Object O = Object();
13277     if (E->getCastKind() == CK_LValueToRValue)
13278       O = getObject(E->getSubExpr(), false);
13279 
13280     if (O)
13281       notePreUse(O, E);
13282     VisitExpr(E);
13283     if (O)
13284       notePostUse(O, E);
13285   }
13286 
13287   void VisitSequencedExpressions(const Expr *SequencedBefore,
13288                                  const Expr *SequencedAfter) {
13289     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
13290     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
13291     SequenceTree::Seq OldRegion = Region;
13292 
13293     {
13294       SequencedSubexpression SeqBefore(*this);
13295       Region = BeforeRegion;
13296       Visit(SequencedBefore);
13297     }
13298 
13299     Region = AfterRegion;
13300     Visit(SequencedAfter);
13301 
13302     Region = OldRegion;
13303 
13304     Tree.merge(BeforeRegion);
13305     Tree.merge(AfterRegion);
13306   }
13307 
13308   void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
13309     // C++17 [expr.sub]p1:
13310     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
13311     //   expression E1 is sequenced before the expression E2.
13312     if (SemaRef.getLangOpts().CPlusPlus17)
13313       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
13314     else {
13315       Visit(ASE->getLHS());
13316       Visit(ASE->getRHS());
13317     }
13318   }
13319 
13320   void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
13321   void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
13322   void VisitBinPtrMem(const BinaryOperator *BO) {
13323     // C++17 [expr.mptr.oper]p4:
13324     //  Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
13325     //  the expression E1 is sequenced before the expression E2.
13326     if (SemaRef.getLangOpts().CPlusPlus17)
13327       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13328     else {
13329       Visit(BO->getLHS());
13330       Visit(BO->getRHS());
13331     }
13332   }
13333 
13334   void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
13335   void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
13336   void VisitBinShlShr(const BinaryOperator *BO) {
13337     // C++17 [expr.shift]p4:
13338     //  The expression E1 is sequenced before the expression E2.
13339     if (SemaRef.getLangOpts().CPlusPlus17)
13340       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13341     else {
13342       Visit(BO->getLHS());
13343       Visit(BO->getRHS());
13344     }
13345   }
13346 
13347   void VisitBinComma(const BinaryOperator *BO) {
13348     // C++11 [expr.comma]p1:
13349     //   Every value computation and side effect associated with the left
13350     //   expression is sequenced before every value computation and side
13351     //   effect associated with the right expression.
13352     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13353   }
13354 
13355   void VisitBinAssign(const BinaryOperator *BO) {
13356     SequenceTree::Seq RHSRegion;
13357     SequenceTree::Seq LHSRegion;
13358     if (SemaRef.getLangOpts().CPlusPlus17) {
13359       RHSRegion = Tree.allocate(Region);
13360       LHSRegion = Tree.allocate(Region);
13361     } else {
13362       RHSRegion = Region;
13363       LHSRegion = Region;
13364     }
13365     SequenceTree::Seq OldRegion = Region;
13366 
13367     // C++11 [expr.ass]p1:
13368     //  [...] the assignment is sequenced after the value computation
13369     //  of the right and left operands, [...]
13370     //
13371     // so check it before inspecting the operands and update the
13372     // map afterwards.
13373     Object O = getObject(BO->getLHS(), /*Mod=*/true);
13374     if (O)
13375       notePreMod(O, BO);
13376 
13377     if (SemaRef.getLangOpts().CPlusPlus17) {
13378       // C++17 [expr.ass]p1:
13379       //  [...] The right operand is sequenced before the left operand. [...]
13380       {
13381         SequencedSubexpression SeqBefore(*this);
13382         Region = RHSRegion;
13383         Visit(BO->getRHS());
13384       }
13385 
13386       Region = LHSRegion;
13387       Visit(BO->getLHS());
13388 
13389       if (O && isa<CompoundAssignOperator>(BO))
13390         notePostUse(O, BO);
13391 
13392     } else {
13393       // C++11 does not specify any sequencing between the LHS and RHS.
13394       Region = LHSRegion;
13395       Visit(BO->getLHS());
13396 
13397       if (O && isa<CompoundAssignOperator>(BO))
13398         notePostUse(O, BO);
13399 
13400       Region = RHSRegion;
13401       Visit(BO->getRHS());
13402     }
13403 
13404     // C++11 [expr.ass]p1:
13405     //  the assignment is sequenced [...] before the value computation of the
13406     //  assignment expression.
13407     // C11 6.5.16/3 has no such rule.
13408     Region = OldRegion;
13409     if (O)
13410       notePostMod(O, BO,
13411                   SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
13412                                                   : UK_ModAsSideEffect);
13413     if (SemaRef.getLangOpts().CPlusPlus17) {
13414       Tree.merge(RHSRegion);
13415       Tree.merge(LHSRegion);
13416     }
13417   }
13418 
13419   void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
13420     VisitBinAssign(CAO);
13421   }
13422 
13423   void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
13424   void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
13425   void VisitUnaryPreIncDec(const UnaryOperator *UO) {
13426     Object O = getObject(UO->getSubExpr(), true);
13427     if (!O)
13428       return VisitExpr(UO);
13429 
13430     notePreMod(O, UO);
13431     Visit(UO->getSubExpr());
13432     // C++11 [expr.pre.incr]p1:
13433     //   the expression ++x is equivalent to x+=1
13434     notePostMod(O, UO,
13435                 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
13436                                                 : UK_ModAsSideEffect);
13437   }
13438 
13439   void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
13440   void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
13441   void VisitUnaryPostIncDec(const UnaryOperator *UO) {
13442     Object O = getObject(UO->getSubExpr(), true);
13443     if (!O)
13444       return VisitExpr(UO);
13445 
13446     notePreMod(O, UO);
13447     Visit(UO->getSubExpr());
13448     notePostMod(O, UO, UK_ModAsSideEffect);
13449   }
13450 
13451   void VisitBinLOr(const BinaryOperator *BO) {
13452     // C++11 [expr.log.or]p2:
13453     //  If the second expression is evaluated, every value computation and
13454     //  side effect associated with the first expression is sequenced before
13455     //  every value computation and side effect associated with the
13456     //  second expression.
13457     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
13458     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
13459     SequenceTree::Seq OldRegion = Region;
13460 
13461     EvaluationTracker Eval(*this);
13462     {
13463       SequencedSubexpression Sequenced(*this);
13464       Region = LHSRegion;
13465       Visit(BO->getLHS());
13466     }
13467 
13468     // C++11 [expr.log.or]p1:
13469     //  [...] the second operand is not evaluated if the first operand
13470     //  evaluates to true.
13471     bool EvalResult = false;
13472     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
13473     bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
13474     if (ShouldVisitRHS) {
13475       Region = RHSRegion;
13476       Visit(BO->getRHS());
13477     }
13478 
13479     Region = OldRegion;
13480     Tree.merge(LHSRegion);
13481     Tree.merge(RHSRegion);
13482   }
13483 
13484   void VisitBinLAnd(const BinaryOperator *BO) {
13485     // C++11 [expr.log.and]p2:
13486     //  If the second expression is evaluated, every value computation and
13487     //  side effect associated with the first expression is sequenced before
13488     //  every value computation and side effect associated with the
13489     //  second expression.
13490     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
13491     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
13492     SequenceTree::Seq OldRegion = Region;
13493 
13494     EvaluationTracker Eval(*this);
13495     {
13496       SequencedSubexpression Sequenced(*this);
13497       Region = LHSRegion;
13498       Visit(BO->getLHS());
13499     }
13500 
13501     // C++11 [expr.log.and]p1:
13502     //  [...] the second operand is not evaluated if the first operand is false.
13503     bool EvalResult = false;
13504     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
13505     bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
13506     if (ShouldVisitRHS) {
13507       Region = RHSRegion;
13508       Visit(BO->getRHS());
13509     }
13510 
13511     Region = OldRegion;
13512     Tree.merge(LHSRegion);
13513     Tree.merge(RHSRegion);
13514   }
13515 
13516   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
13517     // C++11 [expr.cond]p1:
13518     //  [...] Every value computation and side effect associated with the first
13519     //  expression is sequenced before every value computation and side effect
13520     //  associated with the second or third expression.
13521     SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
13522 
13523     // No sequencing is specified between the true and false expression.
13524     // However since exactly one of both is going to be evaluated we can
13525     // consider them to be sequenced. This is needed to avoid warning on
13526     // something like "x ? y+= 1 : y += 2;" in the case where we will visit
13527     // both the true and false expressions because we can't evaluate x.
13528     // This will still allow us to detect an expression like (pre C++17)
13529     // "(x ? y += 1 : y += 2) = y".
13530     //
13531     // We don't wrap the visitation of the true and false expression with
13532     // SequencedSubexpression because we don't want to downgrade modifications
13533     // as side effect in the true and false expressions after the visition
13534     // is done. (for example in the expression "(x ? y++ : y++) + y" we should
13535     // not warn between the two "y++", but we should warn between the "y++"
13536     // and the "y".
13537     SequenceTree::Seq TrueRegion = Tree.allocate(Region);
13538     SequenceTree::Seq FalseRegion = Tree.allocate(Region);
13539     SequenceTree::Seq OldRegion = Region;
13540 
13541     EvaluationTracker Eval(*this);
13542     {
13543       SequencedSubexpression Sequenced(*this);
13544       Region = ConditionRegion;
13545       Visit(CO->getCond());
13546     }
13547 
13548     // C++11 [expr.cond]p1:
13549     // [...] The first expression is contextually converted to bool (Clause 4).
13550     // It is evaluated and if it is true, the result of the conditional
13551     // expression is the value of the second expression, otherwise that of the
13552     // third expression. Only one of the second and third expressions is
13553     // evaluated. [...]
13554     bool EvalResult = false;
13555     bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
13556     bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
13557     bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
13558     if (ShouldVisitTrueExpr) {
13559       Region = TrueRegion;
13560       Visit(CO->getTrueExpr());
13561     }
13562     if (ShouldVisitFalseExpr) {
13563       Region = FalseRegion;
13564       Visit(CO->getFalseExpr());
13565     }
13566 
13567     Region = OldRegion;
13568     Tree.merge(ConditionRegion);
13569     Tree.merge(TrueRegion);
13570     Tree.merge(FalseRegion);
13571   }
13572 
13573   void VisitCallExpr(const CallExpr *CE) {
13574     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
13575 
13576     if (CE->isUnevaluatedBuiltinCall(Context))
13577       return;
13578 
13579     // C++11 [intro.execution]p15:
13580     //   When calling a function [...], every value computation and side effect
13581     //   associated with any argument expression, or with the postfix expression
13582     //   designating the called function, is sequenced before execution of every
13583     //   expression or statement in the body of the function [and thus before
13584     //   the value computation of its result].
13585     SequencedSubexpression Sequenced(*this);
13586     SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
13587       // C++17 [expr.call]p5
13588       //   The postfix-expression is sequenced before each expression in the
13589       //   expression-list and any default argument. [...]
13590       SequenceTree::Seq CalleeRegion;
13591       SequenceTree::Seq OtherRegion;
13592       if (SemaRef.getLangOpts().CPlusPlus17) {
13593         CalleeRegion = Tree.allocate(Region);
13594         OtherRegion = Tree.allocate(Region);
13595       } else {
13596         CalleeRegion = Region;
13597         OtherRegion = Region;
13598       }
13599       SequenceTree::Seq OldRegion = Region;
13600 
13601       // Visit the callee expression first.
13602       Region = CalleeRegion;
13603       if (SemaRef.getLangOpts().CPlusPlus17) {
13604         SequencedSubexpression Sequenced(*this);
13605         Visit(CE->getCallee());
13606       } else {
13607         Visit(CE->getCallee());
13608       }
13609 
13610       // Then visit the argument expressions.
13611       Region = OtherRegion;
13612       for (const Expr *Argument : CE->arguments())
13613         Visit(Argument);
13614 
13615       Region = OldRegion;
13616       if (SemaRef.getLangOpts().CPlusPlus17) {
13617         Tree.merge(CalleeRegion);
13618         Tree.merge(OtherRegion);
13619       }
13620     });
13621   }
13622 
13623   void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
13624     // C++17 [over.match.oper]p2:
13625     //   [...] the operator notation is first transformed to the equivalent
13626     //   function-call notation as summarized in Table 12 (where @ denotes one
13627     //   of the operators covered in the specified subclause). However, the
13628     //   operands are sequenced in the order prescribed for the built-in
13629     //   operator (Clause 8).
13630     //
13631     // From the above only overloaded binary operators and overloaded call
13632     // operators have sequencing rules in C++17 that we need to handle
13633     // separately.
13634     if (!SemaRef.getLangOpts().CPlusPlus17 ||
13635         (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
13636       return VisitCallExpr(CXXOCE);
13637 
13638     enum {
13639       NoSequencing,
13640       LHSBeforeRHS,
13641       RHSBeforeLHS,
13642       LHSBeforeRest
13643     } SequencingKind;
13644     switch (CXXOCE->getOperator()) {
13645     case OO_Equal:
13646     case OO_PlusEqual:
13647     case OO_MinusEqual:
13648     case OO_StarEqual:
13649     case OO_SlashEqual:
13650     case OO_PercentEqual:
13651     case OO_CaretEqual:
13652     case OO_AmpEqual:
13653     case OO_PipeEqual:
13654     case OO_LessLessEqual:
13655     case OO_GreaterGreaterEqual:
13656       SequencingKind = RHSBeforeLHS;
13657       break;
13658 
13659     case OO_LessLess:
13660     case OO_GreaterGreater:
13661     case OO_AmpAmp:
13662     case OO_PipePipe:
13663     case OO_Comma:
13664     case OO_ArrowStar:
13665     case OO_Subscript:
13666       SequencingKind = LHSBeforeRHS;
13667       break;
13668 
13669     case OO_Call:
13670       SequencingKind = LHSBeforeRest;
13671       break;
13672 
13673     default:
13674       SequencingKind = NoSequencing;
13675       break;
13676     }
13677 
13678     if (SequencingKind == NoSequencing)
13679       return VisitCallExpr(CXXOCE);
13680 
13681     // This is a call, so all subexpressions are sequenced before the result.
13682     SequencedSubexpression Sequenced(*this);
13683 
13684     SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
13685       assert(SemaRef.getLangOpts().CPlusPlus17 &&
13686              "Should only get there with C++17 and above!");
13687       assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
13688              "Should only get there with an overloaded binary operator"
13689              " or an overloaded call operator!");
13690 
13691       if (SequencingKind == LHSBeforeRest) {
13692         assert(CXXOCE->getOperator() == OO_Call &&
13693                "We should only have an overloaded call operator here!");
13694 
13695         // This is very similar to VisitCallExpr, except that we only have the
13696         // C++17 case. The postfix-expression is the first argument of the
13697         // CXXOperatorCallExpr. The expressions in the expression-list, if any,
13698         // are in the following arguments.
13699         //
13700         // Note that we intentionally do not visit the callee expression since
13701         // it is just a decayed reference to a function.
13702         SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
13703         SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
13704         SequenceTree::Seq OldRegion = Region;
13705 
13706         assert(CXXOCE->getNumArgs() >= 1 &&
13707                "An overloaded call operator must have at least one argument"
13708                " for the postfix-expression!");
13709         const Expr *PostfixExpr = CXXOCE->getArgs()[0];
13710         llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
13711                                           CXXOCE->getNumArgs() - 1);
13712 
13713         // Visit the postfix-expression first.
13714         {
13715           Region = PostfixExprRegion;
13716           SequencedSubexpression Sequenced(*this);
13717           Visit(PostfixExpr);
13718         }
13719 
13720         // Then visit the argument expressions.
13721         Region = ArgsRegion;
13722         for (const Expr *Arg : Args)
13723           Visit(Arg);
13724 
13725         Region = OldRegion;
13726         Tree.merge(PostfixExprRegion);
13727         Tree.merge(ArgsRegion);
13728       } else {
13729         assert(CXXOCE->getNumArgs() == 2 &&
13730                "Should only have two arguments here!");
13731         assert((SequencingKind == LHSBeforeRHS ||
13732                 SequencingKind == RHSBeforeLHS) &&
13733                "Unexpected sequencing kind!");
13734 
13735         // We do not visit the callee expression since it is just a decayed
13736         // reference to a function.
13737         const Expr *E1 = CXXOCE->getArg(0);
13738         const Expr *E2 = CXXOCE->getArg(1);
13739         if (SequencingKind == RHSBeforeLHS)
13740           std::swap(E1, E2);
13741 
13742         return VisitSequencedExpressions(E1, E2);
13743       }
13744     });
13745   }
13746 
13747   void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
13748     // This is a call, so all subexpressions are sequenced before the result.
13749     SequencedSubexpression Sequenced(*this);
13750 
13751     if (!CCE->isListInitialization())
13752       return VisitExpr(CCE);
13753 
13754     // In C++11, list initializations are sequenced.
13755     SmallVector<SequenceTree::Seq, 32> Elts;
13756     SequenceTree::Seq Parent = Region;
13757     for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
13758                                               E = CCE->arg_end();
13759          I != E; ++I) {
13760       Region = Tree.allocate(Parent);
13761       Elts.push_back(Region);
13762       Visit(*I);
13763     }
13764 
13765     // Forget that the initializers are sequenced.
13766     Region = Parent;
13767     for (unsigned I = 0; I < Elts.size(); ++I)
13768       Tree.merge(Elts[I]);
13769   }
13770 
13771   void VisitInitListExpr(const InitListExpr *ILE) {
13772     if (!SemaRef.getLangOpts().CPlusPlus11)
13773       return VisitExpr(ILE);
13774 
13775     // In C++11, list initializations are sequenced.
13776     SmallVector<SequenceTree::Seq, 32> Elts;
13777     SequenceTree::Seq Parent = Region;
13778     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
13779       const Expr *E = ILE->getInit(I);
13780       if (!E)
13781         continue;
13782       Region = Tree.allocate(Parent);
13783       Elts.push_back(Region);
13784       Visit(E);
13785     }
13786 
13787     // Forget that the initializers are sequenced.
13788     Region = Parent;
13789     for (unsigned I = 0; I < Elts.size(); ++I)
13790       Tree.merge(Elts[I]);
13791   }
13792 };
13793 
13794 } // namespace
13795 
13796 void Sema::CheckUnsequencedOperations(const Expr *E) {
13797   SmallVector<const Expr *, 8> WorkList;
13798   WorkList.push_back(E);
13799   while (!WorkList.empty()) {
13800     const Expr *Item = WorkList.pop_back_val();
13801     SequenceChecker(*this, Item, WorkList);
13802   }
13803 }
13804 
13805 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
13806                               bool IsConstexpr) {
13807   llvm::SaveAndRestore<bool> ConstantContext(
13808       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
13809   CheckImplicitConversions(E, CheckLoc);
13810   if (!E->isInstantiationDependent())
13811     CheckUnsequencedOperations(E);
13812   if (!IsConstexpr && !E->isValueDependent())
13813     CheckForIntOverflow(E);
13814   DiagnoseMisalignedMembers();
13815 }
13816 
13817 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
13818                                        FieldDecl *BitField,
13819                                        Expr *Init) {
13820   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
13821 }
13822 
13823 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
13824                                          SourceLocation Loc) {
13825   if (!PType->isVariablyModifiedType())
13826     return;
13827   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
13828     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
13829     return;
13830   }
13831   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
13832     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
13833     return;
13834   }
13835   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
13836     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
13837     return;
13838   }
13839 
13840   const ArrayType *AT = S.Context.getAsArrayType(PType);
13841   if (!AT)
13842     return;
13843 
13844   if (AT->getSizeModifier() != ArrayType::Star) {
13845     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
13846     return;
13847   }
13848 
13849   S.Diag(Loc, diag::err_array_star_in_function_definition);
13850 }
13851 
13852 /// CheckParmsForFunctionDef - Check that the parameters of the given
13853 /// function are appropriate for the definition of a function. This
13854 /// takes care of any checks that cannot be performed on the
13855 /// declaration itself, e.g., that the types of each of the function
13856 /// parameters are complete.
13857 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
13858                                     bool CheckParameterNames) {
13859   bool HasInvalidParm = false;
13860   for (ParmVarDecl *Param : Parameters) {
13861     // C99 6.7.5.3p4: the parameters in a parameter type list in a
13862     // function declarator that is part of a function definition of
13863     // that function shall not have incomplete type.
13864     //
13865     // This is also C++ [dcl.fct]p6.
13866     if (!Param->isInvalidDecl() &&
13867         RequireCompleteType(Param->getLocation(), Param->getType(),
13868                             diag::err_typecheck_decl_incomplete_type)) {
13869       Param->setInvalidDecl();
13870       HasInvalidParm = true;
13871     }
13872 
13873     // C99 6.9.1p5: If the declarator includes a parameter type list, the
13874     // declaration of each parameter shall include an identifier.
13875     if (CheckParameterNames && Param->getIdentifier() == nullptr &&
13876         !Param->isImplicit() && !getLangOpts().CPlusPlus) {
13877       // Diagnose this as an extension in C17 and earlier.
13878       if (!getLangOpts().C2x)
13879         Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
13880     }
13881 
13882     // C99 6.7.5.3p12:
13883     //   If the function declarator is not part of a definition of that
13884     //   function, parameters may have incomplete type and may use the [*]
13885     //   notation in their sequences of declarator specifiers to specify
13886     //   variable length array types.
13887     QualType PType = Param->getOriginalType();
13888     // FIXME: This diagnostic should point the '[*]' if source-location
13889     // information is added for it.
13890     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
13891 
13892     // If the parameter is a c++ class type and it has to be destructed in the
13893     // callee function, declare the destructor so that it can be called by the
13894     // callee function. Do not perform any direct access check on the dtor here.
13895     if (!Param->isInvalidDecl()) {
13896       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
13897         if (!ClassDecl->isInvalidDecl() &&
13898             !ClassDecl->hasIrrelevantDestructor() &&
13899             !ClassDecl->isDependentContext() &&
13900             ClassDecl->isParamDestroyedInCallee()) {
13901           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
13902           MarkFunctionReferenced(Param->getLocation(), Destructor);
13903           DiagnoseUseOfDecl(Destructor, Param->getLocation());
13904         }
13905       }
13906     }
13907 
13908     // Parameters with the pass_object_size attribute only need to be marked
13909     // constant at function definitions. Because we lack information about
13910     // whether we're on a declaration or definition when we're instantiating the
13911     // attribute, we need to check for constness here.
13912     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
13913       if (!Param->getType().isConstQualified())
13914         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
13915             << Attr->getSpelling() << 1;
13916 
13917     // Check for parameter names shadowing fields from the class.
13918     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
13919       // The owning context for the parameter should be the function, but we
13920       // want to see if this function's declaration context is a record.
13921       DeclContext *DC = Param->getDeclContext();
13922       if (DC && DC->isFunctionOrMethod()) {
13923         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
13924           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
13925                                      RD, /*DeclIsField*/ false);
13926       }
13927     }
13928   }
13929 
13930   return HasInvalidParm;
13931 }
13932 
13933 Optional<std::pair<CharUnits, CharUnits>>
13934 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx);
13935 
13936 /// Compute the alignment and offset of the base class object given the
13937 /// derived-to-base cast expression and the alignment and offset of the derived
13938 /// class object.
13939 static std::pair<CharUnits, CharUnits>
13940 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
13941                                    CharUnits BaseAlignment, CharUnits Offset,
13942                                    ASTContext &Ctx) {
13943   for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
13944        ++PathI) {
13945     const CXXBaseSpecifier *Base = *PathI;
13946     const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
13947     if (Base->isVirtual()) {
13948       // The complete object may have a lower alignment than the non-virtual
13949       // alignment of the base, in which case the base may be misaligned. Choose
13950       // the smaller of the non-virtual alignment and BaseAlignment, which is a
13951       // conservative lower bound of the complete object alignment.
13952       CharUnits NonVirtualAlignment =
13953           Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment();
13954       BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
13955       Offset = CharUnits::Zero();
13956     } else {
13957       const ASTRecordLayout &RL =
13958           Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
13959       Offset += RL.getBaseClassOffset(BaseDecl);
13960     }
13961     DerivedType = Base->getType();
13962   }
13963 
13964   return std::make_pair(BaseAlignment, Offset);
13965 }
13966 
13967 /// Compute the alignment and offset of a binary additive operator.
13968 static Optional<std::pair<CharUnits, CharUnits>>
13969 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
13970                                      bool IsSub, ASTContext &Ctx) {
13971   QualType PointeeType = PtrE->getType()->getPointeeType();
13972 
13973   if (!PointeeType->isConstantSizeType())
13974     return llvm::None;
13975 
13976   auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
13977 
13978   if (!P)
13979     return llvm::None;
13980 
13981   CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
13982   if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
13983     CharUnits Offset = EltSize * IdxRes->getExtValue();
13984     if (IsSub)
13985       Offset = -Offset;
13986     return std::make_pair(P->first, P->second + Offset);
13987   }
13988 
13989   // If the integer expression isn't a constant expression, compute the lower
13990   // bound of the alignment using the alignment and offset of the pointer
13991   // expression and the element size.
13992   return std::make_pair(
13993       P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
13994       CharUnits::Zero());
13995 }
13996 
13997 /// This helper function takes an lvalue expression and returns the alignment of
13998 /// a VarDecl and a constant offset from the VarDecl.
13999 Optional<std::pair<CharUnits, CharUnits>>
14000 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) {
14001   E = E->IgnoreParens();
14002   switch (E->getStmtClass()) {
14003   default:
14004     break;
14005   case Stmt::CStyleCastExprClass:
14006   case Stmt::CXXStaticCastExprClass:
14007   case Stmt::ImplicitCastExprClass: {
14008     auto *CE = cast<CastExpr>(E);
14009     const Expr *From = CE->getSubExpr();
14010     switch (CE->getCastKind()) {
14011     default:
14012       break;
14013     case CK_NoOp:
14014       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14015     case CK_UncheckedDerivedToBase:
14016     case CK_DerivedToBase: {
14017       auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14018       if (!P)
14019         break;
14020       return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
14021                                                 P->second, Ctx);
14022     }
14023     }
14024     break;
14025   }
14026   case Stmt::ArraySubscriptExprClass: {
14027     auto *ASE = cast<ArraySubscriptExpr>(E);
14028     return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(),
14029                                                 false, Ctx);
14030   }
14031   case Stmt::DeclRefExprClass: {
14032     if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
14033       // FIXME: If VD is captured by copy or is an escaping __block variable,
14034       // use the alignment of VD's type.
14035       if (!VD->getType()->isReferenceType())
14036         return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
14037       if (VD->hasInit())
14038         return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
14039     }
14040     break;
14041   }
14042   case Stmt::MemberExprClass: {
14043     auto *ME = cast<MemberExpr>(E);
14044     auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
14045     if (!FD || FD->getType()->isReferenceType())
14046       break;
14047     Optional<std::pair<CharUnits, CharUnits>> P;
14048     if (ME->isArrow())
14049       P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
14050     else
14051       P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
14052     if (!P)
14053       break;
14054     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
14055     uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
14056     return std::make_pair(P->first,
14057                           P->second + CharUnits::fromQuantity(Offset));
14058   }
14059   case Stmt::UnaryOperatorClass: {
14060     auto *UO = cast<UnaryOperator>(E);
14061     switch (UO->getOpcode()) {
14062     default:
14063       break;
14064     case UO_Deref:
14065       return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx);
14066     }
14067     break;
14068   }
14069   case Stmt::BinaryOperatorClass: {
14070     auto *BO = cast<BinaryOperator>(E);
14071     auto Opcode = BO->getOpcode();
14072     switch (Opcode) {
14073     default:
14074       break;
14075     case BO_Comma:
14076       return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx);
14077     }
14078     break;
14079   }
14080   }
14081   return llvm::None;
14082 }
14083 
14084 /// This helper function takes a pointer expression and returns the alignment of
14085 /// a VarDecl and a constant offset from the VarDecl.
14086 Optional<std::pair<CharUnits, CharUnits>>
14087 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) {
14088   E = E->IgnoreParens();
14089   switch (E->getStmtClass()) {
14090   default:
14091     break;
14092   case Stmt::CStyleCastExprClass:
14093   case Stmt::CXXStaticCastExprClass:
14094   case Stmt::ImplicitCastExprClass: {
14095     auto *CE = cast<CastExpr>(E);
14096     const Expr *From = CE->getSubExpr();
14097     switch (CE->getCastKind()) {
14098     default:
14099       break;
14100     case CK_NoOp:
14101       return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14102     case CK_ArrayToPointerDecay:
14103       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14104     case CK_UncheckedDerivedToBase:
14105     case CK_DerivedToBase: {
14106       auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14107       if (!P)
14108         break;
14109       return getDerivedToBaseAlignmentAndOffset(
14110           CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
14111     }
14112     }
14113     break;
14114   }
14115   case Stmt::CXXThisExprClass: {
14116     auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
14117     CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment();
14118     return std::make_pair(Alignment, CharUnits::Zero());
14119   }
14120   case Stmt::UnaryOperatorClass: {
14121     auto *UO = cast<UnaryOperator>(E);
14122     if (UO->getOpcode() == UO_AddrOf)
14123       return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx);
14124     break;
14125   }
14126   case Stmt::BinaryOperatorClass: {
14127     auto *BO = cast<BinaryOperator>(E);
14128     auto Opcode = BO->getOpcode();
14129     switch (Opcode) {
14130     default:
14131       break;
14132     case BO_Add:
14133     case BO_Sub: {
14134       const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
14135       if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
14136         std::swap(LHS, RHS);
14137       return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
14138                                                   Ctx);
14139     }
14140     case BO_Comma:
14141       return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
14142     }
14143     break;
14144   }
14145   }
14146   return llvm::None;
14147 }
14148 
14149 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
14150   // See if we can compute the alignment of a VarDecl and an offset from it.
14151   Optional<std::pair<CharUnits, CharUnits>> P =
14152       getBaseAlignmentAndOffsetFromPtr(E, S.Context);
14153 
14154   if (P)
14155     return P->first.alignmentAtOffset(P->second);
14156 
14157   // If that failed, return the type's alignment.
14158   return S.Context.getTypeAlignInChars(E->getType()->getPointeeType());
14159 }
14160 
14161 /// CheckCastAlign - Implements -Wcast-align, which warns when a
14162 /// pointer cast increases the alignment requirements.
14163 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
14164   // This is actually a lot of work to potentially be doing on every
14165   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
14166   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
14167     return;
14168 
14169   // Ignore dependent types.
14170   if (T->isDependentType() || Op->getType()->isDependentType())
14171     return;
14172 
14173   // Require that the destination be a pointer type.
14174   const PointerType *DestPtr = T->getAs<PointerType>();
14175   if (!DestPtr) return;
14176 
14177   // If the destination has alignment 1, we're done.
14178   QualType DestPointee = DestPtr->getPointeeType();
14179   if (DestPointee->isIncompleteType()) return;
14180   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
14181   if (DestAlign.isOne()) return;
14182 
14183   // Require that the source be a pointer type.
14184   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
14185   if (!SrcPtr) return;
14186   QualType SrcPointee = SrcPtr->getPointeeType();
14187 
14188   // Explicitly allow casts from cv void*.  We already implicitly
14189   // allowed casts to cv void*, since they have alignment 1.
14190   // Also allow casts involving incomplete types, which implicitly
14191   // includes 'void'.
14192   if (SrcPointee->isIncompleteType()) return;
14193 
14194   CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
14195 
14196   if (SrcAlign >= DestAlign) return;
14197 
14198   Diag(TRange.getBegin(), diag::warn_cast_align)
14199     << Op->getType() << T
14200     << static_cast<unsigned>(SrcAlign.getQuantity())
14201     << static_cast<unsigned>(DestAlign.getQuantity())
14202     << TRange << Op->getSourceRange();
14203 }
14204 
14205 /// Check whether this array fits the idiom of a size-one tail padded
14206 /// array member of a struct.
14207 ///
14208 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
14209 /// commonly used to emulate flexible arrays in C89 code.
14210 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
14211                                     const NamedDecl *ND) {
14212   if (Size != 1 || !ND) return false;
14213 
14214   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
14215   if (!FD) return false;
14216 
14217   // Don't consider sizes resulting from macro expansions or template argument
14218   // substitution to form C89 tail-padded arrays.
14219 
14220   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
14221   while (TInfo) {
14222     TypeLoc TL = TInfo->getTypeLoc();
14223     // Look through typedefs.
14224     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
14225       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
14226       TInfo = TDL->getTypeSourceInfo();
14227       continue;
14228     }
14229     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
14230       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
14231       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
14232         return false;
14233     }
14234     break;
14235   }
14236 
14237   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
14238   if (!RD) return false;
14239   if (RD->isUnion()) return false;
14240   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
14241     if (!CRD->isStandardLayout()) return false;
14242   }
14243 
14244   // See if this is the last field decl in the record.
14245   const Decl *D = FD;
14246   while ((D = D->getNextDeclInContext()))
14247     if (isa<FieldDecl>(D))
14248       return false;
14249   return true;
14250 }
14251 
14252 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
14253                             const ArraySubscriptExpr *ASE,
14254                             bool AllowOnePastEnd, bool IndexNegated) {
14255   // Already diagnosed by the constant evaluator.
14256   if (isConstantEvaluated())
14257     return;
14258 
14259   IndexExpr = IndexExpr->IgnoreParenImpCasts();
14260   if (IndexExpr->isValueDependent())
14261     return;
14262 
14263   const Type *EffectiveType =
14264       BaseExpr->getType()->getPointeeOrArrayElementType();
14265   BaseExpr = BaseExpr->IgnoreParenCasts();
14266   const ConstantArrayType *ArrayTy =
14267       Context.getAsConstantArrayType(BaseExpr->getType());
14268 
14269   if (!ArrayTy)
14270     return;
14271 
14272   const Type *BaseType = ArrayTy->getElementType().getTypePtr();
14273   if (EffectiveType->isDependentType() || BaseType->isDependentType())
14274     return;
14275 
14276   Expr::EvalResult Result;
14277   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
14278     return;
14279 
14280   llvm::APSInt index = Result.Val.getInt();
14281   if (IndexNegated)
14282     index = -index;
14283 
14284   const NamedDecl *ND = nullptr;
14285   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14286     ND = DRE->getDecl();
14287   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
14288     ND = ME->getMemberDecl();
14289 
14290   if (index.isUnsigned() || !index.isNegative()) {
14291     // It is possible that the type of the base expression after
14292     // IgnoreParenCasts is incomplete, even though the type of the base
14293     // expression before IgnoreParenCasts is complete (see PR39746 for an
14294     // example). In this case we have no information about whether the array
14295     // access exceeds the array bounds. However we can still diagnose an array
14296     // access which precedes the array bounds.
14297     if (BaseType->isIncompleteType())
14298       return;
14299 
14300     llvm::APInt size = ArrayTy->getSize();
14301     if (!size.isStrictlyPositive())
14302       return;
14303 
14304     if (BaseType != EffectiveType) {
14305       // Make sure we're comparing apples to apples when comparing index to size
14306       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
14307       uint64_t array_typesize = Context.getTypeSize(BaseType);
14308       // Handle ptrarith_typesize being zero, such as when casting to void*
14309       if (!ptrarith_typesize) ptrarith_typesize = 1;
14310       if (ptrarith_typesize != array_typesize) {
14311         // There's a cast to a different size type involved
14312         uint64_t ratio = array_typesize / ptrarith_typesize;
14313         // TODO: Be smarter about handling cases where array_typesize is not a
14314         // multiple of ptrarith_typesize
14315         if (ptrarith_typesize * ratio == array_typesize)
14316           size *= llvm::APInt(size.getBitWidth(), ratio);
14317       }
14318     }
14319 
14320     if (size.getBitWidth() > index.getBitWidth())
14321       index = index.zext(size.getBitWidth());
14322     else if (size.getBitWidth() < index.getBitWidth())
14323       size = size.zext(index.getBitWidth());
14324 
14325     // For array subscripting the index must be less than size, but for pointer
14326     // arithmetic also allow the index (offset) to be equal to size since
14327     // computing the next address after the end of the array is legal and
14328     // commonly done e.g. in C++ iterators and range-based for loops.
14329     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
14330       return;
14331 
14332     // Also don't warn for arrays of size 1 which are members of some
14333     // structure. These are often used to approximate flexible arrays in C89
14334     // code.
14335     if (IsTailPaddedMemberArray(*this, size, ND))
14336       return;
14337 
14338     // Suppress the warning if the subscript expression (as identified by the
14339     // ']' location) and the index expression are both from macro expansions
14340     // within a system header.
14341     if (ASE) {
14342       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
14343           ASE->getRBracketLoc());
14344       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
14345         SourceLocation IndexLoc =
14346             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
14347         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
14348           return;
14349       }
14350     }
14351 
14352     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
14353     if (ASE)
14354       DiagID = diag::warn_array_index_exceeds_bounds;
14355 
14356     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
14357                         PDiag(DiagID) << index.toString(10, true)
14358                                       << size.toString(10, true)
14359                                       << (unsigned)size.getLimitedValue(~0U)
14360                                       << IndexExpr->getSourceRange());
14361   } else {
14362     unsigned DiagID = diag::warn_array_index_precedes_bounds;
14363     if (!ASE) {
14364       DiagID = diag::warn_ptr_arith_precedes_bounds;
14365       if (index.isNegative()) index = -index;
14366     }
14367 
14368     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
14369                         PDiag(DiagID) << index.toString(10, true)
14370                                       << IndexExpr->getSourceRange());
14371   }
14372 
14373   if (!ND) {
14374     // Try harder to find a NamedDecl to point at in the note.
14375     while (const ArraySubscriptExpr *ASE =
14376            dyn_cast<ArraySubscriptExpr>(BaseExpr))
14377       BaseExpr = ASE->getBase()->IgnoreParenCasts();
14378     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14379       ND = DRE->getDecl();
14380     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
14381       ND = ME->getMemberDecl();
14382   }
14383 
14384   if (ND)
14385     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
14386                         PDiag(diag::note_array_declared_here) << ND);
14387 }
14388 
14389 void Sema::CheckArrayAccess(const Expr *expr) {
14390   int AllowOnePastEnd = 0;
14391   while (expr) {
14392     expr = expr->IgnoreParenImpCasts();
14393     switch (expr->getStmtClass()) {
14394       case Stmt::ArraySubscriptExprClass: {
14395         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
14396         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
14397                          AllowOnePastEnd > 0);
14398         expr = ASE->getBase();
14399         break;
14400       }
14401       case Stmt::MemberExprClass: {
14402         expr = cast<MemberExpr>(expr)->getBase();
14403         break;
14404       }
14405       case Stmt::OMPArraySectionExprClass: {
14406         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
14407         if (ASE->getLowerBound())
14408           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
14409                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
14410         return;
14411       }
14412       case Stmt::UnaryOperatorClass: {
14413         // Only unwrap the * and & unary operators
14414         const UnaryOperator *UO = cast<UnaryOperator>(expr);
14415         expr = UO->getSubExpr();
14416         switch (UO->getOpcode()) {
14417           case UO_AddrOf:
14418             AllowOnePastEnd++;
14419             break;
14420           case UO_Deref:
14421             AllowOnePastEnd--;
14422             break;
14423           default:
14424             return;
14425         }
14426         break;
14427       }
14428       case Stmt::ConditionalOperatorClass: {
14429         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
14430         if (const Expr *lhs = cond->getLHS())
14431           CheckArrayAccess(lhs);
14432         if (const Expr *rhs = cond->getRHS())
14433           CheckArrayAccess(rhs);
14434         return;
14435       }
14436       case Stmt::CXXOperatorCallExprClass: {
14437         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
14438         for (const auto *Arg : OCE->arguments())
14439           CheckArrayAccess(Arg);
14440         return;
14441       }
14442       default:
14443         return;
14444     }
14445   }
14446 }
14447 
14448 //===--- CHECK: Objective-C retain cycles ----------------------------------//
14449 
14450 namespace {
14451 
14452 struct RetainCycleOwner {
14453   VarDecl *Variable = nullptr;
14454   SourceRange Range;
14455   SourceLocation Loc;
14456   bool Indirect = false;
14457 
14458   RetainCycleOwner() = default;
14459 
14460   void setLocsFrom(Expr *e) {
14461     Loc = e->getExprLoc();
14462     Range = e->getSourceRange();
14463   }
14464 };
14465 
14466 } // namespace
14467 
14468 /// Consider whether capturing the given variable can possibly lead to
14469 /// a retain cycle.
14470 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
14471   // In ARC, it's captured strongly iff the variable has __strong
14472   // lifetime.  In MRR, it's captured strongly if the variable is
14473   // __block and has an appropriate type.
14474   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
14475     return false;
14476 
14477   owner.Variable = var;
14478   if (ref)
14479     owner.setLocsFrom(ref);
14480   return true;
14481 }
14482 
14483 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
14484   while (true) {
14485     e = e->IgnoreParens();
14486     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
14487       switch (cast->getCastKind()) {
14488       case CK_BitCast:
14489       case CK_LValueBitCast:
14490       case CK_LValueToRValue:
14491       case CK_ARCReclaimReturnedObject:
14492         e = cast->getSubExpr();
14493         continue;
14494 
14495       default:
14496         return false;
14497       }
14498     }
14499 
14500     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
14501       ObjCIvarDecl *ivar = ref->getDecl();
14502       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
14503         return false;
14504 
14505       // Try to find a retain cycle in the base.
14506       if (!findRetainCycleOwner(S, ref->getBase(), owner))
14507         return false;
14508 
14509       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
14510       owner.Indirect = true;
14511       return true;
14512     }
14513 
14514     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
14515       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
14516       if (!var) return false;
14517       return considerVariable(var, ref, owner);
14518     }
14519 
14520     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
14521       if (member->isArrow()) return false;
14522 
14523       // Don't count this as an indirect ownership.
14524       e = member->getBase();
14525       continue;
14526     }
14527 
14528     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
14529       // Only pay attention to pseudo-objects on property references.
14530       ObjCPropertyRefExpr *pre
14531         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
14532                                               ->IgnoreParens());
14533       if (!pre) return false;
14534       if (pre->isImplicitProperty()) return false;
14535       ObjCPropertyDecl *property = pre->getExplicitProperty();
14536       if (!property->isRetaining() &&
14537           !(property->getPropertyIvarDecl() &&
14538             property->getPropertyIvarDecl()->getType()
14539               .getObjCLifetime() == Qualifiers::OCL_Strong))
14540           return false;
14541 
14542       owner.Indirect = true;
14543       if (pre->isSuperReceiver()) {
14544         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
14545         if (!owner.Variable)
14546           return false;
14547         owner.Loc = pre->getLocation();
14548         owner.Range = pre->getSourceRange();
14549         return true;
14550       }
14551       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
14552                               ->getSourceExpr());
14553       continue;
14554     }
14555 
14556     // Array ivars?
14557 
14558     return false;
14559   }
14560 }
14561 
14562 namespace {
14563 
14564   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
14565     ASTContext &Context;
14566     VarDecl *Variable;
14567     Expr *Capturer = nullptr;
14568     bool VarWillBeReased = false;
14569 
14570     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
14571         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
14572           Context(Context), Variable(variable) {}
14573 
14574     void VisitDeclRefExpr(DeclRefExpr *ref) {
14575       if (ref->getDecl() == Variable && !Capturer)
14576         Capturer = ref;
14577     }
14578 
14579     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
14580       if (Capturer) return;
14581       Visit(ref->getBase());
14582       if (Capturer && ref->isFreeIvar())
14583         Capturer = ref;
14584     }
14585 
14586     void VisitBlockExpr(BlockExpr *block) {
14587       // Look inside nested blocks
14588       if (block->getBlockDecl()->capturesVariable(Variable))
14589         Visit(block->getBlockDecl()->getBody());
14590     }
14591 
14592     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
14593       if (Capturer) return;
14594       if (OVE->getSourceExpr())
14595         Visit(OVE->getSourceExpr());
14596     }
14597 
14598     void VisitBinaryOperator(BinaryOperator *BinOp) {
14599       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
14600         return;
14601       Expr *LHS = BinOp->getLHS();
14602       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
14603         if (DRE->getDecl() != Variable)
14604           return;
14605         if (Expr *RHS = BinOp->getRHS()) {
14606           RHS = RHS->IgnoreParenCasts();
14607           Optional<llvm::APSInt> Value;
14608           VarWillBeReased =
14609               (RHS && (Value = RHS->getIntegerConstantExpr(Context)) &&
14610                *Value == 0);
14611         }
14612       }
14613     }
14614   };
14615 
14616 } // namespace
14617 
14618 /// Check whether the given argument is a block which captures a
14619 /// variable.
14620 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
14621   assert(owner.Variable && owner.Loc.isValid());
14622 
14623   e = e->IgnoreParenCasts();
14624 
14625   // Look through [^{...} copy] and Block_copy(^{...}).
14626   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
14627     Selector Cmd = ME->getSelector();
14628     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
14629       e = ME->getInstanceReceiver();
14630       if (!e)
14631         return nullptr;
14632       e = e->IgnoreParenCasts();
14633     }
14634   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
14635     if (CE->getNumArgs() == 1) {
14636       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
14637       if (Fn) {
14638         const IdentifierInfo *FnI = Fn->getIdentifier();
14639         if (FnI && FnI->isStr("_Block_copy")) {
14640           e = CE->getArg(0)->IgnoreParenCasts();
14641         }
14642       }
14643     }
14644   }
14645 
14646   BlockExpr *block = dyn_cast<BlockExpr>(e);
14647   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
14648     return nullptr;
14649 
14650   FindCaptureVisitor visitor(S.Context, owner.Variable);
14651   visitor.Visit(block->getBlockDecl()->getBody());
14652   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
14653 }
14654 
14655 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
14656                                 RetainCycleOwner &owner) {
14657   assert(capturer);
14658   assert(owner.Variable && owner.Loc.isValid());
14659 
14660   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
14661     << owner.Variable << capturer->getSourceRange();
14662   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
14663     << owner.Indirect << owner.Range;
14664 }
14665 
14666 /// Check for a keyword selector that starts with the word 'add' or
14667 /// 'set'.
14668 static bool isSetterLikeSelector(Selector sel) {
14669   if (sel.isUnarySelector()) return false;
14670 
14671   StringRef str = sel.getNameForSlot(0);
14672   while (!str.empty() && str.front() == '_') str = str.substr(1);
14673   if (str.startswith("set"))
14674     str = str.substr(3);
14675   else if (str.startswith("add")) {
14676     // Specially allow 'addOperationWithBlock:'.
14677     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
14678       return false;
14679     str = str.substr(3);
14680   }
14681   else
14682     return false;
14683 
14684   if (str.empty()) return true;
14685   return !isLowercase(str.front());
14686 }
14687 
14688 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
14689                                                     ObjCMessageExpr *Message) {
14690   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
14691                                                 Message->getReceiverInterface(),
14692                                                 NSAPI::ClassId_NSMutableArray);
14693   if (!IsMutableArray) {
14694     return None;
14695   }
14696 
14697   Selector Sel = Message->getSelector();
14698 
14699   Optional<NSAPI::NSArrayMethodKind> MKOpt =
14700     S.NSAPIObj->getNSArrayMethodKind(Sel);
14701   if (!MKOpt) {
14702     return None;
14703   }
14704 
14705   NSAPI::NSArrayMethodKind MK = *MKOpt;
14706 
14707   switch (MK) {
14708     case NSAPI::NSMutableArr_addObject:
14709     case NSAPI::NSMutableArr_insertObjectAtIndex:
14710     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
14711       return 0;
14712     case NSAPI::NSMutableArr_replaceObjectAtIndex:
14713       return 1;
14714 
14715     default:
14716       return None;
14717   }
14718 
14719   return None;
14720 }
14721 
14722 static
14723 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
14724                                                   ObjCMessageExpr *Message) {
14725   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
14726                                             Message->getReceiverInterface(),
14727                                             NSAPI::ClassId_NSMutableDictionary);
14728   if (!IsMutableDictionary) {
14729     return None;
14730   }
14731 
14732   Selector Sel = Message->getSelector();
14733 
14734   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
14735     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
14736   if (!MKOpt) {
14737     return None;
14738   }
14739 
14740   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
14741 
14742   switch (MK) {
14743     case NSAPI::NSMutableDict_setObjectForKey:
14744     case NSAPI::NSMutableDict_setValueForKey:
14745     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
14746       return 0;
14747 
14748     default:
14749       return None;
14750   }
14751 
14752   return None;
14753 }
14754 
14755 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
14756   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
14757                                                 Message->getReceiverInterface(),
14758                                                 NSAPI::ClassId_NSMutableSet);
14759 
14760   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
14761                                             Message->getReceiverInterface(),
14762                                             NSAPI::ClassId_NSMutableOrderedSet);
14763   if (!IsMutableSet && !IsMutableOrderedSet) {
14764     return None;
14765   }
14766 
14767   Selector Sel = Message->getSelector();
14768 
14769   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
14770   if (!MKOpt) {
14771     return None;
14772   }
14773 
14774   NSAPI::NSSetMethodKind MK = *MKOpt;
14775 
14776   switch (MK) {
14777     case NSAPI::NSMutableSet_addObject:
14778     case NSAPI::NSOrderedSet_setObjectAtIndex:
14779     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
14780     case NSAPI::NSOrderedSet_insertObjectAtIndex:
14781       return 0;
14782     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
14783       return 1;
14784   }
14785 
14786   return None;
14787 }
14788 
14789 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
14790   if (!Message->isInstanceMessage()) {
14791     return;
14792   }
14793 
14794   Optional<int> ArgOpt;
14795 
14796   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
14797       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
14798       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
14799     return;
14800   }
14801 
14802   int ArgIndex = *ArgOpt;
14803 
14804   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
14805   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
14806     Arg = OE->getSourceExpr()->IgnoreImpCasts();
14807   }
14808 
14809   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
14810     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
14811       if (ArgRE->isObjCSelfExpr()) {
14812         Diag(Message->getSourceRange().getBegin(),
14813              diag::warn_objc_circular_container)
14814           << ArgRE->getDecl() << StringRef("'super'");
14815       }
14816     }
14817   } else {
14818     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
14819 
14820     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
14821       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
14822     }
14823 
14824     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
14825       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
14826         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
14827           ValueDecl *Decl = ReceiverRE->getDecl();
14828           Diag(Message->getSourceRange().getBegin(),
14829                diag::warn_objc_circular_container)
14830             << Decl << Decl;
14831           if (!ArgRE->isObjCSelfExpr()) {
14832             Diag(Decl->getLocation(),
14833                  diag::note_objc_circular_container_declared_here)
14834               << Decl;
14835           }
14836         }
14837       }
14838     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
14839       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
14840         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
14841           ObjCIvarDecl *Decl = IvarRE->getDecl();
14842           Diag(Message->getSourceRange().getBegin(),
14843                diag::warn_objc_circular_container)
14844             << Decl << Decl;
14845           Diag(Decl->getLocation(),
14846                diag::note_objc_circular_container_declared_here)
14847             << Decl;
14848         }
14849       }
14850     }
14851   }
14852 }
14853 
14854 /// Check a message send to see if it's likely to cause a retain cycle.
14855 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
14856   // Only check instance methods whose selector looks like a setter.
14857   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
14858     return;
14859 
14860   // Try to find a variable that the receiver is strongly owned by.
14861   RetainCycleOwner owner;
14862   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
14863     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
14864       return;
14865   } else {
14866     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
14867     owner.Variable = getCurMethodDecl()->getSelfDecl();
14868     owner.Loc = msg->getSuperLoc();
14869     owner.Range = msg->getSuperLoc();
14870   }
14871 
14872   // Check whether the receiver is captured by any of the arguments.
14873   const ObjCMethodDecl *MD = msg->getMethodDecl();
14874   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
14875     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
14876       // noescape blocks should not be retained by the method.
14877       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
14878         continue;
14879       return diagnoseRetainCycle(*this, capturer, owner);
14880     }
14881   }
14882 }
14883 
14884 /// Check a property assign to see if it's likely to cause a retain cycle.
14885 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
14886   RetainCycleOwner owner;
14887   if (!findRetainCycleOwner(*this, receiver, owner))
14888     return;
14889 
14890   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
14891     diagnoseRetainCycle(*this, capturer, owner);
14892 }
14893 
14894 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
14895   RetainCycleOwner Owner;
14896   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
14897     return;
14898 
14899   // Because we don't have an expression for the variable, we have to set the
14900   // location explicitly here.
14901   Owner.Loc = Var->getLocation();
14902   Owner.Range = Var->getSourceRange();
14903 
14904   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
14905     diagnoseRetainCycle(*this, Capturer, Owner);
14906 }
14907 
14908 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
14909                                      Expr *RHS, bool isProperty) {
14910   // Check if RHS is an Objective-C object literal, which also can get
14911   // immediately zapped in a weak reference.  Note that we explicitly
14912   // allow ObjCStringLiterals, since those are designed to never really die.
14913   RHS = RHS->IgnoreParenImpCasts();
14914 
14915   // This enum needs to match with the 'select' in
14916   // warn_objc_arc_literal_assign (off-by-1).
14917   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
14918   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
14919     return false;
14920 
14921   S.Diag(Loc, diag::warn_arc_literal_assign)
14922     << (unsigned) Kind
14923     << (isProperty ? 0 : 1)
14924     << RHS->getSourceRange();
14925 
14926   return true;
14927 }
14928 
14929 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
14930                                     Qualifiers::ObjCLifetime LT,
14931                                     Expr *RHS, bool isProperty) {
14932   // Strip off any implicit cast added to get to the one ARC-specific.
14933   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
14934     if (cast->getCastKind() == CK_ARCConsumeObject) {
14935       S.Diag(Loc, diag::warn_arc_retained_assign)
14936         << (LT == Qualifiers::OCL_ExplicitNone)
14937         << (isProperty ? 0 : 1)
14938         << RHS->getSourceRange();
14939       return true;
14940     }
14941     RHS = cast->getSubExpr();
14942   }
14943 
14944   if (LT == Qualifiers::OCL_Weak &&
14945       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
14946     return true;
14947 
14948   return false;
14949 }
14950 
14951 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
14952                               QualType LHS, Expr *RHS) {
14953   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
14954 
14955   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
14956     return false;
14957 
14958   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
14959     return true;
14960 
14961   return false;
14962 }
14963 
14964 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
14965                               Expr *LHS, Expr *RHS) {
14966   QualType LHSType;
14967   // PropertyRef on LHS type need be directly obtained from
14968   // its declaration as it has a PseudoType.
14969   ObjCPropertyRefExpr *PRE
14970     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
14971   if (PRE && !PRE->isImplicitProperty()) {
14972     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
14973     if (PD)
14974       LHSType = PD->getType();
14975   }
14976 
14977   if (LHSType.isNull())
14978     LHSType = LHS->getType();
14979 
14980   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
14981 
14982   if (LT == Qualifiers::OCL_Weak) {
14983     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
14984       getCurFunction()->markSafeWeakUse(LHS);
14985   }
14986 
14987   if (checkUnsafeAssigns(Loc, LHSType, RHS))
14988     return;
14989 
14990   // FIXME. Check for other life times.
14991   if (LT != Qualifiers::OCL_None)
14992     return;
14993 
14994   if (PRE) {
14995     if (PRE->isImplicitProperty())
14996       return;
14997     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
14998     if (!PD)
14999       return;
15000 
15001     unsigned Attributes = PD->getPropertyAttributes();
15002     if (Attributes & ObjCPropertyAttribute::kind_assign) {
15003       // when 'assign' attribute was not explicitly specified
15004       // by user, ignore it and rely on property type itself
15005       // for lifetime info.
15006       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
15007       if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
15008           LHSType->isObjCRetainableType())
15009         return;
15010 
15011       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15012         if (cast->getCastKind() == CK_ARCConsumeObject) {
15013           Diag(Loc, diag::warn_arc_retained_property_assign)
15014           << RHS->getSourceRange();
15015           return;
15016         }
15017         RHS = cast->getSubExpr();
15018       }
15019     } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
15020       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
15021         return;
15022     }
15023   }
15024 }
15025 
15026 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
15027 
15028 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
15029                                         SourceLocation StmtLoc,
15030                                         const NullStmt *Body) {
15031   // Do not warn if the body is a macro that expands to nothing, e.g:
15032   //
15033   // #define CALL(x)
15034   // if (condition)
15035   //   CALL(0);
15036   if (Body->hasLeadingEmptyMacro())
15037     return false;
15038 
15039   // Get line numbers of statement and body.
15040   bool StmtLineInvalid;
15041   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
15042                                                       &StmtLineInvalid);
15043   if (StmtLineInvalid)
15044     return false;
15045 
15046   bool BodyLineInvalid;
15047   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
15048                                                       &BodyLineInvalid);
15049   if (BodyLineInvalid)
15050     return false;
15051 
15052   // Warn if null statement and body are on the same line.
15053   if (StmtLine != BodyLine)
15054     return false;
15055 
15056   return true;
15057 }
15058 
15059 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
15060                                  const Stmt *Body,
15061                                  unsigned DiagID) {
15062   // Since this is a syntactic check, don't emit diagnostic for template
15063   // instantiations, this just adds noise.
15064   if (CurrentInstantiationScope)
15065     return;
15066 
15067   // The body should be a null statement.
15068   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15069   if (!NBody)
15070     return;
15071 
15072   // Do the usual checks.
15073   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15074     return;
15075 
15076   Diag(NBody->getSemiLoc(), DiagID);
15077   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15078 }
15079 
15080 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
15081                                  const Stmt *PossibleBody) {
15082   assert(!CurrentInstantiationScope); // Ensured by caller
15083 
15084   SourceLocation StmtLoc;
15085   const Stmt *Body;
15086   unsigned DiagID;
15087   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
15088     StmtLoc = FS->getRParenLoc();
15089     Body = FS->getBody();
15090     DiagID = diag::warn_empty_for_body;
15091   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
15092     StmtLoc = WS->getCond()->getSourceRange().getEnd();
15093     Body = WS->getBody();
15094     DiagID = diag::warn_empty_while_body;
15095   } else
15096     return; // Neither `for' nor `while'.
15097 
15098   // The body should be a null statement.
15099   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15100   if (!NBody)
15101     return;
15102 
15103   // Skip expensive checks if diagnostic is disabled.
15104   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
15105     return;
15106 
15107   // Do the usual checks.
15108   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15109     return;
15110 
15111   // `for(...);' and `while(...);' are popular idioms, so in order to keep
15112   // noise level low, emit diagnostics only if for/while is followed by a
15113   // CompoundStmt, e.g.:
15114   //    for (int i = 0; i < n; i++);
15115   //    {
15116   //      a(i);
15117   //    }
15118   // or if for/while is followed by a statement with more indentation
15119   // than for/while itself:
15120   //    for (int i = 0; i < n; i++);
15121   //      a(i);
15122   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
15123   if (!ProbableTypo) {
15124     bool BodyColInvalid;
15125     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
15126         PossibleBody->getBeginLoc(), &BodyColInvalid);
15127     if (BodyColInvalid)
15128       return;
15129 
15130     bool StmtColInvalid;
15131     unsigned StmtCol =
15132         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
15133     if (StmtColInvalid)
15134       return;
15135 
15136     if (BodyCol > StmtCol)
15137       ProbableTypo = true;
15138   }
15139 
15140   if (ProbableTypo) {
15141     Diag(NBody->getSemiLoc(), DiagID);
15142     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15143   }
15144 }
15145 
15146 //===--- CHECK: Warn on self move with std::move. -------------------------===//
15147 
15148 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
15149 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
15150                              SourceLocation OpLoc) {
15151   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
15152     return;
15153 
15154   if (inTemplateInstantiation())
15155     return;
15156 
15157   // Strip parens and casts away.
15158   LHSExpr = LHSExpr->IgnoreParenImpCasts();
15159   RHSExpr = RHSExpr->IgnoreParenImpCasts();
15160 
15161   // Check for a call expression
15162   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
15163   if (!CE || CE->getNumArgs() != 1)
15164     return;
15165 
15166   // Check for a call to std::move
15167   if (!CE->isCallToStdMove())
15168     return;
15169 
15170   // Get argument from std::move
15171   RHSExpr = CE->getArg(0);
15172 
15173   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
15174   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
15175 
15176   // Two DeclRefExpr's, check that the decls are the same.
15177   if (LHSDeclRef && RHSDeclRef) {
15178     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15179       return;
15180     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15181         RHSDeclRef->getDecl()->getCanonicalDecl())
15182       return;
15183 
15184     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15185                                         << LHSExpr->getSourceRange()
15186                                         << RHSExpr->getSourceRange();
15187     return;
15188   }
15189 
15190   // Member variables require a different approach to check for self moves.
15191   // MemberExpr's are the same if every nested MemberExpr refers to the same
15192   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
15193   // the base Expr's are CXXThisExpr's.
15194   const Expr *LHSBase = LHSExpr;
15195   const Expr *RHSBase = RHSExpr;
15196   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
15197   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
15198   if (!LHSME || !RHSME)
15199     return;
15200 
15201   while (LHSME && RHSME) {
15202     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
15203         RHSME->getMemberDecl()->getCanonicalDecl())
15204       return;
15205 
15206     LHSBase = LHSME->getBase();
15207     RHSBase = RHSME->getBase();
15208     LHSME = dyn_cast<MemberExpr>(LHSBase);
15209     RHSME = dyn_cast<MemberExpr>(RHSBase);
15210   }
15211 
15212   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
15213   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
15214   if (LHSDeclRef && RHSDeclRef) {
15215     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15216       return;
15217     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15218         RHSDeclRef->getDecl()->getCanonicalDecl())
15219       return;
15220 
15221     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15222                                         << LHSExpr->getSourceRange()
15223                                         << RHSExpr->getSourceRange();
15224     return;
15225   }
15226 
15227   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
15228     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15229                                         << LHSExpr->getSourceRange()
15230                                         << RHSExpr->getSourceRange();
15231 }
15232 
15233 //===--- Layout compatibility ----------------------------------------------//
15234 
15235 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
15236 
15237 /// Check if two enumeration types are layout-compatible.
15238 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
15239   // C++11 [dcl.enum] p8:
15240   // Two enumeration types are layout-compatible if they have the same
15241   // underlying type.
15242   return ED1->isComplete() && ED2->isComplete() &&
15243          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
15244 }
15245 
15246 /// Check if two fields are layout-compatible.
15247 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
15248                                FieldDecl *Field2) {
15249   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
15250     return false;
15251 
15252   if (Field1->isBitField() != Field2->isBitField())
15253     return false;
15254 
15255   if (Field1->isBitField()) {
15256     // Make sure that the bit-fields are the same length.
15257     unsigned Bits1 = Field1->getBitWidthValue(C);
15258     unsigned Bits2 = Field2->getBitWidthValue(C);
15259 
15260     if (Bits1 != Bits2)
15261       return false;
15262   }
15263 
15264   return true;
15265 }
15266 
15267 /// Check if two standard-layout structs are layout-compatible.
15268 /// (C++11 [class.mem] p17)
15269 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
15270                                      RecordDecl *RD2) {
15271   // If both records are C++ classes, check that base classes match.
15272   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
15273     // If one of records is a CXXRecordDecl we are in C++ mode,
15274     // thus the other one is a CXXRecordDecl, too.
15275     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
15276     // Check number of base classes.
15277     if (D1CXX->getNumBases() != D2CXX->getNumBases())
15278       return false;
15279 
15280     // Check the base classes.
15281     for (CXXRecordDecl::base_class_const_iterator
15282                Base1 = D1CXX->bases_begin(),
15283            BaseEnd1 = D1CXX->bases_end(),
15284               Base2 = D2CXX->bases_begin();
15285          Base1 != BaseEnd1;
15286          ++Base1, ++Base2) {
15287       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
15288         return false;
15289     }
15290   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
15291     // If only RD2 is a C++ class, it should have zero base classes.
15292     if (D2CXX->getNumBases() > 0)
15293       return false;
15294   }
15295 
15296   // Check the fields.
15297   RecordDecl::field_iterator Field2 = RD2->field_begin(),
15298                              Field2End = RD2->field_end(),
15299                              Field1 = RD1->field_begin(),
15300                              Field1End = RD1->field_end();
15301   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
15302     if (!isLayoutCompatible(C, *Field1, *Field2))
15303       return false;
15304   }
15305   if (Field1 != Field1End || Field2 != Field2End)
15306     return false;
15307 
15308   return true;
15309 }
15310 
15311 /// Check if two standard-layout unions are layout-compatible.
15312 /// (C++11 [class.mem] p18)
15313 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
15314                                     RecordDecl *RD2) {
15315   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
15316   for (auto *Field2 : RD2->fields())
15317     UnmatchedFields.insert(Field2);
15318 
15319   for (auto *Field1 : RD1->fields()) {
15320     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
15321         I = UnmatchedFields.begin(),
15322         E = UnmatchedFields.end();
15323 
15324     for ( ; I != E; ++I) {
15325       if (isLayoutCompatible(C, Field1, *I)) {
15326         bool Result = UnmatchedFields.erase(*I);
15327         (void) Result;
15328         assert(Result);
15329         break;
15330       }
15331     }
15332     if (I == E)
15333       return false;
15334   }
15335 
15336   return UnmatchedFields.empty();
15337 }
15338 
15339 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
15340                                RecordDecl *RD2) {
15341   if (RD1->isUnion() != RD2->isUnion())
15342     return false;
15343 
15344   if (RD1->isUnion())
15345     return isLayoutCompatibleUnion(C, RD1, RD2);
15346   else
15347     return isLayoutCompatibleStruct(C, RD1, RD2);
15348 }
15349 
15350 /// Check if two types are layout-compatible in C++11 sense.
15351 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
15352   if (T1.isNull() || T2.isNull())
15353     return false;
15354 
15355   // C++11 [basic.types] p11:
15356   // If two types T1 and T2 are the same type, then T1 and T2 are
15357   // layout-compatible types.
15358   if (C.hasSameType(T1, T2))
15359     return true;
15360 
15361   T1 = T1.getCanonicalType().getUnqualifiedType();
15362   T2 = T2.getCanonicalType().getUnqualifiedType();
15363 
15364   const Type::TypeClass TC1 = T1->getTypeClass();
15365   const Type::TypeClass TC2 = T2->getTypeClass();
15366 
15367   if (TC1 != TC2)
15368     return false;
15369 
15370   if (TC1 == Type::Enum) {
15371     return isLayoutCompatible(C,
15372                               cast<EnumType>(T1)->getDecl(),
15373                               cast<EnumType>(T2)->getDecl());
15374   } else if (TC1 == Type::Record) {
15375     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
15376       return false;
15377 
15378     return isLayoutCompatible(C,
15379                               cast<RecordType>(T1)->getDecl(),
15380                               cast<RecordType>(T2)->getDecl());
15381   }
15382 
15383   return false;
15384 }
15385 
15386 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
15387 
15388 /// Given a type tag expression find the type tag itself.
15389 ///
15390 /// \param TypeExpr Type tag expression, as it appears in user's code.
15391 ///
15392 /// \param VD Declaration of an identifier that appears in a type tag.
15393 ///
15394 /// \param MagicValue Type tag magic value.
15395 ///
15396 /// \param isConstantEvaluated wether the evalaution should be performed in
15397 
15398 /// constant context.
15399 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
15400                             const ValueDecl **VD, uint64_t *MagicValue,
15401                             bool isConstantEvaluated) {
15402   while(true) {
15403     if (!TypeExpr)
15404       return false;
15405 
15406     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
15407 
15408     switch (TypeExpr->getStmtClass()) {
15409     case Stmt::UnaryOperatorClass: {
15410       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
15411       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
15412         TypeExpr = UO->getSubExpr();
15413         continue;
15414       }
15415       return false;
15416     }
15417 
15418     case Stmt::DeclRefExprClass: {
15419       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
15420       *VD = DRE->getDecl();
15421       return true;
15422     }
15423 
15424     case Stmt::IntegerLiteralClass: {
15425       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
15426       llvm::APInt MagicValueAPInt = IL->getValue();
15427       if (MagicValueAPInt.getActiveBits() <= 64) {
15428         *MagicValue = MagicValueAPInt.getZExtValue();
15429         return true;
15430       } else
15431         return false;
15432     }
15433 
15434     case Stmt::BinaryConditionalOperatorClass:
15435     case Stmt::ConditionalOperatorClass: {
15436       const AbstractConditionalOperator *ACO =
15437           cast<AbstractConditionalOperator>(TypeExpr);
15438       bool Result;
15439       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
15440                                                      isConstantEvaluated)) {
15441         if (Result)
15442           TypeExpr = ACO->getTrueExpr();
15443         else
15444           TypeExpr = ACO->getFalseExpr();
15445         continue;
15446       }
15447       return false;
15448     }
15449 
15450     case Stmt::BinaryOperatorClass: {
15451       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
15452       if (BO->getOpcode() == BO_Comma) {
15453         TypeExpr = BO->getRHS();
15454         continue;
15455       }
15456       return false;
15457     }
15458 
15459     default:
15460       return false;
15461     }
15462   }
15463 }
15464 
15465 /// Retrieve the C type corresponding to type tag TypeExpr.
15466 ///
15467 /// \param TypeExpr Expression that specifies a type tag.
15468 ///
15469 /// \param MagicValues Registered magic values.
15470 ///
15471 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
15472 ///        kind.
15473 ///
15474 /// \param TypeInfo Information about the corresponding C type.
15475 ///
15476 /// \param isConstantEvaluated wether the evalaution should be performed in
15477 /// constant context.
15478 ///
15479 /// \returns true if the corresponding C type was found.
15480 static bool GetMatchingCType(
15481     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
15482     const ASTContext &Ctx,
15483     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
15484         *MagicValues,
15485     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
15486     bool isConstantEvaluated) {
15487   FoundWrongKind = false;
15488 
15489   // Variable declaration that has type_tag_for_datatype attribute.
15490   const ValueDecl *VD = nullptr;
15491 
15492   uint64_t MagicValue;
15493 
15494   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
15495     return false;
15496 
15497   if (VD) {
15498     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
15499       if (I->getArgumentKind() != ArgumentKind) {
15500         FoundWrongKind = true;
15501         return false;
15502       }
15503       TypeInfo.Type = I->getMatchingCType();
15504       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
15505       TypeInfo.MustBeNull = I->getMustBeNull();
15506       return true;
15507     }
15508     return false;
15509   }
15510 
15511   if (!MagicValues)
15512     return false;
15513 
15514   llvm::DenseMap<Sema::TypeTagMagicValue,
15515                  Sema::TypeTagData>::const_iterator I =
15516       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
15517   if (I == MagicValues->end())
15518     return false;
15519 
15520   TypeInfo = I->second;
15521   return true;
15522 }
15523 
15524 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
15525                                       uint64_t MagicValue, QualType Type,
15526                                       bool LayoutCompatible,
15527                                       bool MustBeNull) {
15528   if (!TypeTagForDatatypeMagicValues)
15529     TypeTagForDatatypeMagicValues.reset(
15530         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
15531 
15532   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
15533   (*TypeTagForDatatypeMagicValues)[Magic] =
15534       TypeTagData(Type, LayoutCompatible, MustBeNull);
15535 }
15536 
15537 static bool IsSameCharType(QualType T1, QualType T2) {
15538   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
15539   if (!BT1)
15540     return false;
15541 
15542   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
15543   if (!BT2)
15544     return false;
15545 
15546   BuiltinType::Kind T1Kind = BT1->getKind();
15547   BuiltinType::Kind T2Kind = BT2->getKind();
15548 
15549   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
15550          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
15551          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
15552          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
15553 }
15554 
15555 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
15556                                     const ArrayRef<const Expr *> ExprArgs,
15557                                     SourceLocation CallSiteLoc) {
15558   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
15559   bool IsPointerAttr = Attr->getIsPointer();
15560 
15561   // Retrieve the argument representing the 'type_tag'.
15562   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
15563   if (TypeTagIdxAST >= ExprArgs.size()) {
15564     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
15565         << 0 << Attr->getTypeTagIdx().getSourceIndex();
15566     return;
15567   }
15568   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
15569   bool FoundWrongKind;
15570   TypeTagData TypeInfo;
15571   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
15572                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
15573                         TypeInfo, isConstantEvaluated())) {
15574     if (FoundWrongKind)
15575       Diag(TypeTagExpr->getExprLoc(),
15576            diag::warn_type_tag_for_datatype_wrong_kind)
15577         << TypeTagExpr->getSourceRange();
15578     return;
15579   }
15580 
15581   // Retrieve the argument representing the 'arg_idx'.
15582   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
15583   if (ArgumentIdxAST >= ExprArgs.size()) {
15584     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
15585         << 1 << Attr->getArgumentIdx().getSourceIndex();
15586     return;
15587   }
15588   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
15589   if (IsPointerAttr) {
15590     // Skip implicit cast of pointer to `void *' (as a function argument).
15591     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
15592       if (ICE->getType()->isVoidPointerType() &&
15593           ICE->getCastKind() == CK_BitCast)
15594         ArgumentExpr = ICE->getSubExpr();
15595   }
15596   QualType ArgumentType = ArgumentExpr->getType();
15597 
15598   // Passing a `void*' pointer shouldn't trigger a warning.
15599   if (IsPointerAttr && ArgumentType->isVoidPointerType())
15600     return;
15601 
15602   if (TypeInfo.MustBeNull) {
15603     // Type tag with matching void type requires a null pointer.
15604     if (!ArgumentExpr->isNullPointerConstant(Context,
15605                                              Expr::NPC_ValueDependentIsNotNull)) {
15606       Diag(ArgumentExpr->getExprLoc(),
15607            diag::warn_type_safety_null_pointer_required)
15608           << ArgumentKind->getName()
15609           << ArgumentExpr->getSourceRange()
15610           << TypeTagExpr->getSourceRange();
15611     }
15612     return;
15613   }
15614 
15615   QualType RequiredType = TypeInfo.Type;
15616   if (IsPointerAttr)
15617     RequiredType = Context.getPointerType(RequiredType);
15618 
15619   bool mismatch = false;
15620   if (!TypeInfo.LayoutCompatible) {
15621     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
15622 
15623     // C++11 [basic.fundamental] p1:
15624     // Plain char, signed char, and unsigned char are three distinct types.
15625     //
15626     // But we treat plain `char' as equivalent to `signed char' or `unsigned
15627     // char' depending on the current char signedness mode.
15628     if (mismatch)
15629       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
15630                                            RequiredType->getPointeeType())) ||
15631           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
15632         mismatch = false;
15633   } else
15634     if (IsPointerAttr)
15635       mismatch = !isLayoutCompatible(Context,
15636                                      ArgumentType->getPointeeType(),
15637                                      RequiredType->getPointeeType());
15638     else
15639       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
15640 
15641   if (mismatch)
15642     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
15643         << ArgumentType << ArgumentKind
15644         << TypeInfo.LayoutCompatible << RequiredType
15645         << ArgumentExpr->getSourceRange()
15646         << TypeTagExpr->getSourceRange();
15647 }
15648 
15649 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
15650                                          CharUnits Alignment) {
15651   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
15652 }
15653 
15654 void Sema::DiagnoseMisalignedMembers() {
15655   for (MisalignedMember &m : MisalignedMembers) {
15656     const NamedDecl *ND = m.RD;
15657     if (ND->getName().empty()) {
15658       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
15659         ND = TD;
15660     }
15661     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
15662         << m.MD << ND << m.E->getSourceRange();
15663   }
15664   MisalignedMembers.clear();
15665 }
15666 
15667 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
15668   E = E->IgnoreParens();
15669   if (!T->isPointerType() && !T->isIntegerType())
15670     return;
15671   if (isa<UnaryOperator>(E) &&
15672       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
15673     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
15674     if (isa<MemberExpr>(Op)) {
15675       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
15676       if (MA != MisalignedMembers.end() &&
15677           (T->isIntegerType() ||
15678            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
15679                                    Context.getTypeAlignInChars(
15680                                        T->getPointeeType()) <= MA->Alignment))))
15681         MisalignedMembers.erase(MA);
15682     }
15683   }
15684 }
15685 
15686 void Sema::RefersToMemberWithReducedAlignment(
15687     Expr *E,
15688     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
15689         Action) {
15690   const auto *ME = dyn_cast<MemberExpr>(E);
15691   if (!ME)
15692     return;
15693 
15694   // No need to check expressions with an __unaligned-qualified type.
15695   if (E->getType().getQualifiers().hasUnaligned())
15696     return;
15697 
15698   // For a chain of MemberExpr like "a.b.c.d" this list
15699   // will keep FieldDecl's like [d, c, b].
15700   SmallVector<FieldDecl *, 4> ReverseMemberChain;
15701   const MemberExpr *TopME = nullptr;
15702   bool AnyIsPacked = false;
15703   do {
15704     QualType BaseType = ME->getBase()->getType();
15705     if (BaseType->isDependentType())
15706       return;
15707     if (ME->isArrow())
15708       BaseType = BaseType->getPointeeType();
15709     RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
15710     if (RD->isInvalidDecl())
15711       return;
15712 
15713     ValueDecl *MD = ME->getMemberDecl();
15714     auto *FD = dyn_cast<FieldDecl>(MD);
15715     // We do not care about non-data members.
15716     if (!FD || FD->isInvalidDecl())
15717       return;
15718 
15719     AnyIsPacked =
15720         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
15721     ReverseMemberChain.push_back(FD);
15722 
15723     TopME = ME;
15724     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
15725   } while (ME);
15726   assert(TopME && "We did not compute a topmost MemberExpr!");
15727 
15728   // Not the scope of this diagnostic.
15729   if (!AnyIsPacked)
15730     return;
15731 
15732   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
15733   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
15734   // TODO: The innermost base of the member expression may be too complicated.
15735   // For now, just disregard these cases. This is left for future
15736   // improvement.
15737   if (!DRE && !isa<CXXThisExpr>(TopBase))
15738       return;
15739 
15740   // Alignment expected by the whole expression.
15741   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
15742 
15743   // No need to do anything else with this case.
15744   if (ExpectedAlignment.isOne())
15745     return;
15746 
15747   // Synthesize offset of the whole access.
15748   CharUnits Offset;
15749   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
15750        I++) {
15751     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
15752   }
15753 
15754   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
15755   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
15756       ReverseMemberChain.back()->getParent()->getTypeForDecl());
15757 
15758   // The base expression of the innermost MemberExpr may give
15759   // stronger guarantees than the class containing the member.
15760   if (DRE && !TopME->isArrow()) {
15761     const ValueDecl *VD = DRE->getDecl();
15762     if (!VD->getType()->isReferenceType())
15763       CompleteObjectAlignment =
15764           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
15765   }
15766 
15767   // Check if the synthesized offset fulfills the alignment.
15768   if (Offset % ExpectedAlignment != 0 ||
15769       // It may fulfill the offset it but the effective alignment may still be
15770       // lower than the expected expression alignment.
15771       CompleteObjectAlignment < ExpectedAlignment) {
15772     // If this happens, we want to determine a sensible culprit of this.
15773     // Intuitively, watching the chain of member expressions from right to
15774     // left, we start with the required alignment (as required by the field
15775     // type) but some packed attribute in that chain has reduced the alignment.
15776     // It may happen that another packed structure increases it again. But if
15777     // we are here such increase has not been enough. So pointing the first
15778     // FieldDecl that either is packed or else its RecordDecl is,
15779     // seems reasonable.
15780     FieldDecl *FD = nullptr;
15781     CharUnits Alignment;
15782     for (FieldDecl *FDI : ReverseMemberChain) {
15783       if (FDI->hasAttr<PackedAttr>() ||
15784           FDI->getParent()->hasAttr<PackedAttr>()) {
15785         FD = FDI;
15786         Alignment = std::min(
15787             Context.getTypeAlignInChars(FD->getType()),
15788             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
15789         break;
15790       }
15791     }
15792     assert(FD && "We did not find a packed FieldDecl!");
15793     Action(E, FD->getParent(), FD, Alignment);
15794   }
15795 }
15796 
15797 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
15798   using namespace std::placeholders;
15799 
15800   RefersToMemberWithReducedAlignment(
15801       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
15802                      _2, _3, _4));
15803 }
15804 
15805 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall,
15806                                             ExprResult CallResult) {
15807   if (checkArgCount(*this, TheCall, 1))
15808     return ExprError();
15809 
15810   ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
15811   if (MatrixArg.isInvalid())
15812     return MatrixArg;
15813   Expr *Matrix = MatrixArg.get();
15814 
15815   auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
15816   if (!MType) {
15817     Diag(Matrix->getBeginLoc(), diag::err_builtin_matrix_arg);
15818     return ExprError();
15819   }
15820 
15821   // Create returned matrix type by swapping rows and columns of the argument
15822   // matrix type.
15823   QualType ResultType = Context.getConstantMatrixType(
15824       MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
15825 
15826   // Change the return type to the type of the returned matrix.
15827   TheCall->setType(ResultType);
15828 
15829   // Update call argument to use the possibly converted matrix argument.
15830   TheCall->setArg(0, Matrix);
15831   return CallResult;
15832 }
15833 
15834 // Get and verify the matrix dimensions.
15835 static llvm::Optional<unsigned>
15836 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {
15837   SourceLocation ErrorPos;
15838   Optional<llvm::APSInt> Value =
15839       Expr->getIntegerConstantExpr(S.Context, &ErrorPos);
15840   if (!Value) {
15841     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
15842         << Name;
15843     return {};
15844   }
15845   uint64_t Dim = Value->getZExtValue();
15846   if (!ConstantMatrixType::isDimensionValid(Dim)) {
15847     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
15848         << Name << ConstantMatrixType::getMaxElementsPerDimension();
15849     return {};
15850   }
15851   return Dim;
15852 }
15853 
15854 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
15855                                                   ExprResult CallResult) {
15856   if (!getLangOpts().MatrixTypes) {
15857     Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
15858     return ExprError();
15859   }
15860 
15861   if (checkArgCount(*this, TheCall, 4))
15862     return ExprError();
15863 
15864   unsigned PtrArgIdx = 0;
15865   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
15866   Expr *RowsExpr = TheCall->getArg(1);
15867   Expr *ColumnsExpr = TheCall->getArg(2);
15868   Expr *StrideExpr = TheCall->getArg(3);
15869 
15870   bool ArgError = false;
15871 
15872   // Check pointer argument.
15873   {
15874     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
15875     if (PtrConv.isInvalid())
15876       return PtrConv;
15877     PtrExpr = PtrConv.get();
15878     TheCall->setArg(0, PtrExpr);
15879     if (PtrExpr->isTypeDependent()) {
15880       TheCall->setType(Context.DependentTy);
15881       return TheCall;
15882     }
15883   }
15884 
15885   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
15886   QualType ElementTy;
15887   if (!PtrTy) {
15888     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
15889         << PtrArgIdx + 1;
15890     ArgError = true;
15891   } else {
15892     ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
15893 
15894     if (!ConstantMatrixType::isValidElementType(ElementTy)) {
15895       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
15896           << PtrArgIdx + 1;
15897       ArgError = true;
15898     }
15899   }
15900 
15901   // Apply default Lvalue conversions and convert the expression to size_t.
15902   auto ApplyArgumentConversions = [this](Expr *E) {
15903     ExprResult Conv = DefaultLvalueConversion(E);
15904     if (Conv.isInvalid())
15905       return Conv;
15906 
15907     return tryConvertExprToType(Conv.get(), Context.getSizeType());
15908   };
15909 
15910   // Apply conversion to row and column expressions.
15911   ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
15912   if (!RowsConv.isInvalid()) {
15913     RowsExpr = RowsConv.get();
15914     TheCall->setArg(1, RowsExpr);
15915   } else
15916     RowsExpr = nullptr;
15917 
15918   ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
15919   if (!ColumnsConv.isInvalid()) {
15920     ColumnsExpr = ColumnsConv.get();
15921     TheCall->setArg(2, ColumnsExpr);
15922   } else
15923     ColumnsExpr = nullptr;
15924 
15925   // If any any part of the result matrix type is still pending, just use
15926   // Context.DependentTy, until all parts are resolved.
15927   if ((RowsExpr && RowsExpr->isTypeDependent()) ||
15928       (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
15929     TheCall->setType(Context.DependentTy);
15930     return CallResult;
15931   }
15932 
15933   // Check row and column dimenions.
15934   llvm::Optional<unsigned> MaybeRows;
15935   if (RowsExpr)
15936     MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
15937 
15938   llvm::Optional<unsigned> MaybeColumns;
15939   if (ColumnsExpr)
15940     MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
15941 
15942   // Check stride argument.
15943   ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
15944   if (StrideConv.isInvalid())
15945     return ExprError();
15946   StrideExpr = StrideConv.get();
15947   TheCall->setArg(3, StrideExpr);
15948 
15949   if (MaybeRows) {
15950     if (Optional<llvm::APSInt> Value =
15951             StrideExpr->getIntegerConstantExpr(Context)) {
15952       uint64_t Stride = Value->getZExtValue();
15953       if (Stride < *MaybeRows) {
15954         Diag(StrideExpr->getBeginLoc(),
15955              diag::err_builtin_matrix_stride_too_small);
15956         ArgError = true;
15957       }
15958     }
15959   }
15960 
15961   if (ArgError || !MaybeRows || !MaybeColumns)
15962     return ExprError();
15963 
15964   TheCall->setType(
15965       Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
15966   return CallResult;
15967 }
15968 
15969 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
15970                                                    ExprResult CallResult) {
15971   if (checkArgCount(*this, TheCall, 3))
15972     return ExprError();
15973 
15974   unsigned PtrArgIdx = 1;
15975   Expr *MatrixExpr = TheCall->getArg(0);
15976   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
15977   Expr *StrideExpr = TheCall->getArg(2);
15978 
15979   bool ArgError = false;
15980 
15981   {
15982     ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
15983     if (MatrixConv.isInvalid())
15984       return MatrixConv;
15985     MatrixExpr = MatrixConv.get();
15986     TheCall->setArg(0, MatrixExpr);
15987   }
15988   if (MatrixExpr->isTypeDependent()) {
15989     TheCall->setType(Context.DependentTy);
15990     return TheCall;
15991   }
15992 
15993   auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
15994   if (!MatrixTy) {
15995     Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_matrix_arg) << 0;
15996     ArgError = true;
15997   }
15998 
15999   {
16000     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
16001     if (PtrConv.isInvalid())
16002       return PtrConv;
16003     PtrExpr = PtrConv.get();
16004     TheCall->setArg(1, PtrExpr);
16005     if (PtrExpr->isTypeDependent()) {
16006       TheCall->setType(Context.DependentTy);
16007       return TheCall;
16008     }
16009   }
16010 
16011   // Check pointer argument.
16012   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16013   if (!PtrTy) {
16014     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
16015         << PtrArgIdx + 1;
16016     ArgError = true;
16017   } else {
16018     QualType ElementTy = PtrTy->getPointeeType();
16019     if (ElementTy.isConstQualified()) {
16020       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
16021       ArgError = true;
16022     }
16023     ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
16024     if (MatrixTy &&
16025         !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
16026       Diag(PtrExpr->getBeginLoc(),
16027            diag::err_builtin_matrix_pointer_arg_mismatch)
16028           << ElementTy << MatrixTy->getElementType();
16029       ArgError = true;
16030     }
16031   }
16032 
16033   // Apply default Lvalue conversions and convert the stride expression to
16034   // size_t.
16035   {
16036     ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
16037     if (StrideConv.isInvalid())
16038       return StrideConv;
16039 
16040     StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
16041     if (StrideConv.isInvalid())
16042       return StrideConv;
16043     StrideExpr = StrideConv.get();
16044     TheCall->setArg(2, StrideExpr);
16045   }
16046 
16047   // Check stride argument.
16048   if (MatrixTy) {
16049     if (Optional<llvm::APSInt> Value =
16050             StrideExpr->getIntegerConstantExpr(Context)) {
16051       uint64_t Stride = Value->getZExtValue();
16052       if (Stride < MatrixTy->getNumRows()) {
16053         Diag(StrideExpr->getBeginLoc(),
16054              diag::err_builtin_matrix_stride_too_small);
16055         ArgError = true;
16056       }
16057     }
16058   }
16059 
16060   if (ArgError)
16061     return ExprError();
16062 
16063   return CallResult;
16064 }
16065 
16066 /// \brief Enforce the bounds of a TCB
16067 /// CheckTCBEnforcement - Enforces that every function in a named TCB only
16068 /// directly calls other functions in the same TCB as marked by the enforce_tcb
16069 /// and enforce_tcb_leaf attributes.
16070 void Sema::CheckTCBEnforcement(const CallExpr *TheCall,
16071                                const FunctionDecl *Callee) {
16072   const FunctionDecl *Caller = getCurFunctionDecl();
16073 
16074   // Calls to builtins are not enforced.
16075   if (!Caller || !Caller->hasAttr<EnforceTCBAttr>() ||
16076       Callee->getBuiltinID() != 0)
16077     return;
16078 
16079   // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
16080   // all TCBs the callee is a part of.
16081   llvm::StringSet<> CalleeTCBs;
16082   for_each(Callee->specific_attrs<EnforceTCBAttr>(),
16083            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
16084   for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(),
16085            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
16086 
16087   // Go through the TCBs the caller is a part of and emit warnings if Caller
16088   // is in a TCB that the Callee is not.
16089   for_each(
16090       Caller->specific_attrs<EnforceTCBAttr>(),
16091       [&](const auto *A) {
16092         StringRef CallerTCB = A->getTCBName();
16093         if (CalleeTCBs.count(CallerTCB) == 0) {
16094           this->Diag(TheCall->getExprLoc(),
16095                      diag::warn_tcb_enforcement_violation) << Callee
16096                                                            << CallerTCB;
16097         }
16098       });
16099 }
16100