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   case llvm::Triple::riscv32:
1433   case llvm::Triple::riscv64:
1434     return CheckRISCVBuiltinFunctionCall(TI, BuiltinID, TheCall);
1435   }
1436 }
1437 
1438 ExprResult
1439 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
1440                                CallExpr *TheCall) {
1441   ExprResult TheCallResult(TheCall);
1442 
1443   // Find out if any arguments are required to be integer constant expressions.
1444   unsigned ICEArguments = 0;
1445   ASTContext::GetBuiltinTypeError Error;
1446   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
1447   if (Error != ASTContext::GE_None)
1448     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
1449 
1450   // If any arguments are required to be ICE's, check and diagnose.
1451   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
1452     // Skip arguments not required to be ICE's.
1453     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
1454 
1455     llvm::APSInt Result;
1456     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
1457       return true;
1458     ICEArguments &= ~(1 << ArgNo);
1459   }
1460 
1461   switch (BuiltinID) {
1462   case Builtin::BI__builtin___CFStringMakeConstantString:
1463     assert(TheCall->getNumArgs() == 1 &&
1464            "Wrong # arguments to builtin CFStringMakeConstantString");
1465     if (CheckObjCString(TheCall->getArg(0)))
1466       return ExprError();
1467     break;
1468   case Builtin::BI__builtin_ms_va_start:
1469   case Builtin::BI__builtin_stdarg_start:
1470   case Builtin::BI__builtin_va_start:
1471     if (SemaBuiltinVAStart(BuiltinID, TheCall))
1472       return ExprError();
1473     break;
1474   case Builtin::BI__va_start: {
1475     switch (Context.getTargetInfo().getTriple().getArch()) {
1476     case llvm::Triple::aarch64:
1477     case llvm::Triple::arm:
1478     case llvm::Triple::thumb:
1479       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
1480         return ExprError();
1481       break;
1482     default:
1483       if (SemaBuiltinVAStart(BuiltinID, TheCall))
1484         return ExprError();
1485       break;
1486     }
1487     break;
1488   }
1489 
1490   // The acquire, release, and no fence variants are ARM and AArch64 only.
1491   case Builtin::BI_interlockedbittestandset_acq:
1492   case Builtin::BI_interlockedbittestandset_rel:
1493   case Builtin::BI_interlockedbittestandset_nf:
1494   case Builtin::BI_interlockedbittestandreset_acq:
1495   case Builtin::BI_interlockedbittestandreset_rel:
1496   case Builtin::BI_interlockedbittestandreset_nf:
1497     if (CheckBuiltinTargetSupport(
1498             *this, BuiltinID, TheCall,
1499             {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
1500       return ExprError();
1501     break;
1502 
1503   // The 64-bit bittest variants are x64, ARM, and AArch64 only.
1504   case Builtin::BI_bittest64:
1505   case Builtin::BI_bittestandcomplement64:
1506   case Builtin::BI_bittestandreset64:
1507   case Builtin::BI_bittestandset64:
1508   case Builtin::BI_interlockedbittestandreset64:
1509   case Builtin::BI_interlockedbittestandset64:
1510     if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
1511                                   {llvm::Triple::x86_64, llvm::Triple::arm,
1512                                    llvm::Triple::thumb, llvm::Triple::aarch64}))
1513       return ExprError();
1514     break;
1515 
1516   case Builtin::BI__builtin_isgreater:
1517   case Builtin::BI__builtin_isgreaterequal:
1518   case Builtin::BI__builtin_isless:
1519   case Builtin::BI__builtin_islessequal:
1520   case Builtin::BI__builtin_islessgreater:
1521   case Builtin::BI__builtin_isunordered:
1522     if (SemaBuiltinUnorderedCompare(TheCall))
1523       return ExprError();
1524     break;
1525   case Builtin::BI__builtin_fpclassify:
1526     if (SemaBuiltinFPClassification(TheCall, 6))
1527       return ExprError();
1528     break;
1529   case Builtin::BI__builtin_isfinite:
1530   case Builtin::BI__builtin_isinf:
1531   case Builtin::BI__builtin_isinf_sign:
1532   case Builtin::BI__builtin_isnan:
1533   case Builtin::BI__builtin_isnormal:
1534   case Builtin::BI__builtin_signbit:
1535   case Builtin::BI__builtin_signbitf:
1536   case Builtin::BI__builtin_signbitl:
1537     if (SemaBuiltinFPClassification(TheCall, 1))
1538       return ExprError();
1539     break;
1540   case Builtin::BI__builtin_shufflevector:
1541     return SemaBuiltinShuffleVector(TheCall);
1542     // TheCall will be freed by the smart pointer here, but that's fine, since
1543     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1544   case Builtin::BI__builtin_prefetch:
1545     if (SemaBuiltinPrefetch(TheCall))
1546       return ExprError();
1547     break;
1548   case Builtin::BI__builtin_alloca_with_align:
1549     if (SemaBuiltinAllocaWithAlign(TheCall))
1550       return ExprError();
1551     LLVM_FALLTHROUGH;
1552   case Builtin::BI__builtin_alloca:
1553     Diag(TheCall->getBeginLoc(), diag::warn_alloca)
1554         << TheCall->getDirectCallee();
1555     break;
1556   case Builtin::BI__assume:
1557   case Builtin::BI__builtin_assume:
1558     if (SemaBuiltinAssume(TheCall))
1559       return ExprError();
1560     break;
1561   case Builtin::BI__builtin_assume_aligned:
1562     if (SemaBuiltinAssumeAligned(TheCall))
1563       return ExprError();
1564     break;
1565   case Builtin::BI__builtin_dynamic_object_size:
1566   case Builtin::BI__builtin_object_size:
1567     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1568       return ExprError();
1569     break;
1570   case Builtin::BI__builtin_longjmp:
1571     if (SemaBuiltinLongjmp(TheCall))
1572       return ExprError();
1573     break;
1574   case Builtin::BI__builtin_setjmp:
1575     if (SemaBuiltinSetjmp(TheCall))
1576       return ExprError();
1577     break;
1578   case Builtin::BI__builtin_classify_type:
1579     if (checkArgCount(*this, TheCall, 1)) return true;
1580     TheCall->setType(Context.IntTy);
1581     break;
1582   case Builtin::BI__builtin_complex:
1583     if (SemaBuiltinComplex(TheCall))
1584       return ExprError();
1585     break;
1586   case Builtin::BI__builtin_constant_p: {
1587     if (checkArgCount(*this, TheCall, 1)) return true;
1588     ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
1589     if (Arg.isInvalid()) return true;
1590     TheCall->setArg(0, Arg.get());
1591     TheCall->setType(Context.IntTy);
1592     break;
1593   }
1594   case Builtin::BI__builtin_launder:
1595     return SemaBuiltinLaunder(*this, TheCall);
1596   case Builtin::BI__sync_fetch_and_add:
1597   case Builtin::BI__sync_fetch_and_add_1:
1598   case Builtin::BI__sync_fetch_and_add_2:
1599   case Builtin::BI__sync_fetch_and_add_4:
1600   case Builtin::BI__sync_fetch_and_add_8:
1601   case Builtin::BI__sync_fetch_and_add_16:
1602   case Builtin::BI__sync_fetch_and_sub:
1603   case Builtin::BI__sync_fetch_and_sub_1:
1604   case Builtin::BI__sync_fetch_and_sub_2:
1605   case Builtin::BI__sync_fetch_and_sub_4:
1606   case Builtin::BI__sync_fetch_and_sub_8:
1607   case Builtin::BI__sync_fetch_and_sub_16:
1608   case Builtin::BI__sync_fetch_and_or:
1609   case Builtin::BI__sync_fetch_and_or_1:
1610   case Builtin::BI__sync_fetch_and_or_2:
1611   case Builtin::BI__sync_fetch_and_or_4:
1612   case Builtin::BI__sync_fetch_and_or_8:
1613   case Builtin::BI__sync_fetch_and_or_16:
1614   case Builtin::BI__sync_fetch_and_and:
1615   case Builtin::BI__sync_fetch_and_and_1:
1616   case Builtin::BI__sync_fetch_and_and_2:
1617   case Builtin::BI__sync_fetch_and_and_4:
1618   case Builtin::BI__sync_fetch_and_and_8:
1619   case Builtin::BI__sync_fetch_and_and_16:
1620   case Builtin::BI__sync_fetch_and_xor:
1621   case Builtin::BI__sync_fetch_and_xor_1:
1622   case Builtin::BI__sync_fetch_and_xor_2:
1623   case Builtin::BI__sync_fetch_and_xor_4:
1624   case Builtin::BI__sync_fetch_and_xor_8:
1625   case Builtin::BI__sync_fetch_and_xor_16:
1626   case Builtin::BI__sync_fetch_and_nand:
1627   case Builtin::BI__sync_fetch_and_nand_1:
1628   case Builtin::BI__sync_fetch_and_nand_2:
1629   case Builtin::BI__sync_fetch_and_nand_4:
1630   case Builtin::BI__sync_fetch_and_nand_8:
1631   case Builtin::BI__sync_fetch_and_nand_16:
1632   case Builtin::BI__sync_add_and_fetch:
1633   case Builtin::BI__sync_add_and_fetch_1:
1634   case Builtin::BI__sync_add_and_fetch_2:
1635   case Builtin::BI__sync_add_and_fetch_4:
1636   case Builtin::BI__sync_add_and_fetch_8:
1637   case Builtin::BI__sync_add_and_fetch_16:
1638   case Builtin::BI__sync_sub_and_fetch:
1639   case Builtin::BI__sync_sub_and_fetch_1:
1640   case Builtin::BI__sync_sub_and_fetch_2:
1641   case Builtin::BI__sync_sub_and_fetch_4:
1642   case Builtin::BI__sync_sub_and_fetch_8:
1643   case Builtin::BI__sync_sub_and_fetch_16:
1644   case Builtin::BI__sync_and_and_fetch:
1645   case Builtin::BI__sync_and_and_fetch_1:
1646   case Builtin::BI__sync_and_and_fetch_2:
1647   case Builtin::BI__sync_and_and_fetch_4:
1648   case Builtin::BI__sync_and_and_fetch_8:
1649   case Builtin::BI__sync_and_and_fetch_16:
1650   case Builtin::BI__sync_or_and_fetch:
1651   case Builtin::BI__sync_or_and_fetch_1:
1652   case Builtin::BI__sync_or_and_fetch_2:
1653   case Builtin::BI__sync_or_and_fetch_4:
1654   case Builtin::BI__sync_or_and_fetch_8:
1655   case Builtin::BI__sync_or_and_fetch_16:
1656   case Builtin::BI__sync_xor_and_fetch:
1657   case Builtin::BI__sync_xor_and_fetch_1:
1658   case Builtin::BI__sync_xor_and_fetch_2:
1659   case Builtin::BI__sync_xor_and_fetch_4:
1660   case Builtin::BI__sync_xor_and_fetch_8:
1661   case Builtin::BI__sync_xor_and_fetch_16:
1662   case Builtin::BI__sync_nand_and_fetch:
1663   case Builtin::BI__sync_nand_and_fetch_1:
1664   case Builtin::BI__sync_nand_and_fetch_2:
1665   case Builtin::BI__sync_nand_and_fetch_4:
1666   case Builtin::BI__sync_nand_and_fetch_8:
1667   case Builtin::BI__sync_nand_and_fetch_16:
1668   case Builtin::BI__sync_val_compare_and_swap:
1669   case Builtin::BI__sync_val_compare_and_swap_1:
1670   case Builtin::BI__sync_val_compare_and_swap_2:
1671   case Builtin::BI__sync_val_compare_and_swap_4:
1672   case Builtin::BI__sync_val_compare_and_swap_8:
1673   case Builtin::BI__sync_val_compare_and_swap_16:
1674   case Builtin::BI__sync_bool_compare_and_swap:
1675   case Builtin::BI__sync_bool_compare_and_swap_1:
1676   case Builtin::BI__sync_bool_compare_and_swap_2:
1677   case Builtin::BI__sync_bool_compare_and_swap_4:
1678   case Builtin::BI__sync_bool_compare_and_swap_8:
1679   case Builtin::BI__sync_bool_compare_and_swap_16:
1680   case Builtin::BI__sync_lock_test_and_set:
1681   case Builtin::BI__sync_lock_test_and_set_1:
1682   case Builtin::BI__sync_lock_test_and_set_2:
1683   case Builtin::BI__sync_lock_test_and_set_4:
1684   case Builtin::BI__sync_lock_test_and_set_8:
1685   case Builtin::BI__sync_lock_test_and_set_16:
1686   case Builtin::BI__sync_lock_release:
1687   case Builtin::BI__sync_lock_release_1:
1688   case Builtin::BI__sync_lock_release_2:
1689   case Builtin::BI__sync_lock_release_4:
1690   case Builtin::BI__sync_lock_release_8:
1691   case Builtin::BI__sync_lock_release_16:
1692   case Builtin::BI__sync_swap:
1693   case Builtin::BI__sync_swap_1:
1694   case Builtin::BI__sync_swap_2:
1695   case Builtin::BI__sync_swap_4:
1696   case Builtin::BI__sync_swap_8:
1697   case Builtin::BI__sync_swap_16:
1698     return SemaBuiltinAtomicOverloaded(TheCallResult);
1699   case Builtin::BI__sync_synchronize:
1700     Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1701         << TheCall->getCallee()->getSourceRange();
1702     break;
1703   case Builtin::BI__builtin_nontemporal_load:
1704   case Builtin::BI__builtin_nontemporal_store:
1705     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1706   case Builtin::BI__builtin_memcpy_inline: {
1707     clang::Expr *SizeOp = TheCall->getArg(2);
1708     // We warn about copying to or from `nullptr` pointers when `size` is
1709     // greater than 0. When `size` is value dependent we cannot evaluate its
1710     // value so we bail out.
1711     if (SizeOp->isValueDependent())
1712       break;
1713     if (!SizeOp->EvaluateKnownConstInt(Context).isNullValue()) {
1714       CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
1715       CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
1716     }
1717     break;
1718   }
1719 #define BUILTIN(ID, TYPE, ATTRS)
1720 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1721   case Builtin::BI##ID: \
1722     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1723 #include "clang/Basic/Builtins.def"
1724   case Builtin::BI__annotation:
1725     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1726       return ExprError();
1727     break;
1728   case Builtin::BI__builtin_annotation:
1729     if (SemaBuiltinAnnotation(*this, TheCall))
1730       return ExprError();
1731     break;
1732   case Builtin::BI__builtin_addressof:
1733     if (SemaBuiltinAddressof(*this, TheCall))
1734       return ExprError();
1735     break;
1736   case Builtin::BI__builtin_is_aligned:
1737   case Builtin::BI__builtin_align_up:
1738   case Builtin::BI__builtin_align_down:
1739     if (SemaBuiltinAlignment(*this, TheCall, BuiltinID))
1740       return ExprError();
1741     break;
1742   case Builtin::BI__builtin_add_overflow:
1743   case Builtin::BI__builtin_sub_overflow:
1744   case Builtin::BI__builtin_mul_overflow:
1745     if (SemaBuiltinOverflow(*this, TheCall, BuiltinID))
1746       return ExprError();
1747     break;
1748   case Builtin::BI__builtin_operator_new:
1749   case Builtin::BI__builtin_operator_delete: {
1750     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1751     ExprResult Res =
1752         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1753     if (Res.isInvalid())
1754       CorrectDelayedTyposInExpr(TheCallResult.get());
1755     return Res;
1756   }
1757   case Builtin::BI__builtin_dump_struct: {
1758     // We first want to ensure we are called with 2 arguments
1759     if (checkArgCount(*this, TheCall, 2))
1760       return ExprError();
1761     // Ensure that the first argument is of type 'struct XX *'
1762     const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1763     const QualType PtrArgType = PtrArg->getType();
1764     if (!PtrArgType->isPointerType() ||
1765         !PtrArgType->getPointeeType()->isRecordType()) {
1766       Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1767           << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1768           << "structure pointer";
1769       return ExprError();
1770     }
1771 
1772     // Ensure that the second argument is of type 'FunctionType'
1773     const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1774     const QualType FnPtrArgType = FnPtrArg->getType();
1775     if (!FnPtrArgType->isPointerType()) {
1776       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1777           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1778           << FnPtrArgType << "'int (*)(const char *, ...)'";
1779       return ExprError();
1780     }
1781 
1782     const auto *FuncType =
1783         FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1784 
1785     if (!FuncType) {
1786       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1787           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1788           << FnPtrArgType << "'int (*)(const char *, ...)'";
1789       return ExprError();
1790     }
1791 
1792     if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1793       if (!FT->getNumParams()) {
1794         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1795             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1796             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1797         return ExprError();
1798       }
1799       QualType PT = FT->getParamType(0);
1800       if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1801           !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1802           !PT->getPointeeType().isConstQualified()) {
1803         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1804             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1805             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1806         return ExprError();
1807       }
1808     }
1809 
1810     TheCall->setType(Context.IntTy);
1811     break;
1812   }
1813   case Builtin::BI__builtin_expect_with_probability: {
1814     // We first want to ensure we are called with 3 arguments
1815     if (checkArgCount(*this, TheCall, 3))
1816       return ExprError();
1817     // then check probability is constant float in range [0.0, 1.0]
1818     const Expr *ProbArg = TheCall->getArg(2);
1819     SmallVector<PartialDiagnosticAt, 8> Notes;
1820     Expr::EvalResult Eval;
1821     Eval.Diag = &Notes;
1822     if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
1823         !Eval.Val.isFloat()) {
1824       Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
1825           << ProbArg->getSourceRange();
1826       for (const PartialDiagnosticAt &PDiag : Notes)
1827         Diag(PDiag.first, PDiag.second);
1828       return ExprError();
1829     }
1830     llvm::APFloat Probability = Eval.Val.getFloat();
1831     bool LoseInfo = false;
1832     Probability.convert(llvm::APFloat::IEEEdouble(),
1833                         llvm::RoundingMode::Dynamic, &LoseInfo);
1834     if (!(Probability >= llvm::APFloat(0.0) &&
1835           Probability <= llvm::APFloat(1.0))) {
1836       Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
1837           << ProbArg->getSourceRange();
1838       return ExprError();
1839     }
1840     break;
1841   }
1842   case Builtin::BI__builtin_preserve_access_index:
1843     if (SemaBuiltinPreserveAI(*this, TheCall))
1844       return ExprError();
1845     break;
1846   case Builtin::BI__builtin_call_with_static_chain:
1847     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1848       return ExprError();
1849     break;
1850   case Builtin::BI__exception_code:
1851   case Builtin::BI_exception_code:
1852     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1853                                  diag::err_seh___except_block))
1854       return ExprError();
1855     break;
1856   case Builtin::BI__exception_info:
1857   case Builtin::BI_exception_info:
1858     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1859                                  diag::err_seh___except_filter))
1860       return ExprError();
1861     break;
1862   case Builtin::BI__GetExceptionInfo:
1863     if (checkArgCount(*this, TheCall, 1))
1864       return ExprError();
1865 
1866     if (CheckCXXThrowOperand(
1867             TheCall->getBeginLoc(),
1868             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1869             TheCall))
1870       return ExprError();
1871 
1872     TheCall->setType(Context.VoidPtrTy);
1873     break;
1874   // OpenCL v2.0, s6.13.16 - Pipe functions
1875   case Builtin::BIread_pipe:
1876   case Builtin::BIwrite_pipe:
1877     // Since those two functions are declared with var args, we need a semantic
1878     // check for the argument.
1879     if (SemaBuiltinRWPipe(*this, TheCall))
1880       return ExprError();
1881     break;
1882   case Builtin::BIreserve_read_pipe:
1883   case Builtin::BIreserve_write_pipe:
1884   case Builtin::BIwork_group_reserve_read_pipe:
1885   case Builtin::BIwork_group_reserve_write_pipe:
1886     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1887       return ExprError();
1888     break;
1889   case Builtin::BIsub_group_reserve_read_pipe:
1890   case Builtin::BIsub_group_reserve_write_pipe:
1891     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1892         SemaBuiltinReserveRWPipe(*this, TheCall))
1893       return ExprError();
1894     break;
1895   case Builtin::BIcommit_read_pipe:
1896   case Builtin::BIcommit_write_pipe:
1897   case Builtin::BIwork_group_commit_read_pipe:
1898   case Builtin::BIwork_group_commit_write_pipe:
1899     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1900       return ExprError();
1901     break;
1902   case Builtin::BIsub_group_commit_read_pipe:
1903   case Builtin::BIsub_group_commit_write_pipe:
1904     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1905         SemaBuiltinCommitRWPipe(*this, TheCall))
1906       return ExprError();
1907     break;
1908   case Builtin::BIget_pipe_num_packets:
1909   case Builtin::BIget_pipe_max_packets:
1910     if (SemaBuiltinPipePackets(*this, TheCall))
1911       return ExprError();
1912     break;
1913   case Builtin::BIto_global:
1914   case Builtin::BIto_local:
1915   case Builtin::BIto_private:
1916     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1917       return ExprError();
1918     break;
1919   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1920   case Builtin::BIenqueue_kernel:
1921     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1922       return ExprError();
1923     break;
1924   case Builtin::BIget_kernel_work_group_size:
1925   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1926     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1927       return ExprError();
1928     break;
1929   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1930   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1931     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1932       return ExprError();
1933     break;
1934   case Builtin::BI__builtin_os_log_format:
1935     Cleanup.setExprNeedsCleanups(true);
1936     LLVM_FALLTHROUGH;
1937   case Builtin::BI__builtin_os_log_format_buffer_size:
1938     if (SemaBuiltinOSLogFormat(TheCall))
1939       return ExprError();
1940     break;
1941   case Builtin::BI__builtin_frame_address:
1942   case Builtin::BI__builtin_return_address: {
1943     if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
1944       return ExprError();
1945 
1946     // -Wframe-address warning if non-zero passed to builtin
1947     // return/frame address.
1948     Expr::EvalResult Result;
1949     if (!TheCall->getArg(0)->isValueDependent() &&
1950         TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
1951         Result.Val.getInt() != 0)
1952       Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
1953           << ((BuiltinID == Builtin::BI__builtin_return_address)
1954                   ? "__builtin_return_address"
1955                   : "__builtin_frame_address")
1956           << TheCall->getSourceRange();
1957     break;
1958   }
1959 
1960   case Builtin::BI__builtin_matrix_transpose:
1961     return SemaBuiltinMatrixTranspose(TheCall, TheCallResult);
1962 
1963   case Builtin::BI__builtin_matrix_column_major_load:
1964     return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
1965 
1966   case Builtin::BI__builtin_matrix_column_major_store:
1967     return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
1968   }
1969 
1970   // Since the target specific builtins for each arch overlap, only check those
1971   // of the arch we are compiling for.
1972   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1973     if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
1974       assert(Context.getAuxTargetInfo() &&
1975              "Aux Target Builtin, but not an aux target?");
1976 
1977       if (CheckTSBuiltinFunctionCall(
1978               *Context.getAuxTargetInfo(),
1979               Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
1980         return ExprError();
1981     } else {
1982       if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
1983                                      TheCall))
1984         return ExprError();
1985     }
1986   }
1987 
1988   return TheCallResult;
1989 }
1990 
1991 // Get the valid immediate range for the specified NEON type code.
1992 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1993   NeonTypeFlags Type(t);
1994   int IsQuad = ForceQuad ? true : Type.isQuad();
1995   switch (Type.getEltType()) {
1996   case NeonTypeFlags::Int8:
1997   case NeonTypeFlags::Poly8:
1998     return shift ? 7 : (8 << IsQuad) - 1;
1999   case NeonTypeFlags::Int16:
2000   case NeonTypeFlags::Poly16:
2001     return shift ? 15 : (4 << IsQuad) - 1;
2002   case NeonTypeFlags::Int32:
2003     return shift ? 31 : (2 << IsQuad) - 1;
2004   case NeonTypeFlags::Int64:
2005   case NeonTypeFlags::Poly64:
2006     return shift ? 63 : (1 << IsQuad) - 1;
2007   case NeonTypeFlags::Poly128:
2008     return shift ? 127 : (1 << IsQuad) - 1;
2009   case NeonTypeFlags::Float16:
2010     assert(!shift && "cannot shift float types!");
2011     return (4 << IsQuad) - 1;
2012   case NeonTypeFlags::Float32:
2013     assert(!shift && "cannot shift float types!");
2014     return (2 << IsQuad) - 1;
2015   case NeonTypeFlags::Float64:
2016     assert(!shift && "cannot shift float types!");
2017     return (1 << IsQuad) - 1;
2018   case NeonTypeFlags::BFloat16:
2019     assert(!shift && "cannot shift float types!");
2020     return (4 << IsQuad) - 1;
2021   }
2022   llvm_unreachable("Invalid NeonTypeFlag!");
2023 }
2024 
2025 /// getNeonEltType - Return the QualType corresponding to the elements of
2026 /// the vector type specified by the NeonTypeFlags.  This is used to check
2027 /// the pointer arguments for Neon load/store intrinsics.
2028 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
2029                                bool IsPolyUnsigned, bool IsInt64Long) {
2030   switch (Flags.getEltType()) {
2031   case NeonTypeFlags::Int8:
2032     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
2033   case NeonTypeFlags::Int16:
2034     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
2035   case NeonTypeFlags::Int32:
2036     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
2037   case NeonTypeFlags::Int64:
2038     if (IsInt64Long)
2039       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
2040     else
2041       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
2042                                 : Context.LongLongTy;
2043   case NeonTypeFlags::Poly8:
2044     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
2045   case NeonTypeFlags::Poly16:
2046     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
2047   case NeonTypeFlags::Poly64:
2048     if (IsInt64Long)
2049       return Context.UnsignedLongTy;
2050     else
2051       return Context.UnsignedLongLongTy;
2052   case NeonTypeFlags::Poly128:
2053     break;
2054   case NeonTypeFlags::Float16:
2055     return Context.HalfTy;
2056   case NeonTypeFlags::Float32:
2057     return Context.FloatTy;
2058   case NeonTypeFlags::Float64:
2059     return Context.DoubleTy;
2060   case NeonTypeFlags::BFloat16:
2061     return Context.BFloat16Ty;
2062   }
2063   llvm_unreachable("Invalid NeonTypeFlag!");
2064 }
2065 
2066 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2067   // Range check SVE intrinsics that take immediate values.
2068   SmallVector<std::tuple<int,int,int>, 3> ImmChecks;
2069 
2070   switch (BuiltinID) {
2071   default:
2072     return false;
2073 #define GET_SVE_IMMEDIATE_CHECK
2074 #include "clang/Basic/arm_sve_sema_rangechecks.inc"
2075 #undef GET_SVE_IMMEDIATE_CHECK
2076   }
2077 
2078   // Perform all the immediate checks for this builtin call.
2079   bool HasError = false;
2080   for (auto &I : ImmChecks) {
2081     int ArgNum, CheckTy, ElementSizeInBits;
2082     std::tie(ArgNum, CheckTy, ElementSizeInBits) = I;
2083 
2084     typedef bool(*OptionSetCheckFnTy)(int64_t Value);
2085 
2086     // Function that checks whether the operand (ArgNum) is an immediate
2087     // that is one of the predefined values.
2088     auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm,
2089                                    int ErrDiag) -> bool {
2090       // We can't check the value of a dependent argument.
2091       Expr *Arg = TheCall->getArg(ArgNum);
2092       if (Arg->isTypeDependent() || Arg->isValueDependent())
2093         return false;
2094 
2095       // Check constant-ness first.
2096       llvm::APSInt Imm;
2097       if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm))
2098         return true;
2099 
2100       if (!CheckImm(Imm.getSExtValue()))
2101         return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange();
2102       return false;
2103     };
2104 
2105     switch ((SVETypeFlags::ImmCheckType)CheckTy) {
2106     case SVETypeFlags::ImmCheck0_31:
2107       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31))
2108         HasError = true;
2109       break;
2110     case SVETypeFlags::ImmCheck0_13:
2111       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13))
2112         HasError = true;
2113       break;
2114     case SVETypeFlags::ImmCheck1_16:
2115       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16))
2116         HasError = true;
2117       break;
2118     case SVETypeFlags::ImmCheck0_7:
2119       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7))
2120         HasError = true;
2121       break;
2122     case SVETypeFlags::ImmCheckExtract:
2123       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2124                                       (2048 / ElementSizeInBits) - 1))
2125         HasError = true;
2126       break;
2127     case SVETypeFlags::ImmCheckShiftRight:
2128       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits))
2129         HasError = true;
2130       break;
2131     case SVETypeFlags::ImmCheckShiftRightNarrow:
2132       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1,
2133                                       ElementSizeInBits / 2))
2134         HasError = true;
2135       break;
2136     case SVETypeFlags::ImmCheckShiftLeft:
2137       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2138                                       ElementSizeInBits - 1))
2139         HasError = true;
2140       break;
2141     case SVETypeFlags::ImmCheckLaneIndex:
2142       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2143                                       (128 / (1 * ElementSizeInBits)) - 1))
2144         HasError = true;
2145       break;
2146     case SVETypeFlags::ImmCheckLaneIndexCompRotate:
2147       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2148                                       (128 / (2 * ElementSizeInBits)) - 1))
2149         HasError = true;
2150       break;
2151     case SVETypeFlags::ImmCheckLaneIndexDot:
2152       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2153                                       (128 / (4 * ElementSizeInBits)) - 1))
2154         HasError = true;
2155       break;
2156     case SVETypeFlags::ImmCheckComplexRot90_270:
2157       if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; },
2158                               diag::err_rotation_argument_to_cadd))
2159         HasError = true;
2160       break;
2161     case SVETypeFlags::ImmCheckComplexRotAll90:
2162       if (CheckImmediateInSet(
2163               [](int64_t V) {
2164                 return V == 0 || V == 90 || V == 180 || V == 270;
2165               },
2166               diag::err_rotation_argument_to_cmla))
2167         HasError = true;
2168       break;
2169     case SVETypeFlags::ImmCheck0_1:
2170       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1))
2171         HasError = true;
2172       break;
2173     case SVETypeFlags::ImmCheck0_2:
2174       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2))
2175         HasError = true;
2176       break;
2177     case SVETypeFlags::ImmCheck0_3:
2178       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3))
2179         HasError = true;
2180       break;
2181     }
2182   }
2183 
2184   return HasError;
2185 }
2186 
2187 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI,
2188                                         unsigned BuiltinID, CallExpr *TheCall) {
2189   llvm::APSInt Result;
2190   uint64_t mask = 0;
2191   unsigned TV = 0;
2192   int PtrArgNum = -1;
2193   bool HasConstPtr = false;
2194   switch (BuiltinID) {
2195 #define GET_NEON_OVERLOAD_CHECK
2196 #include "clang/Basic/arm_neon.inc"
2197 #include "clang/Basic/arm_fp16.inc"
2198 #undef GET_NEON_OVERLOAD_CHECK
2199   }
2200 
2201   // For NEON intrinsics which are overloaded on vector element type, validate
2202   // the immediate which specifies which variant to emit.
2203   unsigned ImmArg = TheCall->getNumArgs()-1;
2204   if (mask) {
2205     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
2206       return true;
2207 
2208     TV = Result.getLimitedValue(64);
2209     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
2210       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
2211              << TheCall->getArg(ImmArg)->getSourceRange();
2212   }
2213 
2214   if (PtrArgNum >= 0) {
2215     // Check that pointer arguments have the specified type.
2216     Expr *Arg = TheCall->getArg(PtrArgNum);
2217     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
2218       Arg = ICE->getSubExpr();
2219     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
2220     QualType RHSTy = RHS.get()->getType();
2221 
2222     llvm::Triple::ArchType Arch = TI.getTriple().getArch();
2223     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
2224                           Arch == llvm::Triple::aarch64_32 ||
2225                           Arch == llvm::Triple::aarch64_be;
2226     bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong;
2227     QualType EltTy =
2228         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
2229     if (HasConstPtr)
2230       EltTy = EltTy.withConst();
2231     QualType LHSTy = Context.getPointerType(EltTy);
2232     AssignConvertType ConvTy;
2233     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
2234     if (RHS.isInvalid())
2235       return true;
2236     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
2237                                  RHS.get(), AA_Assigning))
2238       return true;
2239   }
2240 
2241   // For NEON intrinsics which take an immediate value as part of the
2242   // instruction, range check them here.
2243   unsigned i = 0, l = 0, u = 0;
2244   switch (BuiltinID) {
2245   default:
2246     return false;
2247   #define GET_NEON_IMMEDIATE_CHECK
2248   #include "clang/Basic/arm_neon.inc"
2249   #include "clang/Basic/arm_fp16.inc"
2250   #undef GET_NEON_IMMEDIATE_CHECK
2251   }
2252 
2253   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2254 }
2255 
2256 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2257   switch (BuiltinID) {
2258   default:
2259     return false;
2260   #include "clang/Basic/arm_mve_builtin_sema.inc"
2261   }
2262 }
2263 
2264 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2265                                        CallExpr *TheCall) {
2266   bool Err = false;
2267   switch (BuiltinID) {
2268   default:
2269     return false;
2270 #include "clang/Basic/arm_cde_builtin_sema.inc"
2271   }
2272 
2273   if (Err)
2274     return true;
2275 
2276   return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true);
2277 }
2278 
2279 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI,
2280                                         const Expr *CoprocArg, bool WantCDE) {
2281   if (isConstantEvaluated())
2282     return false;
2283 
2284   // We can't check the value of a dependent argument.
2285   if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent())
2286     return false;
2287 
2288   llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context);
2289   int64_t CoprocNo = CoprocNoAP.getExtValue();
2290   assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative");
2291 
2292   uint32_t CDECoprocMask = TI.getARMCDECoprocMask();
2293   bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo));
2294 
2295   if (IsCDECoproc != WantCDE)
2296     return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc)
2297            << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange();
2298 
2299   return false;
2300 }
2301 
2302 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
2303                                         unsigned MaxWidth) {
2304   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
2305           BuiltinID == ARM::BI__builtin_arm_ldaex ||
2306           BuiltinID == ARM::BI__builtin_arm_strex ||
2307           BuiltinID == ARM::BI__builtin_arm_stlex ||
2308           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2309           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2310           BuiltinID == AArch64::BI__builtin_arm_strex ||
2311           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
2312          "unexpected ARM builtin");
2313   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
2314                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
2315                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2316                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
2317 
2318   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2319 
2320   // Ensure that we have the proper number of arguments.
2321   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
2322     return true;
2323 
2324   // Inspect the pointer argument of the atomic builtin.  This should always be
2325   // a pointer type, whose element is an integral scalar or pointer type.
2326   // Because it is a pointer type, we don't have to worry about any implicit
2327   // casts here.
2328   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
2329   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
2330   if (PointerArgRes.isInvalid())
2331     return true;
2332   PointerArg = PointerArgRes.get();
2333 
2334   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2335   if (!pointerType) {
2336     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
2337         << PointerArg->getType() << PointerArg->getSourceRange();
2338     return true;
2339   }
2340 
2341   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
2342   // task is to insert the appropriate casts into the AST. First work out just
2343   // what the appropriate type is.
2344   QualType ValType = pointerType->getPointeeType();
2345   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
2346   if (IsLdrex)
2347     AddrType.addConst();
2348 
2349   // Issue a warning if the cast is dodgy.
2350   CastKind CastNeeded = CK_NoOp;
2351   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
2352     CastNeeded = CK_BitCast;
2353     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
2354         << PointerArg->getType() << Context.getPointerType(AddrType)
2355         << AA_Passing << PointerArg->getSourceRange();
2356   }
2357 
2358   // Finally, do the cast and replace the argument with the corrected version.
2359   AddrType = Context.getPointerType(AddrType);
2360   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
2361   if (PointerArgRes.isInvalid())
2362     return true;
2363   PointerArg = PointerArgRes.get();
2364 
2365   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
2366 
2367   // In general, we allow ints, floats and pointers to be loaded and stored.
2368   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2369       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
2370     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
2371         << PointerArg->getType() << PointerArg->getSourceRange();
2372     return true;
2373   }
2374 
2375   // But ARM doesn't have instructions to deal with 128-bit versions.
2376   if (Context.getTypeSize(ValType) > MaxWidth) {
2377     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
2378     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
2379         << PointerArg->getType() << PointerArg->getSourceRange();
2380     return true;
2381   }
2382 
2383   switch (ValType.getObjCLifetime()) {
2384   case Qualifiers::OCL_None:
2385   case Qualifiers::OCL_ExplicitNone:
2386     // okay
2387     break;
2388 
2389   case Qualifiers::OCL_Weak:
2390   case Qualifiers::OCL_Strong:
2391   case Qualifiers::OCL_Autoreleasing:
2392     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
2393         << ValType << PointerArg->getSourceRange();
2394     return true;
2395   }
2396 
2397   if (IsLdrex) {
2398     TheCall->setType(ValType);
2399     return false;
2400   }
2401 
2402   // Initialize the argument to be stored.
2403   ExprResult ValArg = TheCall->getArg(0);
2404   InitializedEntity Entity = InitializedEntity::InitializeParameter(
2405       Context, ValType, /*consume*/ false);
2406   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2407   if (ValArg.isInvalid())
2408     return true;
2409   TheCall->setArg(0, ValArg.get());
2410 
2411   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
2412   // but the custom checker bypasses all default analysis.
2413   TheCall->setType(Context.IntTy);
2414   return false;
2415 }
2416 
2417 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2418                                        CallExpr *TheCall) {
2419   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
2420       BuiltinID == ARM::BI__builtin_arm_ldaex ||
2421       BuiltinID == ARM::BI__builtin_arm_strex ||
2422       BuiltinID == ARM::BI__builtin_arm_stlex) {
2423     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
2424   }
2425 
2426   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
2427     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2428       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
2429   }
2430 
2431   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2432       BuiltinID == ARM::BI__builtin_arm_wsr64)
2433     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
2434 
2435   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
2436       BuiltinID == ARM::BI__builtin_arm_rsrp ||
2437       BuiltinID == ARM::BI__builtin_arm_wsr ||
2438       BuiltinID == ARM::BI__builtin_arm_wsrp)
2439     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2440 
2441   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2442     return true;
2443   if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
2444     return true;
2445   if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall))
2446     return true;
2447 
2448   // For intrinsics which take an immediate value as part of the instruction,
2449   // range check them here.
2450   // FIXME: VFP Intrinsics should error if VFP not present.
2451   switch (BuiltinID) {
2452   default: return false;
2453   case ARM::BI__builtin_arm_ssat:
2454     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
2455   case ARM::BI__builtin_arm_usat:
2456     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
2457   case ARM::BI__builtin_arm_ssat16:
2458     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
2459   case ARM::BI__builtin_arm_usat16:
2460     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2461   case ARM::BI__builtin_arm_vcvtr_f:
2462   case ARM::BI__builtin_arm_vcvtr_d:
2463     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
2464   case ARM::BI__builtin_arm_dmb:
2465   case ARM::BI__builtin_arm_dsb:
2466   case ARM::BI__builtin_arm_isb:
2467   case ARM::BI__builtin_arm_dbg:
2468     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
2469   case ARM::BI__builtin_arm_cdp:
2470   case ARM::BI__builtin_arm_cdp2:
2471   case ARM::BI__builtin_arm_mcr:
2472   case ARM::BI__builtin_arm_mcr2:
2473   case ARM::BI__builtin_arm_mrc:
2474   case ARM::BI__builtin_arm_mrc2:
2475   case ARM::BI__builtin_arm_mcrr:
2476   case ARM::BI__builtin_arm_mcrr2:
2477   case ARM::BI__builtin_arm_mrrc:
2478   case ARM::BI__builtin_arm_mrrc2:
2479   case ARM::BI__builtin_arm_ldc:
2480   case ARM::BI__builtin_arm_ldcl:
2481   case ARM::BI__builtin_arm_ldc2:
2482   case ARM::BI__builtin_arm_ldc2l:
2483   case ARM::BI__builtin_arm_stc:
2484   case ARM::BI__builtin_arm_stcl:
2485   case ARM::BI__builtin_arm_stc2:
2486   case ARM::BI__builtin_arm_stc2l:
2487     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) ||
2488            CheckARMCoprocessorImmediate(TI, TheCall->getArg(0),
2489                                         /*WantCDE*/ false);
2490   }
2491 }
2492 
2493 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI,
2494                                            unsigned BuiltinID,
2495                                            CallExpr *TheCall) {
2496   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2497       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2498       BuiltinID == AArch64::BI__builtin_arm_strex ||
2499       BuiltinID == AArch64::BI__builtin_arm_stlex) {
2500     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
2501   }
2502 
2503   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
2504     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2505       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
2506       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
2507       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
2508   }
2509 
2510   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2511       BuiltinID == AArch64::BI__builtin_arm_wsr64)
2512     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2513 
2514   // Memory Tagging Extensions (MTE) Intrinsics
2515   if (BuiltinID == AArch64::BI__builtin_arm_irg ||
2516       BuiltinID == AArch64::BI__builtin_arm_addg ||
2517       BuiltinID == AArch64::BI__builtin_arm_gmi ||
2518       BuiltinID == AArch64::BI__builtin_arm_ldg ||
2519       BuiltinID == AArch64::BI__builtin_arm_stg ||
2520       BuiltinID == AArch64::BI__builtin_arm_subp) {
2521     return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
2522   }
2523 
2524   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
2525       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2526       BuiltinID == AArch64::BI__builtin_arm_wsr ||
2527       BuiltinID == AArch64::BI__builtin_arm_wsrp)
2528     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2529 
2530   // Only check the valid encoding range. Any constant in this range would be
2531   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
2532   // an exception for incorrect registers. This matches MSVC behavior.
2533   if (BuiltinID == AArch64::BI_ReadStatusReg ||
2534       BuiltinID == AArch64::BI_WriteStatusReg)
2535     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
2536 
2537   if (BuiltinID == AArch64::BI__getReg)
2538     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
2539 
2540   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2541     return true;
2542 
2543   if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall))
2544     return true;
2545 
2546   // For intrinsics which take an immediate value as part of the instruction,
2547   // range check them here.
2548   unsigned i = 0, l = 0, u = 0;
2549   switch (BuiltinID) {
2550   default: return false;
2551   case AArch64::BI__builtin_arm_dmb:
2552   case AArch64::BI__builtin_arm_dsb:
2553   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
2554   case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
2555   }
2556 
2557   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2558 }
2559 
2560 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) {
2561   if (Arg->getType()->getAsPlaceholderType())
2562     return false;
2563 
2564   // The first argument needs to be a record field access.
2565   // If it is an array element access, we delay decision
2566   // to BPF backend to check whether the access is a
2567   // field access or not.
2568   return (Arg->IgnoreParens()->getObjectKind() == OK_BitField ||
2569           dyn_cast<MemberExpr>(Arg->IgnoreParens()) ||
2570           dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens()));
2571 }
2572 
2573 static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S,
2574                             QualType VectorTy, QualType EltTy) {
2575   QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType();
2576   if (!Context.hasSameType(VectorEltTy, EltTy)) {
2577     S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types)
2578         << Call->getSourceRange() << VectorEltTy << EltTy;
2579     return false;
2580   }
2581   return true;
2582 }
2583 
2584 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) {
2585   QualType ArgType = Arg->getType();
2586   if (ArgType->getAsPlaceholderType())
2587     return false;
2588 
2589   // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type
2590   // format:
2591   //   1. __builtin_preserve_type_info(*(<type> *)0, flag);
2592   //   2. <type> var;
2593   //      __builtin_preserve_type_info(var, flag);
2594   if (!dyn_cast<DeclRefExpr>(Arg->IgnoreParens()) &&
2595       !dyn_cast<UnaryOperator>(Arg->IgnoreParens()))
2596     return false;
2597 
2598   // Typedef type.
2599   if (ArgType->getAs<TypedefType>())
2600     return true;
2601 
2602   // Record type or Enum type.
2603   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2604   if (const auto *RT = Ty->getAs<RecordType>()) {
2605     if (!RT->getDecl()->getDeclName().isEmpty())
2606       return true;
2607   } else if (const auto *ET = Ty->getAs<EnumType>()) {
2608     if (!ET->getDecl()->getDeclName().isEmpty())
2609       return true;
2610   }
2611 
2612   return false;
2613 }
2614 
2615 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) {
2616   QualType ArgType = Arg->getType();
2617   if (ArgType->getAsPlaceholderType())
2618     return false;
2619 
2620   // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type
2621   // format:
2622   //   __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>,
2623   //                                 flag);
2624   const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens());
2625   if (!UO)
2626     return false;
2627 
2628   const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr());
2629   if (!CE || CE->getCastKind() != CK_IntegralToPointer)
2630     return false;
2631 
2632   // The integer must be from an EnumConstantDecl.
2633   const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr());
2634   if (!DR)
2635     return false;
2636 
2637   const EnumConstantDecl *Enumerator =
2638       dyn_cast<EnumConstantDecl>(DR->getDecl());
2639   if (!Enumerator)
2640     return false;
2641 
2642   // The type must be EnumType.
2643   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2644   const auto *ET = Ty->getAs<EnumType>();
2645   if (!ET)
2646     return false;
2647 
2648   // The enum value must be supported.
2649   for (auto *EDI : ET->getDecl()->enumerators()) {
2650     if (EDI == Enumerator)
2651       return true;
2652   }
2653 
2654   return false;
2655 }
2656 
2657 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
2658                                        CallExpr *TheCall) {
2659   assert((BuiltinID == BPF::BI__builtin_preserve_field_info ||
2660           BuiltinID == BPF::BI__builtin_btf_type_id ||
2661           BuiltinID == BPF::BI__builtin_preserve_type_info ||
2662           BuiltinID == BPF::BI__builtin_preserve_enum_value) &&
2663          "unexpected BPF builtin");
2664 
2665   if (checkArgCount(*this, TheCall, 2))
2666     return true;
2667 
2668   // The second argument needs to be a constant int
2669   Expr *Arg = TheCall->getArg(1);
2670   Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context);
2671   diag::kind kind;
2672   if (!Value) {
2673     if (BuiltinID == BPF::BI__builtin_preserve_field_info)
2674       kind = diag::err_preserve_field_info_not_const;
2675     else if (BuiltinID == BPF::BI__builtin_btf_type_id)
2676       kind = diag::err_btf_type_id_not_const;
2677     else if (BuiltinID == BPF::BI__builtin_preserve_type_info)
2678       kind = diag::err_preserve_type_info_not_const;
2679     else
2680       kind = diag::err_preserve_enum_value_not_const;
2681     Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange();
2682     return true;
2683   }
2684 
2685   // The first argument
2686   Arg = TheCall->getArg(0);
2687   bool InvalidArg = false;
2688   bool ReturnUnsignedInt = true;
2689   if (BuiltinID == BPF::BI__builtin_preserve_field_info) {
2690     if (!isValidBPFPreserveFieldInfoArg(Arg)) {
2691       InvalidArg = true;
2692       kind = diag::err_preserve_field_info_not_field;
2693     }
2694   } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) {
2695     if (!isValidBPFPreserveTypeInfoArg(Arg)) {
2696       InvalidArg = true;
2697       kind = diag::err_preserve_type_info_invalid;
2698     }
2699   } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) {
2700     if (!isValidBPFPreserveEnumValueArg(Arg)) {
2701       InvalidArg = true;
2702       kind = diag::err_preserve_enum_value_invalid;
2703     }
2704     ReturnUnsignedInt = false;
2705   } else if (BuiltinID == BPF::BI__builtin_btf_type_id) {
2706     ReturnUnsignedInt = false;
2707   }
2708 
2709   if (InvalidArg) {
2710     Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange();
2711     return true;
2712   }
2713 
2714   if (ReturnUnsignedInt)
2715     TheCall->setType(Context.UnsignedIntTy);
2716   else
2717     TheCall->setType(Context.UnsignedLongTy);
2718   return false;
2719 }
2720 
2721 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2722   struct ArgInfo {
2723     uint8_t OpNum;
2724     bool IsSigned;
2725     uint8_t BitWidth;
2726     uint8_t Align;
2727   };
2728   struct BuiltinInfo {
2729     unsigned BuiltinID;
2730     ArgInfo Infos[2];
2731   };
2732 
2733   static BuiltinInfo Infos[] = {
2734     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
2735     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
2736     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
2737     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  1 }} },
2738     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
2739     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
2740     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
2741     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
2742     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
2743     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
2744     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
2745 
2746     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
2747     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
2748     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
2749     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
2750     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
2751     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
2752     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
2753     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
2754     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
2755     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
2756     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
2757 
2758     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
2759     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
2760     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
2761     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
2762     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
2763     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
2764     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
2765     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
2766     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
2767     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
2768     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
2769     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
2770     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
2771     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
2772     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
2773     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
2774     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
2775     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
2776     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
2777     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
2778     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
2779     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
2780     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
2781     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
2782     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
2783     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
2784     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
2785     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
2786     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
2787     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
2788     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
2789     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
2790     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
2791     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
2792     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
2793     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
2794     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
2795     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
2796     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
2797     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
2798     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
2799     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
2800     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
2801     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
2802     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
2803     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
2804     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
2805     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
2806     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
2807     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
2808     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
2809     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
2810                                                       {{ 1, false, 6,  0 }} },
2811     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
2812     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
2813     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
2814     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
2815     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
2816     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
2817     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
2818                                                       {{ 1, false, 5,  0 }} },
2819     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
2820     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
2821     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
2822     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
2823     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
2824     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
2825                                                        { 2, false, 5,  0 }} },
2826     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
2827                                                        { 2, false, 6,  0 }} },
2828     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
2829                                                        { 3, false, 5,  0 }} },
2830     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
2831                                                        { 3, false, 6,  0 }} },
2832     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
2833     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
2834     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
2835     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
2836     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
2837     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
2838     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
2839     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
2840     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
2841     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
2842     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
2843     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
2844     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
2845     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
2846     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
2847     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
2848                                                       {{ 2, false, 4,  0 },
2849                                                        { 3, false, 5,  0 }} },
2850     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
2851                                                       {{ 2, false, 4,  0 },
2852                                                        { 3, false, 5,  0 }} },
2853     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
2854                                                       {{ 2, false, 4,  0 },
2855                                                        { 3, false, 5,  0 }} },
2856     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
2857                                                       {{ 2, false, 4,  0 },
2858                                                        { 3, false, 5,  0 }} },
2859     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
2860     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
2861     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
2862     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
2863     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
2864     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
2865     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
2866     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
2867     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
2868     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
2869     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
2870                                                        { 2, false, 5,  0 }} },
2871     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
2872                                                        { 2, false, 6,  0 }} },
2873     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
2874     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
2875     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
2876     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
2877     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
2878     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
2879     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
2880     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
2881     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
2882                                                       {{ 1, false, 4,  0 }} },
2883     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
2884     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
2885                                                       {{ 1, false, 4,  0 }} },
2886     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
2887     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
2888     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
2889     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
2890     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
2891     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
2892     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
2893     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
2894     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
2895     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
2896     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
2897     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
2898     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
2899     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
2900     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
2901     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
2902     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
2903     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
2904     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
2905     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
2906                                                       {{ 3, false, 1,  0 }} },
2907     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
2908     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
2909     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
2910     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
2911                                                       {{ 3, false, 1,  0 }} },
2912     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
2913     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
2914     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
2915     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
2916                                                       {{ 3, false, 1,  0 }} },
2917   };
2918 
2919   // Use a dynamically initialized static to sort the table exactly once on
2920   // first run.
2921   static const bool SortOnce =
2922       (llvm::sort(Infos,
2923                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
2924                    return LHS.BuiltinID < RHS.BuiltinID;
2925                  }),
2926        true);
2927   (void)SortOnce;
2928 
2929   const BuiltinInfo *F = llvm::partition_point(
2930       Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
2931   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
2932     return false;
2933 
2934   bool Error = false;
2935 
2936   for (const ArgInfo &A : F->Infos) {
2937     // Ignore empty ArgInfo elements.
2938     if (A.BitWidth == 0)
2939       continue;
2940 
2941     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
2942     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
2943     if (!A.Align) {
2944       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
2945     } else {
2946       unsigned M = 1 << A.Align;
2947       Min *= M;
2948       Max *= M;
2949       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
2950                SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
2951     }
2952   }
2953   return Error;
2954 }
2955 
2956 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
2957                                            CallExpr *TheCall) {
2958   return CheckHexagonBuiltinArgument(BuiltinID, TheCall);
2959 }
2960 
2961 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI,
2962                                         unsigned BuiltinID, CallExpr *TheCall) {
2963   return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) ||
2964          CheckMipsBuiltinArgument(BuiltinID, TheCall);
2965 }
2966 
2967 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
2968                                CallExpr *TheCall) {
2969 
2970   if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
2971       BuiltinID <= Mips::BI__builtin_mips_lwx) {
2972     if (!TI.hasFeature("dsp"))
2973       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
2974   }
2975 
2976   if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
2977       BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
2978     if (!TI.hasFeature("dspr2"))
2979       return Diag(TheCall->getBeginLoc(),
2980                   diag::err_mips_builtin_requires_dspr2);
2981   }
2982 
2983   if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
2984       BuiltinID <= Mips::BI__builtin_msa_xori_b) {
2985     if (!TI.hasFeature("msa"))
2986       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
2987   }
2988 
2989   return false;
2990 }
2991 
2992 // CheckMipsBuiltinArgument - Checks the constant value passed to the
2993 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
2994 // ordering for DSP is unspecified. MSA is ordered by the data format used
2995 // by the underlying instruction i.e., df/m, df/n and then by size.
2996 //
2997 // FIXME: The size tests here should instead be tablegen'd along with the
2998 //        definitions from include/clang/Basic/BuiltinsMips.def.
2999 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
3000 //        be too.
3001 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
3002   unsigned i = 0, l = 0, u = 0, m = 0;
3003   switch (BuiltinID) {
3004   default: return false;
3005   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
3006   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
3007   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
3008   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
3009   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
3010   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
3011   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
3012   // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
3013   // df/m field.
3014   // These intrinsics take an unsigned 3 bit immediate.
3015   case Mips::BI__builtin_msa_bclri_b:
3016   case Mips::BI__builtin_msa_bnegi_b:
3017   case Mips::BI__builtin_msa_bseti_b:
3018   case Mips::BI__builtin_msa_sat_s_b:
3019   case Mips::BI__builtin_msa_sat_u_b:
3020   case Mips::BI__builtin_msa_slli_b:
3021   case Mips::BI__builtin_msa_srai_b:
3022   case Mips::BI__builtin_msa_srari_b:
3023   case Mips::BI__builtin_msa_srli_b:
3024   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
3025   case Mips::BI__builtin_msa_binsli_b:
3026   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
3027   // These intrinsics take an unsigned 4 bit immediate.
3028   case Mips::BI__builtin_msa_bclri_h:
3029   case Mips::BI__builtin_msa_bnegi_h:
3030   case Mips::BI__builtin_msa_bseti_h:
3031   case Mips::BI__builtin_msa_sat_s_h:
3032   case Mips::BI__builtin_msa_sat_u_h:
3033   case Mips::BI__builtin_msa_slli_h:
3034   case Mips::BI__builtin_msa_srai_h:
3035   case Mips::BI__builtin_msa_srari_h:
3036   case Mips::BI__builtin_msa_srli_h:
3037   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
3038   case Mips::BI__builtin_msa_binsli_h:
3039   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
3040   // These intrinsics take an unsigned 5 bit immediate.
3041   // The first block of intrinsics actually have an unsigned 5 bit field,
3042   // not a df/n field.
3043   case Mips::BI__builtin_msa_cfcmsa:
3044   case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
3045   case Mips::BI__builtin_msa_clei_u_b:
3046   case Mips::BI__builtin_msa_clei_u_h:
3047   case Mips::BI__builtin_msa_clei_u_w:
3048   case Mips::BI__builtin_msa_clei_u_d:
3049   case Mips::BI__builtin_msa_clti_u_b:
3050   case Mips::BI__builtin_msa_clti_u_h:
3051   case Mips::BI__builtin_msa_clti_u_w:
3052   case Mips::BI__builtin_msa_clti_u_d:
3053   case Mips::BI__builtin_msa_maxi_u_b:
3054   case Mips::BI__builtin_msa_maxi_u_h:
3055   case Mips::BI__builtin_msa_maxi_u_w:
3056   case Mips::BI__builtin_msa_maxi_u_d:
3057   case Mips::BI__builtin_msa_mini_u_b:
3058   case Mips::BI__builtin_msa_mini_u_h:
3059   case Mips::BI__builtin_msa_mini_u_w:
3060   case Mips::BI__builtin_msa_mini_u_d:
3061   case Mips::BI__builtin_msa_addvi_b:
3062   case Mips::BI__builtin_msa_addvi_h:
3063   case Mips::BI__builtin_msa_addvi_w:
3064   case Mips::BI__builtin_msa_addvi_d:
3065   case Mips::BI__builtin_msa_bclri_w:
3066   case Mips::BI__builtin_msa_bnegi_w:
3067   case Mips::BI__builtin_msa_bseti_w:
3068   case Mips::BI__builtin_msa_sat_s_w:
3069   case Mips::BI__builtin_msa_sat_u_w:
3070   case Mips::BI__builtin_msa_slli_w:
3071   case Mips::BI__builtin_msa_srai_w:
3072   case Mips::BI__builtin_msa_srari_w:
3073   case Mips::BI__builtin_msa_srli_w:
3074   case Mips::BI__builtin_msa_srlri_w:
3075   case Mips::BI__builtin_msa_subvi_b:
3076   case Mips::BI__builtin_msa_subvi_h:
3077   case Mips::BI__builtin_msa_subvi_w:
3078   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
3079   case Mips::BI__builtin_msa_binsli_w:
3080   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
3081   // These intrinsics take an unsigned 6 bit immediate.
3082   case Mips::BI__builtin_msa_bclri_d:
3083   case Mips::BI__builtin_msa_bnegi_d:
3084   case Mips::BI__builtin_msa_bseti_d:
3085   case Mips::BI__builtin_msa_sat_s_d:
3086   case Mips::BI__builtin_msa_sat_u_d:
3087   case Mips::BI__builtin_msa_slli_d:
3088   case Mips::BI__builtin_msa_srai_d:
3089   case Mips::BI__builtin_msa_srari_d:
3090   case Mips::BI__builtin_msa_srli_d:
3091   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
3092   case Mips::BI__builtin_msa_binsli_d:
3093   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
3094   // These intrinsics take a signed 5 bit immediate.
3095   case Mips::BI__builtin_msa_ceqi_b:
3096   case Mips::BI__builtin_msa_ceqi_h:
3097   case Mips::BI__builtin_msa_ceqi_w:
3098   case Mips::BI__builtin_msa_ceqi_d:
3099   case Mips::BI__builtin_msa_clti_s_b:
3100   case Mips::BI__builtin_msa_clti_s_h:
3101   case Mips::BI__builtin_msa_clti_s_w:
3102   case Mips::BI__builtin_msa_clti_s_d:
3103   case Mips::BI__builtin_msa_clei_s_b:
3104   case Mips::BI__builtin_msa_clei_s_h:
3105   case Mips::BI__builtin_msa_clei_s_w:
3106   case Mips::BI__builtin_msa_clei_s_d:
3107   case Mips::BI__builtin_msa_maxi_s_b:
3108   case Mips::BI__builtin_msa_maxi_s_h:
3109   case Mips::BI__builtin_msa_maxi_s_w:
3110   case Mips::BI__builtin_msa_maxi_s_d:
3111   case Mips::BI__builtin_msa_mini_s_b:
3112   case Mips::BI__builtin_msa_mini_s_h:
3113   case Mips::BI__builtin_msa_mini_s_w:
3114   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
3115   // These intrinsics take an unsigned 8 bit immediate.
3116   case Mips::BI__builtin_msa_andi_b:
3117   case Mips::BI__builtin_msa_nori_b:
3118   case Mips::BI__builtin_msa_ori_b:
3119   case Mips::BI__builtin_msa_shf_b:
3120   case Mips::BI__builtin_msa_shf_h:
3121   case Mips::BI__builtin_msa_shf_w:
3122   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
3123   case Mips::BI__builtin_msa_bseli_b:
3124   case Mips::BI__builtin_msa_bmnzi_b:
3125   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
3126   // df/n format
3127   // These intrinsics take an unsigned 4 bit immediate.
3128   case Mips::BI__builtin_msa_copy_s_b:
3129   case Mips::BI__builtin_msa_copy_u_b:
3130   case Mips::BI__builtin_msa_insve_b:
3131   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
3132   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
3133   // These intrinsics take an unsigned 3 bit immediate.
3134   case Mips::BI__builtin_msa_copy_s_h:
3135   case Mips::BI__builtin_msa_copy_u_h:
3136   case Mips::BI__builtin_msa_insve_h:
3137   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
3138   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3139   // These intrinsics take an unsigned 2 bit immediate.
3140   case Mips::BI__builtin_msa_copy_s_w:
3141   case Mips::BI__builtin_msa_copy_u_w:
3142   case Mips::BI__builtin_msa_insve_w:
3143   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
3144   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3145   // These intrinsics take an unsigned 1 bit immediate.
3146   case Mips::BI__builtin_msa_copy_s_d:
3147   case Mips::BI__builtin_msa_copy_u_d:
3148   case Mips::BI__builtin_msa_insve_d:
3149   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
3150   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3151   // Memory offsets and immediate loads.
3152   // These intrinsics take a signed 10 bit immediate.
3153   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
3154   case Mips::BI__builtin_msa_ldi_h:
3155   case Mips::BI__builtin_msa_ldi_w:
3156   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
3157   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3158   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3159   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3160   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3161   case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break;
3162   case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break;
3163   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3164   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3165   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3166   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
3167   case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break;
3168   case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break;
3169   }
3170 
3171   if (!m)
3172     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3173 
3174   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3175          SemaBuiltinConstantArgMultiple(TheCall, i, m);
3176 }
3177 
3178 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str,
3179 /// advancing the pointer over the consumed characters. The decoded type is
3180 /// returned. If the decoded type represents a constant integer with a
3181 /// constraint on its value then Mask is set to that value. The type descriptors
3182 /// used in Str are specific to PPC MMA builtins and are documented in the file
3183 /// defining the PPC builtins.
3184 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str,
3185                                         unsigned &Mask) {
3186   bool RequireICE = false;
3187   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3188   switch (*Str++) {
3189   case 'V':
3190     return Context.getVectorType(Context.UnsignedCharTy, 16,
3191                                  VectorType::VectorKind::AltiVecVector);
3192   case 'i': {
3193     char *End;
3194     unsigned size = strtoul(Str, &End, 10);
3195     assert(End != Str && "Missing constant parameter constraint");
3196     Str = End;
3197     Mask = size;
3198     return Context.IntTy;
3199   }
3200   case 'W': {
3201     char *End;
3202     unsigned size = strtoul(Str, &End, 10);
3203     assert(End != Str && "Missing PowerPC MMA type size");
3204     Str = End;
3205     QualType Type;
3206     switch (size) {
3207   #define PPC_VECTOR_TYPE(typeName, Id, size) \
3208     case size: Type = Context.Id##Ty; break;
3209   #include "clang/Basic/PPCTypes.def"
3210     default: llvm_unreachable("Invalid PowerPC MMA vector type");
3211     }
3212     bool CheckVectorArgs = false;
3213     while (!CheckVectorArgs) {
3214       switch (*Str++) {
3215       case '*':
3216         Type = Context.getPointerType(Type);
3217         break;
3218       case 'C':
3219         Type = Type.withConst();
3220         break;
3221       default:
3222         CheckVectorArgs = true;
3223         --Str;
3224         break;
3225       }
3226     }
3227     return Type;
3228   }
3229   default:
3230     return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true);
3231   }
3232 }
3233 
3234 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3235                                        CallExpr *TheCall) {
3236   unsigned i = 0, l = 0, u = 0;
3237   bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
3238                       BuiltinID == PPC::BI__builtin_divdeu ||
3239                       BuiltinID == PPC::BI__builtin_bpermd;
3240   bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64;
3241   bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
3242                        BuiltinID == PPC::BI__builtin_divweu ||
3243                        BuiltinID == PPC::BI__builtin_divde ||
3244                        BuiltinID == PPC::BI__builtin_divdeu;
3245 
3246   if (Is64BitBltin && !IsTarget64Bit)
3247     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3248            << TheCall->getSourceRange();
3249 
3250   if ((IsBltinExtDiv && !TI.hasFeature("extdiv")) ||
3251       (BuiltinID == PPC::BI__builtin_bpermd && !TI.hasFeature("bpermd")))
3252     return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3253            << TheCall->getSourceRange();
3254 
3255   auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool {
3256     if (!TI.hasFeature("vsx"))
3257       return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3258              << TheCall->getSourceRange();
3259     return false;
3260   };
3261 
3262   switch (BuiltinID) {
3263   default: return false;
3264   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3265   case PPC::BI__builtin_altivec_crypto_vshasigmad:
3266     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3267            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3268   case PPC::BI__builtin_altivec_dss:
3269     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
3270   case PPC::BI__builtin_tbegin:
3271   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
3272   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
3273   case PPC::BI__builtin_tabortwc:
3274   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
3275   case PPC::BI__builtin_tabortwci:
3276   case PPC::BI__builtin_tabortdci:
3277     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3278            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
3279   case PPC::BI__builtin_altivec_dst:
3280   case PPC::BI__builtin_altivec_dstt:
3281   case PPC::BI__builtin_altivec_dstst:
3282   case PPC::BI__builtin_altivec_dststt:
3283     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
3284   case PPC::BI__builtin_vsx_xxpermdi:
3285   case PPC::BI__builtin_vsx_xxsldwi:
3286     return SemaBuiltinVSX(TheCall);
3287   case PPC::BI__builtin_unpack_vector_int128:
3288     return SemaVSXCheck(TheCall) ||
3289            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3290   case PPC::BI__builtin_pack_vector_int128:
3291     return SemaVSXCheck(TheCall);
3292   case PPC::BI__builtin_altivec_vgnb:
3293      return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7);
3294   case PPC::BI__builtin_altivec_vec_replace_elt:
3295   case PPC::BI__builtin_altivec_vec_replace_unaligned: {
3296     QualType VecTy = TheCall->getArg(0)->getType();
3297     QualType EltTy = TheCall->getArg(1)->getType();
3298     unsigned Width = Context.getIntWidth(EltTy);
3299     return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) ||
3300            !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy);
3301   }
3302   case PPC::BI__builtin_vsx_xxeval:
3303      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255);
3304   case PPC::BI__builtin_altivec_vsldbi:
3305      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3306   case PPC::BI__builtin_altivec_vsrdbi:
3307      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3308   case PPC::BI__builtin_vsx_xxpermx:
3309      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7);
3310 #define CUSTOM_BUILTIN(Name, Types, Acc) \
3311   case PPC::BI__builtin_##Name: \
3312     return SemaBuiltinPPCMMACall(TheCall, Types);
3313 #include "clang/Basic/BuiltinsPPC.def"
3314   }
3315   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3316 }
3317 
3318 // Check if the given type is a non-pointer PPC MMA type. This function is used
3319 // in Sema to prevent invalid uses of restricted PPC MMA types.
3320 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) {
3321   if (Type->isPointerType() || Type->isArrayType())
3322     return false;
3323 
3324   QualType CoreType = Type.getCanonicalType().getUnqualifiedType();
3325 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty
3326   if (false
3327 #include "clang/Basic/PPCTypes.def"
3328      ) {
3329     Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type);
3330     return true;
3331   }
3332   return false;
3333 }
3334 
3335 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID,
3336                                           CallExpr *TheCall) {
3337   // position of memory order and scope arguments in the builtin
3338   unsigned OrderIndex, ScopeIndex;
3339   switch (BuiltinID) {
3340   case AMDGPU::BI__builtin_amdgcn_atomic_inc32:
3341   case AMDGPU::BI__builtin_amdgcn_atomic_inc64:
3342   case AMDGPU::BI__builtin_amdgcn_atomic_dec32:
3343   case AMDGPU::BI__builtin_amdgcn_atomic_dec64:
3344     OrderIndex = 2;
3345     ScopeIndex = 3;
3346     break;
3347   case AMDGPU::BI__builtin_amdgcn_fence:
3348     OrderIndex = 0;
3349     ScopeIndex = 1;
3350     break;
3351   default:
3352     return false;
3353   }
3354 
3355   ExprResult Arg = TheCall->getArg(OrderIndex);
3356   auto ArgExpr = Arg.get();
3357   Expr::EvalResult ArgResult;
3358 
3359   if (!ArgExpr->EvaluateAsInt(ArgResult, Context))
3360     return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int)
3361            << ArgExpr->getType();
3362   int ord = ArgResult.Val.getInt().getZExtValue();
3363 
3364   // Check valididty of memory ordering as per C11 / C++11's memody model.
3365   switch (static_cast<llvm::AtomicOrderingCABI>(ord)) {
3366   case llvm::AtomicOrderingCABI::acquire:
3367   case llvm::AtomicOrderingCABI::release:
3368   case llvm::AtomicOrderingCABI::acq_rel:
3369   case llvm::AtomicOrderingCABI::seq_cst:
3370     break;
3371   default: {
3372     return Diag(ArgExpr->getBeginLoc(),
3373                 diag::warn_atomic_op_has_invalid_memory_order)
3374            << ArgExpr->getSourceRange();
3375   }
3376   }
3377 
3378   Arg = TheCall->getArg(ScopeIndex);
3379   ArgExpr = Arg.get();
3380   Expr::EvalResult ArgResult1;
3381   // Check that sync scope is a constant literal
3382   if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context))
3383     return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal)
3384            << ArgExpr->getType();
3385 
3386   return false;
3387 }
3388 
3389 bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI,
3390                                          unsigned BuiltinID,
3391                                          CallExpr *TheCall) {
3392   switch (BuiltinID) {
3393   default:
3394     break;
3395 #define BUILTIN(ID, TYPE, ATTRS) case RISCV::BI##ID:
3396 #include "clang/Basic/BuiltinsRISCV.def"
3397     if (!TI.hasFeature("experimental-v"))
3398       return Diag(TheCall->getBeginLoc(), diag::err_riscvv_builtin_requires_v)
3399              << TheCall->getSourceRange();
3400     break;
3401   }
3402 
3403   return false;
3404 }
3405 
3406 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3407                                            CallExpr *TheCall) {
3408   if (BuiltinID == SystemZ::BI__builtin_tabort) {
3409     Expr *Arg = TheCall->getArg(0);
3410     if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context))
3411       if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256)
3412         return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
3413                << Arg->getSourceRange();
3414   }
3415 
3416   // For intrinsics which take an immediate value as part of the instruction,
3417   // range check them here.
3418   unsigned i = 0, l = 0, u = 0;
3419   switch (BuiltinID) {
3420   default: return false;
3421   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3422   case SystemZ::BI__builtin_s390_verimb:
3423   case SystemZ::BI__builtin_s390_verimh:
3424   case SystemZ::BI__builtin_s390_verimf:
3425   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
3426   case SystemZ::BI__builtin_s390_vfaeb:
3427   case SystemZ::BI__builtin_s390_vfaeh:
3428   case SystemZ::BI__builtin_s390_vfaef:
3429   case SystemZ::BI__builtin_s390_vfaebs:
3430   case SystemZ::BI__builtin_s390_vfaehs:
3431   case SystemZ::BI__builtin_s390_vfaefs:
3432   case SystemZ::BI__builtin_s390_vfaezb:
3433   case SystemZ::BI__builtin_s390_vfaezh:
3434   case SystemZ::BI__builtin_s390_vfaezf:
3435   case SystemZ::BI__builtin_s390_vfaezbs:
3436   case SystemZ::BI__builtin_s390_vfaezhs:
3437   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
3438   case SystemZ::BI__builtin_s390_vfisb:
3439   case SystemZ::BI__builtin_s390_vfidb:
3440     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3441            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3442   case SystemZ::BI__builtin_s390_vftcisb:
3443   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3444   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3445   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3446   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3447   case SystemZ::BI__builtin_s390_vstrcb:
3448   case SystemZ::BI__builtin_s390_vstrch:
3449   case SystemZ::BI__builtin_s390_vstrcf:
3450   case SystemZ::BI__builtin_s390_vstrczb:
3451   case SystemZ::BI__builtin_s390_vstrczh:
3452   case SystemZ::BI__builtin_s390_vstrczf:
3453   case SystemZ::BI__builtin_s390_vstrcbs:
3454   case SystemZ::BI__builtin_s390_vstrchs:
3455   case SystemZ::BI__builtin_s390_vstrcfs:
3456   case SystemZ::BI__builtin_s390_vstrczbs:
3457   case SystemZ::BI__builtin_s390_vstrczhs:
3458   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
3459   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3460   case SystemZ::BI__builtin_s390_vfminsb:
3461   case SystemZ::BI__builtin_s390_vfmaxsb:
3462   case SystemZ::BI__builtin_s390_vfmindb:
3463   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
3464   case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
3465   case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
3466   }
3467   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3468 }
3469 
3470 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3471 /// This checks that the target supports __builtin_cpu_supports and
3472 /// that the string argument is constant and valid.
3473 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI,
3474                                    CallExpr *TheCall) {
3475   Expr *Arg = TheCall->getArg(0);
3476 
3477   // Check if the argument is a string literal.
3478   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3479     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3480            << Arg->getSourceRange();
3481 
3482   // Check the contents of the string.
3483   StringRef Feature =
3484       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3485   if (!TI.validateCpuSupports(Feature))
3486     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
3487            << Arg->getSourceRange();
3488   return false;
3489 }
3490 
3491 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3492 /// This checks that the target supports __builtin_cpu_is and
3493 /// that the string argument is constant and valid.
3494 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) {
3495   Expr *Arg = TheCall->getArg(0);
3496 
3497   // Check if the argument is a string literal.
3498   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3499     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3500            << Arg->getSourceRange();
3501 
3502   // Check the contents of the string.
3503   StringRef Feature =
3504       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3505   if (!TI.validateCpuIs(Feature))
3506     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
3507            << Arg->getSourceRange();
3508   return false;
3509 }
3510 
3511 // Check if the rounding mode is legal.
3512 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3513   // Indicates if this instruction has rounding control or just SAE.
3514   bool HasRC = false;
3515 
3516   unsigned ArgNum = 0;
3517   switch (BuiltinID) {
3518   default:
3519     return false;
3520   case X86::BI__builtin_ia32_vcvttsd2si32:
3521   case X86::BI__builtin_ia32_vcvttsd2si64:
3522   case X86::BI__builtin_ia32_vcvttsd2usi32:
3523   case X86::BI__builtin_ia32_vcvttsd2usi64:
3524   case X86::BI__builtin_ia32_vcvttss2si32:
3525   case X86::BI__builtin_ia32_vcvttss2si64:
3526   case X86::BI__builtin_ia32_vcvttss2usi32:
3527   case X86::BI__builtin_ia32_vcvttss2usi64:
3528     ArgNum = 1;
3529     break;
3530   case X86::BI__builtin_ia32_maxpd512:
3531   case X86::BI__builtin_ia32_maxps512:
3532   case X86::BI__builtin_ia32_minpd512:
3533   case X86::BI__builtin_ia32_minps512:
3534     ArgNum = 2;
3535     break;
3536   case X86::BI__builtin_ia32_cvtps2pd512_mask:
3537   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
3538   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
3539   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
3540   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
3541   case X86::BI__builtin_ia32_cvttps2dq512_mask:
3542   case X86::BI__builtin_ia32_cvttps2qq512_mask:
3543   case X86::BI__builtin_ia32_cvttps2udq512_mask:
3544   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
3545   case X86::BI__builtin_ia32_exp2pd_mask:
3546   case X86::BI__builtin_ia32_exp2ps_mask:
3547   case X86::BI__builtin_ia32_getexppd512_mask:
3548   case X86::BI__builtin_ia32_getexpps512_mask:
3549   case X86::BI__builtin_ia32_rcp28pd_mask:
3550   case X86::BI__builtin_ia32_rcp28ps_mask:
3551   case X86::BI__builtin_ia32_rsqrt28pd_mask:
3552   case X86::BI__builtin_ia32_rsqrt28ps_mask:
3553   case X86::BI__builtin_ia32_vcomisd:
3554   case X86::BI__builtin_ia32_vcomiss:
3555   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
3556     ArgNum = 3;
3557     break;
3558   case X86::BI__builtin_ia32_cmppd512_mask:
3559   case X86::BI__builtin_ia32_cmpps512_mask:
3560   case X86::BI__builtin_ia32_cmpsd_mask:
3561   case X86::BI__builtin_ia32_cmpss_mask:
3562   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
3563   case X86::BI__builtin_ia32_getexpsd128_round_mask:
3564   case X86::BI__builtin_ia32_getexpss128_round_mask:
3565   case X86::BI__builtin_ia32_getmantpd512_mask:
3566   case X86::BI__builtin_ia32_getmantps512_mask:
3567   case X86::BI__builtin_ia32_maxsd_round_mask:
3568   case X86::BI__builtin_ia32_maxss_round_mask:
3569   case X86::BI__builtin_ia32_minsd_round_mask:
3570   case X86::BI__builtin_ia32_minss_round_mask:
3571   case X86::BI__builtin_ia32_rcp28sd_round_mask:
3572   case X86::BI__builtin_ia32_rcp28ss_round_mask:
3573   case X86::BI__builtin_ia32_reducepd512_mask:
3574   case X86::BI__builtin_ia32_reduceps512_mask:
3575   case X86::BI__builtin_ia32_rndscalepd_mask:
3576   case X86::BI__builtin_ia32_rndscaleps_mask:
3577   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
3578   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
3579     ArgNum = 4;
3580     break;
3581   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3582   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3583   case X86::BI__builtin_ia32_fixupimmps512_mask:
3584   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3585   case X86::BI__builtin_ia32_fixupimmsd_mask:
3586   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3587   case X86::BI__builtin_ia32_fixupimmss_mask:
3588   case X86::BI__builtin_ia32_fixupimmss_maskz:
3589   case X86::BI__builtin_ia32_getmantsd_round_mask:
3590   case X86::BI__builtin_ia32_getmantss_round_mask:
3591   case X86::BI__builtin_ia32_rangepd512_mask:
3592   case X86::BI__builtin_ia32_rangeps512_mask:
3593   case X86::BI__builtin_ia32_rangesd128_round_mask:
3594   case X86::BI__builtin_ia32_rangess128_round_mask:
3595   case X86::BI__builtin_ia32_reducesd_mask:
3596   case X86::BI__builtin_ia32_reducess_mask:
3597   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3598   case X86::BI__builtin_ia32_rndscaless_round_mask:
3599     ArgNum = 5;
3600     break;
3601   case X86::BI__builtin_ia32_vcvtsd2si64:
3602   case X86::BI__builtin_ia32_vcvtsd2si32:
3603   case X86::BI__builtin_ia32_vcvtsd2usi32:
3604   case X86::BI__builtin_ia32_vcvtsd2usi64:
3605   case X86::BI__builtin_ia32_vcvtss2si32:
3606   case X86::BI__builtin_ia32_vcvtss2si64:
3607   case X86::BI__builtin_ia32_vcvtss2usi32:
3608   case X86::BI__builtin_ia32_vcvtss2usi64:
3609   case X86::BI__builtin_ia32_sqrtpd512:
3610   case X86::BI__builtin_ia32_sqrtps512:
3611     ArgNum = 1;
3612     HasRC = true;
3613     break;
3614   case X86::BI__builtin_ia32_addpd512:
3615   case X86::BI__builtin_ia32_addps512:
3616   case X86::BI__builtin_ia32_divpd512:
3617   case X86::BI__builtin_ia32_divps512:
3618   case X86::BI__builtin_ia32_mulpd512:
3619   case X86::BI__builtin_ia32_mulps512:
3620   case X86::BI__builtin_ia32_subpd512:
3621   case X86::BI__builtin_ia32_subps512:
3622   case X86::BI__builtin_ia32_cvtsi2sd64:
3623   case X86::BI__builtin_ia32_cvtsi2ss32:
3624   case X86::BI__builtin_ia32_cvtsi2ss64:
3625   case X86::BI__builtin_ia32_cvtusi2sd64:
3626   case X86::BI__builtin_ia32_cvtusi2ss32:
3627   case X86::BI__builtin_ia32_cvtusi2ss64:
3628     ArgNum = 2;
3629     HasRC = true;
3630     break;
3631   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
3632   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
3633   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
3634   case X86::BI__builtin_ia32_cvtpd2dq512_mask:
3635   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
3636   case X86::BI__builtin_ia32_cvtpd2udq512_mask:
3637   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
3638   case X86::BI__builtin_ia32_cvtps2dq512_mask:
3639   case X86::BI__builtin_ia32_cvtps2qq512_mask:
3640   case X86::BI__builtin_ia32_cvtps2udq512_mask:
3641   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
3642   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
3643   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
3644   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
3645   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
3646     ArgNum = 3;
3647     HasRC = true;
3648     break;
3649   case X86::BI__builtin_ia32_addss_round_mask:
3650   case X86::BI__builtin_ia32_addsd_round_mask:
3651   case X86::BI__builtin_ia32_divss_round_mask:
3652   case X86::BI__builtin_ia32_divsd_round_mask:
3653   case X86::BI__builtin_ia32_mulss_round_mask:
3654   case X86::BI__builtin_ia32_mulsd_round_mask:
3655   case X86::BI__builtin_ia32_subss_round_mask:
3656   case X86::BI__builtin_ia32_subsd_round_mask:
3657   case X86::BI__builtin_ia32_scalefpd512_mask:
3658   case X86::BI__builtin_ia32_scalefps512_mask:
3659   case X86::BI__builtin_ia32_scalefsd_round_mask:
3660   case X86::BI__builtin_ia32_scalefss_round_mask:
3661   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
3662   case X86::BI__builtin_ia32_sqrtsd_round_mask:
3663   case X86::BI__builtin_ia32_sqrtss_round_mask:
3664   case X86::BI__builtin_ia32_vfmaddsd3_mask:
3665   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
3666   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
3667   case X86::BI__builtin_ia32_vfmaddss3_mask:
3668   case X86::BI__builtin_ia32_vfmaddss3_maskz:
3669   case X86::BI__builtin_ia32_vfmaddss3_mask3:
3670   case X86::BI__builtin_ia32_vfmaddpd512_mask:
3671   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
3672   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
3673   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
3674   case X86::BI__builtin_ia32_vfmaddps512_mask:
3675   case X86::BI__builtin_ia32_vfmaddps512_maskz:
3676   case X86::BI__builtin_ia32_vfmaddps512_mask3:
3677   case X86::BI__builtin_ia32_vfmsubps512_mask3:
3678   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
3679   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
3680   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
3681   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
3682   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
3683   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
3684   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
3685   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
3686     ArgNum = 4;
3687     HasRC = true;
3688     break;
3689   }
3690 
3691   llvm::APSInt Result;
3692 
3693   // We can't check the value of a dependent argument.
3694   Expr *Arg = TheCall->getArg(ArgNum);
3695   if (Arg->isTypeDependent() || Arg->isValueDependent())
3696     return false;
3697 
3698   // Check constant-ness first.
3699   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3700     return true;
3701 
3702   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
3703   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
3704   // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
3705   // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
3706   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
3707       Result == 8/*ROUND_NO_EXC*/ ||
3708       (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
3709       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
3710     return false;
3711 
3712   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
3713          << Arg->getSourceRange();
3714 }
3715 
3716 // Check if the gather/scatter scale is legal.
3717 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
3718                                              CallExpr *TheCall) {
3719   unsigned ArgNum = 0;
3720   switch (BuiltinID) {
3721   default:
3722     return false;
3723   case X86::BI__builtin_ia32_gatherpfdpd:
3724   case X86::BI__builtin_ia32_gatherpfdps:
3725   case X86::BI__builtin_ia32_gatherpfqpd:
3726   case X86::BI__builtin_ia32_gatherpfqps:
3727   case X86::BI__builtin_ia32_scatterpfdpd:
3728   case X86::BI__builtin_ia32_scatterpfdps:
3729   case X86::BI__builtin_ia32_scatterpfqpd:
3730   case X86::BI__builtin_ia32_scatterpfqps:
3731     ArgNum = 3;
3732     break;
3733   case X86::BI__builtin_ia32_gatherd_pd:
3734   case X86::BI__builtin_ia32_gatherd_pd256:
3735   case X86::BI__builtin_ia32_gatherq_pd:
3736   case X86::BI__builtin_ia32_gatherq_pd256:
3737   case X86::BI__builtin_ia32_gatherd_ps:
3738   case X86::BI__builtin_ia32_gatherd_ps256:
3739   case X86::BI__builtin_ia32_gatherq_ps:
3740   case X86::BI__builtin_ia32_gatherq_ps256:
3741   case X86::BI__builtin_ia32_gatherd_q:
3742   case X86::BI__builtin_ia32_gatherd_q256:
3743   case X86::BI__builtin_ia32_gatherq_q:
3744   case X86::BI__builtin_ia32_gatherq_q256:
3745   case X86::BI__builtin_ia32_gatherd_d:
3746   case X86::BI__builtin_ia32_gatherd_d256:
3747   case X86::BI__builtin_ia32_gatherq_d:
3748   case X86::BI__builtin_ia32_gatherq_d256:
3749   case X86::BI__builtin_ia32_gather3div2df:
3750   case X86::BI__builtin_ia32_gather3div2di:
3751   case X86::BI__builtin_ia32_gather3div4df:
3752   case X86::BI__builtin_ia32_gather3div4di:
3753   case X86::BI__builtin_ia32_gather3div4sf:
3754   case X86::BI__builtin_ia32_gather3div4si:
3755   case X86::BI__builtin_ia32_gather3div8sf:
3756   case X86::BI__builtin_ia32_gather3div8si:
3757   case X86::BI__builtin_ia32_gather3siv2df:
3758   case X86::BI__builtin_ia32_gather3siv2di:
3759   case X86::BI__builtin_ia32_gather3siv4df:
3760   case X86::BI__builtin_ia32_gather3siv4di:
3761   case X86::BI__builtin_ia32_gather3siv4sf:
3762   case X86::BI__builtin_ia32_gather3siv4si:
3763   case X86::BI__builtin_ia32_gather3siv8sf:
3764   case X86::BI__builtin_ia32_gather3siv8si:
3765   case X86::BI__builtin_ia32_gathersiv8df:
3766   case X86::BI__builtin_ia32_gathersiv16sf:
3767   case X86::BI__builtin_ia32_gatherdiv8df:
3768   case X86::BI__builtin_ia32_gatherdiv16sf:
3769   case X86::BI__builtin_ia32_gathersiv8di:
3770   case X86::BI__builtin_ia32_gathersiv16si:
3771   case X86::BI__builtin_ia32_gatherdiv8di:
3772   case X86::BI__builtin_ia32_gatherdiv16si:
3773   case X86::BI__builtin_ia32_scatterdiv2df:
3774   case X86::BI__builtin_ia32_scatterdiv2di:
3775   case X86::BI__builtin_ia32_scatterdiv4df:
3776   case X86::BI__builtin_ia32_scatterdiv4di:
3777   case X86::BI__builtin_ia32_scatterdiv4sf:
3778   case X86::BI__builtin_ia32_scatterdiv4si:
3779   case X86::BI__builtin_ia32_scatterdiv8sf:
3780   case X86::BI__builtin_ia32_scatterdiv8si:
3781   case X86::BI__builtin_ia32_scattersiv2df:
3782   case X86::BI__builtin_ia32_scattersiv2di:
3783   case X86::BI__builtin_ia32_scattersiv4df:
3784   case X86::BI__builtin_ia32_scattersiv4di:
3785   case X86::BI__builtin_ia32_scattersiv4sf:
3786   case X86::BI__builtin_ia32_scattersiv4si:
3787   case X86::BI__builtin_ia32_scattersiv8sf:
3788   case X86::BI__builtin_ia32_scattersiv8si:
3789   case X86::BI__builtin_ia32_scattersiv8df:
3790   case X86::BI__builtin_ia32_scattersiv16sf:
3791   case X86::BI__builtin_ia32_scatterdiv8df:
3792   case X86::BI__builtin_ia32_scatterdiv16sf:
3793   case X86::BI__builtin_ia32_scattersiv8di:
3794   case X86::BI__builtin_ia32_scattersiv16si:
3795   case X86::BI__builtin_ia32_scatterdiv8di:
3796   case X86::BI__builtin_ia32_scatterdiv16si:
3797     ArgNum = 4;
3798     break;
3799   }
3800 
3801   llvm::APSInt Result;
3802 
3803   // We can't check the value of a dependent argument.
3804   Expr *Arg = TheCall->getArg(ArgNum);
3805   if (Arg->isTypeDependent() || Arg->isValueDependent())
3806     return false;
3807 
3808   // Check constant-ness first.
3809   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3810     return true;
3811 
3812   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
3813     return false;
3814 
3815   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
3816          << Arg->getSourceRange();
3817 }
3818 
3819 enum { TileRegLow = 0, TileRegHigh = 7 };
3820 
3821 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
3822                                              ArrayRef<int> ArgNums) {
3823   for (int ArgNum : ArgNums) {
3824     if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh))
3825       return true;
3826   }
3827   return false;
3828 }
3829 
3830 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall,
3831                                         ArrayRef<int> ArgNums) {
3832   // Because the max number of tile register is TileRegHigh + 1, so here we use
3833   // each bit to represent the usage of them in bitset.
3834   std::bitset<TileRegHigh + 1> ArgValues;
3835   for (int ArgNum : ArgNums) {
3836     Expr *Arg = TheCall->getArg(ArgNum);
3837     if (Arg->isTypeDependent() || Arg->isValueDependent())
3838       continue;
3839 
3840     llvm::APSInt Result;
3841     if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3842       return true;
3843     int ArgExtValue = Result.getExtValue();
3844     assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) &&
3845            "Incorrect tile register num.");
3846     if (ArgValues.test(ArgExtValue))
3847       return Diag(TheCall->getBeginLoc(),
3848                   diag::err_x86_builtin_tile_arg_duplicate)
3849              << TheCall->getArg(ArgNum)->getSourceRange();
3850     ArgValues.set(ArgExtValue);
3851   }
3852   return false;
3853 }
3854 
3855 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
3856                                                 ArrayRef<int> ArgNums) {
3857   return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) ||
3858          CheckX86BuiltinTileDuplicate(TheCall, ArgNums);
3859 }
3860 
3861 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) {
3862   switch (BuiltinID) {
3863   default:
3864     return false;
3865   case X86::BI__builtin_ia32_tileloadd64:
3866   case X86::BI__builtin_ia32_tileloaddt164:
3867   case X86::BI__builtin_ia32_tilestored64:
3868   case X86::BI__builtin_ia32_tilezero:
3869     return CheckX86BuiltinTileArgumentsRange(TheCall, 0);
3870   case X86::BI__builtin_ia32_tdpbssd:
3871   case X86::BI__builtin_ia32_tdpbsud:
3872   case X86::BI__builtin_ia32_tdpbusd:
3873   case X86::BI__builtin_ia32_tdpbuud:
3874   case X86::BI__builtin_ia32_tdpbf16ps:
3875     return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2});
3876   }
3877 }
3878 static bool isX86_32Builtin(unsigned BuiltinID) {
3879   // These builtins only work on x86-32 targets.
3880   switch (BuiltinID) {
3881   case X86::BI__builtin_ia32_readeflags_u32:
3882   case X86::BI__builtin_ia32_writeeflags_u32:
3883     return true;
3884   }
3885 
3886   return false;
3887 }
3888 
3889 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3890                                        CallExpr *TheCall) {
3891   if (BuiltinID == X86::BI__builtin_cpu_supports)
3892     return SemaBuiltinCpuSupports(*this, TI, TheCall);
3893 
3894   if (BuiltinID == X86::BI__builtin_cpu_is)
3895     return SemaBuiltinCpuIs(*this, TI, TheCall);
3896 
3897   // Check for 32-bit only builtins on a 64-bit target.
3898   const llvm::Triple &TT = TI.getTriple();
3899   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
3900     return Diag(TheCall->getCallee()->getBeginLoc(),
3901                 diag::err_32_bit_builtin_64_bit_tgt);
3902 
3903   // If the intrinsic has rounding or SAE make sure its valid.
3904   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
3905     return true;
3906 
3907   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
3908   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
3909     return true;
3910 
3911   // If the intrinsic has a tile arguments, make sure they are valid.
3912   if (CheckX86BuiltinTileArguments(BuiltinID, TheCall))
3913     return true;
3914 
3915   // For intrinsics which take an immediate value as part of the instruction,
3916   // range check them here.
3917   int i = 0, l = 0, u = 0;
3918   switch (BuiltinID) {
3919   default:
3920     return false;
3921   case X86::BI__builtin_ia32_vec_ext_v2si:
3922   case X86::BI__builtin_ia32_vec_ext_v2di:
3923   case X86::BI__builtin_ia32_vextractf128_pd256:
3924   case X86::BI__builtin_ia32_vextractf128_ps256:
3925   case X86::BI__builtin_ia32_vextractf128_si256:
3926   case X86::BI__builtin_ia32_extract128i256:
3927   case X86::BI__builtin_ia32_extractf64x4_mask:
3928   case X86::BI__builtin_ia32_extracti64x4_mask:
3929   case X86::BI__builtin_ia32_extractf32x8_mask:
3930   case X86::BI__builtin_ia32_extracti32x8_mask:
3931   case X86::BI__builtin_ia32_extractf64x2_256_mask:
3932   case X86::BI__builtin_ia32_extracti64x2_256_mask:
3933   case X86::BI__builtin_ia32_extractf32x4_256_mask:
3934   case X86::BI__builtin_ia32_extracti32x4_256_mask:
3935     i = 1; l = 0; u = 1;
3936     break;
3937   case X86::BI__builtin_ia32_vec_set_v2di:
3938   case X86::BI__builtin_ia32_vinsertf128_pd256:
3939   case X86::BI__builtin_ia32_vinsertf128_ps256:
3940   case X86::BI__builtin_ia32_vinsertf128_si256:
3941   case X86::BI__builtin_ia32_insert128i256:
3942   case X86::BI__builtin_ia32_insertf32x8:
3943   case X86::BI__builtin_ia32_inserti32x8:
3944   case X86::BI__builtin_ia32_insertf64x4:
3945   case X86::BI__builtin_ia32_inserti64x4:
3946   case X86::BI__builtin_ia32_insertf64x2_256:
3947   case X86::BI__builtin_ia32_inserti64x2_256:
3948   case X86::BI__builtin_ia32_insertf32x4_256:
3949   case X86::BI__builtin_ia32_inserti32x4_256:
3950     i = 2; l = 0; u = 1;
3951     break;
3952   case X86::BI__builtin_ia32_vpermilpd:
3953   case X86::BI__builtin_ia32_vec_ext_v4hi:
3954   case X86::BI__builtin_ia32_vec_ext_v4si:
3955   case X86::BI__builtin_ia32_vec_ext_v4sf:
3956   case X86::BI__builtin_ia32_vec_ext_v4di:
3957   case X86::BI__builtin_ia32_extractf32x4_mask:
3958   case X86::BI__builtin_ia32_extracti32x4_mask:
3959   case X86::BI__builtin_ia32_extractf64x2_512_mask:
3960   case X86::BI__builtin_ia32_extracti64x2_512_mask:
3961     i = 1; l = 0; u = 3;
3962     break;
3963   case X86::BI_mm_prefetch:
3964   case X86::BI__builtin_ia32_vec_ext_v8hi:
3965   case X86::BI__builtin_ia32_vec_ext_v8si:
3966     i = 1; l = 0; u = 7;
3967     break;
3968   case X86::BI__builtin_ia32_sha1rnds4:
3969   case X86::BI__builtin_ia32_blendpd:
3970   case X86::BI__builtin_ia32_shufpd:
3971   case X86::BI__builtin_ia32_vec_set_v4hi:
3972   case X86::BI__builtin_ia32_vec_set_v4si:
3973   case X86::BI__builtin_ia32_vec_set_v4di:
3974   case X86::BI__builtin_ia32_shuf_f32x4_256:
3975   case X86::BI__builtin_ia32_shuf_f64x2_256:
3976   case X86::BI__builtin_ia32_shuf_i32x4_256:
3977   case X86::BI__builtin_ia32_shuf_i64x2_256:
3978   case X86::BI__builtin_ia32_insertf64x2_512:
3979   case X86::BI__builtin_ia32_inserti64x2_512:
3980   case X86::BI__builtin_ia32_insertf32x4:
3981   case X86::BI__builtin_ia32_inserti32x4:
3982     i = 2; l = 0; u = 3;
3983     break;
3984   case X86::BI__builtin_ia32_vpermil2pd:
3985   case X86::BI__builtin_ia32_vpermil2pd256:
3986   case X86::BI__builtin_ia32_vpermil2ps:
3987   case X86::BI__builtin_ia32_vpermil2ps256:
3988     i = 3; l = 0; u = 3;
3989     break;
3990   case X86::BI__builtin_ia32_cmpb128_mask:
3991   case X86::BI__builtin_ia32_cmpw128_mask:
3992   case X86::BI__builtin_ia32_cmpd128_mask:
3993   case X86::BI__builtin_ia32_cmpq128_mask:
3994   case X86::BI__builtin_ia32_cmpb256_mask:
3995   case X86::BI__builtin_ia32_cmpw256_mask:
3996   case X86::BI__builtin_ia32_cmpd256_mask:
3997   case X86::BI__builtin_ia32_cmpq256_mask:
3998   case X86::BI__builtin_ia32_cmpb512_mask:
3999   case X86::BI__builtin_ia32_cmpw512_mask:
4000   case X86::BI__builtin_ia32_cmpd512_mask:
4001   case X86::BI__builtin_ia32_cmpq512_mask:
4002   case X86::BI__builtin_ia32_ucmpb128_mask:
4003   case X86::BI__builtin_ia32_ucmpw128_mask:
4004   case X86::BI__builtin_ia32_ucmpd128_mask:
4005   case X86::BI__builtin_ia32_ucmpq128_mask:
4006   case X86::BI__builtin_ia32_ucmpb256_mask:
4007   case X86::BI__builtin_ia32_ucmpw256_mask:
4008   case X86::BI__builtin_ia32_ucmpd256_mask:
4009   case X86::BI__builtin_ia32_ucmpq256_mask:
4010   case X86::BI__builtin_ia32_ucmpb512_mask:
4011   case X86::BI__builtin_ia32_ucmpw512_mask:
4012   case X86::BI__builtin_ia32_ucmpd512_mask:
4013   case X86::BI__builtin_ia32_ucmpq512_mask:
4014   case X86::BI__builtin_ia32_vpcomub:
4015   case X86::BI__builtin_ia32_vpcomuw:
4016   case X86::BI__builtin_ia32_vpcomud:
4017   case X86::BI__builtin_ia32_vpcomuq:
4018   case X86::BI__builtin_ia32_vpcomb:
4019   case X86::BI__builtin_ia32_vpcomw:
4020   case X86::BI__builtin_ia32_vpcomd:
4021   case X86::BI__builtin_ia32_vpcomq:
4022   case X86::BI__builtin_ia32_vec_set_v8hi:
4023   case X86::BI__builtin_ia32_vec_set_v8si:
4024     i = 2; l = 0; u = 7;
4025     break;
4026   case X86::BI__builtin_ia32_vpermilpd256:
4027   case X86::BI__builtin_ia32_roundps:
4028   case X86::BI__builtin_ia32_roundpd:
4029   case X86::BI__builtin_ia32_roundps256:
4030   case X86::BI__builtin_ia32_roundpd256:
4031   case X86::BI__builtin_ia32_getmantpd128_mask:
4032   case X86::BI__builtin_ia32_getmantpd256_mask:
4033   case X86::BI__builtin_ia32_getmantps128_mask:
4034   case X86::BI__builtin_ia32_getmantps256_mask:
4035   case X86::BI__builtin_ia32_getmantpd512_mask:
4036   case X86::BI__builtin_ia32_getmantps512_mask:
4037   case X86::BI__builtin_ia32_vec_ext_v16qi:
4038   case X86::BI__builtin_ia32_vec_ext_v16hi:
4039     i = 1; l = 0; u = 15;
4040     break;
4041   case X86::BI__builtin_ia32_pblendd128:
4042   case X86::BI__builtin_ia32_blendps:
4043   case X86::BI__builtin_ia32_blendpd256:
4044   case X86::BI__builtin_ia32_shufpd256:
4045   case X86::BI__builtin_ia32_roundss:
4046   case X86::BI__builtin_ia32_roundsd:
4047   case X86::BI__builtin_ia32_rangepd128_mask:
4048   case X86::BI__builtin_ia32_rangepd256_mask:
4049   case X86::BI__builtin_ia32_rangepd512_mask:
4050   case X86::BI__builtin_ia32_rangeps128_mask:
4051   case X86::BI__builtin_ia32_rangeps256_mask:
4052   case X86::BI__builtin_ia32_rangeps512_mask:
4053   case X86::BI__builtin_ia32_getmantsd_round_mask:
4054   case X86::BI__builtin_ia32_getmantss_round_mask:
4055   case X86::BI__builtin_ia32_vec_set_v16qi:
4056   case X86::BI__builtin_ia32_vec_set_v16hi:
4057     i = 2; l = 0; u = 15;
4058     break;
4059   case X86::BI__builtin_ia32_vec_ext_v32qi:
4060     i = 1; l = 0; u = 31;
4061     break;
4062   case X86::BI__builtin_ia32_cmpps:
4063   case X86::BI__builtin_ia32_cmpss:
4064   case X86::BI__builtin_ia32_cmppd:
4065   case X86::BI__builtin_ia32_cmpsd:
4066   case X86::BI__builtin_ia32_cmpps256:
4067   case X86::BI__builtin_ia32_cmppd256:
4068   case X86::BI__builtin_ia32_cmpps128_mask:
4069   case X86::BI__builtin_ia32_cmppd128_mask:
4070   case X86::BI__builtin_ia32_cmpps256_mask:
4071   case X86::BI__builtin_ia32_cmppd256_mask:
4072   case X86::BI__builtin_ia32_cmpps512_mask:
4073   case X86::BI__builtin_ia32_cmppd512_mask:
4074   case X86::BI__builtin_ia32_cmpsd_mask:
4075   case X86::BI__builtin_ia32_cmpss_mask:
4076   case X86::BI__builtin_ia32_vec_set_v32qi:
4077     i = 2; l = 0; u = 31;
4078     break;
4079   case X86::BI__builtin_ia32_permdf256:
4080   case X86::BI__builtin_ia32_permdi256:
4081   case X86::BI__builtin_ia32_permdf512:
4082   case X86::BI__builtin_ia32_permdi512:
4083   case X86::BI__builtin_ia32_vpermilps:
4084   case X86::BI__builtin_ia32_vpermilps256:
4085   case X86::BI__builtin_ia32_vpermilpd512:
4086   case X86::BI__builtin_ia32_vpermilps512:
4087   case X86::BI__builtin_ia32_pshufd:
4088   case X86::BI__builtin_ia32_pshufd256:
4089   case X86::BI__builtin_ia32_pshufd512:
4090   case X86::BI__builtin_ia32_pshufhw:
4091   case X86::BI__builtin_ia32_pshufhw256:
4092   case X86::BI__builtin_ia32_pshufhw512:
4093   case X86::BI__builtin_ia32_pshuflw:
4094   case X86::BI__builtin_ia32_pshuflw256:
4095   case X86::BI__builtin_ia32_pshuflw512:
4096   case X86::BI__builtin_ia32_vcvtps2ph:
4097   case X86::BI__builtin_ia32_vcvtps2ph_mask:
4098   case X86::BI__builtin_ia32_vcvtps2ph256:
4099   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
4100   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
4101   case X86::BI__builtin_ia32_rndscaleps_128_mask:
4102   case X86::BI__builtin_ia32_rndscalepd_128_mask:
4103   case X86::BI__builtin_ia32_rndscaleps_256_mask:
4104   case X86::BI__builtin_ia32_rndscalepd_256_mask:
4105   case X86::BI__builtin_ia32_rndscaleps_mask:
4106   case X86::BI__builtin_ia32_rndscalepd_mask:
4107   case X86::BI__builtin_ia32_reducepd128_mask:
4108   case X86::BI__builtin_ia32_reducepd256_mask:
4109   case X86::BI__builtin_ia32_reducepd512_mask:
4110   case X86::BI__builtin_ia32_reduceps128_mask:
4111   case X86::BI__builtin_ia32_reduceps256_mask:
4112   case X86::BI__builtin_ia32_reduceps512_mask:
4113   case X86::BI__builtin_ia32_prold512:
4114   case X86::BI__builtin_ia32_prolq512:
4115   case X86::BI__builtin_ia32_prold128:
4116   case X86::BI__builtin_ia32_prold256:
4117   case X86::BI__builtin_ia32_prolq128:
4118   case X86::BI__builtin_ia32_prolq256:
4119   case X86::BI__builtin_ia32_prord512:
4120   case X86::BI__builtin_ia32_prorq512:
4121   case X86::BI__builtin_ia32_prord128:
4122   case X86::BI__builtin_ia32_prord256:
4123   case X86::BI__builtin_ia32_prorq128:
4124   case X86::BI__builtin_ia32_prorq256:
4125   case X86::BI__builtin_ia32_fpclasspd128_mask:
4126   case X86::BI__builtin_ia32_fpclasspd256_mask:
4127   case X86::BI__builtin_ia32_fpclassps128_mask:
4128   case X86::BI__builtin_ia32_fpclassps256_mask:
4129   case X86::BI__builtin_ia32_fpclassps512_mask:
4130   case X86::BI__builtin_ia32_fpclasspd512_mask:
4131   case X86::BI__builtin_ia32_fpclasssd_mask:
4132   case X86::BI__builtin_ia32_fpclassss_mask:
4133   case X86::BI__builtin_ia32_pslldqi128_byteshift:
4134   case X86::BI__builtin_ia32_pslldqi256_byteshift:
4135   case X86::BI__builtin_ia32_pslldqi512_byteshift:
4136   case X86::BI__builtin_ia32_psrldqi128_byteshift:
4137   case X86::BI__builtin_ia32_psrldqi256_byteshift:
4138   case X86::BI__builtin_ia32_psrldqi512_byteshift:
4139   case X86::BI__builtin_ia32_kshiftliqi:
4140   case X86::BI__builtin_ia32_kshiftlihi:
4141   case X86::BI__builtin_ia32_kshiftlisi:
4142   case X86::BI__builtin_ia32_kshiftlidi:
4143   case X86::BI__builtin_ia32_kshiftriqi:
4144   case X86::BI__builtin_ia32_kshiftrihi:
4145   case X86::BI__builtin_ia32_kshiftrisi:
4146   case X86::BI__builtin_ia32_kshiftridi:
4147     i = 1; l = 0; u = 255;
4148     break;
4149   case X86::BI__builtin_ia32_vperm2f128_pd256:
4150   case X86::BI__builtin_ia32_vperm2f128_ps256:
4151   case X86::BI__builtin_ia32_vperm2f128_si256:
4152   case X86::BI__builtin_ia32_permti256:
4153   case X86::BI__builtin_ia32_pblendw128:
4154   case X86::BI__builtin_ia32_pblendw256:
4155   case X86::BI__builtin_ia32_blendps256:
4156   case X86::BI__builtin_ia32_pblendd256:
4157   case X86::BI__builtin_ia32_palignr128:
4158   case X86::BI__builtin_ia32_palignr256:
4159   case X86::BI__builtin_ia32_palignr512:
4160   case X86::BI__builtin_ia32_alignq512:
4161   case X86::BI__builtin_ia32_alignd512:
4162   case X86::BI__builtin_ia32_alignd128:
4163   case X86::BI__builtin_ia32_alignd256:
4164   case X86::BI__builtin_ia32_alignq128:
4165   case X86::BI__builtin_ia32_alignq256:
4166   case X86::BI__builtin_ia32_vcomisd:
4167   case X86::BI__builtin_ia32_vcomiss:
4168   case X86::BI__builtin_ia32_shuf_f32x4:
4169   case X86::BI__builtin_ia32_shuf_f64x2:
4170   case X86::BI__builtin_ia32_shuf_i32x4:
4171   case X86::BI__builtin_ia32_shuf_i64x2:
4172   case X86::BI__builtin_ia32_shufpd512:
4173   case X86::BI__builtin_ia32_shufps:
4174   case X86::BI__builtin_ia32_shufps256:
4175   case X86::BI__builtin_ia32_shufps512:
4176   case X86::BI__builtin_ia32_dbpsadbw128:
4177   case X86::BI__builtin_ia32_dbpsadbw256:
4178   case X86::BI__builtin_ia32_dbpsadbw512:
4179   case X86::BI__builtin_ia32_vpshldd128:
4180   case X86::BI__builtin_ia32_vpshldd256:
4181   case X86::BI__builtin_ia32_vpshldd512:
4182   case X86::BI__builtin_ia32_vpshldq128:
4183   case X86::BI__builtin_ia32_vpshldq256:
4184   case X86::BI__builtin_ia32_vpshldq512:
4185   case X86::BI__builtin_ia32_vpshldw128:
4186   case X86::BI__builtin_ia32_vpshldw256:
4187   case X86::BI__builtin_ia32_vpshldw512:
4188   case X86::BI__builtin_ia32_vpshrdd128:
4189   case X86::BI__builtin_ia32_vpshrdd256:
4190   case X86::BI__builtin_ia32_vpshrdd512:
4191   case X86::BI__builtin_ia32_vpshrdq128:
4192   case X86::BI__builtin_ia32_vpshrdq256:
4193   case X86::BI__builtin_ia32_vpshrdq512:
4194   case X86::BI__builtin_ia32_vpshrdw128:
4195   case X86::BI__builtin_ia32_vpshrdw256:
4196   case X86::BI__builtin_ia32_vpshrdw512:
4197     i = 2; l = 0; u = 255;
4198     break;
4199   case X86::BI__builtin_ia32_fixupimmpd512_mask:
4200   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
4201   case X86::BI__builtin_ia32_fixupimmps512_mask:
4202   case X86::BI__builtin_ia32_fixupimmps512_maskz:
4203   case X86::BI__builtin_ia32_fixupimmsd_mask:
4204   case X86::BI__builtin_ia32_fixupimmsd_maskz:
4205   case X86::BI__builtin_ia32_fixupimmss_mask:
4206   case X86::BI__builtin_ia32_fixupimmss_maskz:
4207   case X86::BI__builtin_ia32_fixupimmpd128_mask:
4208   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
4209   case X86::BI__builtin_ia32_fixupimmpd256_mask:
4210   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
4211   case X86::BI__builtin_ia32_fixupimmps128_mask:
4212   case X86::BI__builtin_ia32_fixupimmps128_maskz:
4213   case X86::BI__builtin_ia32_fixupimmps256_mask:
4214   case X86::BI__builtin_ia32_fixupimmps256_maskz:
4215   case X86::BI__builtin_ia32_pternlogd512_mask:
4216   case X86::BI__builtin_ia32_pternlogd512_maskz:
4217   case X86::BI__builtin_ia32_pternlogq512_mask:
4218   case X86::BI__builtin_ia32_pternlogq512_maskz:
4219   case X86::BI__builtin_ia32_pternlogd128_mask:
4220   case X86::BI__builtin_ia32_pternlogd128_maskz:
4221   case X86::BI__builtin_ia32_pternlogd256_mask:
4222   case X86::BI__builtin_ia32_pternlogd256_maskz:
4223   case X86::BI__builtin_ia32_pternlogq128_mask:
4224   case X86::BI__builtin_ia32_pternlogq128_maskz:
4225   case X86::BI__builtin_ia32_pternlogq256_mask:
4226   case X86::BI__builtin_ia32_pternlogq256_maskz:
4227     i = 3; l = 0; u = 255;
4228     break;
4229   case X86::BI__builtin_ia32_gatherpfdpd:
4230   case X86::BI__builtin_ia32_gatherpfdps:
4231   case X86::BI__builtin_ia32_gatherpfqpd:
4232   case X86::BI__builtin_ia32_gatherpfqps:
4233   case X86::BI__builtin_ia32_scatterpfdpd:
4234   case X86::BI__builtin_ia32_scatterpfdps:
4235   case X86::BI__builtin_ia32_scatterpfqpd:
4236   case X86::BI__builtin_ia32_scatterpfqps:
4237     i = 4; l = 2; u = 3;
4238     break;
4239   case X86::BI__builtin_ia32_reducesd_mask:
4240   case X86::BI__builtin_ia32_reducess_mask:
4241   case X86::BI__builtin_ia32_rndscalesd_round_mask:
4242   case X86::BI__builtin_ia32_rndscaless_round_mask:
4243     i = 4; l = 0; u = 255;
4244     break;
4245   }
4246 
4247   // Note that we don't force a hard error on the range check here, allowing
4248   // template-generated or macro-generated dead code to potentially have out-of-
4249   // range values. These need to code generate, but don't need to necessarily
4250   // make any sense. We use a warning that defaults to an error.
4251   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
4252 }
4253 
4254 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
4255 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
4256 /// Returns true when the format fits the function and the FormatStringInfo has
4257 /// been populated.
4258 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
4259                                FormatStringInfo *FSI) {
4260   FSI->HasVAListArg = Format->getFirstArg() == 0;
4261   FSI->FormatIdx = Format->getFormatIdx() - 1;
4262   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
4263 
4264   // The way the format attribute works in GCC, the implicit this argument
4265   // of member functions is counted. However, it doesn't appear in our own
4266   // lists, so decrement format_idx in that case.
4267   if (IsCXXMember) {
4268     if(FSI->FormatIdx == 0)
4269       return false;
4270     --FSI->FormatIdx;
4271     if (FSI->FirstDataArg != 0)
4272       --FSI->FirstDataArg;
4273   }
4274   return true;
4275 }
4276 
4277 /// Checks if a the given expression evaluates to null.
4278 ///
4279 /// Returns true if the value evaluates to null.
4280 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4281   // If the expression has non-null type, it doesn't evaluate to null.
4282   if (auto nullability
4283         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
4284     if (*nullability == NullabilityKind::NonNull)
4285       return false;
4286   }
4287 
4288   // As a special case, transparent unions initialized with zero are
4289   // considered null for the purposes of the nonnull attribute.
4290   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
4291     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
4292       if (const CompoundLiteralExpr *CLE =
4293           dyn_cast<CompoundLiteralExpr>(Expr))
4294         if (const InitListExpr *ILE =
4295             dyn_cast<InitListExpr>(CLE->getInitializer()))
4296           Expr = ILE->getInit(0);
4297   }
4298 
4299   bool Result;
4300   return (!Expr->isValueDependent() &&
4301           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
4302           !Result);
4303 }
4304 
4305 static void CheckNonNullArgument(Sema &S,
4306                                  const Expr *ArgExpr,
4307                                  SourceLocation CallSiteLoc) {
4308   if (CheckNonNullExpr(S, ArgExpr))
4309     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
4310                           S.PDiag(diag::warn_null_arg)
4311                               << ArgExpr->getSourceRange());
4312 }
4313 
4314 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
4315   FormatStringInfo FSI;
4316   if ((GetFormatStringType(Format) == FST_NSString) &&
4317       getFormatStringInfo(Format, false, &FSI)) {
4318     Idx = FSI.FormatIdx;
4319     return true;
4320   }
4321   return false;
4322 }
4323 
4324 /// Diagnose use of %s directive in an NSString which is being passed
4325 /// as formatting string to formatting method.
4326 static void
4327 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
4328                                         const NamedDecl *FDecl,
4329                                         Expr **Args,
4330                                         unsigned NumArgs) {
4331   unsigned Idx = 0;
4332   bool Format = false;
4333   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
4334   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
4335     Idx = 2;
4336     Format = true;
4337   }
4338   else
4339     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4340       if (S.GetFormatNSStringIdx(I, Idx)) {
4341         Format = true;
4342         break;
4343       }
4344     }
4345   if (!Format || NumArgs <= Idx)
4346     return;
4347   const Expr *FormatExpr = Args[Idx];
4348   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
4349     FormatExpr = CSCE->getSubExpr();
4350   const StringLiteral *FormatString;
4351   if (const ObjCStringLiteral *OSL =
4352       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
4353     FormatString = OSL->getString();
4354   else
4355     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
4356   if (!FormatString)
4357     return;
4358   if (S.FormatStringHasSArg(FormatString)) {
4359     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
4360       << "%s" << 1 << 1;
4361     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
4362       << FDecl->getDeclName();
4363   }
4364 }
4365 
4366 /// Determine whether the given type has a non-null nullability annotation.
4367 static bool isNonNullType(ASTContext &ctx, QualType type) {
4368   if (auto nullability = type->getNullability(ctx))
4369     return *nullability == NullabilityKind::NonNull;
4370 
4371   return false;
4372 }
4373 
4374 static void CheckNonNullArguments(Sema &S,
4375                                   const NamedDecl *FDecl,
4376                                   const FunctionProtoType *Proto,
4377                                   ArrayRef<const Expr *> Args,
4378                                   SourceLocation CallSiteLoc) {
4379   assert((FDecl || Proto) && "Need a function declaration or prototype");
4380 
4381   // Already checked by by constant evaluator.
4382   if (S.isConstantEvaluated())
4383     return;
4384   // Check the attributes attached to the method/function itself.
4385   llvm::SmallBitVector NonNullArgs;
4386   if (FDecl) {
4387     // Handle the nonnull attribute on the function/method declaration itself.
4388     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4389       if (!NonNull->args_size()) {
4390         // Easy case: all pointer arguments are nonnull.
4391         for (const auto *Arg : Args)
4392           if (S.isValidPointerAttrType(Arg->getType()))
4393             CheckNonNullArgument(S, Arg, CallSiteLoc);
4394         return;
4395       }
4396 
4397       for (const ParamIdx &Idx : NonNull->args()) {
4398         unsigned IdxAST = Idx.getASTIndex();
4399         if (IdxAST >= Args.size())
4400           continue;
4401         if (NonNullArgs.empty())
4402           NonNullArgs.resize(Args.size());
4403         NonNullArgs.set(IdxAST);
4404       }
4405     }
4406   }
4407 
4408   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4409     // Handle the nonnull attribute on the parameters of the
4410     // function/method.
4411     ArrayRef<ParmVarDecl*> parms;
4412     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4413       parms = FD->parameters();
4414     else
4415       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4416 
4417     unsigned ParamIndex = 0;
4418     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4419          I != E; ++I, ++ParamIndex) {
4420       const ParmVarDecl *PVD = *I;
4421       if (PVD->hasAttr<NonNullAttr>() ||
4422           isNonNullType(S.Context, PVD->getType())) {
4423         if (NonNullArgs.empty())
4424           NonNullArgs.resize(Args.size());
4425 
4426         NonNullArgs.set(ParamIndex);
4427       }
4428     }
4429   } else {
4430     // If we have a non-function, non-method declaration but no
4431     // function prototype, try to dig out the function prototype.
4432     if (!Proto) {
4433       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4434         QualType type = VD->getType().getNonReferenceType();
4435         if (auto pointerType = type->getAs<PointerType>())
4436           type = pointerType->getPointeeType();
4437         else if (auto blockType = type->getAs<BlockPointerType>())
4438           type = blockType->getPointeeType();
4439         // FIXME: data member pointers?
4440 
4441         // Dig out the function prototype, if there is one.
4442         Proto = type->getAs<FunctionProtoType>();
4443       }
4444     }
4445 
4446     // Fill in non-null argument information from the nullability
4447     // information on the parameter types (if we have them).
4448     if (Proto) {
4449       unsigned Index = 0;
4450       for (auto paramType : Proto->getParamTypes()) {
4451         if (isNonNullType(S.Context, paramType)) {
4452           if (NonNullArgs.empty())
4453             NonNullArgs.resize(Args.size());
4454 
4455           NonNullArgs.set(Index);
4456         }
4457 
4458         ++Index;
4459       }
4460     }
4461   }
4462 
4463   // Check for non-null arguments.
4464   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4465        ArgIndex != ArgIndexEnd; ++ArgIndex) {
4466     if (NonNullArgs[ArgIndex])
4467       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
4468   }
4469 }
4470 
4471 /// Handles the checks for format strings, non-POD arguments to vararg
4472 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
4473 /// attributes.
4474 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
4475                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
4476                      bool IsMemberFunction, SourceLocation Loc,
4477                      SourceRange Range, VariadicCallType CallType) {
4478   // FIXME: We should check as much as we can in the template definition.
4479   if (CurContext->isDependentContext())
4480     return;
4481 
4482   // Printf and scanf checking.
4483   llvm::SmallBitVector CheckedVarArgs;
4484   if (FDecl) {
4485     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4486       // Only create vector if there are format attributes.
4487       CheckedVarArgs.resize(Args.size());
4488 
4489       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4490                            CheckedVarArgs);
4491     }
4492   }
4493 
4494   // Refuse POD arguments that weren't caught by the format string
4495   // checks above.
4496   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4497   if (CallType != VariadicDoesNotApply &&
4498       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4499     unsigned NumParams = Proto ? Proto->getNumParams()
4500                        : FDecl && isa<FunctionDecl>(FDecl)
4501                            ? cast<FunctionDecl>(FDecl)->getNumParams()
4502                        : FDecl && isa<ObjCMethodDecl>(FDecl)
4503                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
4504                        : 0;
4505 
4506     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4507       // Args[ArgIdx] can be null in malformed code.
4508       if (const Expr *Arg = Args[ArgIdx]) {
4509         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4510           checkVariadicArgument(Arg, CallType);
4511       }
4512     }
4513   }
4514 
4515   if (FDecl || Proto) {
4516     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4517 
4518     // Type safety checking.
4519     if (FDecl) {
4520       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4521         CheckArgumentWithTypeTag(I, Args, Loc);
4522     }
4523   }
4524 
4525   if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
4526     auto *AA = FDecl->getAttr<AllocAlignAttr>();
4527     const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
4528     if (!Arg->isValueDependent()) {
4529       Expr::EvalResult Align;
4530       if (Arg->EvaluateAsInt(Align, Context)) {
4531         const llvm::APSInt &I = Align.Val.getInt();
4532         if (!I.isPowerOf2())
4533           Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
4534               << Arg->getSourceRange();
4535 
4536         if (I > Sema::MaximumAlignment)
4537           Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
4538               << Arg->getSourceRange() << Sema::MaximumAlignment;
4539       }
4540     }
4541   }
4542 
4543   if (FD)
4544     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4545 }
4546 
4547 /// CheckConstructorCall - Check a constructor call for correctness and safety
4548 /// properties not enforced by the C type system.
4549 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
4550                                 ArrayRef<const Expr *> Args,
4551                                 const FunctionProtoType *Proto,
4552                                 SourceLocation Loc) {
4553   VariadicCallType CallType =
4554     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4555   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4556             Loc, SourceRange(), CallType);
4557 }
4558 
4559 /// CheckFunctionCall - Check a direct function call for various correctness
4560 /// and safety properties not strictly enforced by the C type system.
4561 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
4562                              const FunctionProtoType *Proto) {
4563   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4564                               isa<CXXMethodDecl>(FDecl);
4565   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4566                           IsMemberOperatorCall;
4567   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4568                                                   TheCall->getCallee());
4569   Expr** Args = TheCall->getArgs();
4570   unsigned NumArgs = TheCall->getNumArgs();
4571 
4572   Expr *ImplicitThis = nullptr;
4573   if (IsMemberOperatorCall) {
4574     // If this is a call to a member operator, hide the first argument
4575     // from checkCall.
4576     // FIXME: Our choice of AST representation here is less than ideal.
4577     ImplicitThis = Args[0];
4578     ++Args;
4579     --NumArgs;
4580   } else if (IsMemberFunction)
4581     ImplicitThis =
4582         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4583 
4584   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
4585             IsMemberFunction, TheCall->getRParenLoc(),
4586             TheCall->getCallee()->getSourceRange(), CallType);
4587 
4588   IdentifierInfo *FnInfo = FDecl->getIdentifier();
4589   // None of the checks below are needed for functions that don't have
4590   // simple names (e.g., C++ conversion functions).
4591   if (!FnInfo)
4592     return false;
4593 
4594   CheckTCBEnforcement(TheCall, FDecl);
4595 
4596   CheckAbsoluteValueFunction(TheCall, FDecl);
4597   CheckMaxUnsignedZero(TheCall, FDecl);
4598 
4599   if (getLangOpts().ObjC)
4600     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
4601 
4602   unsigned CMId = FDecl->getMemoryFunctionKind();
4603 
4604   // Handle memory setting and copying functions.
4605   switch (CMId) {
4606   case 0:
4607     return false;
4608   case Builtin::BIstrlcpy: // fallthrough
4609   case Builtin::BIstrlcat:
4610     CheckStrlcpycatArguments(TheCall, FnInfo);
4611     break;
4612   case Builtin::BIstrncat:
4613     CheckStrncatArguments(TheCall, FnInfo);
4614     break;
4615   case Builtin::BIfree:
4616     CheckFreeArguments(TheCall);
4617     break;
4618   default:
4619     CheckMemaccessArguments(TheCall, CMId, FnInfo);
4620   }
4621 
4622   return false;
4623 }
4624 
4625 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
4626                                ArrayRef<const Expr *> Args) {
4627   VariadicCallType CallType =
4628       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
4629 
4630   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
4631             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
4632             CallType);
4633 
4634   return false;
4635 }
4636 
4637 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4638                             const FunctionProtoType *Proto) {
4639   QualType Ty;
4640   if (const auto *V = dyn_cast<VarDecl>(NDecl))
4641     Ty = V->getType().getNonReferenceType();
4642   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4643     Ty = F->getType().getNonReferenceType();
4644   else
4645     return false;
4646 
4647   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4648       !Ty->isFunctionProtoType())
4649     return false;
4650 
4651   VariadicCallType CallType;
4652   if (!Proto || !Proto->isVariadic()) {
4653     CallType = VariadicDoesNotApply;
4654   } else if (Ty->isBlockPointerType()) {
4655     CallType = VariadicBlock;
4656   } else { // Ty->isFunctionPointerType()
4657     CallType = VariadicFunction;
4658   }
4659 
4660   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4661             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4662             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4663             TheCall->getCallee()->getSourceRange(), CallType);
4664 
4665   return false;
4666 }
4667 
4668 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
4669 /// such as function pointers returned from functions.
4670 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4671   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4672                                                   TheCall->getCallee());
4673   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4674             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4675             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4676             TheCall->getCallee()->getSourceRange(), CallType);
4677 
4678   return false;
4679 }
4680 
4681 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4682   if (!llvm::isValidAtomicOrderingCABI(Ordering))
4683     return false;
4684 
4685   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4686   switch (Op) {
4687   case AtomicExpr::AO__c11_atomic_init:
4688   case AtomicExpr::AO__opencl_atomic_init:
4689     llvm_unreachable("There is no ordering argument for an init");
4690 
4691   case AtomicExpr::AO__c11_atomic_load:
4692   case AtomicExpr::AO__opencl_atomic_load:
4693   case AtomicExpr::AO__atomic_load_n:
4694   case AtomicExpr::AO__atomic_load:
4695     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4696            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4697 
4698   case AtomicExpr::AO__c11_atomic_store:
4699   case AtomicExpr::AO__opencl_atomic_store:
4700   case AtomicExpr::AO__atomic_store:
4701   case AtomicExpr::AO__atomic_store_n:
4702     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4703            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4704            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4705 
4706   default:
4707     return true;
4708   }
4709 }
4710 
4711 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
4712                                          AtomicExpr::AtomicOp Op) {
4713   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4714   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4715   MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
4716   return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
4717                          DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
4718                          Op);
4719 }
4720 
4721 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
4722                                  SourceLocation RParenLoc, MultiExprArg Args,
4723                                  AtomicExpr::AtomicOp Op,
4724                                  AtomicArgumentOrder ArgOrder) {
4725   // All the non-OpenCL operations take one of the following forms.
4726   // The OpenCL operations take the __c11 forms with one extra argument for
4727   // synchronization scope.
4728   enum {
4729     // C    __c11_atomic_init(A *, C)
4730     Init,
4731 
4732     // C    __c11_atomic_load(A *, int)
4733     Load,
4734 
4735     // void __atomic_load(A *, CP, int)
4736     LoadCopy,
4737 
4738     // void __atomic_store(A *, CP, int)
4739     Copy,
4740 
4741     // C    __c11_atomic_add(A *, M, int)
4742     Arithmetic,
4743 
4744     // C    __atomic_exchange_n(A *, CP, int)
4745     Xchg,
4746 
4747     // void __atomic_exchange(A *, C *, CP, int)
4748     GNUXchg,
4749 
4750     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4751     C11CmpXchg,
4752 
4753     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4754     GNUCmpXchg
4755   } Form = Init;
4756 
4757   const unsigned NumForm = GNUCmpXchg + 1;
4758   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
4759   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
4760   // where:
4761   //   C is an appropriate type,
4762   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4763   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4764   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4765   //   the int parameters are for orderings.
4766 
4767   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4768       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4769       "need to update code for modified forms");
4770   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
4771                     AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
4772                         AtomicExpr::AO__atomic_load,
4773                 "need to update code for modified C11 atomics");
4774   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
4775                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
4776   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
4777                Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
4778                IsOpenCL;
4779   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4780              Op == AtomicExpr::AO__atomic_store_n ||
4781              Op == AtomicExpr::AO__atomic_exchange_n ||
4782              Op == AtomicExpr::AO__atomic_compare_exchange_n;
4783   bool IsAddSub = false;
4784 
4785   switch (Op) {
4786   case AtomicExpr::AO__c11_atomic_init:
4787   case AtomicExpr::AO__opencl_atomic_init:
4788     Form = Init;
4789     break;
4790 
4791   case AtomicExpr::AO__c11_atomic_load:
4792   case AtomicExpr::AO__opencl_atomic_load:
4793   case AtomicExpr::AO__atomic_load_n:
4794     Form = Load;
4795     break;
4796 
4797   case AtomicExpr::AO__atomic_load:
4798     Form = LoadCopy;
4799     break;
4800 
4801   case AtomicExpr::AO__c11_atomic_store:
4802   case AtomicExpr::AO__opencl_atomic_store:
4803   case AtomicExpr::AO__atomic_store:
4804   case AtomicExpr::AO__atomic_store_n:
4805     Form = Copy;
4806     break;
4807 
4808   case AtomicExpr::AO__c11_atomic_fetch_add:
4809   case AtomicExpr::AO__c11_atomic_fetch_sub:
4810   case AtomicExpr::AO__opencl_atomic_fetch_add:
4811   case AtomicExpr::AO__opencl_atomic_fetch_sub:
4812   case AtomicExpr::AO__atomic_fetch_add:
4813   case AtomicExpr::AO__atomic_fetch_sub:
4814   case AtomicExpr::AO__atomic_add_fetch:
4815   case AtomicExpr::AO__atomic_sub_fetch:
4816     IsAddSub = true;
4817     LLVM_FALLTHROUGH;
4818   case AtomicExpr::AO__c11_atomic_fetch_and:
4819   case AtomicExpr::AO__c11_atomic_fetch_or:
4820   case AtomicExpr::AO__c11_atomic_fetch_xor:
4821   case AtomicExpr::AO__opencl_atomic_fetch_and:
4822   case AtomicExpr::AO__opencl_atomic_fetch_or:
4823   case AtomicExpr::AO__opencl_atomic_fetch_xor:
4824   case AtomicExpr::AO__atomic_fetch_and:
4825   case AtomicExpr::AO__atomic_fetch_or:
4826   case AtomicExpr::AO__atomic_fetch_xor:
4827   case AtomicExpr::AO__atomic_fetch_nand:
4828   case AtomicExpr::AO__atomic_and_fetch:
4829   case AtomicExpr::AO__atomic_or_fetch:
4830   case AtomicExpr::AO__atomic_xor_fetch:
4831   case AtomicExpr::AO__atomic_nand_fetch:
4832   case AtomicExpr::AO__c11_atomic_fetch_min:
4833   case AtomicExpr::AO__c11_atomic_fetch_max:
4834   case AtomicExpr::AO__opencl_atomic_fetch_min:
4835   case AtomicExpr::AO__opencl_atomic_fetch_max:
4836   case AtomicExpr::AO__atomic_min_fetch:
4837   case AtomicExpr::AO__atomic_max_fetch:
4838   case AtomicExpr::AO__atomic_fetch_min:
4839   case AtomicExpr::AO__atomic_fetch_max:
4840     Form = Arithmetic;
4841     break;
4842 
4843   case AtomicExpr::AO__c11_atomic_exchange:
4844   case AtomicExpr::AO__opencl_atomic_exchange:
4845   case AtomicExpr::AO__atomic_exchange_n:
4846     Form = Xchg;
4847     break;
4848 
4849   case AtomicExpr::AO__atomic_exchange:
4850     Form = GNUXchg;
4851     break;
4852 
4853   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
4854   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
4855   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
4856   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
4857     Form = C11CmpXchg;
4858     break;
4859 
4860   case AtomicExpr::AO__atomic_compare_exchange:
4861   case AtomicExpr::AO__atomic_compare_exchange_n:
4862     Form = GNUCmpXchg;
4863     break;
4864   }
4865 
4866   unsigned AdjustedNumArgs = NumArgs[Form];
4867   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
4868     ++AdjustedNumArgs;
4869   // Check we have the right number of arguments.
4870   if (Args.size() < AdjustedNumArgs) {
4871     Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
4872         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4873         << ExprRange;
4874     return ExprError();
4875   } else if (Args.size() > AdjustedNumArgs) {
4876     Diag(Args[AdjustedNumArgs]->getBeginLoc(),
4877          diag::err_typecheck_call_too_many_args)
4878         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4879         << ExprRange;
4880     return ExprError();
4881   }
4882 
4883   // Inspect the first argument of the atomic operation.
4884   Expr *Ptr = Args[0];
4885   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
4886   if (ConvertedPtr.isInvalid())
4887     return ExprError();
4888 
4889   Ptr = ConvertedPtr.get();
4890   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
4891   if (!pointerType) {
4892     Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
4893         << Ptr->getType() << Ptr->getSourceRange();
4894     return ExprError();
4895   }
4896 
4897   // For a __c11 builtin, this should be a pointer to an _Atomic type.
4898   QualType AtomTy = pointerType->getPointeeType(); // 'A'
4899   QualType ValType = AtomTy; // 'C'
4900   if (IsC11) {
4901     if (!AtomTy->isAtomicType()) {
4902       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
4903           << Ptr->getType() << Ptr->getSourceRange();
4904       return ExprError();
4905     }
4906     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
4907         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
4908       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
4909           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
4910           << Ptr->getSourceRange();
4911       return ExprError();
4912     }
4913     ValType = AtomTy->castAs<AtomicType>()->getValueType();
4914   } else if (Form != Load && Form != LoadCopy) {
4915     if (ValType.isConstQualified()) {
4916       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
4917           << Ptr->getType() << Ptr->getSourceRange();
4918       return ExprError();
4919     }
4920   }
4921 
4922   // For an arithmetic operation, the implied arithmetic must be well-formed.
4923   if (Form == Arithmetic) {
4924     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
4925     if (IsAddSub && !ValType->isIntegerType()
4926         && !ValType->isPointerType()) {
4927       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4928           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4929       return ExprError();
4930     }
4931     if (!IsAddSub && !ValType->isIntegerType()) {
4932       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
4933           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4934       return ExprError();
4935     }
4936     if (IsC11 && ValType->isPointerType() &&
4937         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
4938                             diag::err_incomplete_type)) {
4939       return ExprError();
4940     }
4941   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
4942     // For __atomic_*_n operations, the value type must be a scalar integral or
4943     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
4944     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4945         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4946     return ExprError();
4947   }
4948 
4949   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
4950       !AtomTy->isScalarType()) {
4951     // For GNU atomics, require a trivially-copyable type. This is not part of
4952     // the GNU atomics specification, but we enforce it for sanity.
4953     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
4954         << Ptr->getType() << Ptr->getSourceRange();
4955     return ExprError();
4956   }
4957 
4958   switch (ValType.getObjCLifetime()) {
4959   case Qualifiers::OCL_None:
4960   case Qualifiers::OCL_ExplicitNone:
4961     // okay
4962     break;
4963 
4964   case Qualifiers::OCL_Weak:
4965   case Qualifiers::OCL_Strong:
4966   case Qualifiers::OCL_Autoreleasing:
4967     // FIXME: Can this happen? By this point, ValType should be known
4968     // to be trivially copyable.
4969     Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
4970         << ValType << Ptr->getSourceRange();
4971     return ExprError();
4972   }
4973 
4974   // All atomic operations have an overload which takes a pointer to a volatile
4975   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
4976   // into the result or the other operands. Similarly atomic_load takes a
4977   // pointer to a const 'A'.
4978   ValType.removeLocalVolatile();
4979   ValType.removeLocalConst();
4980   QualType ResultType = ValType;
4981   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
4982       Form == Init)
4983     ResultType = Context.VoidTy;
4984   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
4985     ResultType = Context.BoolTy;
4986 
4987   // The type of a parameter passed 'by value'. In the GNU atomics, such
4988   // arguments are actually passed as pointers.
4989   QualType ByValType = ValType; // 'CP'
4990   bool IsPassedByAddress = false;
4991   if (!IsC11 && !IsN) {
4992     ByValType = Ptr->getType();
4993     IsPassedByAddress = true;
4994   }
4995 
4996   SmallVector<Expr *, 5> APIOrderedArgs;
4997   if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
4998     APIOrderedArgs.push_back(Args[0]);
4999     switch (Form) {
5000     case Init:
5001     case Load:
5002       APIOrderedArgs.push_back(Args[1]); // Val1/Order
5003       break;
5004     case LoadCopy:
5005     case Copy:
5006     case Arithmetic:
5007     case Xchg:
5008       APIOrderedArgs.push_back(Args[2]); // Val1
5009       APIOrderedArgs.push_back(Args[1]); // Order
5010       break;
5011     case GNUXchg:
5012       APIOrderedArgs.push_back(Args[2]); // Val1
5013       APIOrderedArgs.push_back(Args[3]); // Val2
5014       APIOrderedArgs.push_back(Args[1]); // Order
5015       break;
5016     case C11CmpXchg:
5017       APIOrderedArgs.push_back(Args[2]); // Val1
5018       APIOrderedArgs.push_back(Args[4]); // Val2
5019       APIOrderedArgs.push_back(Args[1]); // Order
5020       APIOrderedArgs.push_back(Args[3]); // OrderFail
5021       break;
5022     case GNUCmpXchg:
5023       APIOrderedArgs.push_back(Args[2]); // Val1
5024       APIOrderedArgs.push_back(Args[4]); // Val2
5025       APIOrderedArgs.push_back(Args[5]); // Weak
5026       APIOrderedArgs.push_back(Args[1]); // Order
5027       APIOrderedArgs.push_back(Args[3]); // OrderFail
5028       break;
5029     }
5030   } else
5031     APIOrderedArgs.append(Args.begin(), Args.end());
5032 
5033   // The first argument's non-CV pointer type is used to deduce the type of
5034   // subsequent arguments, except for:
5035   //  - weak flag (always converted to bool)
5036   //  - memory order (always converted to int)
5037   //  - scope  (always converted to int)
5038   for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
5039     QualType Ty;
5040     if (i < NumVals[Form] + 1) {
5041       switch (i) {
5042       case 0:
5043         // The first argument is always a pointer. It has a fixed type.
5044         // It is always dereferenced, a nullptr is undefined.
5045         CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5046         // Nothing else to do: we already know all we want about this pointer.
5047         continue;
5048       case 1:
5049         // The second argument is the non-atomic operand. For arithmetic, this
5050         // is always passed by value, and for a compare_exchange it is always
5051         // passed by address. For the rest, GNU uses by-address and C11 uses
5052         // by-value.
5053         assert(Form != Load);
5054         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
5055           Ty = ValType;
5056         else if (Form == Copy || Form == Xchg) {
5057           if (IsPassedByAddress) {
5058             // The value pointer is always dereferenced, a nullptr is undefined.
5059             CheckNonNullArgument(*this, APIOrderedArgs[i],
5060                                  ExprRange.getBegin());
5061           }
5062           Ty = ByValType;
5063         } else if (Form == Arithmetic)
5064           Ty = Context.getPointerDiffType();
5065         else {
5066           Expr *ValArg = APIOrderedArgs[i];
5067           // The value pointer is always dereferenced, a nullptr is undefined.
5068           CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
5069           LangAS AS = LangAS::Default;
5070           // Keep address space of non-atomic pointer type.
5071           if (const PointerType *PtrTy =
5072                   ValArg->getType()->getAs<PointerType>()) {
5073             AS = PtrTy->getPointeeType().getAddressSpace();
5074           }
5075           Ty = Context.getPointerType(
5076               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
5077         }
5078         break;
5079       case 2:
5080         // The third argument to compare_exchange / GNU exchange is the desired
5081         // value, either by-value (for the C11 and *_n variant) or as a pointer.
5082         if (IsPassedByAddress)
5083           CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5084         Ty = ByValType;
5085         break;
5086       case 3:
5087         // The fourth argument to GNU compare_exchange is a 'weak' flag.
5088         Ty = Context.BoolTy;
5089         break;
5090       }
5091     } else {
5092       // The order(s) and scope are always converted to int.
5093       Ty = Context.IntTy;
5094     }
5095 
5096     InitializedEntity Entity =
5097         InitializedEntity::InitializeParameter(Context, Ty, false);
5098     ExprResult Arg = APIOrderedArgs[i];
5099     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5100     if (Arg.isInvalid())
5101       return true;
5102     APIOrderedArgs[i] = Arg.get();
5103   }
5104 
5105   // Permute the arguments into a 'consistent' order.
5106   SmallVector<Expr*, 5> SubExprs;
5107   SubExprs.push_back(Ptr);
5108   switch (Form) {
5109   case Init:
5110     // Note, AtomicExpr::getVal1() has a special case for this atomic.
5111     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5112     break;
5113   case Load:
5114     SubExprs.push_back(APIOrderedArgs[1]); // Order
5115     break;
5116   case LoadCopy:
5117   case Copy:
5118   case Arithmetic:
5119   case Xchg:
5120     SubExprs.push_back(APIOrderedArgs[2]); // Order
5121     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5122     break;
5123   case GNUXchg:
5124     // Note, AtomicExpr::getVal2() has a special case for this atomic.
5125     SubExprs.push_back(APIOrderedArgs[3]); // Order
5126     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5127     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5128     break;
5129   case C11CmpXchg:
5130     SubExprs.push_back(APIOrderedArgs[3]); // Order
5131     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5132     SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
5133     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5134     break;
5135   case GNUCmpXchg:
5136     SubExprs.push_back(APIOrderedArgs[4]); // Order
5137     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5138     SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
5139     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5140     SubExprs.push_back(APIOrderedArgs[3]); // Weak
5141     break;
5142   }
5143 
5144   if (SubExprs.size() >= 2 && Form != Init) {
5145     if (Optional<llvm::APSInt> Result =
5146             SubExprs[1]->getIntegerConstantExpr(Context))
5147       if (!isValidOrderingForOp(Result->getSExtValue(), Op))
5148         Diag(SubExprs[1]->getBeginLoc(),
5149              diag::warn_atomic_op_has_invalid_memory_order)
5150             << SubExprs[1]->getSourceRange();
5151   }
5152 
5153   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
5154     auto *Scope = Args[Args.size() - 1];
5155     if (Optional<llvm::APSInt> Result =
5156             Scope->getIntegerConstantExpr(Context)) {
5157       if (!ScopeModel->isValid(Result->getZExtValue()))
5158         Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
5159             << Scope->getSourceRange();
5160     }
5161     SubExprs.push_back(Scope);
5162   }
5163 
5164   AtomicExpr *AE = new (Context)
5165       AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
5166 
5167   if ((Op == AtomicExpr::AO__c11_atomic_load ||
5168        Op == AtomicExpr::AO__c11_atomic_store ||
5169        Op == AtomicExpr::AO__opencl_atomic_load ||
5170        Op == AtomicExpr::AO__opencl_atomic_store ) &&
5171       Context.AtomicUsesUnsupportedLibcall(AE))
5172     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
5173         << ((Op == AtomicExpr::AO__c11_atomic_load ||
5174              Op == AtomicExpr::AO__opencl_atomic_load)
5175                 ? 0
5176                 : 1);
5177 
5178   if (ValType->isExtIntType()) {
5179     Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_ext_int_prohibit);
5180     return ExprError();
5181   }
5182 
5183   return AE;
5184 }
5185 
5186 /// checkBuiltinArgument - Given a call to a builtin function, perform
5187 /// normal type-checking on the given argument, updating the call in
5188 /// place.  This is useful when a builtin function requires custom
5189 /// type-checking for some of its arguments but not necessarily all of
5190 /// them.
5191 ///
5192 /// Returns true on error.
5193 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
5194   FunctionDecl *Fn = E->getDirectCallee();
5195   assert(Fn && "builtin call without direct callee!");
5196 
5197   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
5198   InitializedEntity Entity =
5199     InitializedEntity::InitializeParameter(S.Context, Param);
5200 
5201   ExprResult Arg = E->getArg(0);
5202   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
5203   if (Arg.isInvalid())
5204     return true;
5205 
5206   E->setArg(ArgIndex, Arg.get());
5207   return false;
5208 }
5209 
5210 /// We have a call to a function like __sync_fetch_and_add, which is an
5211 /// overloaded function based on the pointer type of its first argument.
5212 /// The main BuildCallExpr routines have already promoted the types of
5213 /// arguments because all of these calls are prototyped as void(...).
5214 ///
5215 /// This function goes through and does final semantic checking for these
5216 /// builtins, as well as generating any warnings.
5217 ExprResult
5218 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
5219   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
5220   Expr *Callee = TheCall->getCallee();
5221   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
5222   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5223 
5224   // Ensure that we have at least one argument to do type inference from.
5225   if (TheCall->getNumArgs() < 1) {
5226     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5227         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
5228     return ExprError();
5229   }
5230 
5231   // Inspect the first argument of the atomic builtin.  This should always be
5232   // a pointer type, whose element is an integral scalar or pointer type.
5233   // Because it is a pointer type, we don't have to worry about any implicit
5234   // casts here.
5235   // FIXME: We don't allow floating point scalars as input.
5236   Expr *FirstArg = TheCall->getArg(0);
5237   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
5238   if (FirstArgResult.isInvalid())
5239     return ExprError();
5240   FirstArg = FirstArgResult.get();
5241   TheCall->setArg(0, FirstArg);
5242 
5243   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5244   if (!pointerType) {
5245     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
5246         << FirstArg->getType() << FirstArg->getSourceRange();
5247     return ExprError();
5248   }
5249 
5250   QualType ValType = pointerType->getPointeeType();
5251   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5252       !ValType->isBlockPointerType()) {
5253     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
5254         << FirstArg->getType() << FirstArg->getSourceRange();
5255     return ExprError();
5256   }
5257 
5258   if (ValType.isConstQualified()) {
5259     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
5260         << FirstArg->getType() << FirstArg->getSourceRange();
5261     return ExprError();
5262   }
5263 
5264   switch (ValType.getObjCLifetime()) {
5265   case Qualifiers::OCL_None:
5266   case Qualifiers::OCL_ExplicitNone:
5267     // okay
5268     break;
5269 
5270   case Qualifiers::OCL_Weak:
5271   case Qualifiers::OCL_Strong:
5272   case Qualifiers::OCL_Autoreleasing:
5273     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
5274         << ValType << FirstArg->getSourceRange();
5275     return ExprError();
5276   }
5277 
5278   // Strip any qualifiers off ValType.
5279   ValType = ValType.getUnqualifiedType();
5280 
5281   // The majority of builtins return a value, but a few have special return
5282   // types, so allow them to override appropriately below.
5283   QualType ResultType = ValType;
5284 
5285   // We need to figure out which concrete builtin this maps onto.  For example,
5286   // __sync_fetch_and_add with a 2 byte object turns into
5287   // __sync_fetch_and_add_2.
5288 #define BUILTIN_ROW(x) \
5289   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5290     Builtin::BI##x##_8, Builtin::BI##x##_16 }
5291 
5292   static const unsigned BuiltinIndices[][5] = {
5293     BUILTIN_ROW(__sync_fetch_and_add),
5294     BUILTIN_ROW(__sync_fetch_and_sub),
5295     BUILTIN_ROW(__sync_fetch_and_or),
5296     BUILTIN_ROW(__sync_fetch_and_and),
5297     BUILTIN_ROW(__sync_fetch_and_xor),
5298     BUILTIN_ROW(__sync_fetch_and_nand),
5299 
5300     BUILTIN_ROW(__sync_add_and_fetch),
5301     BUILTIN_ROW(__sync_sub_and_fetch),
5302     BUILTIN_ROW(__sync_and_and_fetch),
5303     BUILTIN_ROW(__sync_or_and_fetch),
5304     BUILTIN_ROW(__sync_xor_and_fetch),
5305     BUILTIN_ROW(__sync_nand_and_fetch),
5306 
5307     BUILTIN_ROW(__sync_val_compare_and_swap),
5308     BUILTIN_ROW(__sync_bool_compare_and_swap),
5309     BUILTIN_ROW(__sync_lock_test_and_set),
5310     BUILTIN_ROW(__sync_lock_release),
5311     BUILTIN_ROW(__sync_swap)
5312   };
5313 #undef BUILTIN_ROW
5314 
5315   // Determine the index of the size.
5316   unsigned SizeIndex;
5317   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
5318   case 1: SizeIndex = 0; break;
5319   case 2: SizeIndex = 1; break;
5320   case 4: SizeIndex = 2; break;
5321   case 8: SizeIndex = 3; break;
5322   case 16: SizeIndex = 4; break;
5323   default:
5324     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
5325         << FirstArg->getType() << FirstArg->getSourceRange();
5326     return ExprError();
5327   }
5328 
5329   // Each of these builtins has one pointer argument, followed by some number of
5330   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5331   // that we ignore.  Find out which row of BuiltinIndices to read from as well
5332   // as the number of fixed args.
5333   unsigned BuiltinID = FDecl->getBuiltinID();
5334   unsigned BuiltinIndex, NumFixed = 1;
5335   bool WarnAboutSemanticsChange = false;
5336   switch (BuiltinID) {
5337   default: llvm_unreachable("Unknown overloaded atomic builtin!");
5338   case Builtin::BI__sync_fetch_and_add:
5339   case Builtin::BI__sync_fetch_and_add_1:
5340   case Builtin::BI__sync_fetch_and_add_2:
5341   case Builtin::BI__sync_fetch_and_add_4:
5342   case Builtin::BI__sync_fetch_and_add_8:
5343   case Builtin::BI__sync_fetch_and_add_16:
5344     BuiltinIndex = 0;
5345     break;
5346 
5347   case Builtin::BI__sync_fetch_and_sub:
5348   case Builtin::BI__sync_fetch_and_sub_1:
5349   case Builtin::BI__sync_fetch_and_sub_2:
5350   case Builtin::BI__sync_fetch_and_sub_4:
5351   case Builtin::BI__sync_fetch_and_sub_8:
5352   case Builtin::BI__sync_fetch_and_sub_16:
5353     BuiltinIndex = 1;
5354     break;
5355 
5356   case Builtin::BI__sync_fetch_and_or:
5357   case Builtin::BI__sync_fetch_and_or_1:
5358   case Builtin::BI__sync_fetch_and_or_2:
5359   case Builtin::BI__sync_fetch_and_or_4:
5360   case Builtin::BI__sync_fetch_and_or_8:
5361   case Builtin::BI__sync_fetch_and_or_16:
5362     BuiltinIndex = 2;
5363     break;
5364 
5365   case Builtin::BI__sync_fetch_and_and:
5366   case Builtin::BI__sync_fetch_and_and_1:
5367   case Builtin::BI__sync_fetch_and_and_2:
5368   case Builtin::BI__sync_fetch_and_and_4:
5369   case Builtin::BI__sync_fetch_and_and_8:
5370   case Builtin::BI__sync_fetch_and_and_16:
5371     BuiltinIndex = 3;
5372     break;
5373 
5374   case Builtin::BI__sync_fetch_and_xor:
5375   case Builtin::BI__sync_fetch_and_xor_1:
5376   case Builtin::BI__sync_fetch_and_xor_2:
5377   case Builtin::BI__sync_fetch_and_xor_4:
5378   case Builtin::BI__sync_fetch_and_xor_8:
5379   case Builtin::BI__sync_fetch_and_xor_16:
5380     BuiltinIndex = 4;
5381     break;
5382 
5383   case Builtin::BI__sync_fetch_and_nand:
5384   case Builtin::BI__sync_fetch_and_nand_1:
5385   case Builtin::BI__sync_fetch_and_nand_2:
5386   case Builtin::BI__sync_fetch_and_nand_4:
5387   case Builtin::BI__sync_fetch_and_nand_8:
5388   case Builtin::BI__sync_fetch_and_nand_16:
5389     BuiltinIndex = 5;
5390     WarnAboutSemanticsChange = true;
5391     break;
5392 
5393   case Builtin::BI__sync_add_and_fetch:
5394   case Builtin::BI__sync_add_and_fetch_1:
5395   case Builtin::BI__sync_add_and_fetch_2:
5396   case Builtin::BI__sync_add_and_fetch_4:
5397   case Builtin::BI__sync_add_and_fetch_8:
5398   case Builtin::BI__sync_add_and_fetch_16:
5399     BuiltinIndex = 6;
5400     break;
5401 
5402   case Builtin::BI__sync_sub_and_fetch:
5403   case Builtin::BI__sync_sub_and_fetch_1:
5404   case Builtin::BI__sync_sub_and_fetch_2:
5405   case Builtin::BI__sync_sub_and_fetch_4:
5406   case Builtin::BI__sync_sub_and_fetch_8:
5407   case Builtin::BI__sync_sub_and_fetch_16:
5408     BuiltinIndex = 7;
5409     break;
5410 
5411   case Builtin::BI__sync_and_and_fetch:
5412   case Builtin::BI__sync_and_and_fetch_1:
5413   case Builtin::BI__sync_and_and_fetch_2:
5414   case Builtin::BI__sync_and_and_fetch_4:
5415   case Builtin::BI__sync_and_and_fetch_8:
5416   case Builtin::BI__sync_and_and_fetch_16:
5417     BuiltinIndex = 8;
5418     break;
5419 
5420   case Builtin::BI__sync_or_and_fetch:
5421   case Builtin::BI__sync_or_and_fetch_1:
5422   case Builtin::BI__sync_or_and_fetch_2:
5423   case Builtin::BI__sync_or_and_fetch_4:
5424   case Builtin::BI__sync_or_and_fetch_8:
5425   case Builtin::BI__sync_or_and_fetch_16:
5426     BuiltinIndex = 9;
5427     break;
5428 
5429   case Builtin::BI__sync_xor_and_fetch:
5430   case Builtin::BI__sync_xor_and_fetch_1:
5431   case Builtin::BI__sync_xor_and_fetch_2:
5432   case Builtin::BI__sync_xor_and_fetch_4:
5433   case Builtin::BI__sync_xor_and_fetch_8:
5434   case Builtin::BI__sync_xor_and_fetch_16:
5435     BuiltinIndex = 10;
5436     break;
5437 
5438   case Builtin::BI__sync_nand_and_fetch:
5439   case Builtin::BI__sync_nand_and_fetch_1:
5440   case Builtin::BI__sync_nand_and_fetch_2:
5441   case Builtin::BI__sync_nand_and_fetch_4:
5442   case Builtin::BI__sync_nand_and_fetch_8:
5443   case Builtin::BI__sync_nand_and_fetch_16:
5444     BuiltinIndex = 11;
5445     WarnAboutSemanticsChange = true;
5446     break;
5447 
5448   case Builtin::BI__sync_val_compare_and_swap:
5449   case Builtin::BI__sync_val_compare_and_swap_1:
5450   case Builtin::BI__sync_val_compare_and_swap_2:
5451   case Builtin::BI__sync_val_compare_and_swap_4:
5452   case Builtin::BI__sync_val_compare_and_swap_8:
5453   case Builtin::BI__sync_val_compare_and_swap_16:
5454     BuiltinIndex = 12;
5455     NumFixed = 2;
5456     break;
5457 
5458   case Builtin::BI__sync_bool_compare_and_swap:
5459   case Builtin::BI__sync_bool_compare_and_swap_1:
5460   case Builtin::BI__sync_bool_compare_and_swap_2:
5461   case Builtin::BI__sync_bool_compare_and_swap_4:
5462   case Builtin::BI__sync_bool_compare_and_swap_8:
5463   case Builtin::BI__sync_bool_compare_and_swap_16:
5464     BuiltinIndex = 13;
5465     NumFixed = 2;
5466     ResultType = Context.BoolTy;
5467     break;
5468 
5469   case Builtin::BI__sync_lock_test_and_set:
5470   case Builtin::BI__sync_lock_test_and_set_1:
5471   case Builtin::BI__sync_lock_test_and_set_2:
5472   case Builtin::BI__sync_lock_test_and_set_4:
5473   case Builtin::BI__sync_lock_test_and_set_8:
5474   case Builtin::BI__sync_lock_test_and_set_16:
5475     BuiltinIndex = 14;
5476     break;
5477 
5478   case Builtin::BI__sync_lock_release:
5479   case Builtin::BI__sync_lock_release_1:
5480   case Builtin::BI__sync_lock_release_2:
5481   case Builtin::BI__sync_lock_release_4:
5482   case Builtin::BI__sync_lock_release_8:
5483   case Builtin::BI__sync_lock_release_16:
5484     BuiltinIndex = 15;
5485     NumFixed = 0;
5486     ResultType = Context.VoidTy;
5487     break;
5488 
5489   case Builtin::BI__sync_swap:
5490   case Builtin::BI__sync_swap_1:
5491   case Builtin::BI__sync_swap_2:
5492   case Builtin::BI__sync_swap_4:
5493   case Builtin::BI__sync_swap_8:
5494   case Builtin::BI__sync_swap_16:
5495     BuiltinIndex = 16;
5496     break;
5497   }
5498 
5499   // Now that we know how many fixed arguments we expect, first check that we
5500   // have at least that many.
5501   if (TheCall->getNumArgs() < 1+NumFixed) {
5502     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5503         << 0 << 1 + NumFixed << TheCall->getNumArgs()
5504         << Callee->getSourceRange();
5505     return ExprError();
5506   }
5507 
5508   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5509       << Callee->getSourceRange();
5510 
5511   if (WarnAboutSemanticsChange) {
5512     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
5513         << Callee->getSourceRange();
5514   }
5515 
5516   // Get the decl for the concrete builtin from this, we can tell what the
5517   // concrete integer type we should convert to is.
5518   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5519   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
5520   FunctionDecl *NewBuiltinDecl;
5521   if (NewBuiltinID == BuiltinID)
5522     NewBuiltinDecl = FDecl;
5523   else {
5524     // Perform builtin lookup to avoid redeclaring it.
5525     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
5526     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5527     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5528     assert(Res.getFoundDecl());
5529     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
5530     if (!NewBuiltinDecl)
5531       return ExprError();
5532   }
5533 
5534   // The first argument --- the pointer --- has a fixed type; we
5535   // deduce the types of the rest of the arguments accordingly.  Walk
5536   // the remaining arguments, converting them to the deduced value type.
5537   for (unsigned i = 0; i != NumFixed; ++i) {
5538     ExprResult Arg = TheCall->getArg(i+1);
5539 
5540     // GCC does an implicit conversion to the pointer or integer ValType.  This
5541     // can fail in some cases (1i -> int**), check for this error case now.
5542     // Initialize the argument.
5543     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5544                                                    ValType, /*consume*/ false);
5545     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5546     if (Arg.isInvalid())
5547       return ExprError();
5548 
5549     // Okay, we have something that *can* be converted to the right type.  Check
5550     // to see if there is a potentially weird extension going on here.  This can
5551     // happen when you do an atomic operation on something like an char* and
5552     // pass in 42.  The 42 gets converted to char.  This is even more strange
5553     // for things like 45.123 -> char, etc.
5554     // FIXME: Do this check.
5555     TheCall->setArg(i+1, Arg.get());
5556   }
5557 
5558   // Create a new DeclRefExpr to refer to the new decl.
5559   DeclRefExpr *NewDRE = DeclRefExpr::Create(
5560       Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
5561       /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
5562       DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
5563 
5564   // Set the callee in the CallExpr.
5565   // FIXME: This loses syntactic information.
5566   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5567   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5568                                               CK_BuiltinFnToFnPtr);
5569   TheCall->setCallee(PromotedCall.get());
5570 
5571   // Change the result type of the call to match the original value type. This
5572   // is arbitrary, but the codegen for these builtins ins design to handle it
5573   // gracefully.
5574   TheCall->setType(ResultType);
5575 
5576   // Prohibit use of _ExtInt with atomic builtins.
5577   // The arguments would have already been converted to the first argument's
5578   // type, so only need to check the first argument.
5579   const auto *ExtIntValType = ValType->getAs<ExtIntType>();
5580   if (ExtIntValType && !llvm::isPowerOf2_64(ExtIntValType->getNumBits())) {
5581     Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
5582     return ExprError();
5583   }
5584 
5585   return TheCallResult;
5586 }
5587 
5588 /// SemaBuiltinNontemporalOverloaded - We have a call to
5589 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
5590 /// overloaded function based on the pointer type of its last argument.
5591 ///
5592 /// This function goes through and does final semantic checking for these
5593 /// builtins.
5594 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5595   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5596   DeclRefExpr *DRE =
5597       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5598   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5599   unsigned BuiltinID = FDecl->getBuiltinID();
5600   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5601           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5602          "Unexpected nontemporal load/store builtin!");
5603   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5604   unsigned numArgs = isStore ? 2 : 1;
5605 
5606   // Ensure that we have the proper number of arguments.
5607   if (checkArgCount(*this, TheCall, numArgs))
5608     return ExprError();
5609 
5610   // Inspect the last argument of the nontemporal builtin.  This should always
5611   // be a pointer type, from which we imply the type of the memory access.
5612   // Because it is a pointer type, we don't have to worry about any implicit
5613   // casts here.
5614   Expr *PointerArg = TheCall->getArg(numArgs - 1);
5615   ExprResult PointerArgResult =
5616       DefaultFunctionArrayLvalueConversion(PointerArg);
5617 
5618   if (PointerArgResult.isInvalid())
5619     return ExprError();
5620   PointerArg = PointerArgResult.get();
5621   TheCall->setArg(numArgs - 1, PointerArg);
5622 
5623   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5624   if (!pointerType) {
5625     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
5626         << PointerArg->getType() << PointerArg->getSourceRange();
5627     return ExprError();
5628   }
5629 
5630   QualType ValType = pointerType->getPointeeType();
5631 
5632   // Strip any qualifiers off ValType.
5633   ValType = ValType.getUnqualifiedType();
5634   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5635       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5636       !ValType->isVectorType()) {
5637     Diag(DRE->getBeginLoc(),
5638          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5639         << PointerArg->getType() << PointerArg->getSourceRange();
5640     return ExprError();
5641   }
5642 
5643   if (!isStore) {
5644     TheCall->setType(ValType);
5645     return TheCallResult;
5646   }
5647 
5648   ExprResult ValArg = TheCall->getArg(0);
5649   InitializedEntity Entity = InitializedEntity::InitializeParameter(
5650       Context, ValType, /*consume*/ false);
5651   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
5652   if (ValArg.isInvalid())
5653     return ExprError();
5654 
5655   TheCall->setArg(0, ValArg.get());
5656   TheCall->setType(Context.VoidTy);
5657   return TheCallResult;
5658 }
5659 
5660 /// CheckObjCString - Checks that the argument to the builtin
5661 /// CFString constructor is correct
5662 /// Note: It might also make sense to do the UTF-16 conversion here (would
5663 /// simplify the backend).
5664 bool Sema::CheckObjCString(Expr *Arg) {
5665   Arg = Arg->IgnoreParenCasts();
5666   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
5667 
5668   if (!Literal || !Literal->isAscii()) {
5669     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
5670         << Arg->getSourceRange();
5671     return true;
5672   }
5673 
5674   if (Literal->containsNonAsciiOrNull()) {
5675     StringRef String = Literal->getString();
5676     unsigned NumBytes = String.size();
5677     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
5678     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
5679     llvm::UTF16 *ToPtr = &ToBuf[0];
5680 
5681     llvm::ConversionResult Result =
5682         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
5683                                  ToPtr + NumBytes, llvm::strictConversion);
5684     // Check for conversion failure.
5685     if (Result != llvm::conversionOK)
5686       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
5687           << Arg->getSourceRange();
5688   }
5689   return false;
5690 }
5691 
5692 /// CheckObjCString - Checks that the format string argument to the os_log()
5693 /// and os_trace() functions is correct, and converts it to const char *.
5694 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5695   Arg = Arg->IgnoreParenCasts();
5696   auto *Literal = dyn_cast<StringLiteral>(Arg);
5697   if (!Literal) {
5698     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
5699       Literal = ObjcLiteral->getString();
5700     }
5701   }
5702 
5703   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
5704     return ExprError(
5705         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
5706         << Arg->getSourceRange());
5707   }
5708 
5709   ExprResult Result(Literal);
5710   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
5711   InitializedEntity Entity =
5712       InitializedEntity::InitializeParameter(Context, ResultTy, false);
5713   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
5714   return Result;
5715 }
5716 
5717 /// Check that the user is calling the appropriate va_start builtin for the
5718 /// target and calling convention.
5719 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5720   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5721   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
5722   bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
5723                     TT.getArch() == llvm::Triple::aarch64_32);
5724   bool IsWindows = TT.isOSWindows();
5725   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5726   if (IsX64 || IsAArch64) {
5727     CallingConv CC = CC_C;
5728     if (const FunctionDecl *FD = S.getCurFunctionDecl())
5729       CC = FD->getType()->castAs<FunctionType>()->getCallConv();
5730     if (IsMSVAStart) {
5731       // Don't allow this in System V ABI functions.
5732       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
5733         return S.Diag(Fn->getBeginLoc(),
5734                       diag::err_ms_va_start_used_in_sysv_function);
5735     } else {
5736       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
5737       // On x64 Windows, don't allow this in System V ABI functions.
5738       // (Yes, that means there's no corresponding way to support variadic
5739       // System V ABI functions on Windows.)
5740       if ((IsWindows && CC == CC_X86_64SysV) ||
5741           (!IsWindows && CC == CC_Win64))
5742         return S.Diag(Fn->getBeginLoc(),
5743                       diag::err_va_start_used_in_wrong_abi_function)
5744                << !IsWindows;
5745     }
5746     return false;
5747   }
5748 
5749   if (IsMSVAStart)
5750     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
5751   return false;
5752 }
5753 
5754 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
5755                                              ParmVarDecl **LastParam = nullptr) {
5756   // Determine whether the current function, block, or obj-c method is variadic
5757   // and get its parameter list.
5758   bool IsVariadic = false;
5759   ArrayRef<ParmVarDecl *> Params;
5760   DeclContext *Caller = S.CurContext;
5761   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
5762     IsVariadic = Block->isVariadic();
5763     Params = Block->parameters();
5764   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
5765     IsVariadic = FD->isVariadic();
5766     Params = FD->parameters();
5767   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
5768     IsVariadic = MD->isVariadic();
5769     // FIXME: This isn't correct for methods (results in bogus warning).
5770     Params = MD->parameters();
5771   } else if (isa<CapturedDecl>(Caller)) {
5772     // We don't support va_start in a CapturedDecl.
5773     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
5774     return true;
5775   } else {
5776     // This must be some other declcontext that parses exprs.
5777     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
5778     return true;
5779   }
5780 
5781   if (!IsVariadic) {
5782     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
5783     return true;
5784   }
5785 
5786   if (LastParam)
5787     *LastParam = Params.empty() ? nullptr : Params.back();
5788 
5789   return false;
5790 }
5791 
5792 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
5793 /// for validity.  Emit an error and return true on failure; return false
5794 /// on success.
5795 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5796   Expr *Fn = TheCall->getCallee();
5797 
5798   if (checkVAStartABI(*this, BuiltinID, Fn))
5799     return true;
5800 
5801   if (checkArgCount(*this, TheCall, 2))
5802     return true;
5803 
5804   // Type-check the first argument normally.
5805   if (checkBuiltinArgument(*this, TheCall, 0))
5806     return true;
5807 
5808   // Check that the current function is variadic, and get its last parameter.
5809   ParmVarDecl *LastParam;
5810   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
5811     return true;
5812 
5813   // Verify that the second argument to the builtin is the last argument of the
5814   // current function or method.
5815   bool SecondArgIsLastNamedArgument = false;
5816   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
5817 
5818   // These are valid if SecondArgIsLastNamedArgument is false after the next
5819   // block.
5820   QualType Type;
5821   SourceLocation ParamLoc;
5822   bool IsCRegister = false;
5823 
5824   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
5825     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
5826       SecondArgIsLastNamedArgument = PV == LastParam;
5827 
5828       Type = PV->getType();
5829       ParamLoc = PV->getLocation();
5830       IsCRegister =
5831           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
5832     }
5833   }
5834 
5835   if (!SecondArgIsLastNamedArgument)
5836     Diag(TheCall->getArg(1)->getBeginLoc(),
5837          diag::warn_second_arg_of_va_start_not_last_named_param);
5838   else if (IsCRegister || Type->isReferenceType() ||
5839            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
5840              // Promotable integers are UB, but enumerations need a bit of
5841              // extra checking to see what their promotable type actually is.
5842              if (!Type->isPromotableIntegerType())
5843                return false;
5844              if (!Type->isEnumeralType())
5845                return true;
5846              const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
5847              return !(ED &&
5848                       Context.typesAreCompatible(ED->getPromotionType(), Type));
5849            }()) {
5850     unsigned Reason = 0;
5851     if (Type->isReferenceType())  Reason = 1;
5852     else if (IsCRegister)         Reason = 2;
5853     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
5854     Diag(ParamLoc, diag::note_parameter_type) << Type;
5855   }
5856 
5857   TheCall->setType(Context.VoidTy);
5858   return false;
5859 }
5860 
5861 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
5862   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
5863   //                 const char *named_addr);
5864 
5865   Expr *Func = Call->getCallee();
5866 
5867   if (Call->getNumArgs() < 3)
5868     return Diag(Call->getEndLoc(),
5869                 diag::err_typecheck_call_too_few_args_at_least)
5870            << 0 /*function call*/ << 3 << Call->getNumArgs();
5871 
5872   // Type-check the first argument normally.
5873   if (checkBuiltinArgument(*this, Call, 0))
5874     return true;
5875 
5876   // Check that the current function is variadic.
5877   if (checkVAStartIsInVariadicFunction(*this, Func))
5878     return true;
5879 
5880   // __va_start on Windows does not validate the parameter qualifiers
5881 
5882   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
5883   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
5884 
5885   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
5886   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
5887 
5888   const QualType &ConstCharPtrTy =
5889       Context.getPointerType(Context.CharTy.withConst());
5890   if (!Arg1Ty->isPointerType() ||
5891       Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
5892     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5893         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
5894         << 0                                      /* qualifier difference */
5895         << 3                                      /* parameter mismatch */
5896         << 2 << Arg1->getType() << ConstCharPtrTy;
5897 
5898   const QualType SizeTy = Context.getSizeType();
5899   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
5900     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5901         << Arg2->getType() << SizeTy << 1 /* different class */
5902         << 0                              /* qualifier difference */
5903         << 3                              /* parameter mismatch */
5904         << 3 << Arg2->getType() << SizeTy;
5905 
5906   return false;
5907 }
5908 
5909 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
5910 /// friends.  This is declared to take (...), so we have to check everything.
5911 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
5912   if (checkArgCount(*this, TheCall, 2))
5913     return true;
5914 
5915   ExprResult OrigArg0 = TheCall->getArg(0);
5916   ExprResult OrigArg1 = TheCall->getArg(1);
5917 
5918   // Do standard promotions between the two arguments, returning their common
5919   // type.
5920   QualType Res = UsualArithmeticConversions(
5921       OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
5922   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
5923     return true;
5924 
5925   // Make sure any conversions are pushed back into the call; this is
5926   // type safe since unordered compare builtins are declared as "_Bool
5927   // foo(...)".
5928   TheCall->setArg(0, OrigArg0.get());
5929   TheCall->setArg(1, OrigArg1.get());
5930 
5931   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
5932     return false;
5933 
5934   // If the common type isn't a real floating type, then the arguments were
5935   // invalid for this operation.
5936   if (Res.isNull() || !Res->isRealFloatingType())
5937     return Diag(OrigArg0.get()->getBeginLoc(),
5938                 diag::err_typecheck_call_invalid_ordered_compare)
5939            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
5940            << SourceRange(OrigArg0.get()->getBeginLoc(),
5941                           OrigArg1.get()->getEndLoc());
5942 
5943   return false;
5944 }
5945 
5946 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
5947 /// __builtin_isnan and friends.  This is declared to take (...), so we have
5948 /// to check everything. We expect the last argument to be a floating point
5949 /// value.
5950 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
5951   if (checkArgCount(*this, TheCall, NumArgs))
5952     return true;
5953 
5954   // __builtin_fpclassify is the only case where NumArgs != 1, so we can count
5955   // on all preceding parameters just being int.  Try all of those.
5956   for (unsigned i = 0; i < NumArgs - 1; ++i) {
5957     Expr *Arg = TheCall->getArg(i);
5958 
5959     if (Arg->isTypeDependent())
5960       return false;
5961 
5962     ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);
5963 
5964     if (Res.isInvalid())
5965       return true;
5966     TheCall->setArg(i, Res.get());
5967   }
5968 
5969   Expr *OrigArg = TheCall->getArg(NumArgs-1);
5970 
5971   if (OrigArg->isTypeDependent())
5972     return false;
5973 
5974   // Usual Unary Conversions will convert half to float, which we want for
5975   // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
5976   // type how it is, but do normal L->Rvalue conversions.
5977   if (Context.getTargetInfo().useFP16ConversionIntrinsics())
5978     OrigArg = UsualUnaryConversions(OrigArg).get();
5979   else
5980     OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
5981   TheCall->setArg(NumArgs - 1, OrigArg);
5982 
5983   // This operation requires a non-_Complex floating-point number.
5984   if (!OrigArg->getType()->isRealFloatingType())
5985     return Diag(OrigArg->getBeginLoc(),
5986                 diag::err_typecheck_call_invalid_unary_fp)
5987            << OrigArg->getType() << OrigArg->getSourceRange();
5988 
5989   return false;
5990 }
5991 
5992 /// Perform semantic analysis for a call to __builtin_complex.
5993 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) {
5994   if (checkArgCount(*this, TheCall, 2))
5995     return true;
5996 
5997   bool Dependent = false;
5998   for (unsigned I = 0; I != 2; ++I) {
5999     Expr *Arg = TheCall->getArg(I);
6000     QualType T = Arg->getType();
6001     if (T->isDependentType()) {
6002       Dependent = true;
6003       continue;
6004     }
6005 
6006     // Despite supporting _Complex int, GCC requires a real floating point type
6007     // for the operands of __builtin_complex.
6008     if (!T->isRealFloatingType()) {
6009       return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
6010              << Arg->getType() << Arg->getSourceRange();
6011     }
6012 
6013     ExprResult Converted = DefaultLvalueConversion(Arg);
6014     if (Converted.isInvalid())
6015       return true;
6016     TheCall->setArg(I, Converted.get());
6017   }
6018 
6019   if (Dependent) {
6020     TheCall->setType(Context.DependentTy);
6021     return false;
6022   }
6023 
6024   Expr *Real = TheCall->getArg(0);
6025   Expr *Imag = TheCall->getArg(1);
6026   if (!Context.hasSameType(Real->getType(), Imag->getType())) {
6027     return Diag(Real->getBeginLoc(),
6028                 diag::err_typecheck_call_different_arg_types)
6029            << Real->getType() << Imag->getType()
6030            << Real->getSourceRange() << Imag->getSourceRange();
6031   }
6032 
6033   // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers;
6034   // don't allow this builtin to form those types either.
6035   // FIXME: Should we allow these types?
6036   if (Real->getType()->isFloat16Type())
6037     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6038            << "_Float16";
6039   if (Real->getType()->isHalfType())
6040     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6041            << "half";
6042 
6043   TheCall->setType(Context.getComplexType(Real->getType()));
6044   return false;
6045 }
6046 
6047 // Customized Sema Checking for VSX builtins that have the following signature:
6048 // vector [...] builtinName(vector [...], vector [...], const int);
6049 // Which takes the same type of vectors (any legal vector type) for the first
6050 // two arguments and takes compile time constant for the third argument.
6051 // Example builtins are :
6052 // vector double vec_xxpermdi(vector double, vector double, int);
6053 // vector short vec_xxsldwi(vector short, vector short, int);
6054 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
6055   unsigned ExpectedNumArgs = 3;
6056   if (checkArgCount(*this, TheCall, ExpectedNumArgs))
6057     return true;
6058 
6059   // Check the third argument is a compile time constant
6060   if (!TheCall->getArg(2)->isIntegerConstantExpr(Context))
6061     return Diag(TheCall->getBeginLoc(),
6062                 diag::err_vsx_builtin_nonconstant_argument)
6063            << 3 /* argument index */ << TheCall->getDirectCallee()
6064            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
6065                           TheCall->getArg(2)->getEndLoc());
6066 
6067   QualType Arg1Ty = TheCall->getArg(0)->getType();
6068   QualType Arg2Ty = TheCall->getArg(1)->getType();
6069 
6070   // Check the type of argument 1 and argument 2 are vectors.
6071   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
6072   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
6073       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
6074     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
6075            << TheCall->getDirectCallee()
6076            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6077                           TheCall->getArg(1)->getEndLoc());
6078   }
6079 
6080   // Check the first two arguments are the same type.
6081   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
6082     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
6083            << TheCall->getDirectCallee()
6084            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6085                           TheCall->getArg(1)->getEndLoc());
6086   }
6087 
6088   // When default clang type checking is turned off and the customized type
6089   // checking is used, the returning type of the function must be explicitly
6090   // set. Otherwise it is _Bool by default.
6091   TheCall->setType(Arg1Ty);
6092 
6093   return false;
6094 }
6095 
6096 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
6097 // This is declared to take (...), so we have to check everything.
6098 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
6099   if (TheCall->getNumArgs() < 2)
6100     return ExprError(Diag(TheCall->getEndLoc(),
6101                           diag::err_typecheck_call_too_few_args_at_least)
6102                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
6103                      << TheCall->getSourceRange());
6104 
6105   // Determine which of the following types of shufflevector we're checking:
6106   // 1) unary, vector mask: (lhs, mask)
6107   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
6108   QualType resType = TheCall->getArg(0)->getType();
6109   unsigned numElements = 0;
6110 
6111   if (!TheCall->getArg(0)->isTypeDependent() &&
6112       !TheCall->getArg(1)->isTypeDependent()) {
6113     QualType LHSType = TheCall->getArg(0)->getType();
6114     QualType RHSType = TheCall->getArg(1)->getType();
6115 
6116     if (!LHSType->isVectorType() || !RHSType->isVectorType())
6117       return ExprError(
6118           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
6119           << TheCall->getDirectCallee()
6120           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6121                          TheCall->getArg(1)->getEndLoc()));
6122 
6123     numElements = LHSType->castAs<VectorType>()->getNumElements();
6124     unsigned numResElements = TheCall->getNumArgs() - 2;
6125 
6126     // Check to see if we have a call with 2 vector arguments, the unary shuffle
6127     // with mask.  If so, verify that RHS is an integer vector type with the
6128     // same number of elts as lhs.
6129     if (TheCall->getNumArgs() == 2) {
6130       if (!RHSType->hasIntegerRepresentation() ||
6131           RHSType->castAs<VectorType>()->getNumElements() != numElements)
6132         return ExprError(Diag(TheCall->getBeginLoc(),
6133                               diag::err_vec_builtin_incompatible_vector)
6134                          << TheCall->getDirectCallee()
6135                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
6136                                         TheCall->getArg(1)->getEndLoc()));
6137     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
6138       return ExprError(Diag(TheCall->getBeginLoc(),
6139                             diag::err_vec_builtin_incompatible_vector)
6140                        << TheCall->getDirectCallee()
6141                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6142                                       TheCall->getArg(1)->getEndLoc()));
6143     } else if (numElements != numResElements) {
6144       QualType eltType = LHSType->castAs<VectorType>()->getElementType();
6145       resType = Context.getVectorType(eltType, numResElements,
6146                                       VectorType::GenericVector);
6147     }
6148   }
6149 
6150   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
6151     if (TheCall->getArg(i)->isTypeDependent() ||
6152         TheCall->getArg(i)->isValueDependent())
6153       continue;
6154 
6155     Optional<llvm::APSInt> Result;
6156     if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context)))
6157       return ExprError(Diag(TheCall->getBeginLoc(),
6158                             diag::err_shufflevector_nonconstant_argument)
6159                        << TheCall->getArg(i)->getSourceRange());
6160 
6161     // Allow -1 which will be translated to undef in the IR.
6162     if (Result->isSigned() && Result->isAllOnesValue())
6163       continue;
6164 
6165     if (Result->getActiveBits() > 64 ||
6166         Result->getZExtValue() >= numElements * 2)
6167       return ExprError(Diag(TheCall->getBeginLoc(),
6168                             diag::err_shufflevector_argument_too_large)
6169                        << TheCall->getArg(i)->getSourceRange());
6170   }
6171 
6172   SmallVector<Expr*, 32> exprs;
6173 
6174   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
6175     exprs.push_back(TheCall->getArg(i));
6176     TheCall->setArg(i, nullptr);
6177   }
6178 
6179   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
6180                                          TheCall->getCallee()->getBeginLoc(),
6181                                          TheCall->getRParenLoc());
6182 }
6183 
6184 /// SemaConvertVectorExpr - Handle __builtin_convertvector
6185 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
6186                                        SourceLocation BuiltinLoc,
6187                                        SourceLocation RParenLoc) {
6188   ExprValueKind VK = VK_RValue;
6189   ExprObjectKind OK = OK_Ordinary;
6190   QualType DstTy = TInfo->getType();
6191   QualType SrcTy = E->getType();
6192 
6193   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
6194     return ExprError(Diag(BuiltinLoc,
6195                           diag::err_convertvector_non_vector)
6196                      << E->getSourceRange());
6197   if (!DstTy->isVectorType() && !DstTy->isDependentType())
6198     return ExprError(Diag(BuiltinLoc,
6199                           diag::err_convertvector_non_vector_type));
6200 
6201   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
6202     unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
6203     unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
6204     if (SrcElts != DstElts)
6205       return ExprError(Diag(BuiltinLoc,
6206                             diag::err_convertvector_incompatible_vector)
6207                        << E->getSourceRange());
6208   }
6209 
6210   return new (Context)
6211       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
6212 }
6213 
6214 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
6215 // This is declared to take (const void*, ...) and can take two
6216 // optional constant int args.
6217 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
6218   unsigned NumArgs = TheCall->getNumArgs();
6219 
6220   if (NumArgs > 3)
6221     return Diag(TheCall->getEndLoc(),
6222                 diag::err_typecheck_call_too_many_args_at_most)
6223            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6224 
6225   // Argument 0 is checked for us and the remaining arguments must be
6226   // constant integers.
6227   for (unsigned i = 1; i != NumArgs; ++i)
6228     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
6229       return true;
6230 
6231   return false;
6232 }
6233 
6234 /// SemaBuiltinAssume - Handle __assume (MS Extension).
6235 // __assume does not evaluate its arguments, and should warn if its argument
6236 // has side effects.
6237 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
6238   Expr *Arg = TheCall->getArg(0);
6239   if (Arg->isInstantiationDependent()) return false;
6240 
6241   if (Arg->HasSideEffects(Context))
6242     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
6243         << Arg->getSourceRange()
6244         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
6245 
6246   return false;
6247 }
6248 
6249 /// Handle __builtin_alloca_with_align. This is declared
6250 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
6251 /// than 8.
6252 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
6253   // The alignment must be a constant integer.
6254   Expr *Arg = TheCall->getArg(1);
6255 
6256   // We can't check the value of a dependent argument.
6257   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6258     if (const auto *UE =
6259             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
6260       if (UE->getKind() == UETT_AlignOf ||
6261           UE->getKind() == UETT_PreferredAlignOf)
6262         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
6263             << Arg->getSourceRange();
6264 
6265     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
6266 
6267     if (!Result.isPowerOf2())
6268       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6269              << Arg->getSourceRange();
6270 
6271     if (Result < Context.getCharWidth())
6272       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
6273              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6274 
6275     if (Result > std::numeric_limits<int32_t>::max())
6276       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
6277              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6278   }
6279 
6280   return false;
6281 }
6282 
6283 /// Handle __builtin_assume_aligned. This is declared
6284 /// as (const void*, size_t, ...) and can take one optional constant int arg.
6285 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
6286   unsigned NumArgs = TheCall->getNumArgs();
6287 
6288   if (NumArgs > 3)
6289     return Diag(TheCall->getEndLoc(),
6290                 diag::err_typecheck_call_too_many_args_at_most)
6291            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6292 
6293   // The alignment must be a constant integer.
6294   Expr *Arg = TheCall->getArg(1);
6295 
6296   // We can't check the value of a dependent argument.
6297   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6298     llvm::APSInt Result;
6299     if (SemaBuiltinConstantArg(TheCall, 1, Result))
6300       return true;
6301 
6302     if (!Result.isPowerOf2())
6303       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6304              << Arg->getSourceRange();
6305 
6306     if (Result > Sema::MaximumAlignment)
6307       Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
6308           << Arg->getSourceRange() << Sema::MaximumAlignment;
6309   }
6310 
6311   if (NumArgs > 2) {
6312     ExprResult Arg(TheCall->getArg(2));
6313     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6314       Context.getSizeType(), false);
6315     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6316     if (Arg.isInvalid()) return true;
6317     TheCall->setArg(2, Arg.get());
6318   }
6319 
6320   return false;
6321 }
6322 
6323 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
6324   unsigned BuiltinID =
6325       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
6326   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6327 
6328   unsigned NumArgs = TheCall->getNumArgs();
6329   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6330   if (NumArgs < NumRequiredArgs) {
6331     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
6332            << 0 /* function call */ << NumRequiredArgs << NumArgs
6333            << TheCall->getSourceRange();
6334   }
6335   if (NumArgs >= NumRequiredArgs + 0x100) {
6336     return Diag(TheCall->getEndLoc(),
6337                 diag::err_typecheck_call_too_many_args_at_most)
6338            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6339            << TheCall->getSourceRange();
6340   }
6341   unsigned i = 0;
6342 
6343   // For formatting call, check buffer arg.
6344   if (!IsSizeCall) {
6345     ExprResult Arg(TheCall->getArg(i));
6346     InitializedEntity Entity = InitializedEntity::InitializeParameter(
6347         Context, Context.VoidPtrTy, false);
6348     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6349     if (Arg.isInvalid())
6350       return true;
6351     TheCall->setArg(i, Arg.get());
6352     i++;
6353   }
6354 
6355   // Check string literal arg.
6356   unsigned FormatIdx = i;
6357   {
6358     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
6359     if (Arg.isInvalid())
6360       return true;
6361     TheCall->setArg(i, Arg.get());
6362     i++;
6363   }
6364 
6365   // Make sure variadic args are scalar.
6366   unsigned FirstDataArg = i;
6367   while (i < NumArgs) {
6368     ExprResult Arg = DefaultVariadicArgumentPromotion(
6369         TheCall->getArg(i), VariadicFunction, nullptr);
6370     if (Arg.isInvalid())
6371       return true;
6372     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
6373     if (ArgSize.getQuantity() >= 0x100) {
6374       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
6375              << i << (int)ArgSize.getQuantity() << 0xff
6376              << TheCall->getSourceRange();
6377     }
6378     TheCall->setArg(i, Arg.get());
6379     i++;
6380   }
6381 
6382   // Check formatting specifiers. NOTE: We're only doing this for the non-size
6383   // call to avoid duplicate diagnostics.
6384   if (!IsSizeCall) {
6385     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6386     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6387     bool Success = CheckFormatArguments(
6388         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
6389         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
6390         CheckedVarArgs);
6391     if (!Success)
6392       return true;
6393   }
6394 
6395   if (IsSizeCall) {
6396     TheCall->setType(Context.getSizeType());
6397   } else {
6398     TheCall->setType(Context.VoidPtrTy);
6399   }
6400   return false;
6401 }
6402 
6403 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
6404 /// TheCall is a constant expression.
6405 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
6406                                   llvm::APSInt &Result) {
6407   Expr *Arg = TheCall->getArg(ArgNum);
6408   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6409   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6410 
6411   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
6412 
6413   Optional<llvm::APSInt> R;
6414   if (!(R = Arg->getIntegerConstantExpr(Context)))
6415     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6416            << FDecl->getDeclName() << Arg->getSourceRange();
6417   Result = *R;
6418   return false;
6419 }
6420 
6421 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
6422 /// TheCall is a constant expression in the range [Low, High].
6423 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
6424                                        int Low, int High, bool RangeIsError) {
6425   if (isConstantEvaluated())
6426     return false;
6427   llvm::APSInt Result;
6428 
6429   // We can't check the value of a dependent argument.
6430   Expr *Arg = TheCall->getArg(ArgNum);
6431   if (Arg->isTypeDependent() || Arg->isValueDependent())
6432     return false;
6433 
6434   // Check constant-ness first.
6435   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6436     return true;
6437 
6438   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6439     if (RangeIsError)
6440       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
6441              << Result.toString(10) << Low << High << Arg->getSourceRange();
6442     else
6443       // Defer the warning until we know if the code will be emitted so that
6444       // dead code can ignore this.
6445       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6446                           PDiag(diag::warn_argument_invalid_range)
6447                               << Result.toString(10) << Low << High
6448                               << Arg->getSourceRange());
6449   }
6450 
6451   return false;
6452 }
6453 
6454 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
6455 /// TheCall is a constant expression is a multiple of Num..
6456 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
6457                                           unsigned Num) {
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   if (Result.getSExtValue() % Num != 0)
6470     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6471            << Num << Arg->getSourceRange();
6472 
6473   return false;
6474 }
6475 
6476 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
6477 /// constant expression representing a power of 2.
6478 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
6479   llvm::APSInt Result;
6480 
6481   // We can't check the value of a dependent argument.
6482   Expr *Arg = TheCall->getArg(ArgNum);
6483   if (Arg->isTypeDependent() || Arg->isValueDependent())
6484     return false;
6485 
6486   // Check constant-ness first.
6487   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6488     return true;
6489 
6490   // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
6491   // and only if x is a power of 2.
6492   if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
6493     return false;
6494 
6495   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
6496          << Arg->getSourceRange();
6497 }
6498 
6499 static bool IsShiftedByte(llvm::APSInt Value) {
6500   if (Value.isNegative())
6501     return false;
6502 
6503   // Check if it's a shifted byte, by shifting it down
6504   while (true) {
6505     // If the value fits in the bottom byte, the check passes.
6506     if (Value < 0x100)
6507       return true;
6508 
6509     // Otherwise, if the value has _any_ bits in the bottom byte, the check
6510     // fails.
6511     if ((Value & 0xFF) != 0)
6512       return false;
6513 
6514     // If the bottom 8 bits are all 0, but something above that is nonzero,
6515     // then shifting the value right by 8 bits won't affect whether it's a
6516     // shifted byte or not. So do that, and go round again.
6517     Value >>= 8;
6518   }
6519 }
6520 
6521 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
6522 /// a constant expression representing an arbitrary byte value shifted left by
6523 /// a multiple of 8 bits.
6524 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
6525                                              unsigned ArgBits) {
6526   llvm::APSInt Result;
6527 
6528   // We can't check the value of a dependent argument.
6529   Expr *Arg = TheCall->getArg(ArgNum);
6530   if (Arg->isTypeDependent() || Arg->isValueDependent())
6531     return false;
6532 
6533   // Check constant-ness first.
6534   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6535     return true;
6536 
6537   // Truncate to the given size.
6538   Result = Result.getLoBits(ArgBits);
6539   Result.setIsUnsigned(true);
6540 
6541   if (IsShiftedByte(Result))
6542     return false;
6543 
6544   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
6545          << Arg->getSourceRange();
6546 }
6547 
6548 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
6549 /// TheCall is a constant expression representing either a shifted byte value,
6550 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
6551 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
6552 /// Arm MVE intrinsics.
6553 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
6554                                                    int ArgNum,
6555                                                    unsigned ArgBits) {
6556   llvm::APSInt Result;
6557 
6558   // We can't check the value of a dependent argument.
6559   Expr *Arg = TheCall->getArg(ArgNum);
6560   if (Arg->isTypeDependent() || Arg->isValueDependent())
6561     return false;
6562 
6563   // Check constant-ness first.
6564   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6565     return true;
6566 
6567   // Truncate to the given size.
6568   Result = Result.getLoBits(ArgBits);
6569   Result.setIsUnsigned(true);
6570 
6571   // Check to see if it's in either of the required forms.
6572   if (IsShiftedByte(Result) ||
6573       (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
6574     return false;
6575 
6576   return Diag(TheCall->getBeginLoc(),
6577               diag::err_argument_not_shifted_byte_or_xxff)
6578          << Arg->getSourceRange();
6579 }
6580 
6581 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
6582 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
6583   if (BuiltinID == AArch64::BI__builtin_arm_irg) {
6584     if (checkArgCount(*this, TheCall, 2))
6585       return true;
6586     Expr *Arg0 = TheCall->getArg(0);
6587     Expr *Arg1 = TheCall->getArg(1);
6588 
6589     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6590     if (FirstArg.isInvalid())
6591       return true;
6592     QualType FirstArgType = FirstArg.get()->getType();
6593     if (!FirstArgType->isAnyPointerType())
6594       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6595                << "first" << FirstArgType << Arg0->getSourceRange();
6596     TheCall->setArg(0, FirstArg.get());
6597 
6598     ExprResult SecArg = DefaultLvalueConversion(Arg1);
6599     if (SecArg.isInvalid())
6600       return true;
6601     QualType SecArgType = SecArg.get()->getType();
6602     if (!SecArgType->isIntegerType())
6603       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6604                << "second" << SecArgType << Arg1->getSourceRange();
6605 
6606     // Derive the return type from the pointer argument.
6607     TheCall->setType(FirstArgType);
6608     return false;
6609   }
6610 
6611   if (BuiltinID == AArch64::BI__builtin_arm_addg) {
6612     if (checkArgCount(*this, TheCall, 2))
6613       return true;
6614 
6615     Expr *Arg0 = TheCall->getArg(0);
6616     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6617     if (FirstArg.isInvalid())
6618       return true;
6619     QualType FirstArgType = FirstArg.get()->getType();
6620     if (!FirstArgType->isAnyPointerType())
6621       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6622                << "first" << FirstArgType << Arg0->getSourceRange();
6623     TheCall->setArg(0, FirstArg.get());
6624 
6625     // Derive the return type from the pointer argument.
6626     TheCall->setType(FirstArgType);
6627 
6628     // Second arg must be an constant in range [0,15]
6629     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6630   }
6631 
6632   if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
6633     if (checkArgCount(*this, TheCall, 2))
6634       return true;
6635     Expr *Arg0 = TheCall->getArg(0);
6636     Expr *Arg1 = TheCall->getArg(1);
6637 
6638     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6639     if (FirstArg.isInvalid())
6640       return true;
6641     QualType FirstArgType = FirstArg.get()->getType();
6642     if (!FirstArgType->isAnyPointerType())
6643       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6644                << "first" << FirstArgType << Arg0->getSourceRange();
6645 
6646     QualType SecArgType = Arg1->getType();
6647     if (!SecArgType->isIntegerType())
6648       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6649                << "second" << SecArgType << Arg1->getSourceRange();
6650     TheCall->setType(Context.IntTy);
6651     return false;
6652   }
6653 
6654   if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
6655       BuiltinID == AArch64::BI__builtin_arm_stg) {
6656     if (checkArgCount(*this, TheCall, 1))
6657       return true;
6658     Expr *Arg0 = TheCall->getArg(0);
6659     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6660     if (FirstArg.isInvalid())
6661       return true;
6662 
6663     QualType FirstArgType = FirstArg.get()->getType();
6664     if (!FirstArgType->isAnyPointerType())
6665       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6666                << "first" << FirstArgType << Arg0->getSourceRange();
6667     TheCall->setArg(0, FirstArg.get());
6668 
6669     // Derive the return type from the pointer argument.
6670     if (BuiltinID == AArch64::BI__builtin_arm_ldg)
6671       TheCall->setType(FirstArgType);
6672     return false;
6673   }
6674 
6675   if (BuiltinID == AArch64::BI__builtin_arm_subp) {
6676     Expr *ArgA = TheCall->getArg(0);
6677     Expr *ArgB = TheCall->getArg(1);
6678 
6679     ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
6680     ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
6681 
6682     if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
6683       return true;
6684 
6685     QualType ArgTypeA = ArgExprA.get()->getType();
6686     QualType ArgTypeB = ArgExprB.get()->getType();
6687 
6688     auto isNull = [&] (Expr *E) -> bool {
6689       return E->isNullPointerConstant(
6690                         Context, Expr::NPC_ValueDependentIsNotNull); };
6691 
6692     // argument should be either a pointer or null
6693     if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
6694       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6695         << "first" << ArgTypeA << ArgA->getSourceRange();
6696 
6697     if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
6698       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6699         << "second" << ArgTypeB << ArgB->getSourceRange();
6700 
6701     // Ensure Pointee types are compatible
6702     if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
6703         ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
6704       QualType pointeeA = ArgTypeA->getPointeeType();
6705       QualType pointeeB = ArgTypeB->getPointeeType();
6706       if (!Context.typesAreCompatible(
6707              Context.getCanonicalType(pointeeA).getUnqualifiedType(),
6708              Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
6709         return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
6710           << ArgTypeA <<  ArgTypeB << ArgA->getSourceRange()
6711           << ArgB->getSourceRange();
6712       }
6713     }
6714 
6715     // at least one argument should be pointer type
6716     if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
6717       return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
6718         <<  ArgTypeA << ArgTypeB << ArgA->getSourceRange();
6719 
6720     if (isNull(ArgA)) // adopt type of the other pointer
6721       ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
6722 
6723     if (isNull(ArgB))
6724       ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
6725 
6726     TheCall->setArg(0, ArgExprA.get());
6727     TheCall->setArg(1, ArgExprB.get());
6728     TheCall->setType(Context.LongLongTy);
6729     return false;
6730   }
6731   assert(false && "Unhandled ARM MTE intrinsic");
6732   return true;
6733 }
6734 
6735 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
6736 /// TheCall is an ARM/AArch64 special register string literal.
6737 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
6738                                     int ArgNum, unsigned ExpectedFieldNum,
6739                                     bool AllowName) {
6740   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
6741                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
6742                       BuiltinID == ARM::BI__builtin_arm_rsr ||
6743                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
6744                       BuiltinID == ARM::BI__builtin_arm_wsr ||
6745                       BuiltinID == ARM::BI__builtin_arm_wsrp;
6746   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
6747                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
6748                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
6749                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
6750                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
6751                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
6752   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
6753 
6754   // We can't check the value of a dependent argument.
6755   Expr *Arg = TheCall->getArg(ArgNum);
6756   if (Arg->isTypeDependent() || Arg->isValueDependent())
6757     return false;
6758 
6759   // Check if the argument is a string literal.
6760   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
6761     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
6762            << Arg->getSourceRange();
6763 
6764   // Check the type of special register given.
6765   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
6766   SmallVector<StringRef, 6> Fields;
6767   Reg.split(Fields, ":");
6768 
6769   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
6770     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6771            << Arg->getSourceRange();
6772 
6773   // If the string is the name of a register then we cannot check that it is
6774   // valid here but if the string is of one the forms described in ACLE then we
6775   // can check that the supplied fields are integers and within the valid
6776   // ranges.
6777   if (Fields.size() > 1) {
6778     bool FiveFields = Fields.size() == 5;
6779 
6780     bool ValidString = true;
6781     if (IsARMBuiltin) {
6782       ValidString &= Fields[0].startswith_lower("cp") ||
6783                      Fields[0].startswith_lower("p");
6784       if (ValidString)
6785         Fields[0] =
6786           Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
6787 
6788       ValidString &= Fields[2].startswith_lower("c");
6789       if (ValidString)
6790         Fields[2] = Fields[2].drop_front(1);
6791 
6792       if (FiveFields) {
6793         ValidString &= Fields[3].startswith_lower("c");
6794         if (ValidString)
6795           Fields[3] = Fields[3].drop_front(1);
6796       }
6797     }
6798 
6799     SmallVector<int, 5> Ranges;
6800     if (FiveFields)
6801       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
6802     else
6803       Ranges.append({15, 7, 15});
6804 
6805     for (unsigned i=0; i<Fields.size(); ++i) {
6806       int IntField;
6807       ValidString &= !Fields[i].getAsInteger(10, IntField);
6808       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
6809     }
6810 
6811     if (!ValidString)
6812       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6813              << Arg->getSourceRange();
6814   } else if (IsAArch64Builtin && Fields.size() == 1) {
6815     // If the register name is one of those that appear in the condition below
6816     // and the special register builtin being used is one of the write builtins,
6817     // then we require that the argument provided for writing to the register
6818     // is an integer constant expression. This is because it will be lowered to
6819     // an MSR (immediate) instruction, so we need to know the immediate at
6820     // compile time.
6821     if (TheCall->getNumArgs() != 2)
6822       return false;
6823 
6824     std::string RegLower = Reg.lower();
6825     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
6826         RegLower != "pan" && RegLower != "uao")
6827       return false;
6828 
6829     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6830   }
6831 
6832   return false;
6833 }
6834 
6835 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity.
6836 /// Emit an error and return true on failure; return false on success.
6837 /// TypeStr is a string containing the type descriptor of the value returned by
6838 /// the builtin and the descriptors of the expected type of the arguments.
6839 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, const char *TypeStr) {
6840 
6841   assert((TypeStr[0] != '\0') &&
6842          "Invalid types in PPC MMA builtin declaration");
6843 
6844   unsigned Mask = 0;
6845   unsigned ArgNum = 0;
6846 
6847   // The first type in TypeStr is the type of the value returned by the
6848   // builtin. So we first read that type and change the type of TheCall.
6849   QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
6850   TheCall->setType(type);
6851 
6852   while (*TypeStr != '\0') {
6853     Mask = 0;
6854     QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
6855     if (ArgNum >= TheCall->getNumArgs()) {
6856       ArgNum++;
6857       break;
6858     }
6859 
6860     Expr *Arg = TheCall->getArg(ArgNum);
6861     QualType ArgType = Arg->getType();
6862 
6863     if ((ExpectedType->isVoidPointerType() && !ArgType->isPointerType()) ||
6864         (!ExpectedType->isVoidPointerType() &&
6865            ArgType.getCanonicalType() != ExpectedType))
6866       return Diag(Arg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6867              << ArgType << ExpectedType << 1 << 0 << 0;
6868 
6869     // If the value of the Mask is not 0, we have a constraint in the size of
6870     // the integer argument so here we ensure the argument is a constant that
6871     // is in the valid range.
6872     if (Mask != 0 &&
6873         SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true))
6874       return true;
6875 
6876     ArgNum++;
6877   }
6878 
6879   // In case we exited early from the previous loop, there are other types to
6880   // read from TypeStr. So we need to read them all to ensure we have the right
6881   // number of arguments in TheCall and if it is not the case, to display a
6882   // better error message.
6883   while (*TypeStr != '\0') {
6884     (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
6885     ArgNum++;
6886   }
6887   if (checkArgCount(*this, TheCall, ArgNum))
6888     return true;
6889 
6890   return false;
6891 }
6892 
6893 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
6894 /// This checks that the target supports __builtin_longjmp and
6895 /// that val is a constant 1.
6896 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
6897   if (!Context.getTargetInfo().hasSjLjLowering())
6898     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
6899            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6900 
6901   Expr *Arg = TheCall->getArg(1);
6902   llvm::APSInt Result;
6903 
6904   // TODO: This is less than ideal. Overload this to take a value.
6905   if (SemaBuiltinConstantArg(TheCall, 1, Result))
6906     return true;
6907 
6908   if (Result != 1)
6909     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
6910            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
6911 
6912   return false;
6913 }
6914 
6915 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
6916 /// This checks that the target supports __builtin_setjmp.
6917 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
6918   if (!Context.getTargetInfo().hasSjLjLowering())
6919     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
6920            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6921   return false;
6922 }
6923 
6924 namespace {
6925 
6926 class UncoveredArgHandler {
6927   enum { Unknown = -1, AllCovered = -2 };
6928 
6929   signed FirstUncoveredArg = Unknown;
6930   SmallVector<const Expr *, 4> DiagnosticExprs;
6931 
6932 public:
6933   UncoveredArgHandler() = default;
6934 
6935   bool hasUncoveredArg() const {
6936     return (FirstUncoveredArg >= 0);
6937   }
6938 
6939   unsigned getUncoveredArg() const {
6940     assert(hasUncoveredArg() && "no uncovered argument");
6941     return FirstUncoveredArg;
6942   }
6943 
6944   void setAllCovered() {
6945     // A string has been found with all arguments covered, so clear out
6946     // the diagnostics.
6947     DiagnosticExprs.clear();
6948     FirstUncoveredArg = AllCovered;
6949   }
6950 
6951   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
6952     assert(NewFirstUncoveredArg >= 0 && "Outside range");
6953 
6954     // Don't update if a previous string covers all arguments.
6955     if (FirstUncoveredArg == AllCovered)
6956       return;
6957 
6958     // UncoveredArgHandler tracks the highest uncovered argument index
6959     // and with it all the strings that match this index.
6960     if (NewFirstUncoveredArg == FirstUncoveredArg)
6961       DiagnosticExprs.push_back(StrExpr);
6962     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
6963       DiagnosticExprs.clear();
6964       DiagnosticExprs.push_back(StrExpr);
6965       FirstUncoveredArg = NewFirstUncoveredArg;
6966     }
6967   }
6968 
6969   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
6970 };
6971 
6972 enum StringLiteralCheckType {
6973   SLCT_NotALiteral,
6974   SLCT_UncheckedLiteral,
6975   SLCT_CheckedLiteral
6976 };
6977 
6978 } // namespace
6979 
6980 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
6981                                      BinaryOperatorKind BinOpKind,
6982                                      bool AddendIsRight) {
6983   unsigned BitWidth = Offset.getBitWidth();
6984   unsigned AddendBitWidth = Addend.getBitWidth();
6985   // There might be negative interim results.
6986   if (Addend.isUnsigned()) {
6987     Addend = Addend.zext(++AddendBitWidth);
6988     Addend.setIsSigned(true);
6989   }
6990   // Adjust the bit width of the APSInts.
6991   if (AddendBitWidth > BitWidth) {
6992     Offset = Offset.sext(AddendBitWidth);
6993     BitWidth = AddendBitWidth;
6994   } else if (BitWidth > AddendBitWidth) {
6995     Addend = Addend.sext(BitWidth);
6996   }
6997 
6998   bool Ov = false;
6999   llvm::APSInt ResOffset = Offset;
7000   if (BinOpKind == BO_Add)
7001     ResOffset = Offset.sadd_ov(Addend, Ov);
7002   else {
7003     assert(AddendIsRight && BinOpKind == BO_Sub &&
7004            "operator must be add or sub with addend on the right");
7005     ResOffset = Offset.ssub_ov(Addend, Ov);
7006   }
7007 
7008   // We add an offset to a pointer here so we should support an offset as big as
7009   // possible.
7010   if (Ov) {
7011     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
7012            "index (intermediate) result too big");
7013     Offset = Offset.sext(2 * BitWidth);
7014     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
7015     return;
7016   }
7017 
7018   Offset = ResOffset;
7019 }
7020 
7021 namespace {
7022 
7023 // This is a wrapper class around StringLiteral to support offsetted string
7024 // literals as format strings. It takes the offset into account when returning
7025 // the string and its length or the source locations to display notes correctly.
7026 class FormatStringLiteral {
7027   const StringLiteral *FExpr;
7028   int64_t Offset;
7029 
7030  public:
7031   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
7032       : FExpr(fexpr), Offset(Offset) {}
7033 
7034   StringRef getString() const {
7035     return FExpr->getString().drop_front(Offset);
7036   }
7037 
7038   unsigned getByteLength() const {
7039     return FExpr->getByteLength() - getCharByteWidth() * Offset;
7040   }
7041 
7042   unsigned getLength() const { return FExpr->getLength() - Offset; }
7043   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
7044 
7045   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
7046 
7047   QualType getType() const { return FExpr->getType(); }
7048 
7049   bool isAscii() const { return FExpr->isAscii(); }
7050   bool isWide() const { return FExpr->isWide(); }
7051   bool isUTF8() const { return FExpr->isUTF8(); }
7052   bool isUTF16() const { return FExpr->isUTF16(); }
7053   bool isUTF32() const { return FExpr->isUTF32(); }
7054   bool isPascal() const { return FExpr->isPascal(); }
7055 
7056   SourceLocation getLocationOfByte(
7057       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
7058       const TargetInfo &Target, unsigned *StartToken = nullptr,
7059       unsigned *StartTokenByteOffset = nullptr) const {
7060     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
7061                                     StartToken, StartTokenByteOffset);
7062   }
7063 
7064   SourceLocation getBeginLoc() const LLVM_READONLY {
7065     return FExpr->getBeginLoc().getLocWithOffset(Offset);
7066   }
7067 
7068   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
7069 };
7070 
7071 }  // namespace
7072 
7073 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
7074                               const Expr *OrigFormatExpr,
7075                               ArrayRef<const Expr *> Args,
7076                               bool HasVAListArg, unsigned format_idx,
7077                               unsigned firstDataArg,
7078                               Sema::FormatStringType Type,
7079                               bool inFunctionCall,
7080                               Sema::VariadicCallType CallType,
7081                               llvm::SmallBitVector &CheckedVarArgs,
7082                               UncoveredArgHandler &UncoveredArg,
7083                               bool IgnoreStringsWithoutSpecifiers);
7084 
7085 // Determine if an expression is a string literal or constant string.
7086 // If this function returns false on the arguments to a function expecting a
7087 // format string, we will usually need to emit a warning.
7088 // True string literals are then checked by CheckFormatString.
7089 static StringLiteralCheckType
7090 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
7091                       bool HasVAListArg, unsigned format_idx,
7092                       unsigned firstDataArg, Sema::FormatStringType Type,
7093                       Sema::VariadicCallType CallType, bool InFunctionCall,
7094                       llvm::SmallBitVector &CheckedVarArgs,
7095                       UncoveredArgHandler &UncoveredArg,
7096                       llvm::APSInt Offset,
7097                       bool IgnoreStringsWithoutSpecifiers = false) {
7098   if (S.isConstantEvaluated())
7099     return SLCT_NotALiteral;
7100  tryAgain:
7101   assert(Offset.isSigned() && "invalid offset");
7102 
7103   if (E->isTypeDependent() || E->isValueDependent())
7104     return SLCT_NotALiteral;
7105 
7106   E = E->IgnoreParenCasts();
7107 
7108   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
7109     // Technically -Wformat-nonliteral does not warn about this case.
7110     // The behavior of printf and friends in this case is implementation
7111     // dependent.  Ideally if the format string cannot be null then
7112     // it should have a 'nonnull' attribute in the function prototype.
7113     return SLCT_UncheckedLiteral;
7114 
7115   switch (E->getStmtClass()) {
7116   case Stmt::BinaryConditionalOperatorClass:
7117   case Stmt::ConditionalOperatorClass: {
7118     // The expression is a literal if both sub-expressions were, and it was
7119     // completely checked only if both sub-expressions were checked.
7120     const AbstractConditionalOperator *C =
7121         cast<AbstractConditionalOperator>(E);
7122 
7123     // Determine whether it is necessary to check both sub-expressions, for
7124     // example, because the condition expression is a constant that can be
7125     // evaluated at compile time.
7126     bool CheckLeft = true, CheckRight = true;
7127 
7128     bool Cond;
7129     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
7130                                                  S.isConstantEvaluated())) {
7131       if (Cond)
7132         CheckRight = false;
7133       else
7134         CheckLeft = false;
7135     }
7136 
7137     // We need to maintain the offsets for the right and the left hand side
7138     // separately to check if every possible indexed expression is a valid
7139     // string literal. They might have different offsets for different string
7140     // literals in the end.
7141     StringLiteralCheckType Left;
7142     if (!CheckLeft)
7143       Left = SLCT_UncheckedLiteral;
7144     else {
7145       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
7146                                    HasVAListArg, format_idx, firstDataArg,
7147                                    Type, CallType, InFunctionCall,
7148                                    CheckedVarArgs, UncoveredArg, Offset,
7149                                    IgnoreStringsWithoutSpecifiers);
7150       if (Left == SLCT_NotALiteral || !CheckRight) {
7151         return Left;
7152       }
7153     }
7154 
7155     StringLiteralCheckType Right = checkFormatStringExpr(
7156         S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
7157         Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7158         IgnoreStringsWithoutSpecifiers);
7159 
7160     return (CheckLeft && Left < Right) ? Left : Right;
7161   }
7162 
7163   case Stmt::ImplicitCastExprClass:
7164     E = cast<ImplicitCastExpr>(E)->getSubExpr();
7165     goto tryAgain;
7166 
7167   case Stmt::OpaqueValueExprClass:
7168     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
7169       E = src;
7170       goto tryAgain;
7171     }
7172     return SLCT_NotALiteral;
7173 
7174   case Stmt::PredefinedExprClass:
7175     // While __func__, etc., are technically not string literals, they
7176     // cannot contain format specifiers and thus are not a security
7177     // liability.
7178     return SLCT_UncheckedLiteral;
7179 
7180   case Stmt::DeclRefExprClass: {
7181     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7182 
7183     // As an exception, do not flag errors for variables binding to
7184     // const string literals.
7185     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
7186       bool isConstant = false;
7187       QualType T = DR->getType();
7188 
7189       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
7190         isConstant = AT->getElementType().isConstant(S.Context);
7191       } else if (const PointerType *PT = T->getAs<PointerType>()) {
7192         isConstant = T.isConstant(S.Context) &&
7193                      PT->getPointeeType().isConstant(S.Context);
7194       } else if (T->isObjCObjectPointerType()) {
7195         // In ObjC, there is usually no "const ObjectPointer" type,
7196         // so don't check if the pointee type is constant.
7197         isConstant = T.isConstant(S.Context);
7198       }
7199 
7200       if (isConstant) {
7201         if (const Expr *Init = VD->getAnyInitializer()) {
7202           // Look through initializers like const char c[] = { "foo" }
7203           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
7204             if (InitList->isStringLiteralInit())
7205               Init = InitList->getInit(0)->IgnoreParenImpCasts();
7206           }
7207           return checkFormatStringExpr(S, Init, Args,
7208                                        HasVAListArg, format_idx,
7209                                        firstDataArg, Type, CallType,
7210                                        /*InFunctionCall*/ false, CheckedVarArgs,
7211                                        UncoveredArg, Offset);
7212         }
7213       }
7214 
7215       // For vprintf* functions (i.e., HasVAListArg==true), we add a
7216       // special check to see if the format string is a function parameter
7217       // of the function calling the printf function.  If the function
7218       // has an attribute indicating it is a printf-like function, then we
7219       // should suppress warnings concerning non-literals being used in a call
7220       // to a vprintf function.  For example:
7221       //
7222       // void
7223       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
7224       //      va_list ap;
7225       //      va_start(ap, fmt);
7226       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
7227       //      ...
7228       // }
7229       if (HasVAListArg) {
7230         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
7231           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
7232             int PVIndex = PV->getFunctionScopeIndex() + 1;
7233             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
7234               // adjust for implicit parameter
7235               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
7236                 if (MD->isInstance())
7237                   ++PVIndex;
7238               // We also check if the formats are compatible.
7239               // We can't pass a 'scanf' string to a 'printf' function.
7240               if (PVIndex == PVFormat->getFormatIdx() &&
7241                   Type == S.GetFormatStringType(PVFormat))
7242                 return SLCT_UncheckedLiteral;
7243             }
7244           }
7245         }
7246       }
7247     }
7248 
7249     return SLCT_NotALiteral;
7250   }
7251 
7252   case Stmt::CallExprClass:
7253   case Stmt::CXXMemberCallExprClass: {
7254     const CallExpr *CE = cast<CallExpr>(E);
7255     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
7256       bool IsFirst = true;
7257       StringLiteralCheckType CommonResult;
7258       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
7259         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
7260         StringLiteralCheckType Result = checkFormatStringExpr(
7261             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7262             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7263             IgnoreStringsWithoutSpecifiers);
7264         if (IsFirst) {
7265           CommonResult = Result;
7266           IsFirst = false;
7267         }
7268       }
7269       if (!IsFirst)
7270         return CommonResult;
7271 
7272       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
7273         unsigned BuiltinID = FD->getBuiltinID();
7274         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
7275             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
7276           const Expr *Arg = CE->getArg(0);
7277           return checkFormatStringExpr(S, Arg, Args,
7278                                        HasVAListArg, format_idx,
7279                                        firstDataArg, Type, CallType,
7280                                        InFunctionCall, CheckedVarArgs,
7281                                        UncoveredArg, Offset,
7282                                        IgnoreStringsWithoutSpecifiers);
7283         }
7284       }
7285     }
7286 
7287     return SLCT_NotALiteral;
7288   }
7289   case Stmt::ObjCMessageExprClass: {
7290     const auto *ME = cast<ObjCMessageExpr>(E);
7291     if (const auto *MD = ME->getMethodDecl()) {
7292       if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
7293         // As a special case heuristic, if we're using the method -[NSBundle
7294         // localizedStringForKey:value:table:], ignore any key strings that lack
7295         // format specifiers. The idea is that if the key doesn't have any
7296         // format specifiers then its probably just a key to map to the
7297         // localized strings. If it does have format specifiers though, then its
7298         // likely that the text of the key is the format string in the
7299         // programmer's language, and should be checked.
7300         const ObjCInterfaceDecl *IFace;
7301         if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
7302             IFace->getIdentifier()->isStr("NSBundle") &&
7303             MD->getSelector().isKeywordSelector(
7304                 {"localizedStringForKey", "value", "table"})) {
7305           IgnoreStringsWithoutSpecifiers = true;
7306         }
7307 
7308         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
7309         return checkFormatStringExpr(
7310             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7311             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7312             IgnoreStringsWithoutSpecifiers);
7313       }
7314     }
7315 
7316     return SLCT_NotALiteral;
7317   }
7318   case Stmt::ObjCStringLiteralClass:
7319   case Stmt::StringLiteralClass: {
7320     const StringLiteral *StrE = nullptr;
7321 
7322     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
7323       StrE = ObjCFExpr->getString();
7324     else
7325       StrE = cast<StringLiteral>(E);
7326 
7327     if (StrE) {
7328       if (Offset.isNegative() || Offset > StrE->getLength()) {
7329         // TODO: It would be better to have an explicit warning for out of
7330         // bounds literals.
7331         return SLCT_NotALiteral;
7332       }
7333       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
7334       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
7335                         firstDataArg, Type, InFunctionCall, CallType,
7336                         CheckedVarArgs, UncoveredArg,
7337                         IgnoreStringsWithoutSpecifiers);
7338       return SLCT_CheckedLiteral;
7339     }
7340 
7341     return SLCT_NotALiteral;
7342   }
7343   case Stmt::BinaryOperatorClass: {
7344     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
7345 
7346     // A string literal + an int offset is still a string literal.
7347     if (BinOp->isAdditiveOp()) {
7348       Expr::EvalResult LResult, RResult;
7349 
7350       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
7351           LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7352       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
7353           RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7354 
7355       if (LIsInt != RIsInt) {
7356         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
7357 
7358         if (LIsInt) {
7359           if (BinOpKind == BO_Add) {
7360             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
7361             E = BinOp->getRHS();
7362             goto tryAgain;
7363           }
7364         } else {
7365           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
7366           E = BinOp->getLHS();
7367           goto tryAgain;
7368         }
7369       }
7370     }
7371 
7372     return SLCT_NotALiteral;
7373   }
7374   case Stmt::UnaryOperatorClass: {
7375     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
7376     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
7377     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
7378       Expr::EvalResult IndexResult;
7379       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
7380                                        Expr::SE_NoSideEffects,
7381                                        S.isConstantEvaluated())) {
7382         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
7383                    /*RHS is int*/ true);
7384         E = ASE->getBase();
7385         goto tryAgain;
7386       }
7387     }
7388 
7389     return SLCT_NotALiteral;
7390   }
7391 
7392   default:
7393     return SLCT_NotALiteral;
7394   }
7395 }
7396 
7397 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
7398   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
7399       .Case("scanf", FST_Scanf)
7400       .Cases("printf", "printf0", FST_Printf)
7401       .Cases("NSString", "CFString", FST_NSString)
7402       .Case("strftime", FST_Strftime)
7403       .Case("strfmon", FST_Strfmon)
7404       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
7405       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
7406       .Case("os_trace", FST_OSLog)
7407       .Case("os_log", FST_OSLog)
7408       .Default(FST_Unknown);
7409 }
7410 
7411 /// CheckFormatArguments - Check calls to printf and scanf (and similar
7412 /// functions) for correct use of format strings.
7413 /// Returns true if a format string has been fully checked.
7414 bool Sema::CheckFormatArguments(const FormatAttr *Format,
7415                                 ArrayRef<const Expr *> Args,
7416                                 bool IsCXXMember,
7417                                 VariadicCallType CallType,
7418                                 SourceLocation Loc, SourceRange Range,
7419                                 llvm::SmallBitVector &CheckedVarArgs) {
7420   FormatStringInfo FSI;
7421   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
7422     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
7423                                 FSI.FirstDataArg, GetFormatStringType(Format),
7424                                 CallType, Loc, Range, CheckedVarArgs);
7425   return false;
7426 }
7427 
7428 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
7429                                 bool HasVAListArg, unsigned format_idx,
7430                                 unsigned firstDataArg, FormatStringType Type,
7431                                 VariadicCallType CallType,
7432                                 SourceLocation Loc, SourceRange Range,
7433                                 llvm::SmallBitVector &CheckedVarArgs) {
7434   // CHECK: printf/scanf-like function is called with no format string.
7435   if (format_idx >= Args.size()) {
7436     Diag(Loc, diag::warn_missing_format_string) << Range;
7437     return false;
7438   }
7439 
7440   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
7441 
7442   // CHECK: format string is not a string literal.
7443   //
7444   // Dynamically generated format strings are difficult to
7445   // automatically vet at compile time.  Requiring that format strings
7446   // are string literals: (1) permits the checking of format strings by
7447   // the compiler and thereby (2) can practically remove the source of
7448   // many format string exploits.
7449 
7450   // Format string can be either ObjC string (e.g. @"%d") or
7451   // C string (e.g. "%d")
7452   // ObjC string uses the same format specifiers as C string, so we can use
7453   // the same format string checking logic for both ObjC and C strings.
7454   UncoveredArgHandler UncoveredArg;
7455   StringLiteralCheckType CT =
7456       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
7457                             format_idx, firstDataArg, Type, CallType,
7458                             /*IsFunctionCall*/ true, CheckedVarArgs,
7459                             UncoveredArg,
7460                             /*no string offset*/ llvm::APSInt(64, false) = 0);
7461 
7462   // Generate a diagnostic where an uncovered argument is detected.
7463   if (UncoveredArg.hasUncoveredArg()) {
7464     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
7465     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
7466     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
7467   }
7468 
7469   if (CT != SLCT_NotALiteral)
7470     // Literal format string found, check done!
7471     return CT == SLCT_CheckedLiteral;
7472 
7473   // Strftime is particular as it always uses a single 'time' argument,
7474   // so it is safe to pass a non-literal string.
7475   if (Type == FST_Strftime)
7476     return false;
7477 
7478   // Do not emit diag when the string param is a macro expansion and the
7479   // format is either NSString or CFString. This is a hack to prevent
7480   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
7481   // which are usually used in place of NS and CF string literals.
7482   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
7483   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
7484     return false;
7485 
7486   // If there are no arguments specified, warn with -Wformat-security, otherwise
7487   // warn only with -Wformat-nonliteral.
7488   if (Args.size() == firstDataArg) {
7489     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
7490       << OrigFormatExpr->getSourceRange();
7491     switch (Type) {
7492     default:
7493       break;
7494     case FST_Kprintf:
7495     case FST_FreeBSDKPrintf:
7496     case FST_Printf:
7497       Diag(FormatLoc, diag::note_format_security_fixit)
7498         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
7499       break;
7500     case FST_NSString:
7501       Diag(FormatLoc, diag::note_format_security_fixit)
7502         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
7503       break;
7504     }
7505   } else {
7506     Diag(FormatLoc, diag::warn_format_nonliteral)
7507       << OrigFormatExpr->getSourceRange();
7508   }
7509   return false;
7510 }
7511 
7512 namespace {
7513 
7514 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
7515 protected:
7516   Sema &S;
7517   const FormatStringLiteral *FExpr;
7518   const Expr *OrigFormatExpr;
7519   const Sema::FormatStringType FSType;
7520   const unsigned FirstDataArg;
7521   const unsigned NumDataArgs;
7522   const char *Beg; // Start of format string.
7523   const bool HasVAListArg;
7524   ArrayRef<const Expr *> Args;
7525   unsigned FormatIdx;
7526   llvm::SmallBitVector CoveredArgs;
7527   bool usesPositionalArgs = false;
7528   bool atFirstArg = true;
7529   bool inFunctionCall;
7530   Sema::VariadicCallType CallType;
7531   llvm::SmallBitVector &CheckedVarArgs;
7532   UncoveredArgHandler &UncoveredArg;
7533 
7534 public:
7535   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
7536                      const Expr *origFormatExpr,
7537                      const Sema::FormatStringType type, unsigned firstDataArg,
7538                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
7539                      ArrayRef<const Expr *> Args, unsigned formatIdx,
7540                      bool inFunctionCall, Sema::VariadicCallType callType,
7541                      llvm::SmallBitVector &CheckedVarArgs,
7542                      UncoveredArgHandler &UncoveredArg)
7543       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
7544         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
7545         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
7546         inFunctionCall(inFunctionCall), CallType(callType),
7547         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
7548     CoveredArgs.resize(numDataArgs);
7549     CoveredArgs.reset();
7550   }
7551 
7552   void DoneProcessing();
7553 
7554   void HandleIncompleteSpecifier(const char *startSpecifier,
7555                                  unsigned specifierLen) override;
7556 
7557   void HandleInvalidLengthModifier(
7558                            const analyze_format_string::FormatSpecifier &FS,
7559                            const analyze_format_string::ConversionSpecifier &CS,
7560                            const char *startSpecifier, unsigned specifierLen,
7561                            unsigned DiagID);
7562 
7563   void HandleNonStandardLengthModifier(
7564                     const analyze_format_string::FormatSpecifier &FS,
7565                     const char *startSpecifier, unsigned specifierLen);
7566 
7567   void HandleNonStandardConversionSpecifier(
7568                     const analyze_format_string::ConversionSpecifier &CS,
7569                     const char *startSpecifier, unsigned specifierLen);
7570 
7571   void HandlePosition(const char *startPos, unsigned posLen) override;
7572 
7573   void HandleInvalidPosition(const char *startSpecifier,
7574                              unsigned specifierLen,
7575                              analyze_format_string::PositionContext p) override;
7576 
7577   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
7578 
7579   void HandleNullChar(const char *nullCharacter) override;
7580 
7581   template <typename Range>
7582   static void
7583   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
7584                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
7585                        bool IsStringLocation, Range StringRange,
7586                        ArrayRef<FixItHint> Fixit = None);
7587 
7588 protected:
7589   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
7590                                         const char *startSpec,
7591                                         unsigned specifierLen,
7592                                         const char *csStart, unsigned csLen);
7593 
7594   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
7595                                          const char *startSpec,
7596                                          unsigned specifierLen);
7597 
7598   SourceRange getFormatStringRange();
7599   CharSourceRange getSpecifierRange(const char *startSpecifier,
7600                                     unsigned specifierLen);
7601   SourceLocation getLocationOfByte(const char *x);
7602 
7603   const Expr *getDataArg(unsigned i) const;
7604 
7605   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
7606                     const analyze_format_string::ConversionSpecifier &CS,
7607                     const char *startSpecifier, unsigned specifierLen,
7608                     unsigned argIndex);
7609 
7610   template <typename Range>
7611   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
7612                             bool IsStringLocation, Range StringRange,
7613                             ArrayRef<FixItHint> Fixit = None);
7614 };
7615 
7616 } // namespace
7617 
7618 SourceRange CheckFormatHandler::getFormatStringRange() {
7619   return OrigFormatExpr->getSourceRange();
7620 }
7621 
7622 CharSourceRange CheckFormatHandler::
7623 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
7624   SourceLocation Start = getLocationOfByte(startSpecifier);
7625   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
7626 
7627   // Advance the end SourceLocation by one due to half-open ranges.
7628   End = End.getLocWithOffset(1);
7629 
7630   return CharSourceRange::getCharRange(Start, End);
7631 }
7632 
7633 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
7634   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
7635                                   S.getLangOpts(), S.Context.getTargetInfo());
7636 }
7637 
7638 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
7639                                                    unsigned specifierLen){
7640   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
7641                        getLocationOfByte(startSpecifier),
7642                        /*IsStringLocation*/true,
7643                        getSpecifierRange(startSpecifier, specifierLen));
7644 }
7645 
7646 void CheckFormatHandler::HandleInvalidLengthModifier(
7647     const analyze_format_string::FormatSpecifier &FS,
7648     const analyze_format_string::ConversionSpecifier &CS,
7649     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
7650   using namespace analyze_format_string;
7651 
7652   const LengthModifier &LM = FS.getLengthModifier();
7653   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7654 
7655   // See if we know how to fix this length modifier.
7656   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7657   if (FixedLM) {
7658     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7659                          getLocationOfByte(LM.getStart()),
7660                          /*IsStringLocation*/true,
7661                          getSpecifierRange(startSpecifier, specifierLen));
7662 
7663     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7664       << FixedLM->toString()
7665       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7666 
7667   } else {
7668     FixItHint Hint;
7669     if (DiagID == diag::warn_format_nonsensical_length)
7670       Hint = FixItHint::CreateRemoval(LMRange);
7671 
7672     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7673                          getLocationOfByte(LM.getStart()),
7674                          /*IsStringLocation*/true,
7675                          getSpecifierRange(startSpecifier, specifierLen),
7676                          Hint);
7677   }
7678 }
7679 
7680 void CheckFormatHandler::HandleNonStandardLengthModifier(
7681     const analyze_format_string::FormatSpecifier &FS,
7682     const char *startSpecifier, unsigned specifierLen) {
7683   using namespace analyze_format_string;
7684 
7685   const LengthModifier &LM = FS.getLengthModifier();
7686   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7687 
7688   // See if we know how to fix this length modifier.
7689   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7690   if (FixedLM) {
7691     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7692                            << LM.toString() << 0,
7693                          getLocationOfByte(LM.getStart()),
7694                          /*IsStringLocation*/true,
7695                          getSpecifierRange(startSpecifier, specifierLen));
7696 
7697     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7698       << FixedLM->toString()
7699       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7700 
7701   } else {
7702     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7703                            << LM.toString() << 0,
7704                          getLocationOfByte(LM.getStart()),
7705                          /*IsStringLocation*/true,
7706                          getSpecifierRange(startSpecifier, specifierLen));
7707   }
7708 }
7709 
7710 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
7711     const analyze_format_string::ConversionSpecifier &CS,
7712     const char *startSpecifier, unsigned specifierLen) {
7713   using namespace analyze_format_string;
7714 
7715   // See if we know how to fix this conversion specifier.
7716   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
7717   if (FixedCS) {
7718     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7719                           << CS.toString() << /*conversion specifier*/1,
7720                          getLocationOfByte(CS.getStart()),
7721                          /*IsStringLocation*/true,
7722                          getSpecifierRange(startSpecifier, specifierLen));
7723 
7724     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
7725     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
7726       << FixedCS->toString()
7727       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
7728   } else {
7729     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7730                           << CS.toString() << /*conversion specifier*/1,
7731                          getLocationOfByte(CS.getStart()),
7732                          /*IsStringLocation*/true,
7733                          getSpecifierRange(startSpecifier, specifierLen));
7734   }
7735 }
7736 
7737 void CheckFormatHandler::HandlePosition(const char *startPos,
7738                                         unsigned posLen) {
7739   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
7740                                getLocationOfByte(startPos),
7741                                /*IsStringLocation*/true,
7742                                getSpecifierRange(startPos, posLen));
7743 }
7744 
7745 void
7746 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
7747                                      analyze_format_string::PositionContext p) {
7748   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
7749                          << (unsigned) p,
7750                        getLocationOfByte(startPos), /*IsStringLocation*/true,
7751                        getSpecifierRange(startPos, posLen));
7752 }
7753 
7754 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
7755                                             unsigned posLen) {
7756   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
7757                                getLocationOfByte(startPos),
7758                                /*IsStringLocation*/true,
7759                                getSpecifierRange(startPos, posLen));
7760 }
7761 
7762 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
7763   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
7764     // The presence of a null character is likely an error.
7765     EmitFormatDiagnostic(
7766       S.PDiag(diag::warn_printf_format_string_contains_null_char),
7767       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
7768       getFormatStringRange());
7769   }
7770 }
7771 
7772 // Note that this may return NULL if there was an error parsing or building
7773 // one of the argument expressions.
7774 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
7775   return Args[FirstDataArg + i];
7776 }
7777 
7778 void CheckFormatHandler::DoneProcessing() {
7779   // Does the number of data arguments exceed the number of
7780   // format conversions in the format string?
7781   if (!HasVAListArg) {
7782       // Find any arguments that weren't covered.
7783     CoveredArgs.flip();
7784     signed notCoveredArg = CoveredArgs.find_first();
7785     if (notCoveredArg >= 0) {
7786       assert((unsigned)notCoveredArg < NumDataArgs);
7787       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
7788     } else {
7789       UncoveredArg.setAllCovered();
7790     }
7791   }
7792 }
7793 
7794 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
7795                                    const Expr *ArgExpr) {
7796   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
7797          "Invalid state");
7798 
7799   if (!ArgExpr)
7800     return;
7801 
7802   SourceLocation Loc = ArgExpr->getBeginLoc();
7803 
7804   if (S.getSourceManager().isInSystemMacro(Loc))
7805     return;
7806 
7807   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
7808   for (auto E : DiagnosticExprs)
7809     PDiag << E->getSourceRange();
7810 
7811   CheckFormatHandler::EmitFormatDiagnostic(
7812                                   S, IsFunctionCall, DiagnosticExprs[0],
7813                                   PDiag, Loc, /*IsStringLocation*/false,
7814                                   DiagnosticExprs[0]->getSourceRange());
7815 }
7816 
7817 bool
7818 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
7819                                                      SourceLocation Loc,
7820                                                      const char *startSpec,
7821                                                      unsigned specifierLen,
7822                                                      const char *csStart,
7823                                                      unsigned csLen) {
7824   bool keepGoing = true;
7825   if (argIndex < NumDataArgs) {
7826     // Consider the argument coverered, even though the specifier doesn't
7827     // make sense.
7828     CoveredArgs.set(argIndex);
7829   }
7830   else {
7831     // If argIndex exceeds the number of data arguments we
7832     // don't issue a warning because that is just a cascade of warnings (and
7833     // they may have intended '%%' anyway). We don't want to continue processing
7834     // the format string after this point, however, as we will like just get
7835     // gibberish when trying to match arguments.
7836     keepGoing = false;
7837   }
7838 
7839   StringRef Specifier(csStart, csLen);
7840 
7841   // If the specifier in non-printable, it could be the first byte of a UTF-8
7842   // sequence. In that case, print the UTF-8 code point. If not, print the byte
7843   // hex value.
7844   std::string CodePointStr;
7845   if (!llvm::sys::locale::isPrint(*csStart)) {
7846     llvm::UTF32 CodePoint;
7847     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
7848     const llvm::UTF8 *E =
7849         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
7850     llvm::ConversionResult Result =
7851         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
7852 
7853     if (Result != llvm::conversionOK) {
7854       unsigned char FirstChar = *csStart;
7855       CodePoint = (llvm::UTF32)FirstChar;
7856     }
7857 
7858     llvm::raw_string_ostream OS(CodePointStr);
7859     if (CodePoint < 256)
7860       OS << "\\x" << llvm::format("%02x", CodePoint);
7861     else if (CodePoint <= 0xFFFF)
7862       OS << "\\u" << llvm::format("%04x", CodePoint);
7863     else
7864       OS << "\\U" << llvm::format("%08x", CodePoint);
7865     OS.flush();
7866     Specifier = CodePointStr;
7867   }
7868 
7869   EmitFormatDiagnostic(
7870       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
7871       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
7872 
7873   return keepGoing;
7874 }
7875 
7876 void
7877 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
7878                                                       const char *startSpec,
7879                                                       unsigned specifierLen) {
7880   EmitFormatDiagnostic(
7881     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
7882     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
7883 }
7884 
7885 bool
7886 CheckFormatHandler::CheckNumArgs(
7887   const analyze_format_string::FormatSpecifier &FS,
7888   const analyze_format_string::ConversionSpecifier &CS,
7889   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
7890 
7891   if (argIndex >= NumDataArgs) {
7892     PartialDiagnostic PDiag = FS.usesPositionalArg()
7893       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
7894            << (argIndex+1) << NumDataArgs)
7895       : S.PDiag(diag::warn_printf_insufficient_data_args);
7896     EmitFormatDiagnostic(
7897       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
7898       getSpecifierRange(startSpecifier, specifierLen));
7899 
7900     // Since more arguments than conversion tokens are given, by extension
7901     // all arguments are covered, so mark this as so.
7902     UncoveredArg.setAllCovered();
7903     return false;
7904   }
7905   return true;
7906 }
7907 
7908 template<typename Range>
7909 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
7910                                               SourceLocation Loc,
7911                                               bool IsStringLocation,
7912                                               Range StringRange,
7913                                               ArrayRef<FixItHint> FixIt) {
7914   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
7915                        Loc, IsStringLocation, StringRange, FixIt);
7916 }
7917 
7918 /// If the format string is not within the function call, emit a note
7919 /// so that the function call and string are in diagnostic messages.
7920 ///
7921 /// \param InFunctionCall if true, the format string is within the function
7922 /// call and only one diagnostic message will be produced.  Otherwise, an
7923 /// extra note will be emitted pointing to location of the format string.
7924 ///
7925 /// \param ArgumentExpr the expression that is passed as the format string
7926 /// argument in the function call.  Used for getting locations when two
7927 /// diagnostics are emitted.
7928 ///
7929 /// \param PDiag the callee should already have provided any strings for the
7930 /// diagnostic message.  This function only adds locations and fixits
7931 /// to diagnostics.
7932 ///
7933 /// \param Loc primary location for diagnostic.  If two diagnostics are
7934 /// required, one will be at Loc and a new SourceLocation will be created for
7935 /// the other one.
7936 ///
7937 /// \param IsStringLocation if true, Loc points to the format string should be
7938 /// used for the note.  Otherwise, Loc points to the argument list and will
7939 /// be used with PDiag.
7940 ///
7941 /// \param StringRange some or all of the string to highlight.  This is
7942 /// templated so it can accept either a CharSourceRange or a SourceRange.
7943 ///
7944 /// \param FixIt optional fix it hint for the format string.
7945 template <typename Range>
7946 void CheckFormatHandler::EmitFormatDiagnostic(
7947     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
7948     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
7949     Range StringRange, ArrayRef<FixItHint> FixIt) {
7950   if (InFunctionCall) {
7951     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
7952     D << StringRange;
7953     D << FixIt;
7954   } else {
7955     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
7956       << ArgumentExpr->getSourceRange();
7957 
7958     const Sema::SemaDiagnosticBuilder &Note =
7959       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
7960              diag::note_format_string_defined);
7961 
7962     Note << StringRange;
7963     Note << FixIt;
7964   }
7965 }
7966 
7967 //===--- CHECK: Printf format string checking ------------------------------===//
7968 
7969 namespace {
7970 
7971 class CheckPrintfHandler : public CheckFormatHandler {
7972 public:
7973   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
7974                      const Expr *origFormatExpr,
7975                      const Sema::FormatStringType type, unsigned firstDataArg,
7976                      unsigned numDataArgs, bool isObjC, const char *beg,
7977                      bool hasVAListArg, ArrayRef<const Expr *> Args,
7978                      unsigned formatIdx, bool inFunctionCall,
7979                      Sema::VariadicCallType CallType,
7980                      llvm::SmallBitVector &CheckedVarArgs,
7981                      UncoveredArgHandler &UncoveredArg)
7982       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7983                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
7984                            inFunctionCall, CallType, CheckedVarArgs,
7985                            UncoveredArg) {}
7986 
7987   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
7988 
7989   /// Returns true if '%@' specifiers are allowed in the format string.
7990   bool allowsObjCArg() const {
7991     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
7992            FSType == Sema::FST_OSTrace;
7993   }
7994 
7995   bool HandleInvalidPrintfConversionSpecifier(
7996                                       const analyze_printf::PrintfSpecifier &FS,
7997                                       const char *startSpecifier,
7998                                       unsigned specifierLen) override;
7999 
8000   void handleInvalidMaskType(StringRef MaskType) override;
8001 
8002   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8003                              const char *startSpecifier,
8004                              unsigned specifierLen) override;
8005   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8006                        const char *StartSpecifier,
8007                        unsigned SpecifierLen,
8008                        const Expr *E);
8009 
8010   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
8011                     const char *startSpecifier, unsigned specifierLen);
8012   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
8013                            const analyze_printf::OptionalAmount &Amt,
8014                            unsigned type,
8015                            const char *startSpecifier, unsigned specifierLen);
8016   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8017                   const analyze_printf::OptionalFlag &flag,
8018                   const char *startSpecifier, unsigned specifierLen);
8019   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
8020                          const analyze_printf::OptionalFlag &ignoredFlag,
8021                          const analyze_printf::OptionalFlag &flag,
8022                          const char *startSpecifier, unsigned specifierLen);
8023   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
8024                            const Expr *E);
8025 
8026   void HandleEmptyObjCModifierFlag(const char *startFlag,
8027                                    unsigned flagLen) override;
8028 
8029   void HandleInvalidObjCModifierFlag(const char *startFlag,
8030                                             unsigned flagLen) override;
8031 
8032   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
8033                                            const char *flagsEnd,
8034                                            const char *conversionPosition)
8035                                              override;
8036 };
8037 
8038 } // namespace
8039 
8040 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
8041                                       const analyze_printf::PrintfSpecifier &FS,
8042                                       const char *startSpecifier,
8043                                       unsigned specifierLen) {
8044   const analyze_printf::PrintfConversionSpecifier &CS =
8045     FS.getConversionSpecifier();
8046 
8047   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8048                                           getLocationOfByte(CS.getStart()),
8049                                           startSpecifier, specifierLen,
8050                                           CS.getStart(), CS.getLength());
8051 }
8052 
8053 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
8054   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
8055 }
8056 
8057 bool CheckPrintfHandler::HandleAmount(
8058                                const analyze_format_string::OptionalAmount &Amt,
8059                                unsigned k, const char *startSpecifier,
8060                                unsigned specifierLen) {
8061   if (Amt.hasDataArgument()) {
8062     if (!HasVAListArg) {
8063       unsigned argIndex = Amt.getArgIndex();
8064       if (argIndex >= NumDataArgs) {
8065         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
8066                                << k,
8067                              getLocationOfByte(Amt.getStart()),
8068                              /*IsStringLocation*/true,
8069                              getSpecifierRange(startSpecifier, specifierLen));
8070         // Don't do any more checking.  We will just emit
8071         // spurious errors.
8072         return false;
8073       }
8074 
8075       // Type check the data argument.  It should be an 'int'.
8076       // Although not in conformance with C99, we also allow the argument to be
8077       // an 'unsigned int' as that is a reasonably safe case.  GCC also
8078       // doesn't emit a warning for that case.
8079       CoveredArgs.set(argIndex);
8080       const Expr *Arg = getDataArg(argIndex);
8081       if (!Arg)
8082         return false;
8083 
8084       QualType T = Arg->getType();
8085 
8086       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
8087       assert(AT.isValid());
8088 
8089       if (!AT.matchesType(S.Context, T)) {
8090         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
8091                                << k << AT.getRepresentativeTypeName(S.Context)
8092                                << T << Arg->getSourceRange(),
8093                              getLocationOfByte(Amt.getStart()),
8094                              /*IsStringLocation*/true,
8095                              getSpecifierRange(startSpecifier, specifierLen));
8096         // Don't do any more checking.  We will just emit
8097         // spurious errors.
8098         return false;
8099       }
8100     }
8101   }
8102   return true;
8103 }
8104 
8105 void CheckPrintfHandler::HandleInvalidAmount(
8106                                       const analyze_printf::PrintfSpecifier &FS,
8107                                       const analyze_printf::OptionalAmount &Amt,
8108                                       unsigned type,
8109                                       const char *startSpecifier,
8110                                       unsigned specifierLen) {
8111   const analyze_printf::PrintfConversionSpecifier &CS =
8112     FS.getConversionSpecifier();
8113 
8114   FixItHint fixit =
8115     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
8116       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
8117                                  Amt.getConstantLength()))
8118       : FixItHint();
8119 
8120   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
8121                          << type << CS.toString(),
8122                        getLocationOfByte(Amt.getStart()),
8123                        /*IsStringLocation*/true,
8124                        getSpecifierRange(startSpecifier, specifierLen),
8125                        fixit);
8126 }
8127 
8128 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8129                                     const analyze_printf::OptionalFlag &flag,
8130                                     const char *startSpecifier,
8131                                     unsigned specifierLen) {
8132   // Warn about pointless flag with a fixit removal.
8133   const analyze_printf::PrintfConversionSpecifier &CS =
8134     FS.getConversionSpecifier();
8135   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
8136                          << flag.toString() << CS.toString(),
8137                        getLocationOfByte(flag.getPosition()),
8138                        /*IsStringLocation*/true,
8139                        getSpecifierRange(startSpecifier, specifierLen),
8140                        FixItHint::CreateRemoval(
8141                          getSpecifierRange(flag.getPosition(), 1)));
8142 }
8143 
8144 void CheckPrintfHandler::HandleIgnoredFlag(
8145                                 const analyze_printf::PrintfSpecifier &FS,
8146                                 const analyze_printf::OptionalFlag &ignoredFlag,
8147                                 const analyze_printf::OptionalFlag &flag,
8148                                 const char *startSpecifier,
8149                                 unsigned specifierLen) {
8150   // Warn about ignored flag with a fixit removal.
8151   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
8152                          << ignoredFlag.toString() << flag.toString(),
8153                        getLocationOfByte(ignoredFlag.getPosition()),
8154                        /*IsStringLocation*/true,
8155                        getSpecifierRange(startSpecifier, specifierLen),
8156                        FixItHint::CreateRemoval(
8157                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
8158 }
8159 
8160 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
8161                                                      unsigned flagLen) {
8162   // Warn about an empty flag.
8163   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
8164                        getLocationOfByte(startFlag),
8165                        /*IsStringLocation*/true,
8166                        getSpecifierRange(startFlag, flagLen));
8167 }
8168 
8169 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
8170                                                        unsigned flagLen) {
8171   // Warn about an invalid flag.
8172   auto Range = getSpecifierRange(startFlag, flagLen);
8173   StringRef flag(startFlag, flagLen);
8174   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
8175                       getLocationOfByte(startFlag),
8176                       /*IsStringLocation*/true,
8177                       Range, FixItHint::CreateRemoval(Range));
8178 }
8179 
8180 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
8181     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
8182     // Warn about using '[...]' without a '@' conversion.
8183     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
8184     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
8185     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
8186                          getLocationOfByte(conversionPosition),
8187                          /*IsStringLocation*/true,
8188                          Range, FixItHint::CreateRemoval(Range));
8189 }
8190 
8191 // Determines if the specified is a C++ class or struct containing
8192 // a member with the specified name and kind (e.g. a CXXMethodDecl named
8193 // "c_str()").
8194 template<typename MemberKind>
8195 static llvm::SmallPtrSet<MemberKind*, 1>
8196 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
8197   const RecordType *RT = Ty->getAs<RecordType>();
8198   llvm::SmallPtrSet<MemberKind*, 1> Results;
8199 
8200   if (!RT)
8201     return Results;
8202   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
8203   if (!RD || !RD->getDefinition())
8204     return Results;
8205 
8206   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
8207                  Sema::LookupMemberName);
8208   R.suppressDiagnostics();
8209 
8210   // We just need to include all members of the right kind turned up by the
8211   // filter, at this point.
8212   if (S.LookupQualifiedName(R, RT->getDecl()))
8213     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8214       NamedDecl *decl = (*I)->getUnderlyingDecl();
8215       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
8216         Results.insert(FK);
8217     }
8218   return Results;
8219 }
8220 
8221 /// Check if we could call '.c_str()' on an object.
8222 ///
8223 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
8224 /// allow the call, or if it would be ambiguous).
8225 bool Sema::hasCStrMethod(const Expr *E) {
8226   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8227 
8228   MethodSet Results =
8229       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
8230   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8231        MI != ME; ++MI)
8232     if ((*MI)->getMinRequiredArguments() == 0)
8233       return true;
8234   return false;
8235 }
8236 
8237 // Check if a (w)string was passed when a (w)char* was needed, and offer a
8238 // better diagnostic if so. AT is assumed to be valid.
8239 // Returns true when a c_str() conversion method is found.
8240 bool CheckPrintfHandler::checkForCStrMembers(
8241     const analyze_printf::ArgType &AT, const Expr *E) {
8242   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8243 
8244   MethodSet Results =
8245       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
8246 
8247   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8248        MI != ME; ++MI) {
8249     const CXXMethodDecl *Method = *MI;
8250     if (Method->getMinRequiredArguments() == 0 &&
8251         AT.matchesType(S.Context, Method->getReturnType())) {
8252       // FIXME: Suggest parens if the expression needs them.
8253       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
8254       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
8255           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
8256       return true;
8257     }
8258   }
8259 
8260   return false;
8261 }
8262 
8263 bool
8264 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
8265                                             &FS,
8266                                           const char *startSpecifier,
8267                                           unsigned specifierLen) {
8268   using namespace analyze_format_string;
8269   using namespace analyze_printf;
8270 
8271   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
8272 
8273   if (FS.consumesDataArgument()) {
8274     if (atFirstArg) {
8275         atFirstArg = false;
8276         usesPositionalArgs = FS.usesPositionalArg();
8277     }
8278     else if (usesPositionalArgs != FS.usesPositionalArg()) {
8279       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8280                                         startSpecifier, specifierLen);
8281       return false;
8282     }
8283   }
8284 
8285   // First check if the field width, precision, and conversion specifier
8286   // have matching data arguments.
8287   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
8288                     startSpecifier, specifierLen)) {
8289     return false;
8290   }
8291 
8292   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
8293                     startSpecifier, specifierLen)) {
8294     return false;
8295   }
8296 
8297   if (!CS.consumesDataArgument()) {
8298     // FIXME: Technically specifying a precision or field width here
8299     // makes no sense.  Worth issuing a warning at some point.
8300     return true;
8301   }
8302 
8303   // Consume the argument.
8304   unsigned argIndex = FS.getArgIndex();
8305   if (argIndex < NumDataArgs) {
8306     // The check to see if the argIndex is valid will come later.
8307     // We set the bit here because we may exit early from this
8308     // function if we encounter some other error.
8309     CoveredArgs.set(argIndex);
8310   }
8311 
8312   // FreeBSD kernel extensions.
8313   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
8314       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
8315     // We need at least two arguments.
8316     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
8317       return false;
8318 
8319     // Claim the second argument.
8320     CoveredArgs.set(argIndex + 1);
8321 
8322     // Type check the first argument (int for %b, pointer for %D)
8323     const Expr *Ex = getDataArg(argIndex);
8324     const analyze_printf::ArgType &AT =
8325       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
8326         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
8327     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
8328       EmitFormatDiagnostic(
8329           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8330               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
8331               << false << Ex->getSourceRange(),
8332           Ex->getBeginLoc(), /*IsStringLocation*/ false,
8333           getSpecifierRange(startSpecifier, specifierLen));
8334 
8335     // Type check the second argument (char * for both %b and %D)
8336     Ex = getDataArg(argIndex + 1);
8337     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
8338     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
8339       EmitFormatDiagnostic(
8340           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8341               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
8342               << false << Ex->getSourceRange(),
8343           Ex->getBeginLoc(), /*IsStringLocation*/ false,
8344           getSpecifierRange(startSpecifier, specifierLen));
8345 
8346      return true;
8347   }
8348 
8349   // Check for using an Objective-C specific conversion specifier
8350   // in a non-ObjC literal.
8351   if (!allowsObjCArg() && CS.isObjCArg()) {
8352     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8353                                                   specifierLen);
8354   }
8355 
8356   // %P can only be used with os_log.
8357   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
8358     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8359                                                   specifierLen);
8360   }
8361 
8362   // %n is not allowed with os_log.
8363   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
8364     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
8365                          getLocationOfByte(CS.getStart()),
8366                          /*IsStringLocation*/ false,
8367                          getSpecifierRange(startSpecifier, specifierLen));
8368 
8369     return true;
8370   }
8371 
8372   // Only scalars are allowed for os_trace.
8373   if (FSType == Sema::FST_OSTrace &&
8374       (CS.getKind() == ConversionSpecifier::PArg ||
8375        CS.getKind() == ConversionSpecifier::sArg ||
8376        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
8377     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8378                                                   specifierLen);
8379   }
8380 
8381   // Check for use of public/private annotation outside of os_log().
8382   if (FSType != Sema::FST_OSLog) {
8383     if (FS.isPublic().isSet()) {
8384       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8385                                << "public",
8386                            getLocationOfByte(FS.isPublic().getPosition()),
8387                            /*IsStringLocation*/ false,
8388                            getSpecifierRange(startSpecifier, specifierLen));
8389     }
8390     if (FS.isPrivate().isSet()) {
8391       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8392                                << "private",
8393                            getLocationOfByte(FS.isPrivate().getPosition()),
8394                            /*IsStringLocation*/ false,
8395                            getSpecifierRange(startSpecifier, specifierLen));
8396     }
8397   }
8398 
8399   // Check for invalid use of field width
8400   if (!FS.hasValidFieldWidth()) {
8401     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
8402         startSpecifier, specifierLen);
8403   }
8404 
8405   // Check for invalid use of precision
8406   if (!FS.hasValidPrecision()) {
8407     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
8408         startSpecifier, specifierLen);
8409   }
8410 
8411   // Precision is mandatory for %P specifier.
8412   if (CS.getKind() == ConversionSpecifier::PArg &&
8413       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
8414     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
8415                          getLocationOfByte(startSpecifier),
8416                          /*IsStringLocation*/ false,
8417                          getSpecifierRange(startSpecifier, specifierLen));
8418   }
8419 
8420   // Check each flag does not conflict with any other component.
8421   if (!FS.hasValidThousandsGroupingPrefix())
8422     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
8423   if (!FS.hasValidLeadingZeros())
8424     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
8425   if (!FS.hasValidPlusPrefix())
8426     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
8427   if (!FS.hasValidSpacePrefix())
8428     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
8429   if (!FS.hasValidAlternativeForm())
8430     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
8431   if (!FS.hasValidLeftJustified())
8432     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
8433 
8434   // Check that flags are not ignored by another flag
8435   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
8436     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
8437         startSpecifier, specifierLen);
8438   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
8439     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
8440             startSpecifier, specifierLen);
8441 
8442   // Check the length modifier is valid with the given conversion specifier.
8443   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8444                                  S.getLangOpts()))
8445     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8446                                 diag::warn_format_nonsensical_length);
8447   else if (!FS.hasStandardLengthModifier())
8448     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8449   else if (!FS.hasStandardLengthConversionCombination())
8450     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8451                                 diag::warn_format_non_standard_conversion_spec);
8452 
8453   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8454     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8455 
8456   // The remaining checks depend on the data arguments.
8457   if (HasVAListArg)
8458     return true;
8459 
8460   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8461     return false;
8462 
8463   const Expr *Arg = getDataArg(argIndex);
8464   if (!Arg)
8465     return true;
8466 
8467   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
8468 }
8469 
8470 static bool requiresParensToAddCast(const Expr *E) {
8471   // FIXME: We should have a general way to reason about operator
8472   // precedence and whether parens are actually needed here.
8473   // Take care of a few common cases where they aren't.
8474   const Expr *Inside = E->IgnoreImpCasts();
8475   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
8476     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
8477 
8478   switch (Inside->getStmtClass()) {
8479   case Stmt::ArraySubscriptExprClass:
8480   case Stmt::CallExprClass:
8481   case Stmt::CharacterLiteralClass:
8482   case Stmt::CXXBoolLiteralExprClass:
8483   case Stmt::DeclRefExprClass:
8484   case Stmt::FloatingLiteralClass:
8485   case Stmt::IntegerLiteralClass:
8486   case Stmt::MemberExprClass:
8487   case Stmt::ObjCArrayLiteralClass:
8488   case Stmt::ObjCBoolLiteralExprClass:
8489   case Stmt::ObjCBoxedExprClass:
8490   case Stmt::ObjCDictionaryLiteralClass:
8491   case Stmt::ObjCEncodeExprClass:
8492   case Stmt::ObjCIvarRefExprClass:
8493   case Stmt::ObjCMessageExprClass:
8494   case Stmt::ObjCPropertyRefExprClass:
8495   case Stmt::ObjCStringLiteralClass:
8496   case Stmt::ObjCSubscriptRefExprClass:
8497   case Stmt::ParenExprClass:
8498   case Stmt::StringLiteralClass:
8499   case Stmt::UnaryOperatorClass:
8500     return false;
8501   default:
8502     return true;
8503   }
8504 }
8505 
8506 static std::pair<QualType, StringRef>
8507 shouldNotPrintDirectly(const ASTContext &Context,
8508                        QualType IntendedTy,
8509                        const Expr *E) {
8510   // Use a 'while' to peel off layers of typedefs.
8511   QualType TyTy = IntendedTy;
8512   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
8513     StringRef Name = UserTy->getDecl()->getName();
8514     QualType CastTy = llvm::StringSwitch<QualType>(Name)
8515       .Case("CFIndex", Context.getNSIntegerType())
8516       .Case("NSInteger", Context.getNSIntegerType())
8517       .Case("NSUInteger", Context.getNSUIntegerType())
8518       .Case("SInt32", Context.IntTy)
8519       .Case("UInt32", Context.UnsignedIntTy)
8520       .Default(QualType());
8521 
8522     if (!CastTy.isNull())
8523       return std::make_pair(CastTy, Name);
8524 
8525     TyTy = UserTy->desugar();
8526   }
8527 
8528   // Strip parens if necessary.
8529   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
8530     return shouldNotPrintDirectly(Context,
8531                                   PE->getSubExpr()->getType(),
8532                                   PE->getSubExpr());
8533 
8534   // If this is a conditional expression, then its result type is constructed
8535   // via usual arithmetic conversions and thus there might be no necessary
8536   // typedef sugar there.  Recurse to operands to check for NSInteger &
8537   // Co. usage condition.
8538   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8539     QualType TrueTy, FalseTy;
8540     StringRef TrueName, FalseName;
8541 
8542     std::tie(TrueTy, TrueName) =
8543       shouldNotPrintDirectly(Context,
8544                              CO->getTrueExpr()->getType(),
8545                              CO->getTrueExpr());
8546     std::tie(FalseTy, FalseName) =
8547       shouldNotPrintDirectly(Context,
8548                              CO->getFalseExpr()->getType(),
8549                              CO->getFalseExpr());
8550 
8551     if (TrueTy == FalseTy)
8552       return std::make_pair(TrueTy, TrueName);
8553     else if (TrueTy.isNull())
8554       return std::make_pair(FalseTy, FalseName);
8555     else if (FalseTy.isNull())
8556       return std::make_pair(TrueTy, TrueName);
8557   }
8558 
8559   return std::make_pair(QualType(), StringRef());
8560 }
8561 
8562 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
8563 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
8564 /// type do not count.
8565 static bool
8566 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
8567   QualType From = ICE->getSubExpr()->getType();
8568   QualType To = ICE->getType();
8569   // It's an integer promotion if the destination type is the promoted
8570   // source type.
8571   if (ICE->getCastKind() == CK_IntegralCast &&
8572       From->isPromotableIntegerType() &&
8573       S.Context.getPromotedIntegerType(From) == To)
8574     return true;
8575   // Look through vector types, since we do default argument promotion for
8576   // those in OpenCL.
8577   if (const auto *VecTy = From->getAs<ExtVectorType>())
8578     From = VecTy->getElementType();
8579   if (const auto *VecTy = To->getAs<ExtVectorType>())
8580     To = VecTy->getElementType();
8581   // It's a floating promotion if the source type is a lower rank.
8582   return ICE->getCastKind() == CK_FloatingCast &&
8583          S.Context.getFloatingTypeOrder(From, To) < 0;
8584 }
8585 
8586 bool
8587 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8588                                     const char *StartSpecifier,
8589                                     unsigned SpecifierLen,
8590                                     const Expr *E) {
8591   using namespace analyze_format_string;
8592   using namespace analyze_printf;
8593 
8594   // Now type check the data expression that matches the
8595   // format specifier.
8596   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
8597   if (!AT.isValid())
8598     return true;
8599 
8600   QualType ExprTy = E->getType();
8601   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
8602     ExprTy = TET->getUnderlyingExpr()->getType();
8603   }
8604 
8605   // Diagnose attempts to print a boolean value as a character. Unlike other
8606   // -Wformat diagnostics, this is fine from a type perspective, but it still
8607   // doesn't make sense.
8608   if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
8609       E->isKnownToHaveBooleanValue()) {
8610     const CharSourceRange &CSR =
8611         getSpecifierRange(StartSpecifier, SpecifierLen);
8612     SmallString<4> FSString;
8613     llvm::raw_svector_ostream os(FSString);
8614     FS.toString(os);
8615     EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
8616                              << FSString,
8617                          E->getExprLoc(), false, CSR);
8618     return true;
8619   }
8620 
8621   analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
8622   if (Match == analyze_printf::ArgType::Match)
8623     return true;
8624 
8625   // Look through argument promotions for our error message's reported type.
8626   // This includes the integral and floating promotions, but excludes array
8627   // and function pointer decay (seeing that an argument intended to be a
8628   // string has type 'char [6]' is probably more confusing than 'char *') and
8629   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
8630   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8631     if (isArithmeticArgumentPromotion(S, ICE)) {
8632       E = ICE->getSubExpr();
8633       ExprTy = E->getType();
8634 
8635       // Check if we didn't match because of an implicit cast from a 'char'
8636       // or 'short' to an 'int'.  This is done because printf is a varargs
8637       // function.
8638       if (ICE->getType() == S.Context.IntTy ||
8639           ICE->getType() == S.Context.UnsignedIntTy) {
8640         // All further checking is done on the subexpression
8641         const analyze_printf::ArgType::MatchKind ImplicitMatch =
8642             AT.matchesType(S.Context, ExprTy);
8643         if (ImplicitMatch == analyze_printf::ArgType::Match)
8644           return true;
8645         if (ImplicitMatch == ArgType::NoMatchPedantic ||
8646             ImplicitMatch == ArgType::NoMatchTypeConfusion)
8647           Match = ImplicitMatch;
8648       }
8649     }
8650   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
8651     // Special case for 'a', which has type 'int' in C.
8652     // Note, however, that we do /not/ want to treat multibyte constants like
8653     // 'MooV' as characters! This form is deprecated but still exists.
8654     if (ExprTy == S.Context.IntTy)
8655       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
8656         ExprTy = S.Context.CharTy;
8657   }
8658 
8659   // Look through enums to their underlying type.
8660   bool IsEnum = false;
8661   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
8662     ExprTy = EnumTy->getDecl()->getIntegerType();
8663     IsEnum = true;
8664   }
8665 
8666   // %C in an Objective-C context prints a unichar, not a wchar_t.
8667   // If the argument is an integer of some kind, believe the %C and suggest
8668   // a cast instead of changing the conversion specifier.
8669   QualType IntendedTy = ExprTy;
8670   if (isObjCContext() &&
8671       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
8672     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
8673         !ExprTy->isCharType()) {
8674       // 'unichar' is defined as a typedef of unsigned short, but we should
8675       // prefer using the typedef if it is visible.
8676       IntendedTy = S.Context.UnsignedShortTy;
8677 
8678       // While we are here, check if the value is an IntegerLiteral that happens
8679       // to be within the valid range.
8680       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
8681         const llvm::APInt &V = IL->getValue();
8682         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
8683           return true;
8684       }
8685 
8686       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
8687                           Sema::LookupOrdinaryName);
8688       if (S.LookupName(Result, S.getCurScope())) {
8689         NamedDecl *ND = Result.getFoundDecl();
8690         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
8691           if (TD->getUnderlyingType() == IntendedTy)
8692             IntendedTy = S.Context.getTypedefType(TD);
8693       }
8694     }
8695   }
8696 
8697   // Special-case some of Darwin's platform-independence types by suggesting
8698   // casts to primitive types that are known to be large enough.
8699   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
8700   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
8701     QualType CastTy;
8702     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
8703     if (!CastTy.isNull()) {
8704       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
8705       // (long in ASTContext). Only complain to pedants.
8706       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
8707           (AT.isSizeT() || AT.isPtrdiffT()) &&
8708           AT.matchesType(S.Context, CastTy))
8709         Match = ArgType::NoMatchPedantic;
8710       IntendedTy = CastTy;
8711       ShouldNotPrintDirectly = true;
8712     }
8713   }
8714 
8715   // We may be able to offer a FixItHint if it is a supported type.
8716   PrintfSpecifier fixedFS = FS;
8717   bool Success =
8718       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
8719 
8720   if (Success) {
8721     // Get the fix string from the fixed format specifier
8722     SmallString<16> buf;
8723     llvm::raw_svector_ostream os(buf);
8724     fixedFS.toString(os);
8725 
8726     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
8727 
8728     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
8729       unsigned Diag;
8730       switch (Match) {
8731       case ArgType::Match: llvm_unreachable("expected non-matching");
8732       case ArgType::NoMatchPedantic:
8733         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8734         break;
8735       case ArgType::NoMatchTypeConfusion:
8736         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8737         break;
8738       case ArgType::NoMatch:
8739         Diag = diag::warn_format_conversion_argument_type_mismatch;
8740         break;
8741       }
8742 
8743       // In this case, the specifier is wrong and should be changed to match
8744       // the argument.
8745       EmitFormatDiagnostic(S.PDiag(Diag)
8746                                << AT.getRepresentativeTypeName(S.Context)
8747                                << IntendedTy << IsEnum << E->getSourceRange(),
8748                            E->getBeginLoc(),
8749                            /*IsStringLocation*/ false, SpecRange,
8750                            FixItHint::CreateReplacement(SpecRange, os.str()));
8751     } else {
8752       // The canonical type for formatting this value is different from the
8753       // actual type of the expression. (This occurs, for example, with Darwin's
8754       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
8755       // should be printed as 'long' for 64-bit compatibility.)
8756       // Rather than emitting a normal format/argument mismatch, we want to
8757       // add a cast to the recommended type (and correct the format string
8758       // if necessary).
8759       SmallString<16> CastBuf;
8760       llvm::raw_svector_ostream CastFix(CastBuf);
8761       CastFix << "(";
8762       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
8763       CastFix << ")";
8764 
8765       SmallVector<FixItHint,4> Hints;
8766       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
8767         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
8768 
8769       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
8770         // If there's already a cast present, just replace it.
8771         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
8772         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
8773 
8774       } else if (!requiresParensToAddCast(E)) {
8775         // If the expression has high enough precedence,
8776         // just write the C-style cast.
8777         Hints.push_back(
8778             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8779       } else {
8780         // Otherwise, add parens around the expression as well as the cast.
8781         CastFix << "(";
8782         Hints.push_back(
8783             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8784 
8785         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
8786         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
8787       }
8788 
8789       if (ShouldNotPrintDirectly) {
8790         // The expression has a type that should not be printed directly.
8791         // We extract the name from the typedef because we don't want to show
8792         // the underlying type in the diagnostic.
8793         StringRef Name;
8794         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
8795           Name = TypedefTy->getDecl()->getName();
8796         else
8797           Name = CastTyName;
8798         unsigned Diag = Match == ArgType::NoMatchPedantic
8799                             ? diag::warn_format_argument_needs_cast_pedantic
8800                             : diag::warn_format_argument_needs_cast;
8801         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
8802                                            << E->getSourceRange(),
8803                              E->getBeginLoc(), /*IsStringLocation=*/false,
8804                              SpecRange, Hints);
8805       } else {
8806         // In this case, the expression could be printed using a different
8807         // specifier, but we've decided that the specifier is probably correct
8808         // and we should cast instead. Just use the normal warning message.
8809         EmitFormatDiagnostic(
8810             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8811                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
8812                 << E->getSourceRange(),
8813             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
8814       }
8815     }
8816   } else {
8817     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
8818                                                    SpecifierLen);
8819     // Since the warning for passing non-POD types to variadic functions
8820     // was deferred until now, we emit a warning for non-POD
8821     // arguments here.
8822     switch (S.isValidVarArgType(ExprTy)) {
8823     case Sema::VAK_Valid:
8824     case Sema::VAK_ValidInCXX11: {
8825       unsigned Diag;
8826       switch (Match) {
8827       case ArgType::Match: llvm_unreachable("expected non-matching");
8828       case ArgType::NoMatchPedantic:
8829         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8830         break;
8831       case ArgType::NoMatchTypeConfusion:
8832         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8833         break;
8834       case ArgType::NoMatch:
8835         Diag = diag::warn_format_conversion_argument_type_mismatch;
8836         break;
8837       }
8838 
8839       EmitFormatDiagnostic(
8840           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
8841                         << IsEnum << CSR << E->getSourceRange(),
8842           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8843       break;
8844     }
8845     case Sema::VAK_Undefined:
8846     case Sema::VAK_MSVCUndefined:
8847       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
8848                                << S.getLangOpts().CPlusPlus11 << ExprTy
8849                                << CallType
8850                                << AT.getRepresentativeTypeName(S.Context) << CSR
8851                                << E->getSourceRange(),
8852                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8853       checkForCStrMembers(AT, E);
8854       break;
8855 
8856     case Sema::VAK_Invalid:
8857       if (ExprTy->isObjCObjectType())
8858         EmitFormatDiagnostic(
8859             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
8860                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
8861                 << AT.getRepresentativeTypeName(S.Context) << CSR
8862                 << E->getSourceRange(),
8863             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8864       else
8865         // FIXME: If this is an initializer list, suggest removing the braces
8866         // or inserting a cast to the target type.
8867         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
8868             << isa<InitListExpr>(E) << ExprTy << CallType
8869             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
8870       break;
8871     }
8872 
8873     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
8874            "format string specifier index out of range");
8875     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
8876   }
8877 
8878   return true;
8879 }
8880 
8881 //===--- CHECK: Scanf format string checking ------------------------------===//
8882 
8883 namespace {
8884 
8885 class CheckScanfHandler : public CheckFormatHandler {
8886 public:
8887   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
8888                     const Expr *origFormatExpr, Sema::FormatStringType type,
8889                     unsigned firstDataArg, unsigned numDataArgs,
8890                     const char *beg, bool hasVAListArg,
8891                     ArrayRef<const Expr *> Args, unsigned formatIdx,
8892                     bool inFunctionCall, Sema::VariadicCallType CallType,
8893                     llvm::SmallBitVector &CheckedVarArgs,
8894                     UncoveredArgHandler &UncoveredArg)
8895       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8896                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
8897                            inFunctionCall, CallType, CheckedVarArgs,
8898                            UncoveredArg) {}
8899 
8900   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
8901                             const char *startSpecifier,
8902                             unsigned specifierLen) override;
8903 
8904   bool HandleInvalidScanfConversionSpecifier(
8905           const analyze_scanf::ScanfSpecifier &FS,
8906           const char *startSpecifier,
8907           unsigned specifierLen) override;
8908 
8909   void HandleIncompleteScanList(const char *start, const char *end) override;
8910 };
8911 
8912 } // namespace
8913 
8914 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
8915                                                  const char *end) {
8916   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
8917                        getLocationOfByte(end), /*IsStringLocation*/true,
8918                        getSpecifierRange(start, end - start));
8919 }
8920 
8921 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
8922                                         const analyze_scanf::ScanfSpecifier &FS,
8923                                         const char *startSpecifier,
8924                                         unsigned specifierLen) {
8925   const analyze_scanf::ScanfConversionSpecifier &CS =
8926     FS.getConversionSpecifier();
8927 
8928   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8929                                           getLocationOfByte(CS.getStart()),
8930                                           startSpecifier, specifierLen,
8931                                           CS.getStart(), CS.getLength());
8932 }
8933 
8934 bool CheckScanfHandler::HandleScanfSpecifier(
8935                                        const analyze_scanf::ScanfSpecifier &FS,
8936                                        const char *startSpecifier,
8937                                        unsigned specifierLen) {
8938   using namespace analyze_scanf;
8939   using namespace analyze_format_string;
8940 
8941   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
8942 
8943   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
8944   // be used to decide if we are using positional arguments consistently.
8945   if (FS.consumesDataArgument()) {
8946     if (atFirstArg) {
8947       atFirstArg = false;
8948       usesPositionalArgs = FS.usesPositionalArg();
8949     }
8950     else if (usesPositionalArgs != FS.usesPositionalArg()) {
8951       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8952                                         startSpecifier, specifierLen);
8953       return false;
8954     }
8955   }
8956 
8957   // Check if the field with is non-zero.
8958   const OptionalAmount &Amt = FS.getFieldWidth();
8959   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
8960     if (Amt.getConstantAmount() == 0) {
8961       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
8962                                                    Amt.getConstantLength());
8963       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
8964                            getLocationOfByte(Amt.getStart()),
8965                            /*IsStringLocation*/true, R,
8966                            FixItHint::CreateRemoval(R));
8967     }
8968   }
8969 
8970   if (!FS.consumesDataArgument()) {
8971     // FIXME: Technically specifying a precision or field width here
8972     // makes no sense.  Worth issuing a warning at some point.
8973     return true;
8974   }
8975 
8976   // Consume the argument.
8977   unsigned argIndex = FS.getArgIndex();
8978   if (argIndex < NumDataArgs) {
8979       // The check to see if the argIndex is valid will come later.
8980       // We set the bit here because we may exit early from this
8981       // function if we encounter some other error.
8982     CoveredArgs.set(argIndex);
8983   }
8984 
8985   // Check the length modifier is valid with the given conversion specifier.
8986   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8987                                  S.getLangOpts()))
8988     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8989                                 diag::warn_format_nonsensical_length);
8990   else if (!FS.hasStandardLengthModifier())
8991     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8992   else if (!FS.hasStandardLengthConversionCombination())
8993     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8994                                 diag::warn_format_non_standard_conversion_spec);
8995 
8996   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8997     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8998 
8999   // The remaining checks depend on the data arguments.
9000   if (HasVAListArg)
9001     return true;
9002 
9003   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9004     return false;
9005 
9006   // Check that the argument type matches the format specifier.
9007   const Expr *Ex = getDataArg(argIndex);
9008   if (!Ex)
9009     return true;
9010 
9011   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
9012 
9013   if (!AT.isValid()) {
9014     return true;
9015   }
9016 
9017   analyze_format_string::ArgType::MatchKind Match =
9018       AT.matchesType(S.Context, Ex->getType());
9019   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
9020   if (Match == analyze_format_string::ArgType::Match)
9021     return true;
9022 
9023   ScanfSpecifier fixedFS = FS;
9024   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
9025                                  S.getLangOpts(), S.Context);
9026 
9027   unsigned Diag =
9028       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9029                : diag::warn_format_conversion_argument_type_mismatch;
9030 
9031   if (Success) {
9032     // Get the fix string from the fixed format specifier.
9033     SmallString<128> buf;
9034     llvm::raw_svector_ostream os(buf);
9035     fixedFS.toString(os);
9036 
9037     EmitFormatDiagnostic(
9038         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
9039                       << Ex->getType() << false << Ex->getSourceRange(),
9040         Ex->getBeginLoc(),
9041         /*IsStringLocation*/ false,
9042         getSpecifierRange(startSpecifier, specifierLen),
9043         FixItHint::CreateReplacement(
9044             getSpecifierRange(startSpecifier, specifierLen), os.str()));
9045   } else {
9046     EmitFormatDiagnostic(S.PDiag(Diag)
9047                              << AT.getRepresentativeTypeName(S.Context)
9048                              << Ex->getType() << false << Ex->getSourceRange(),
9049                          Ex->getBeginLoc(),
9050                          /*IsStringLocation*/ false,
9051                          getSpecifierRange(startSpecifier, specifierLen));
9052   }
9053 
9054   return true;
9055 }
9056 
9057 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
9058                               const Expr *OrigFormatExpr,
9059                               ArrayRef<const Expr *> Args,
9060                               bool HasVAListArg, unsigned format_idx,
9061                               unsigned firstDataArg,
9062                               Sema::FormatStringType Type,
9063                               bool inFunctionCall,
9064                               Sema::VariadicCallType CallType,
9065                               llvm::SmallBitVector &CheckedVarArgs,
9066                               UncoveredArgHandler &UncoveredArg,
9067                               bool IgnoreStringsWithoutSpecifiers) {
9068   // CHECK: is the format string a wide literal?
9069   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
9070     CheckFormatHandler::EmitFormatDiagnostic(
9071         S, inFunctionCall, Args[format_idx],
9072         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
9073         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9074     return;
9075   }
9076 
9077   // Str - The format string.  NOTE: this is NOT null-terminated!
9078   StringRef StrRef = FExpr->getString();
9079   const char *Str = StrRef.data();
9080   // Account for cases where the string literal is truncated in a declaration.
9081   const ConstantArrayType *T =
9082     S.Context.getAsConstantArrayType(FExpr->getType());
9083   assert(T && "String literal not of constant array type!");
9084   size_t TypeSize = T->getSize().getZExtValue();
9085   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9086   const unsigned numDataArgs = Args.size() - firstDataArg;
9087 
9088   if (IgnoreStringsWithoutSpecifiers &&
9089       !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
9090           Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
9091     return;
9092 
9093   // Emit a warning if the string literal is truncated and does not contain an
9094   // embedded null character.
9095   if (TypeSize <= StrRef.size() &&
9096       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
9097     CheckFormatHandler::EmitFormatDiagnostic(
9098         S, inFunctionCall, Args[format_idx],
9099         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
9100         FExpr->getBeginLoc(),
9101         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
9102     return;
9103   }
9104 
9105   // CHECK: empty format string?
9106   if (StrLen == 0 && numDataArgs > 0) {
9107     CheckFormatHandler::EmitFormatDiagnostic(
9108         S, inFunctionCall, Args[format_idx],
9109         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
9110         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9111     return;
9112   }
9113 
9114   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
9115       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
9116       Type == Sema::FST_OSTrace) {
9117     CheckPrintfHandler H(
9118         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
9119         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
9120         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
9121         CheckedVarArgs, UncoveredArg);
9122 
9123     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
9124                                                   S.getLangOpts(),
9125                                                   S.Context.getTargetInfo(),
9126                                             Type == Sema::FST_FreeBSDKPrintf))
9127       H.DoneProcessing();
9128   } else if (Type == Sema::FST_Scanf) {
9129     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9130                         numDataArgs, Str, HasVAListArg, Args, format_idx,
9131                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
9132 
9133     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
9134                                                  S.getLangOpts(),
9135                                                  S.Context.getTargetInfo()))
9136       H.DoneProcessing();
9137   } // TODO: handle other formats
9138 }
9139 
9140 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
9141   // Str - The format string.  NOTE: this is NOT null-terminated!
9142   StringRef StrRef = FExpr->getString();
9143   const char *Str = StrRef.data();
9144   // Account for cases where the string literal is truncated in a declaration.
9145   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
9146   assert(T && "String literal not of constant array type!");
9147   size_t TypeSize = T->getSize().getZExtValue();
9148   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9149   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
9150                                                          getLangOpts(),
9151                                                          Context.getTargetInfo());
9152 }
9153 
9154 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
9155 
9156 // Returns the related absolute value function that is larger, of 0 if one
9157 // does not exist.
9158 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
9159   switch (AbsFunction) {
9160   default:
9161     return 0;
9162 
9163   case Builtin::BI__builtin_abs:
9164     return Builtin::BI__builtin_labs;
9165   case Builtin::BI__builtin_labs:
9166     return Builtin::BI__builtin_llabs;
9167   case Builtin::BI__builtin_llabs:
9168     return 0;
9169 
9170   case Builtin::BI__builtin_fabsf:
9171     return Builtin::BI__builtin_fabs;
9172   case Builtin::BI__builtin_fabs:
9173     return Builtin::BI__builtin_fabsl;
9174   case Builtin::BI__builtin_fabsl:
9175     return 0;
9176 
9177   case Builtin::BI__builtin_cabsf:
9178     return Builtin::BI__builtin_cabs;
9179   case Builtin::BI__builtin_cabs:
9180     return Builtin::BI__builtin_cabsl;
9181   case Builtin::BI__builtin_cabsl:
9182     return 0;
9183 
9184   case Builtin::BIabs:
9185     return Builtin::BIlabs;
9186   case Builtin::BIlabs:
9187     return Builtin::BIllabs;
9188   case Builtin::BIllabs:
9189     return 0;
9190 
9191   case Builtin::BIfabsf:
9192     return Builtin::BIfabs;
9193   case Builtin::BIfabs:
9194     return Builtin::BIfabsl;
9195   case Builtin::BIfabsl:
9196     return 0;
9197 
9198   case Builtin::BIcabsf:
9199    return Builtin::BIcabs;
9200   case Builtin::BIcabs:
9201     return Builtin::BIcabsl;
9202   case Builtin::BIcabsl:
9203     return 0;
9204   }
9205 }
9206 
9207 // Returns the argument type of the absolute value function.
9208 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
9209                                              unsigned AbsType) {
9210   if (AbsType == 0)
9211     return QualType();
9212 
9213   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
9214   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
9215   if (Error != ASTContext::GE_None)
9216     return QualType();
9217 
9218   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
9219   if (!FT)
9220     return QualType();
9221 
9222   if (FT->getNumParams() != 1)
9223     return QualType();
9224 
9225   return FT->getParamType(0);
9226 }
9227 
9228 // Returns the best absolute value function, or zero, based on type and
9229 // current absolute value function.
9230 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
9231                                    unsigned AbsFunctionKind) {
9232   unsigned BestKind = 0;
9233   uint64_t ArgSize = Context.getTypeSize(ArgType);
9234   for (unsigned Kind = AbsFunctionKind; Kind != 0;
9235        Kind = getLargerAbsoluteValueFunction(Kind)) {
9236     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
9237     if (Context.getTypeSize(ParamType) >= ArgSize) {
9238       if (BestKind == 0)
9239         BestKind = Kind;
9240       else if (Context.hasSameType(ParamType, ArgType)) {
9241         BestKind = Kind;
9242         break;
9243       }
9244     }
9245   }
9246   return BestKind;
9247 }
9248 
9249 enum AbsoluteValueKind {
9250   AVK_Integer,
9251   AVK_Floating,
9252   AVK_Complex
9253 };
9254 
9255 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
9256   if (T->isIntegralOrEnumerationType())
9257     return AVK_Integer;
9258   if (T->isRealFloatingType())
9259     return AVK_Floating;
9260   if (T->isAnyComplexType())
9261     return AVK_Complex;
9262 
9263   llvm_unreachable("Type not integer, floating, or complex");
9264 }
9265 
9266 // Changes the absolute value function to a different type.  Preserves whether
9267 // the function is a builtin.
9268 static unsigned changeAbsFunction(unsigned AbsKind,
9269                                   AbsoluteValueKind ValueKind) {
9270   switch (ValueKind) {
9271   case AVK_Integer:
9272     switch (AbsKind) {
9273     default:
9274       return 0;
9275     case Builtin::BI__builtin_fabsf:
9276     case Builtin::BI__builtin_fabs:
9277     case Builtin::BI__builtin_fabsl:
9278     case Builtin::BI__builtin_cabsf:
9279     case Builtin::BI__builtin_cabs:
9280     case Builtin::BI__builtin_cabsl:
9281       return Builtin::BI__builtin_abs;
9282     case Builtin::BIfabsf:
9283     case Builtin::BIfabs:
9284     case Builtin::BIfabsl:
9285     case Builtin::BIcabsf:
9286     case Builtin::BIcabs:
9287     case Builtin::BIcabsl:
9288       return Builtin::BIabs;
9289     }
9290   case AVK_Floating:
9291     switch (AbsKind) {
9292     default:
9293       return 0;
9294     case Builtin::BI__builtin_abs:
9295     case Builtin::BI__builtin_labs:
9296     case Builtin::BI__builtin_llabs:
9297     case Builtin::BI__builtin_cabsf:
9298     case Builtin::BI__builtin_cabs:
9299     case Builtin::BI__builtin_cabsl:
9300       return Builtin::BI__builtin_fabsf;
9301     case Builtin::BIabs:
9302     case Builtin::BIlabs:
9303     case Builtin::BIllabs:
9304     case Builtin::BIcabsf:
9305     case Builtin::BIcabs:
9306     case Builtin::BIcabsl:
9307       return Builtin::BIfabsf;
9308     }
9309   case AVK_Complex:
9310     switch (AbsKind) {
9311     default:
9312       return 0;
9313     case Builtin::BI__builtin_abs:
9314     case Builtin::BI__builtin_labs:
9315     case Builtin::BI__builtin_llabs:
9316     case Builtin::BI__builtin_fabsf:
9317     case Builtin::BI__builtin_fabs:
9318     case Builtin::BI__builtin_fabsl:
9319       return Builtin::BI__builtin_cabsf;
9320     case Builtin::BIabs:
9321     case Builtin::BIlabs:
9322     case Builtin::BIllabs:
9323     case Builtin::BIfabsf:
9324     case Builtin::BIfabs:
9325     case Builtin::BIfabsl:
9326       return Builtin::BIcabsf;
9327     }
9328   }
9329   llvm_unreachable("Unable to convert function");
9330 }
9331 
9332 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
9333   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
9334   if (!FnInfo)
9335     return 0;
9336 
9337   switch (FDecl->getBuiltinID()) {
9338   default:
9339     return 0;
9340   case Builtin::BI__builtin_abs:
9341   case Builtin::BI__builtin_fabs:
9342   case Builtin::BI__builtin_fabsf:
9343   case Builtin::BI__builtin_fabsl:
9344   case Builtin::BI__builtin_labs:
9345   case Builtin::BI__builtin_llabs:
9346   case Builtin::BI__builtin_cabs:
9347   case Builtin::BI__builtin_cabsf:
9348   case Builtin::BI__builtin_cabsl:
9349   case Builtin::BIabs:
9350   case Builtin::BIlabs:
9351   case Builtin::BIllabs:
9352   case Builtin::BIfabs:
9353   case Builtin::BIfabsf:
9354   case Builtin::BIfabsl:
9355   case Builtin::BIcabs:
9356   case Builtin::BIcabsf:
9357   case Builtin::BIcabsl:
9358     return FDecl->getBuiltinID();
9359   }
9360   llvm_unreachable("Unknown Builtin type");
9361 }
9362 
9363 // If the replacement is valid, emit a note with replacement function.
9364 // Additionally, suggest including the proper header if not already included.
9365 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
9366                             unsigned AbsKind, QualType ArgType) {
9367   bool EmitHeaderHint = true;
9368   const char *HeaderName = nullptr;
9369   const char *FunctionName = nullptr;
9370   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
9371     FunctionName = "std::abs";
9372     if (ArgType->isIntegralOrEnumerationType()) {
9373       HeaderName = "cstdlib";
9374     } else if (ArgType->isRealFloatingType()) {
9375       HeaderName = "cmath";
9376     } else {
9377       llvm_unreachable("Invalid Type");
9378     }
9379 
9380     // Lookup all std::abs
9381     if (NamespaceDecl *Std = S.getStdNamespace()) {
9382       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
9383       R.suppressDiagnostics();
9384       S.LookupQualifiedName(R, Std);
9385 
9386       for (const auto *I : R) {
9387         const FunctionDecl *FDecl = nullptr;
9388         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
9389           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
9390         } else {
9391           FDecl = dyn_cast<FunctionDecl>(I);
9392         }
9393         if (!FDecl)
9394           continue;
9395 
9396         // Found std::abs(), check that they are the right ones.
9397         if (FDecl->getNumParams() != 1)
9398           continue;
9399 
9400         // Check that the parameter type can handle the argument.
9401         QualType ParamType = FDecl->getParamDecl(0)->getType();
9402         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
9403             S.Context.getTypeSize(ArgType) <=
9404                 S.Context.getTypeSize(ParamType)) {
9405           // Found a function, don't need the header hint.
9406           EmitHeaderHint = false;
9407           break;
9408         }
9409       }
9410     }
9411   } else {
9412     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
9413     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
9414 
9415     if (HeaderName) {
9416       DeclarationName DN(&S.Context.Idents.get(FunctionName));
9417       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
9418       R.suppressDiagnostics();
9419       S.LookupName(R, S.getCurScope());
9420 
9421       if (R.isSingleResult()) {
9422         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
9423         if (FD && FD->getBuiltinID() == AbsKind) {
9424           EmitHeaderHint = false;
9425         } else {
9426           return;
9427         }
9428       } else if (!R.empty()) {
9429         return;
9430       }
9431     }
9432   }
9433 
9434   S.Diag(Loc, diag::note_replace_abs_function)
9435       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
9436 
9437   if (!HeaderName)
9438     return;
9439 
9440   if (!EmitHeaderHint)
9441     return;
9442 
9443   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
9444                                                     << FunctionName;
9445 }
9446 
9447 template <std::size_t StrLen>
9448 static bool IsStdFunction(const FunctionDecl *FDecl,
9449                           const char (&Str)[StrLen]) {
9450   if (!FDecl)
9451     return false;
9452   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
9453     return false;
9454   if (!FDecl->isInStdNamespace())
9455     return false;
9456 
9457   return true;
9458 }
9459 
9460 // Warn when using the wrong abs() function.
9461 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
9462                                       const FunctionDecl *FDecl) {
9463   if (Call->getNumArgs() != 1)
9464     return;
9465 
9466   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
9467   bool IsStdAbs = IsStdFunction(FDecl, "abs");
9468   if (AbsKind == 0 && !IsStdAbs)
9469     return;
9470 
9471   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9472   QualType ParamType = Call->getArg(0)->getType();
9473 
9474   // Unsigned types cannot be negative.  Suggest removing the absolute value
9475   // function call.
9476   if (ArgType->isUnsignedIntegerType()) {
9477     const char *FunctionName =
9478         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
9479     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
9480     Diag(Call->getExprLoc(), diag::note_remove_abs)
9481         << FunctionName
9482         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
9483     return;
9484   }
9485 
9486   // Taking the absolute value of a pointer is very suspicious, they probably
9487   // wanted to index into an array, dereference a pointer, call a function, etc.
9488   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
9489     unsigned DiagType = 0;
9490     if (ArgType->isFunctionType())
9491       DiagType = 1;
9492     else if (ArgType->isArrayType())
9493       DiagType = 2;
9494 
9495     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
9496     return;
9497   }
9498 
9499   // std::abs has overloads which prevent most of the absolute value problems
9500   // from occurring.
9501   if (IsStdAbs)
9502     return;
9503 
9504   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
9505   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
9506 
9507   // The argument and parameter are the same kind.  Check if they are the right
9508   // size.
9509   if (ArgValueKind == ParamValueKind) {
9510     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
9511       return;
9512 
9513     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
9514     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
9515         << FDecl << ArgType << ParamType;
9516 
9517     if (NewAbsKind == 0)
9518       return;
9519 
9520     emitReplacement(*this, Call->getExprLoc(),
9521                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9522     return;
9523   }
9524 
9525   // ArgValueKind != ParamValueKind
9526   // The wrong type of absolute value function was used.  Attempt to find the
9527   // proper one.
9528   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
9529   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
9530   if (NewAbsKind == 0)
9531     return;
9532 
9533   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
9534       << FDecl << ParamValueKind << ArgValueKind;
9535 
9536   emitReplacement(*this, Call->getExprLoc(),
9537                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9538 }
9539 
9540 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
9541 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
9542                                 const FunctionDecl *FDecl) {
9543   if (!Call || !FDecl) return;
9544 
9545   // Ignore template specializations and macros.
9546   if (inTemplateInstantiation()) return;
9547   if (Call->getExprLoc().isMacroID()) return;
9548 
9549   // Only care about the one template argument, two function parameter std::max
9550   if (Call->getNumArgs() != 2) return;
9551   if (!IsStdFunction(FDecl, "max")) return;
9552   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
9553   if (!ArgList) return;
9554   if (ArgList->size() != 1) return;
9555 
9556   // Check that template type argument is unsigned integer.
9557   const auto& TA = ArgList->get(0);
9558   if (TA.getKind() != TemplateArgument::Type) return;
9559   QualType ArgType = TA.getAsType();
9560   if (!ArgType->isUnsignedIntegerType()) return;
9561 
9562   // See if either argument is a literal zero.
9563   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
9564     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
9565     if (!MTE) return false;
9566     const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
9567     if (!Num) return false;
9568     if (Num->getValue() != 0) return false;
9569     return true;
9570   };
9571 
9572   const Expr *FirstArg = Call->getArg(0);
9573   const Expr *SecondArg = Call->getArg(1);
9574   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
9575   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
9576 
9577   // Only warn when exactly one argument is zero.
9578   if (IsFirstArgZero == IsSecondArgZero) return;
9579 
9580   SourceRange FirstRange = FirstArg->getSourceRange();
9581   SourceRange SecondRange = SecondArg->getSourceRange();
9582 
9583   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
9584 
9585   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
9586       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
9587 
9588   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
9589   SourceRange RemovalRange;
9590   if (IsFirstArgZero) {
9591     RemovalRange = SourceRange(FirstRange.getBegin(),
9592                                SecondRange.getBegin().getLocWithOffset(-1));
9593   } else {
9594     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
9595                                SecondRange.getEnd());
9596   }
9597 
9598   Diag(Call->getExprLoc(), diag::note_remove_max_call)
9599         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
9600         << FixItHint::CreateRemoval(RemovalRange);
9601 }
9602 
9603 //===--- CHECK: Standard memory functions ---------------------------------===//
9604 
9605 /// Takes the expression passed to the size_t parameter of functions
9606 /// such as memcmp, strncat, etc and warns if it's a comparison.
9607 ///
9608 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
9609 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
9610                                            IdentifierInfo *FnName,
9611                                            SourceLocation FnLoc,
9612                                            SourceLocation RParenLoc) {
9613   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
9614   if (!Size)
9615     return false;
9616 
9617   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
9618   if (!Size->isComparisonOp() && !Size->isLogicalOp())
9619     return false;
9620 
9621   SourceRange SizeRange = Size->getSourceRange();
9622   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
9623       << SizeRange << FnName;
9624   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
9625       << FnName
9626       << FixItHint::CreateInsertion(
9627              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
9628       << FixItHint::CreateRemoval(RParenLoc);
9629   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
9630       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
9631       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
9632                                     ")");
9633 
9634   return true;
9635 }
9636 
9637 /// Determine whether the given type is or contains a dynamic class type
9638 /// (e.g., whether it has a vtable).
9639 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
9640                                                      bool &IsContained) {
9641   // Look through array types while ignoring qualifiers.
9642   const Type *Ty = T->getBaseElementTypeUnsafe();
9643   IsContained = false;
9644 
9645   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
9646   RD = RD ? RD->getDefinition() : nullptr;
9647   if (!RD || RD->isInvalidDecl())
9648     return nullptr;
9649 
9650   if (RD->isDynamicClass())
9651     return RD;
9652 
9653   // Check all the fields.  If any bases were dynamic, the class is dynamic.
9654   // It's impossible for a class to transitively contain itself by value, so
9655   // infinite recursion is impossible.
9656   for (auto *FD : RD->fields()) {
9657     bool SubContained;
9658     if (const CXXRecordDecl *ContainedRD =
9659             getContainedDynamicClass(FD->getType(), SubContained)) {
9660       IsContained = true;
9661       return ContainedRD;
9662     }
9663   }
9664 
9665   return nullptr;
9666 }
9667 
9668 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
9669   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
9670     if (Unary->getKind() == UETT_SizeOf)
9671       return Unary;
9672   return nullptr;
9673 }
9674 
9675 /// If E is a sizeof expression, returns its argument expression,
9676 /// otherwise returns NULL.
9677 static const Expr *getSizeOfExprArg(const Expr *E) {
9678   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9679     if (!SizeOf->isArgumentType())
9680       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
9681   return nullptr;
9682 }
9683 
9684 /// If E is a sizeof expression, returns its argument type.
9685 static QualType getSizeOfArgType(const Expr *E) {
9686   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9687     return SizeOf->getTypeOfArgument();
9688   return QualType();
9689 }
9690 
9691 namespace {
9692 
9693 struct SearchNonTrivialToInitializeField
9694     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
9695   using Super =
9696       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
9697 
9698   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
9699 
9700   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
9701                      SourceLocation SL) {
9702     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9703       asDerived().visitArray(PDIK, AT, SL);
9704       return;
9705     }
9706 
9707     Super::visitWithKind(PDIK, FT, SL);
9708   }
9709 
9710   void visitARCStrong(QualType FT, SourceLocation SL) {
9711     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9712   }
9713   void visitARCWeak(QualType FT, SourceLocation SL) {
9714     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9715   }
9716   void visitStruct(QualType FT, SourceLocation SL) {
9717     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9718       visit(FD->getType(), FD->getLocation());
9719   }
9720   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
9721                   const ArrayType *AT, SourceLocation SL) {
9722     visit(getContext().getBaseElementType(AT), SL);
9723   }
9724   void visitTrivial(QualType FT, SourceLocation SL) {}
9725 
9726   static void diag(QualType RT, const Expr *E, Sema &S) {
9727     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
9728   }
9729 
9730   ASTContext &getContext() { return S.getASTContext(); }
9731 
9732   const Expr *E;
9733   Sema &S;
9734 };
9735 
9736 struct SearchNonTrivialToCopyField
9737     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
9738   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
9739 
9740   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
9741 
9742   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
9743                      SourceLocation SL) {
9744     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9745       asDerived().visitArray(PCK, AT, SL);
9746       return;
9747     }
9748 
9749     Super::visitWithKind(PCK, FT, SL);
9750   }
9751 
9752   void visitARCStrong(QualType FT, SourceLocation SL) {
9753     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9754   }
9755   void visitARCWeak(QualType FT, SourceLocation SL) {
9756     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9757   }
9758   void visitStruct(QualType FT, SourceLocation SL) {
9759     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9760       visit(FD->getType(), FD->getLocation());
9761   }
9762   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
9763                   SourceLocation SL) {
9764     visit(getContext().getBaseElementType(AT), SL);
9765   }
9766   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
9767                 SourceLocation SL) {}
9768   void visitTrivial(QualType FT, SourceLocation SL) {}
9769   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
9770 
9771   static void diag(QualType RT, const Expr *E, Sema &S) {
9772     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
9773   }
9774 
9775   ASTContext &getContext() { return S.getASTContext(); }
9776 
9777   const Expr *E;
9778   Sema &S;
9779 };
9780 
9781 }
9782 
9783 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
9784 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
9785   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
9786 
9787   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
9788     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
9789       return false;
9790 
9791     return doesExprLikelyComputeSize(BO->getLHS()) ||
9792            doesExprLikelyComputeSize(BO->getRHS());
9793   }
9794 
9795   return getAsSizeOfExpr(SizeofExpr) != nullptr;
9796 }
9797 
9798 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
9799 ///
9800 /// \code
9801 ///   #define MACRO 0
9802 ///   foo(MACRO);
9803 ///   foo(0);
9804 /// \endcode
9805 ///
9806 /// This should return true for the first call to foo, but not for the second
9807 /// (regardless of whether foo is a macro or function).
9808 static bool isArgumentExpandedFromMacro(SourceManager &SM,
9809                                         SourceLocation CallLoc,
9810                                         SourceLocation ArgLoc) {
9811   if (!CallLoc.isMacroID())
9812     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
9813 
9814   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
9815          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
9816 }
9817 
9818 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
9819 /// last two arguments transposed.
9820 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
9821   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
9822     return;
9823 
9824   const Expr *SizeArg =
9825     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
9826 
9827   auto isLiteralZero = [](const Expr *E) {
9828     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
9829   };
9830 
9831   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
9832   SourceLocation CallLoc = Call->getRParenLoc();
9833   SourceManager &SM = S.getSourceManager();
9834   if (isLiteralZero(SizeArg) &&
9835       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
9836 
9837     SourceLocation DiagLoc = SizeArg->getExprLoc();
9838 
9839     // Some platforms #define bzero to __builtin_memset. See if this is the
9840     // case, and if so, emit a better diagnostic.
9841     if (BId == Builtin::BIbzero ||
9842         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
9843                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
9844       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
9845       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
9846     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
9847       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
9848       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
9849     }
9850     return;
9851   }
9852 
9853   // If the second argument to a memset is a sizeof expression and the third
9854   // isn't, this is also likely an error. This should catch
9855   // 'memset(buf, sizeof(buf), 0xff)'.
9856   if (BId == Builtin::BImemset &&
9857       doesExprLikelyComputeSize(Call->getArg(1)) &&
9858       !doesExprLikelyComputeSize(Call->getArg(2))) {
9859     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
9860     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
9861     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
9862     return;
9863   }
9864 }
9865 
9866 /// Check for dangerous or invalid arguments to memset().
9867 ///
9868 /// This issues warnings on known problematic, dangerous or unspecified
9869 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
9870 /// function calls.
9871 ///
9872 /// \param Call The call expression to diagnose.
9873 void Sema::CheckMemaccessArguments(const CallExpr *Call,
9874                                    unsigned BId,
9875                                    IdentifierInfo *FnName) {
9876   assert(BId != 0);
9877 
9878   // It is possible to have a non-standard definition of memset.  Validate
9879   // we have enough arguments, and if not, abort further checking.
9880   unsigned ExpectedNumArgs =
9881       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
9882   if (Call->getNumArgs() < ExpectedNumArgs)
9883     return;
9884 
9885   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
9886                       BId == Builtin::BIstrndup ? 1 : 2);
9887   unsigned LenArg =
9888       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
9889   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
9890 
9891   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
9892                                      Call->getBeginLoc(), Call->getRParenLoc()))
9893     return;
9894 
9895   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
9896   CheckMemaccessSize(*this, BId, Call);
9897 
9898   // We have special checking when the length is a sizeof expression.
9899   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
9900   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
9901   llvm::FoldingSetNodeID SizeOfArgID;
9902 
9903   // Although widely used, 'bzero' is not a standard function. Be more strict
9904   // with the argument types before allowing diagnostics and only allow the
9905   // form bzero(ptr, sizeof(...)).
9906   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9907   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
9908     return;
9909 
9910   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
9911     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
9912     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
9913 
9914     QualType DestTy = Dest->getType();
9915     QualType PointeeTy;
9916     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
9917       PointeeTy = DestPtrTy->getPointeeType();
9918 
9919       // Never warn about void type pointers. This can be used to suppress
9920       // false positives.
9921       if (PointeeTy->isVoidType())
9922         continue;
9923 
9924       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
9925       // actually comparing the expressions for equality. Because computing the
9926       // expression IDs can be expensive, we only do this if the diagnostic is
9927       // enabled.
9928       if (SizeOfArg &&
9929           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
9930                            SizeOfArg->getExprLoc())) {
9931         // We only compute IDs for expressions if the warning is enabled, and
9932         // cache the sizeof arg's ID.
9933         if (SizeOfArgID == llvm::FoldingSetNodeID())
9934           SizeOfArg->Profile(SizeOfArgID, Context, true);
9935         llvm::FoldingSetNodeID DestID;
9936         Dest->Profile(DestID, Context, true);
9937         if (DestID == SizeOfArgID) {
9938           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
9939           //       over sizeof(src) as well.
9940           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
9941           StringRef ReadableName = FnName->getName();
9942 
9943           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
9944             if (UnaryOp->getOpcode() == UO_AddrOf)
9945               ActionIdx = 1; // If its an address-of operator, just remove it.
9946           if (!PointeeTy->isIncompleteType() &&
9947               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
9948             ActionIdx = 2; // If the pointee's size is sizeof(char),
9949                            // suggest an explicit length.
9950 
9951           // If the function is defined as a builtin macro, do not show macro
9952           // expansion.
9953           SourceLocation SL = SizeOfArg->getExprLoc();
9954           SourceRange DSR = Dest->getSourceRange();
9955           SourceRange SSR = SizeOfArg->getSourceRange();
9956           SourceManager &SM = getSourceManager();
9957 
9958           if (SM.isMacroArgExpansion(SL)) {
9959             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
9960             SL = SM.getSpellingLoc(SL);
9961             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
9962                              SM.getSpellingLoc(DSR.getEnd()));
9963             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
9964                              SM.getSpellingLoc(SSR.getEnd()));
9965           }
9966 
9967           DiagRuntimeBehavior(SL, SizeOfArg,
9968                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
9969                                 << ReadableName
9970                                 << PointeeTy
9971                                 << DestTy
9972                                 << DSR
9973                                 << SSR);
9974           DiagRuntimeBehavior(SL, SizeOfArg,
9975                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
9976                                 << ActionIdx
9977                                 << SSR);
9978 
9979           break;
9980         }
9981       }
9982 
9983       // Also check for cases where the sizeof argument is the exact same
9984       // type as the memory argument, and where it points to a user-defined
9985       // record type.
9986       if (SizeOfArgTy != QualType()) {
9987         if (PointeeTy->isRecordType() &&
9988             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
9989           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
9990                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
9991                                 << FnName << SizeOfArgTy << ArgIdx
9992                                 << PointeeTy << Dest->getSourceRange()
9993                                 << LenExpr->getSourceRange());
9994           break;
9995         }
9996       }
9997     } else if (DestTy->isArrayType()) {
9998       PointeeTy = DestTy;
9999     }
10000 
10001     if (PointeeTy == QualType())
10002       continue;
10003 
10004     // Always complain about dynamic classes.
10005     bool IsContained;
10006     if (const CXXRecordDecl *ContainedRD =
10007             getContainedDynamicClass(PointeeTy, IsContained)) {
10008 
10009       unsigned OperationType = 0;
10010       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
10011       // "overwritten" if we're warning about the destination for any call
10012       // but memcmp; otherwise a verb appropriate to the call.
10013       if (ArgIdx != 0 || IsCmp) {
10014         if (BId == Builtin::BImemcpy)
10015           OperationType = 1;
10016         else if(BId == Builtin::BImemmove)
10017           OperationType = 2;
10018         else if (IsCmp)
10019           OperationType = 3;
10020       }
10021 
10022       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10023                           PDiag(diag::warn_dyn_class_memaccess)
10024                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
10025                               << IsContained << ContainedRD << OperationType
10026                               << Call->getCallee()->getSourceRange());
10027     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
10028              BId != Builtin::BImemset)
10029       DiagRuntimeBehavior(
10030         Dest->getExprLoc(), Dest,
10031         PDiag(diag::warn_arc_object_memaccess)
10032           << ArgIdx << FnName << PointeeTy
10033           << Call->getCallee()->getSourceRange());
10034     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
10035       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10036           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
10037         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10038                             PDiag(diag::warn_cstruct_memaccess)
10039                                 << ArgIdx << FnName << PointeeTy << 0);
10040         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
10041       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10042                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
10043         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10044                             PDiag(diag::warn_cstruct_memaccess)
10045                                 << ArgIdx << FnName << PointeeTy << 1);
10046         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
10047       } else {
10048         continue;
10049       }
10050     } else
10051       continue;
10052 
10053     DiagRuntimeBehavior(
10054       Dest->getExprLoc(), Dest,
10055       PDiag(diag::note_bad_memaccess_silence)
10056         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
10057     break;
10058   }
10059 }
10060 
10061 // A little helper routine: ignore addition and subtraction of integer literals.
10062 // This intentionally does not ignore all integer constant expressions because
10063 // we don't want to remove sizeof().
10064 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
10065   Ex = Ex->IgnoreParenCasts();
10066 
10067   while (true) {
10068     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
10069     if (!BO || !BO->isAdditiveOp())
10070       break;
10071 
10072     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
10073     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
10074 
10075     if (isa<IntegerLiteral>(RHS))
10076       Ex = LHS;
10077     else if (isa<IntegerLiteral>(LHS))
10078       Ex = RHS;
10079     else
10080       break;
10081   }
10082 
10083   return Ex;
10084 }
10085 
10086 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
10087                                                       ASTContext &Context) {
10088   // Only handle constant-sized or VLAs, but not flexible members.
10089   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
10090     // Only issue the FIXIT for arrays of size > 1.
10091     if (CAT->getSize().getSExtValue() <= 1)
10092       return false;
10093   } else if (!Ty->isVariableArrayType()) {
10094     return false;
10095   }
10096   return true;
10097 }
10098 
10099 // Warn if the user has made the 'size' argument to strlcpy or strlcat
10100 // be the size of the source, instead of the destination.
10101 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
10102                                     IdentifierInfo *FnName) {
10103 
10104   // Don't crash if the user has the wrong number of arguments
10105   unsigned NumArgs = Call->getNumArgs();
10106   if ((NumArgs != 3) && (NumArgs != 4))
10107     return;
10108 
10109   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
10110   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
10111   const Expr *CompareWithSrc = nullptr;
10112 
10113   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
10114                                      Call->getBeginLoc(), Call->getRParenLoc()))
10115     return;
10116 
10117   // Look for 'strlcpy(dst, x, sizeof(x))'
10118   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
10119     CompareWithSrc = Ex;
10120   else {
10121     // Look for 'strlcpy(dst, x, strlen(x))'
10122     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
10123       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
10124           SizeCall->getNumArgs() == 1)
10125         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
10126     }
10127   }
10128 
10129   if (!CompareWithSrc)
10130     return;
10131 
10132   // Determine if the argument to sizeof/strlen is equal to the source
10133   // argument.  In principle there's all kinds of things you could do
10134   // here, for instance creating an == expression and evaluating it with
10135   // EvaluateAsBooleanCondition, but this uses a more direct technique:
10136   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
10137   if (!SrcArgDRE)
10138     return;
10139 
10140   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
10141   if (!CompareWithSrcDRE ||
10142       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
10143     return;
10144 
10145   const Expr *OriginalSizeArg = Call->getArg(2);
10146   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
10147       << OriginalSizeArg->getSourceRange() << FnName;
10148 
10149   // Output a FIXIT hint if the destination is an array (rather than a
10150   // pointer to an array).  This could be enhanced to handle some
10151   // pointers if we know the actual size, like if DstArg is 'array+2'
10152   // we could say 'sizeof(array)-2'.
10153   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
10154   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
10155     return;
10156 
10157   SmallString<128> sizeString;
10158   llvm::raw_svector_ostream OS(sizeString);
10159   OS << "sizeof(";
10160   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10161   OS << ")";
10162 
10163   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
10164       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
10165                                       OS.str());
10166 }
10167 
10168 /// Check if two expressions refer to the same declaration.
10169 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
10170   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
10171     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
10172       return D1->getDecl() == D2->getDecl();
10173   return false;
10174 }
10175 
10176 static const Expr *getStrlenExprArg(const Expr *E) {
10177   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10178     const FunctionDecl *FD = CE->getDirectCallee();
10179     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
10180       return nullptr;
10181     return CE->getArg(0)->IgnoreParenCasts();
10182   }
10183   return nullptr;
10184 }
10185 
10186 // Warn on anti-patterns as the 'size' argument to strncat.
10187 // The correct size argument should look like following:
10188 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
10189 void Sema::CheckStrncatArguments(const CallExpr *CE,
10190                                  IdentifierInfo *FnName) {
10191   // Don't crash if the user has the wrong number of arguments.
10192   if (CE->getNumArgs() < 3)
10193     return;
10194   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
10195   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
10196   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
10197 
10198   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
10199                                      CE->getRParenLoc()))
10200     return;
10201 
10202   // Identify common expressions, which are wrongly used as the size argument
10203   // to strncat and may lead to buffer overflows.
10204   unsigned PatternType = 0;
10205   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
10206     // - sizeof(dst)
10207     if (referToTheSameDecl(SizeOfArg, DstArg))
10208       PatternType = 1;
10209     // - sizeof(src)
10210     else if (referToTheSameDecl(SizeOfArg, SrcArg))
10211       PatternType = 2;
10212   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
10213     if (BE->getOpcode() == BO_Sub) {
10214       const Expr *L = BE->getLHS()->IgnoreParenCasts();
10215       const Expr *R = BE->getRHS()->IgnoreParenCasts();
10216       // - sizeof(dst) - strlen(dst)
10217       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
10218           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
10219         PatternType = 1;
10220       // - sizeof(src) - (anything)
10221       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
10222         PatternType = 2;
10223     }
10224   }
10225 
10226   if (PatternType == 0)
10227     return;
10228 
10229   // Generate the diagnostic.
10230   SourceLocation SL = LenArg->getBeginLoc();
10231   SourceRange SR = LenArg->getSourceRange();
10232   SourceManager &SM = getSourceManager();
10233 
10234   // If the function is defined as a builtin macro, do not show macro expansion.
10235   if (SM.isMacroArgExpansion(SL)) {
10236     SL = SM.getSpellingLoc(SL);
10237     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
10238                      SM.getSpellingLoc(SR.getEnd()));
10239   }
10240 
10241   // Check if the destination is an array (rather than a pointer to an array).
10242   QualType DstTy = DstArg->getType();
10243   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
10244                                                                     Context);
10245   if (!isKnownSizeArray) {
10246     if (PatternType == 1)
10247       Diag(SL, diag::warn_strncat_wrong_size) << SR;
10248     else
10249       Diag(SL, diag::warn_strncat_src_size) << SR;
10250     return;
10251   }
10252 
10253   if (PatternType == 1)
10254     Diag(SL, diag::warn_strncat_large_size) << SR;
10255   else
10256     Diag(SL, diag::warn_strncat_src_size) << SR;
10257 
10258   SmallString<128> sizeString;
10259   llvm::raw_svector_ostream OS(sizeString);
10260   OS << "sizeof(";
10261   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10262   OS << ") - ";
10263   OS << "strlen(";
10264   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10265   OS << ") - 1";
10266 
10267   Diag(SL, diag::note_strncat_wrong_size)
10268     << FixItHint::CreateReplacement(SR, OS.str());
10269 }
10270 
10271 namespace {
10272 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
10273                                 const UnaryOperator *UnaryExpr,
10274                                 const VarDecl *Var) {
10275   StorageClass Class = Var->getStorageClass();
10276   if (Class == StorageClass::SC_Extern ||
10277       Class == StorageClass::SC_PrivateExtern ||
10278       Var->getType()->isReferenceType())
10279     return;
10280 
10281   S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
10282       << CalleeName << Var;
10283 }
10284 
10285 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
10286                                 const UnaryOperator *UnaryExpr, const Decl *D) {
10287   if (const auto *Field = dyn_cast<FieldDecl>(D))
10288     S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
10289         << CalleeName << Field;
10290 }
10291 
10292 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
10293                                  const UnaryOperator *UnaryExpr) {
10294   if (UnaryExpr->getOpcode() != UnaryOperator::Opcode::UO_AddrOf)
10295     return;
10296 
10297   if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr()))
10298     if (const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl()))
10299       return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, Var);
10300 
10301   if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
10302     return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
10303                                       Lvalue->getMemberDecl());
10304 }
10305 
10306 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
10307                                   const DeclRefExpr *Lvalue) {
10308   if (!Lvalue->getType()->isArrayType())
10309     return;
10310 
10311   const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
10312   if (Var == nullptr)
10313     return;
10314 
10315   S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
10316       << CalleeName << Var;
10317 }
10318 } // namespace
10319 
10320 /// Alerts the user that they are attempting to free a non-malloc'd object.
10321 void Sema::CheckFreeArguments(const CallExpr *E) {
10322   const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
10323   const std::string CalleeName =
10324       dyn_cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
10325 
10326   if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
10327     return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
10328 
10329   if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
10330     return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
10331 }
10332 
10333 void
10334 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
10335                          SourceLocation ReturnLoc,
10336                          bool isObjCMethod,
10337                          const AttrVec *Attrs,
10338                          const FunctionDecl *FD) {
10339   // Check if the return value is null but should not be.
10340   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
10341        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
10342       CheckNonNullExpr(*this, RetValExp))
10343     Diag(ReturnLoc, diag::warn_null_ret)
10344       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
10345 
10346   // C++11 [basic.stc.dynamic.allocation]p4:
10347   //   If an allocation function declared with a non-throwing
10348   //   exception-specification fails to allocate storage, it shall return
10349   //   a null pointer. Any other allocation function that fails to allocate
10350   //   storage shall indicate failure only by throwing an exception [...]
10351   if (FD) {
10352     OverloadedOperatorKind Op = FD->getOverloadedOperator();
10353     if (Op == OO_New || Op == OO_Array_New) {
10354       const FunctionProtoType *Proto
10355         = FD->getType()->castAs<FunctionProtoType>();
10356       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
10357           CheckNonNullExpr(*this, RetValExp))
10358         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
10359           << FD << getLangOpts().CPlusPlus11;
10360     }
10361   }
10362 
10363   // PPC MMA non-pointer types are not allowed as return type. Checking the type
10364   // here prevent the user from using a PPC MMA type as trailing return type.
10365   if (Context.getTargetInfo().getTriple().isPPC64())
10366     CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
10367 }
10368 
10369 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
10370 
10371 /// Check for comparisons of floating point operands using != and ==.
10372 /// Issue a warning if these are no self-comparisons, as they are not likely
10373 /// to do what the programmer intended.
10374 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
10375   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
10376   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
10377 
10378   // Special case: check for x == x (which is OK).
10379   // Do not emit warnings for such cases.
10380   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
10381     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
10382       if (DRL->getDecl() == DRR->getDecl())
10383         return;
10384 
10385   // Special case: check for comparisons against literals that can be exactly
10386   //  represented by APFloat.  In such cases, do not emit a warning.  This
10387   //  is a heuristic: often comparison against such literals are used to
10388   //  detect if a value in a variable has not changed.  This clearly can
10389   //  lead to false negatives.
10390   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
10391     if (FLL->isExact())
10392       return;
10393   } else
10394     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
10395       if (FLR->isExact())
10396         return;
10397 
10398   // Check for comparisons with builtin types.
10399   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
10400     if (CL->getBuiltinCallee())
10401       return;
10402 
10403   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
10404     if (CR->getBuiltinCallee())
10405       return;
10406 
10407   // Emit the diagnostic.
10408   Diag(Loc, diag::warn_floatingpoint_eq)
10409     << LHS->getSourceRange() << RHS->getSourceRange();
10410 }
10411 
10412 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
10413 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
10414 
10415 namespace {
10416 
10417 /// Structure recording the 'active' range of an integer-valued
10418 /// expression.
10419 struct IntRange {
10420   /// The number of bits active in the int. Note that this includes exactly one
10421   /// sign bit if !NonNegative.
10422   unsigned Width;
10423 
10424   /// True if the int is known not to have negative values. If so, all leading
10425   /// bits before Width are known zero, otherwise they are known to be the
10426   /// same as the MSB within Width.
10427   bool NonNegative;
10428 
10429   IntRange(unsigned Width, bool NonNegative)
10430       : Width(Width), NonNegative(NonNegative) {}
10431 
10432   /// Number of bits excluding the sign bit.
10433   unsigned valueBits() const {
10434     return NonNegative ? Width : Width - 1;
10435   }
10436 
10437   /// Returns the range of the bool type.
10438   static IntRange forBoolType() {
10439     return IntRange(1, true);
10440   }
10441 
10442   /// Returns the range of an opaque value of the given integral type.
10443   static IntRange forValueOfType(ASTContext &C, QualType T) {
10444     return forValueOfCanonicalType(C,
10445                           T->getCanonicalTypeInternal().getTypePtr());
10446   }
10447 
10448   /// Returns the range of an opaque value of a canonical integral type.
10449   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
10450     assert(T->isCanonicalUnqualified());
10451 
10452     if (const VectorType *VT = dyn_cast<VectorType>(T))
10453       T = VT->getElementType().getTypePtr();
10454     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
10455       T = CT->getElementType().getTypePtr();
10456     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
10457       T = AT->getValueType().getTypePtr();
10458 
10459     if (!C.getLangOpts().CPlusPlus) {
10460       // For enum types in C code, use the underlying datatype.
10461       if (const EnumType *ET = dyn_cast<EnumType>(T))
10462         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
10463     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
10464       // For enum types in C++, use the known bit width of the enumerators.
10465       EnumDecl *Enum = ET->getDecl();
10466       // In C++11, enums can have a fixed underlying type. Use this type to
10467       // compute the range.
10468       if (Enum->isFixed()) {
10469         return IntRange(C.getIntWidth(QualType(T, 0)),
10470                         !ET->isSignedIntegerOrEnumerationType());
10471       }
10472 
10473       unsigned NumPositive = Enum->getNumPositiveBits();
10474       unsigned NumNegative = Enum->getNumNegativeBits();
10475 
10476       if (NumNegative == 0)
10477         return IntRange(NumPositive, true/*NonNegative*/);
10478       else
10479         return IntRange(std::max(NumPositive + 1, NumNegative),
10480                         false/*NonNegative*/);
10481     }
10482 
10483     if (const auto *EIT = dyn_cast<ExtIntType>(T))
10484       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
10485 
10486     const BuiltinType *BT = cast<BuiltinType>(T);
10487     assert(BT->isInteger());
10488 
10489     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10490   }
10491 
10492   /// Returns the "target" range of a canonical integral type, i.e.
10493   /// the range of values expressible in the type.
10494   ///
10495   /// This matches forValueOfCanonicalType except that enums have the
10496   /// full range of their type, not the range of their enumerators.
10497   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
10498     assert(T->isCanonicalUnqualified());
10499 
10500     if (const VectorType *VT = dyn_cast<VectorType>(T))
10501       T = VT->getElementType().getTypePtr();
10502     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
10503       T = CT->getElementType().getTypePtr();
10504     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
10505       T = AT->getValueType().getTypePtr();
10506     if (const EnumType *ET = dyn_cast<EnumType>(T))
10507       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
10508 
10509     if (const auto *EIT = dyn_cast<ExtIntType>(T))
10510       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
10511 
10512     const BuiltinType *BT = cast<BuiltinType>(T);
10513     assert(BT->isInteger());
10514 
10515     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10516   }
10517 
10518   /// Returns the supremum of two ranges: i.e. their conservative merge.
10519   static IntRange join(IntRange L, IntRange R) {
10520     bool Unsigned = L.NonNegative && R.NonNegative;
10521     return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
10522                     L.NonNegative && R.NonNegative);
10523   }
10524 
10525   /// Return the range of a bitwise-AND of the two ranges.
10526   static IntRange bit_and(IntRange L, IntRange R) {
10527     unsigned Bits = std::max(L.Width, R.Width);
10528     bool NonNegative = false;
10529     if (L.NonNegative) {
10530       Bits = std::min(Bits, L.Width);
10531       NonNegative = true;
10532     }
10533     if (R.NonNegative) {
10534       Bits = std::min(Bits, R.Width);
10535       NonNegative = true;
10536     }
10537     return IntRange(Bits, NonNegative);
10538   }
10539 
10540   /// Return the range of a sum of the two ranges.
10541   static IntRange sum(IntRange L, IntRange R) {
10542     bool Unsigned = L.NonNegative && R.NonNegative;
10543     return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
10544                     Unsigned);
10545   }
10546 
10547   /// Return the range of a difference of the two ranges.
10548   static IntRange difference(IntRange L, IntRange R) {
10549     // We need a 1-bit-wider range if:
10550     //   1) LHS can be negative: least value can be reduced.
10551     //   2) RHS can be negative: greatest value can be increased.
10552     bool CanWiden = !L.NonNegative || !R.NonNegative;
10553     bool Unsigned = L.NonNegative && R.Width == 0;
10554     return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
10555                         !Unsigned,
10556                     Unsigned);
10557   }
10558 
10559   /// Return the range of a product of the two ranges.
10560   static IntRange product(IntRange L, IntRange R) {
10561     // If both LHS and RHS can be negative, we can form
10562     //   -2^L * -2^R = 2^(L + R)
10563     // which requires L + R + 1 value bits to represent.
10564     bool CanWiden = !L.NonNegative && !R.NonNegative;
10565     bool Unsigned = L.NonNegative && R.NonNegative;
10566     return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
10567                     Unsigned);
10568   }
10569 
10570   /// Return the range of a remainder operation between the two ranges.
10571   static IntRange rem(IntRange L, IntRange R) {
10572     // The result of a remainder can't be larger than the result of
10573     // either side. The sign of the result is the sign of the LHS.
10574     bool Unsigned = L.NonNegative;
10575     return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
10576                     Unsigned);
10577   }
10578 };
10579 
10580 } // namespace
10581 
10582 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
10583                               unsigned MaxWidth) {
10584   if (value.isSigned() && value.isNegative())
10585     return IntRange(value.getMinSignedBits(), false);
10586 
10587   if (value.getBitWidth() > MaxWidth)
10588     value = value.trunc(MaxWidth);
10589 
10590   // isNonNegative() just checks the sign bit without considering
10591   // signedness.
10592   return IntRange(value.getActiveBits(), true);
10593 }
10594 
10595 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
10596                               unsigned MaxWidth) {
10597   if (result.isInt())
10598     return GetValueRange(C, result.getInt(), MaxWidth);
10599 
10600   if (result.isVector()) {
10601     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
10602     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
10603       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
10604       R = IntRange::join(R, El);
10605     }
10606     return R;
10607   }
10608 
10609   if (result.isComplexInt()) {
10610     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
10611     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
10612     return IntRange::join(R, I);
10613   }
10614 
10615   // This can happen with lossless casts to intptr_t of "based" lvalues.
10616   // Assume it might use arbitrary bits.
10617   // FIXME: The only reason we need to pass the type in here is to get
10618   // the sign right on this one case.  It would be nice if APValue
10619   // preserved this.
10620   assert(result.isLValue() || result.isAddrLabelDiff());
10621   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
10622 }
10623 
10624 static QualType GetExprType(const Expr *E) {
10625   QualType Ty = E->getType();
10626   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
10627     Ty = AtomicRHS->getValueType();
10628   return Ty;
10629 }
10630 
10631 /// Pseudo-evaluate the given integer expression, estimating the
10632 /// range of values it might take.
10633 ///
10634 /// \param MaxWidth The width to which the value will be truncated.
10635 /// \param Approximate If \c true, return a likely range for the result: in
10636 ///        particular, assume that aritmetic on narrower types doesn't leave
10637 ///        those types. If \c false, return a range including all possible
10638 ///        result values.
10639 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
10640                              bool InConstantContext, bool Approximate) {
10641   E = E->IgnoreParens();
10642 
10643   // Try a full evaluation first.
10644   Expr::EvalResult result;
10645   if (E->EvaluateAsRValue(result, C, InConstantContext))
10646     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
10647 
10648   // I think we only want to look through implicit casts here; if the
10649   // user has an explicit widening cast, we should treat the value as
10650   // being of the new, wider type.
10651   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
10652     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
10653       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
10654                           Approximate);
10655 
10656     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
10657 
10658     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
10659                          CE->getCastKind() == CK_BooleanToSignedIntegral;
10660 
10661     // Assume that non-integer casts can span the full range of the type.
10662     if (!isIntegerCast)
10663       return OutputTypeRange;
10664 
10665     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
10666                                      std::min(MaxWidth, OutputTypeRange.Width),
10667                                      InConstantContext, Approximate);
10668 
10669     // Bail out if the subexpr's range is as wide as the cast type.
10670     if (SubRange.Width >= OutputTypeRange.Width)
10671       return OutputTypeRange;
10672 
10673     // Otherwise, we take the smaller width, and we're non-negative if
10674     // either the output type or the subexpr is.
10675     return IntRange(SubRange.Width,
10676                     SubRange.NonNegative || OutputTypeRange.NonNegative);
10677   }
10678 
10679   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
10680     // If we can fold the condition, just take that operand.
10681     bool CondResult;
10682     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
10683       return GetExprRange(C,
10684                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
10685                           MaxWidth, InConstantContext, Approximate);
10686 
10687     // Otherwise, conservatively merge.
10688     // GetExprRange requires an integer expression, but a throw expression
10689     // results in a void type.
10690     Expr *E = CO->getTrueExpr();
10691     IntRange L = E->getType()->isVoidType()
10692                      ? IntRange{0, true}
10693                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
10694     E = CO->getFalseExpr();
10695     IntRange R = E->getType()->isVoidType()
10696                      ? IntRange{0, true}
10697                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
10698     return IntRange::join(L, R);
10699   }
10700 
10701   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
10702     IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
10703 
10704     switch (BO->getOpcode()) {
10705     case BO_Cmp:
10706       llvm_unreachable("builtin <=> should have class type");
10707 
10708     // Boolean-valued operations are single-bit and positive.
10709     case BO_LAnd:
10710     case BO_LOr:
10711     case BO_LT:
10712     case BO_GT:
10713     case BO_LE:
10714     case BO_GE:
10715     case BO_EQ:
10716     case BO_NE:
10717       return IntRange::forBoolType();
10718 
10719     // The type of the assignments is the type of the LHS, so the RHS
10720     // is not necessarily the same type.
10721     case BO_MulAssign:
10722     case BO_DivAssign:
10723     case BO_RemAssign:
10724     case BO_AddAssign:
10725     case BO_SubAssign:
10726     case BO_XorAssign:
10727     case BO_OrAssign:
10728       // TODO: bitfields?
10729       return IntRange::forValueOfType(C, GetExprType(E));
10730 
10731     // Simple assignments just pass through the RHS, which will have
10732     // been coerced to the LHS type.
10733     case BO_Assign:
10734       // TODO: bitfields?
10735       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
10736                           Approximate);
10737 
10738     // Operations with opaque sources are black-listed.
10739     case BO_PtrMemD:
10740     case BO_PtrMemI:
10741       return IntRange::forValueOfType(C, GetExprType(E));
10742 
10743     // Bitwise-and uses the *infinum* of the two source ranges.
10744     case BO_And:
10745     case BO_AndAssign:
10746       Combine = IntRange::bit_and;
10747       break;
10748 
10749     // Left shift gets black-listed based on a judgement call.
10750     case BO_Shl:
10751       // ...except that we want to treat '1 << (blah)' as logically
10752       // positive.  It's an important idiom.
10753       if (IntegerLiteral *I
10754             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
10755         if (I->getValue() == 1) {
10756           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
10757           return IntRange(R.Width, /*NonNegative*/ true);
10758         }
10759       }
10760       LLVM_FALLTHROUGH;
10761 
10762     case BO_ShlAssign:
10763       return IntRange::forValueOfType(C, GetExprType(E));
10764 
10765     // Right shift by a constant can narrow its left argument.
10766     case BO_Shr:
10767     case BO_ShrAssign: {
10768       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext,
10769                                 Approximate);
10770 
10771       // If the shift amount is a positive constant, drop the width by
10772       // that much.
10773       if (Optional<llvm::APSInt> shift =
10774               BO->getRHS()->getIntegerConstantExpr(C)) {
10775         if (shift->isNonNegative()) {
10776           unsigned zext = shift->getZExtValue();
10777           if (zext >= L.Width)
10778             L.Width = (L.NonNegative ? 0 : 1);
10779           else
10780             L.Width -= zext;
10781         }
10782       }
10783 
10784       return L;
10785     }
10786 
10787     // Comma acts as its right operand.
10788     case BO_Comma:
10789       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
10790                           Approximate);
10791 
10792     case BO_Add:
10793       if (!Approximate)
10794         Combine = IntRange::sum;
10795       break;
10796 
10797     case BO_Sub:
10798       if (BO->getLHS()->getType()->isPointerType())
10799         return IntRange::forValueOfType(C, GetExprType(E));
10800       if (!Approximate)
10801         Combine = IntRange::difference;
10802       break;
10803 
10804     case BO_Mul:
10805       if (!Approximate)
10806         Combine = IntRange::product;
10807       break;
10808 
10809     // The width of a division result is mostly determined by the size
10810     // of the LHS.
10811     case BO_Div: {
10812       // Don't 'pre-truncate' the operands.
10813       unsigned opWidth = C.getIntWidth(GetExprType(E));
10814       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext,
10815                                 Approximate);
10816 
10817       // If the divisor is constant, use that.
10818       if (Optional<llvm::APSInt> divisor =
10819               BO->getRHS()->getIntegerConstantExpr(C)) {
10820         unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
10821         if (log2 >= L.Width)
10822           L.Width = (L.NonNegative ? 0 : 1);
10823         else
10824           L.Width = std::min(L.Width - log2, MaxWidth);
10825         return L;
10826       }
10827 
10828       // Otherwise, just use the LHS's width.
10829       // FIXME: This is wrong if the LHS could be its minimal value and the RHS
10830       // could be -1.
10831       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext,
10832                                 Approximate);
10833       return IntRange(L.Width, L.NonNegative && R.NonNegative);
10834     }
10835 
10836     case BO_Rem:
10837       Combine = IntRange::rem;
10838       break;
10839 
10840     // The default behavior is okay for these.
10841     case BO_Xor:
10842     case BO_Or:
10843       break;
10844     }
10845 
10846     // Combine the two ranges, but limit the result to the type in which we
10847     // performed the computation.
10848     QualType T = GetExprType(E);
10849     unsigned opWidth = C.getIntWidth(T);
10850     IntRange L =
10851         GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate);
10852     IntRange R =
10853         GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate);
10854     IntRange C = Combine(L, R);
10855     C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
10856     C.Width = std::min(C.Width, MaxWidth);
10857     return C;
10858   }
10859 
10860   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
10861     switch (UO->getOpcode()) {
10862     // Boolean-valued operations are white-listed.
10863     case UO_LNot:
10864       return IntRange::forBoolType();
10865 
10866     // Operations with opaque sources are black-listed.
10867     case UO_Deref:
10868     case UO_AddrOf: // should be impossible
10869       return IntRange::forValueOfType(C, GetExprType(E));
10870 
10871     default:
10872       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
10873                           Approximate);
10874     }
10875   }
10876 
10877   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
10878     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
10879                         Approximate);
10880 
10881   if (const auto *BitField = E->getSourceBitField())
10882     return IntRange(BitField->getBitWidthValue(C),
10883                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
10884 
10885   return IntRange::forValueOfType(C, GetExprType(E));
10886 }
10887 
10888 static IntRange GetExprRange(ASTContext &C, const Expr *E,
10889                              bool InConstantContext, bool Approximate) {
10890   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
10891                       Approximate);
10892 }
10893 
10894 /// Checks whether the given value, which currently has the given
10895 /// source semantics, has the same value when coerced through the
10896 /// target semantics.
10897 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
10898                                  const llvm::fltSemantics &Src,
10899                                  const llvm::fltSemantics &Tgt) {
10900   llvm::APFloat truncated = value;
10901 
10902   bool ignored;
10903   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
10904   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
10905 
10906   return truncated.bitwiseIsEqual(value);
10907 }
10908 
10909 /// Checks whether the given value, which currently has the given
10910 /// source semantics, has the same value when coerced through the
10911 /// target semantics.
10912 ///
10913 /// The value might be a vector of floats (or a complex number).
10914 static bool IsSameFloatAfterCast(const APValue &value,
10915                                  const llvm::fltSemantics &Src,
10916                                  const llvm::fltSemantics &Tgt) {
10917   if (value.isFloat())
10918     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
10919 
10920   if (value.isVector()) {
10921     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
10922       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
10923         return false;
10924     return true;
10925   }
10926 
10927   assert(value.isComplexFloat());
10928   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
10929           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
10930 }
10931 
10932 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
10933                                        bool IsListInit = false);
10934 
10935 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
10936   // Suppress cases where we are comparing against an enum constant.
10937   if (const DeclRefExpr *DR =
10938       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
10939     if (isa<EnumConstantDecl>(DR->getDecl()))
10940       return true;
10941 
10942   // Suppress cases where the value is expanded from a macro, unless that macro
10943   // is how a language represents a boolean literal. This is the case in both C
10944   // and Objective-C.
10945   SourceLocation BeginLoc = E->getBeginLoc();
10946   if (BeginLoc.isMacroID()) {
10947     StringRef MacroName = Lexer::getImmediateMacroName(
10948         BeginLoc, S.getSourceManager(), S.getLangOpts());
10949     return MacroName != "YES" && MacroName != "NO" &&
10950            MacroName != "true" && MacroName != "false";
10951   }
10952 
10953   return false;
10954 }
10955 
10956 static bool isKnownToHaveUnsignedValue(Expr *E) {
10957   return E->getType()->isIntegerType() &&
10958          (!E->getType()->isSignedIntegerType() ||
10959           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
10960 }
10961 
10962 namespace {
10963 /// The promoted range of values of a type. In general this has the
10964 /// following structure:
10965 ///
10966 ///     |-----------| . . . |-----------|
10967 ///     ^           ^       ^           ^
10968 ///    Min       HoleMin  HoleMax      Max
10969 ///
10970 /// ... where there is only a hole if a signed type is promoted to unsigned
10971 /// (in which case Min and Max are the smallest and largest representable
10972 /// values).
10973 struct PromotedRange {
10974   // Min, or HoleMax if there is a hole.
10975   llvm::APSInt PromotedMin;
10976   // Max, or HoleMin if there is a hole.
10977   llvm::APSInt PromotedMax;
10978 
10979   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
10980     if (R.Width == 0)
10981       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
10982     else if (R.Width >= BitWidth && !Unsigned) {
10983       // Promotion made the type *narrower*. This happens when promoting
10984       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
10985       // Treat all values of 'signed int' as being in range for now.
10986       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
10987       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
10988     } else {
10989       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
10990                         .extOrTrunc(BitWidth);
10991       PromotedMin.setIsUnsigned(Unsigned);
10992 
10993       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
10994                         .extOrTrunc(BitWidth);
10995       PromotedMax.setIsUnsigned(Unsigned);
10996     }
10997   }
10998 
10999   // Determine whether this range is contiguous (has no hole).
11000   bool isContiguous() const { return PromotedMin <= PromotedMax; }
11001 
11002   // Where a constant value is within the range.
11003   enum ComparisonResult {
11004     LT = 0x1,
11005     LE = 0x2,
11006     GT = 0x4,
11007     GE = 0x8,
11008     EQ = 0x10,
11009     NE = 0x20,
11010     InRangeFlag = 0x40,
11011 
11012     Less = LE | LT | NE,
11013     Min = LE | InRangeFlag,
11014     InRange = InRangeFlag,
11015     Max = GE | InRangeFlag,
11016     Greater = GE | GT | NE,
11017 
11018     OnlyValue = LE | GE | EQ | InRangeFlag,
11019     InHole = NE
11020   };
11021 
11022   ComparisonResult compare(const llvm::APSInt &Value) const {
11023     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
11024            Value.isUnsigned() == PromotedMin.isUnsigned());
11025     if (!isContiguous()) {
11026       assert(Value.isUnsigned() && "discontiguous range for signed compare");
11027       if (Value.isMinValue()) return Min;
11028       if (Value.isMaxValue()) return Max;
11029       if (Value >= PromotedMin) return InRange;
11030       if (Value <= PromotedMax) return InRange;
11031       return InHole;
11032     }
11033 
11034     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
11035     case -1: return Less;
11036     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
11037     case 1:
11038       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
11039       case -1: return InRange;
11040       case 0: return Max;
11041       case 1: return Greater;
11042       }
11043     }
11044 
11045     llvm_unreachable("impossible compare result");
11046   }
11047 
11048   static llvm::Optional<StringRef>
11049   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
11050     if (Op == BO_Cmp) {
11051       ComparisonResult LTFlag = LT, GTFlag = GT;
11052       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
11053 
11054       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
11055       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
11056       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
11057       return llvm::None;
11058     }
11059 
11060     ComparisonResult TrueFlag, FalseFlag;
11061     if (Op == BO_EQ) {
11062       TrueFlag = EQ;
11063       FalseFlag = NE;
11064     } else if (Op == BO_NE) {
11065       TrueFlag = NE;
11066       FalseFlag = EQ;
11067     } else {
11068       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
11069         TrueFlag = LT;
11070         FalseFlag = GE;
11071       } else {
11072         TrueFlag = GT;
11073         FalseFlag = LE;
11074       }
11075       if (Op == BO_GE || Op == BO_LE)
11076         std::swap(TrueFlag, FalseFlag);
11077     }
11078     if (R & TrueFlag)
11079       return StringRef("true");
11080     if (R & FalseFlag)
11081       return StringRef("false");
11082     return llvm::None;
11083   }
11084 };
11085 }
11086 
11087 static bool HasEnumType(Expr *E) {
11088   // Strip off implicit integral promotions.
11089   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
11090     if (ICE->getCastKind() != CK_IntegralCast &&
11091         ICE->getCastKind() != CK_NoOp)
11092       break;
11093     E = ICE->getSubExpr();
11094   }
11095 
11096   return E->getType()->isEnumeralType();
11097 }
11098 
11099 static int classifyConstantValue(Expr *Constant) {
11100   // The values of this enumeration are used in the diagnostics
11101   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
11102   enum ConstantValueKind {
11103     Miscellaneous = 0,
11104     LiteralTrue,
11105     LiteralFalse
11106   };
11107   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
11108     return BL->getValue() ? ConstantValueKind::LiteralTrue
11109                           : ConstantValueKind::LiteralFalse;
11110   return ConstantValueKind::Miscellaneous;
11111 }
11112 
11113 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
11114                                         Expr *Constant, Expr *Other,
11115                                         const llvm::APSInt &Value,
11116                                         bool RhsConstant) {
11117   if (S.inTemplateInstantiation())
11118     return false;
11119 
11120   Expr *OriginalOther = Other;
11121 
11122   Constant = Constant->IgnoreParenImpCasts();
11123   Other = Other->IgnoreParenImpCasts();
11124 
11125   // Suppress warnings on tautological comparisons between values of the same
11126   // enumeration type. There are only two ways we could warn on this:
11127   //  - If the constant is outside the range of representable values of
11128   //    the enumeration. In such a case, we should warn about the cast
11129   //    to enumeration type, not about the comparison.
11130   //  - If the constant is the maximum / minimum in-range value. For an
11131   //    enumeratin type, such comparisons can be meaningful and useful.
11132   if (Constant->getType()->isEnumeralType() &&
11133       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
11134     return false;
11135 
11136   IntRange OtherValueRange = GetExprRange(
11137       S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false);
11138 
11139   QualType OtherT = Other->getType();
11140   if (const auto *AT = OtherT->getAs<AtomicType>())
11141     OtherT = AT->getValueType();
11142   IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
11143 
11144   // Special case for ObjC BOOL on targets where its a typedef for a signed char
11145   // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
11146   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
11147                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
11148                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
11149 
11150   // Whether we're treating Other as being a bool because of the form of
11151   // expression despite it having another type (typically 'int' in C).
11152   bool OtherIsBooleanDespiteType =
11153       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
11154   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
11155     OtherTypeRange = OtherValueRange = IntRange::forBoolType();
11156 
11157   // Check if all values in the range of possible values of this expression
11158   // lead to the same comparison outcome.
11159   PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(),
11160                                         Value.isUnsigned());
11161   auto Cmp = OtherPromotedValueRange.compare(Value);
11162   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
11163   if (!Result)
11164     return false;
11165 
11166   // Also consider the range determined by the type alone. This allows us to
11167   // classify the warning under the proper diagnostic group.
11168   bool TautologicalTypeCompare = false;
11169   {
11170     PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
11171                                          Value.isUnsigned());
11172     auto TypeCmp = OtherPromotedTypeRange.compare(Value);
11173     if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
11174                                                        RhsConstant)) {
11175       TautologicalTypeCompare = true;
11176       Cmp = TypeCmp;
11177       Result = TypeResult;
11178     }
11179   }
11180 
11181   // Don't warn if the non-constant operand actually always evaluates to the
11182   // same value.
11183   if (!TautologicalTypeCompare && OtherValueRange.Width == 0)
11184     return false;
11185 
11186   // Suppress the diagnostic for an in-range comparison if the constant comes
11187   // from a macro or enumerator. We don't want to diagnose
11188   //
11189   //   some_long_value <= INT_MAX
11190   //
11191   // when sizeof(int) == sizeof(long).
11192   bool InRange = Cmp & PromotedRange::InRangeFlag;
11193   if (InRange && IsEnumConstOrFromMacro(S, Constant))
11194     return false;
11195 
11196   // A comparison of an unsigned bit-field against 0 is really a type problem,
11197   // even though at the type level the bit-field might promote to 'signed int'.
11198   if (Other->refersToBitField() && InRange && Value == 0 &&
11199       Other->getType()->isUnsignedIntegerOrEnumerationType())
11200     TautologicalTypeCompare = true;
11201 
11202   // If this is a comparison to an enum constant, include that
11203   // constant in the diagnostic.
11204   const EnumConstantDecl *ED = nullptr;
11205   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
11206     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
11207 
11208   // Should be enough for uint128 (39 decimal digits)
11209   SmallString<64> PrettySourceValue;
11210   llvm::raw_svector_ostream OS(PrettySourceValue);
11211   if (ED) {
11212     OS << '\'' << *ED << "' (" << Value << ")";
11213   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
11214                Constant->IgnoreParenImpCasts())) {
11215     OS << (BL->getValue() ? "YES" : "NO");
11216   } else {
11217     OS << Value;
11218   }
11219 
11220   if (!TautologicalTypeCompare) {
11221     S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
11222         << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative
11223         << E->getOpcodeStr() << OS.str() << *Result
11224         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11225     return true;
11226   }
11227 
11228   if (IsObjCSignedCharBool) {
11229     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
11230                           S.PDiag(diag::warn_tautological_compare_objc_bool)
11231                               << OS.str() << *Result);
11232     return true;
11233   }
11234 
11235   // FIXME: We use a somewhat different formatting for the in-range cases and
11236   // cases involving boolean values for historical reasons. We should pick a
11237   // consistent way of presenting these diagnostics.
11238   if (!InRange || Other->isKnownToHaveBooleanValue()) {
11239 
11240     S.DiagRuntimeBehavior(
11241         E->getOperatorLoc(), E,
11242         S.PDiag(!InRange ? diag::warn_out_of_range_compare
11243                          : diag::warn_tautological_bool_compare)
11244             << OS.str() << classifyConstantValue(Constant) << OtherT
11245             << OtherIsBooleanDespiteType << *Result
11246             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
11247   } else {
11248     unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
11249                         ? (HasEnumType(OriginalOther)
11250                                ? diag::warn_unsigned_enum_always_true_comparison
11251                                : diag::warn_unsigned_always_true_comparison)
11252                         : diag::warn_tautological_constant_compare;
11253 
11254     S.Diag(E->getOperatorLoc(), Diag)
11255         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
11256         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11257   }
11258 
11259   return true;
11260 }
11261 
11262 /// Analyze the operands of the given comparison.  Implements the
11263 /// fallback case from AnalyzeComparison.
11264 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
11265   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11266   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11267 }
11268 
11269 /// Implements -Wsign-compare.
11270 ///
11271 /// \param E the binary operator to check for warnings
11272 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
11273   // The type the comparison is being performed in.
11274   QualType T = E->getLHS()->getType();
11275 
11276   // Only analyze comparison operators where both sides have been converted to
11277   // the same type.
11278   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
11279     return AnalyzeImpConvsInComparison(S, E);
11280 
11281   // Don't analyze value-dependent comparisons directly.
11282   if (E->isValueDependent())
11283     return AnalyzeImpConvsInComparison(S, E);
11284 
11285   Expr *LHS = E->getLHS();
11286   Expr *RHS = E->getRHS();
11287 
11288   if (T->isIntegralType(S.Context)) {
11289     Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context);
11290     Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context);
11291 
11292     // We don't care about expressions whose result is a constant.
11293     if (RHSValue && LHSValue)
11294       return AnalyzeImpConvsInComparison(S, E);
11295 
11296     // We only care about expressions where just one side is literal
11297     if ((bool)RHSValue ^ (bool)LHSValue) {
11298       // Is the constant on the RHS or LHS?
11299       const bool RhsConstant = (bool)RHSValue;
11300       Expr *Const = RhsConstant ? RHS : LHS;
11301       Expr *Other = RhsConstant ? LHS : RHS;
11302       const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
11303 
11304       // Check whether an integer constant comparison results in a value
11305       // of 'true' or 'false'.
11306       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
11307         return AnalyzeImpConvsInComparison(S, E);
11308     }
11309   }
11310 
11311   if (!T->hasUnsignedIntegerRepresentation()) {
11312     // We don't do anything special if this isn't an unsigned integral
11313     // comparison:  we're only interested in integral comparisons, and
11314     // signed comparisons only happen in cases we don't care to warn about.
11315     return AnalyzeImpConvsInComparison(S, E);
11316   }
11317 
11318   LHS = LHS->IgnoreParenImpCasts();
11319   RHS = RHS->IgnoreParenImpCasts();
11320 
11321   if (!S.getLangOpts().CPlusPlus) {
11322     // Avoid warning about comparison of integers with different signs when
11323     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
11324     // the type of `E`.
11325     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
11326       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11327     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
11328       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11329   }
11330 
11331   // Check to see if one of the (unmodified) operands is of different
11332   // signedness.
11333   Expr *signedOperand, *unsignedOperand;
11334   if (LHS->getType()->hasSignedIntegerRepresentation()) {
11335     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
11336            "unsigned comparison between two signed integer expressions?");
11337     signedOperand = LHS;
11338     unsignedOperand = RHS;
11339   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
11340     signedOperand = RHS;
11341     unsignedOperand = LHS;
11342   } else {
11343     return AnalyzeImpConvsInComparison(S, E);
11344   }
11345 
11346   // Otherwise, calculate the effective range of the signed operand.
11347   IntRange signedRange = GetExprRange(
11348       S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true);
11349 
11350   // Go ahead and analyze implicit conversions in the operands.  Note
11351   // that we skip the implicit conversions on both sides.
11352   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
11353   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
11354 
11355   // If the signed range is non-negative, -Wsign-compare won't fire.
11356   if (signedRange.NonNegative)
11357     return;
11358 
11359   // For (in)equality comparisons, if the unsigned operand is a
11360   // constant which cannot collide with a overflowed signed operand,
11361   // then reinterpreting the signed operand as unsigned will not
11362   // change the result of the comparison.
11363   if (E->isEqualityOp()) {
11364     unsigned comparisonWidth = S.Context.getIntWidth(T);
11365     IntRange unsignedRange =
11366         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(),
11367                      /*Approximate*/ true);
11368 
11369     // We should never be unable to prove that the unsigned operand is
11370     // non-negative.
11371     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
11372 
11373     if (unsignedRange.Width < comparisonWidth)
11374       return;
11375   }
11376 
11377   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
11378                         S.PDiag(diag::warn_mixed_sign_comparison)
11379                             << LHS->getType() << RHS->getType()
11380                             << LHS->getSourceRange() << RHS->getSourceRange());
11381 }
11382 
11383 /// Analyzes an attempt to assign the given value to a bitfield.
11384 ///
11385 /// Returns true if there was something fishy about the attempt.
11386 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
11387                                       SourceLocation InitLoc) {
11388   assert(Bitfield->isBitField());
11389   if (Bitfield->isInvalidDecl())
11390     return false;
11391 
11392   // White-list bool bitfields.
11393   QualType BitfieldType = Bitfield->getType();
11394   if (BitfieldType->isBooleanType())
11395      return false;
11396 
11397   if (BitfieldType->isEnumeralType()) {
11398     EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
11399     // If the underlying enum type was not explicitly specified as an unsigned
11400     // type and the enum contain only positive values, MSVC++ will cause an
11401     // inconsistency by storing this as a signed type.
11402     if (S.getLangOpts().CPlusPlus11 &&
11403         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
11404         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
11405         BitfieldEnumDecl->getNumNegativeBits() == 0) {
11406       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
11407           << BitfieldEnumDecl;
11408     }
11409   }
11410 
11411   if (Bitfield->getType()->isBooleanType())
11412     return false;
11413 
11414   // Ignore value- or type-dependent expressions.
11415   if (Bitfield->getBitWidth()->isValueDependent() ||
11416       Bitfield->getBitWidth()->isTypeDependent() ||
11417       Init->isValueDependent() ||
11418       Init->isTypeDependent())
11419     return false;
11420 
11421   Expr *OriginalInit = Init->IgnoreParenImpCasts();
11422   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
11423 
11424   Expr::EvalResult Result;
11425   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
11426                                    Expr::SE_AllowSideEffects)) {
11427     // The RHS is not constant.  If the RHS has an enum type, make sure the
11428     // bitfield is wide enough to hold all the values of the enum without
11429     // truncation.
11430     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
11431       EnumDecl *ED = EnumTy->getDecl();
11432       bool SignedBitfield = BitfieldType->isSignedIntegerType();
11433 
11434       // Enum types are implicitly signed on Windows, so check if there are any
11435       // negative enumerators to see if the enum was intended to be signed or
11436       // not.
11437       bool SignedEnum = ED->getNumNegativeBits() > 0;
11438 
11439       // Check for surprising sign changes when assigning enum values to a
11440       // bitfield of different signedness.  If the bitfield is signed and we
11441       // have exactly the right number of bits to store this unsigned enum,
11442       // suggest changing the enum to an unsigned type. This typically happens
11443       // on Windows where unfixed enums always use an underlying type of 'int'.
11444       unsigned DiagID = 0;
11445       if (SignedEnum && !SignedBitfield) {
11446         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
11447       } else if (SignedBitfield && !SignedEnum &&
11448                  ED->getNumPositiveBits() == FieldWidth) {
11449         DiagID = diag::warn_signed_bitfield_enum_conversion;
11450       }
11451 
11452       if (DiagID) {
11453         S.Diag(InitLoc, DiagID) << Bitfield << ED;
11454         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
11455         SourceRange TypeRange =
11456             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
11457         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
11458             << SignedEnum << TypeRange;
11459       }
11460 
11461       // Compute the required bitwidth. If the enum has negative values, we need
11462       // one more bit than the normal number of positive bits to represent the
11463       // sign bit.
11464       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
11465                                                   ED->getNumNegativeBits())
11466                                        : ED->getNumPositiveBits();
11467 
11468       // Check the bitwidth.
11469       if (BitsNeeded > FieldWidth) {
11470         Expr *WidthExpr = Bitfield->getBitWidth();
11471         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
11472             << Bitfield << ED;
11473         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
11474             << BitsNeeded << ED << WidthExpr->getSourceRange();
11475       }
11476     }
11477 
11478     return false;
11479   }
11480 
11481   llvm::APSInt Value = Result.Val.getInt();
11482 
11483   unsigned OriginalWidth = Value.getBitWidth();
11484 
11485   if (!Value.isSigned() || Value.isNegative())
11486     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
11487       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
11488         OriginalWidth = Value.getMinSignedBits();
11489 
11490   if (OriginalWidth <= FieldWidth)
11491     return false;
11492 
11493   // Compute the value which the bitfield will contain.
11494   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
11495   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
11496 
11497   // Check whether the stored value is equal to the original value.
11498   TruncatedValue = TruncatedValue.extend(OriginalWidth);
11499   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
11500     return false;
11501 
11502   // Special-case bitfields of width 1: booleans are naturally 0/1, and
11503   // therefore don't strictly fit into a signed bitfield of width 1.
11504   if (FieldWidth == 1 && Value == 1)
11505     return false;
11506 
11507   std::string PrettyValue = Value.toString(10);
11508   std::string PrettyTrunc = TruncatedValue.toString(10);
11509 
11510   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
11511     << PrettyValue << PrettyTrunc << OriginalInit->getType()
11512     << Init->getSourceRange();
11513 
11514   return true;
11515 }
11516 
11517 /// Analyze the given simple or compound assignment for warning-worthy
11518 /// operations.
11519 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
11520   // Just recurse on the LHS.
11521   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11522 
11523   // We want to recurse on the RHS as normal unless we're assigning to
11524   // a bitfield.
11525   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
11526     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
11527                                   E->getOperatorLoc())) {
11528       // Recurse, ignoring any implicit conversions on the RHS.
11529       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
11530                                         E->getOperatorLoc());
11531     }
11532   }
11533 
11534   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11535 
11536   // Diagnose implicitly sequentially-consistent atomic assignment.
11537   if (E->getLHS()->getType()->isAtomicType())
11538     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
11539 }
11540 
11541 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
11542 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
11543                             SourceLocation CContext, unsigned diag,
11544                             bool pruneControlFlow = false) {
11545   if (pruneControlFlow) {
11546     S.DiagRuntimeBehavior(E->getExprLoc(), E,
11547                           S.PDiag(diag)
11548                               << SourceType << T << E->getSourceRange()
11549                               << SourceRange(CContext));
11550     return;
11551   }
11552   S.Diag(E->getExprLoc(), diag)
11553     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
11554 }
11555 
11556 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
11557 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
11558                             SourceLocation CContext,
11559                             unsigned diag, bool pruneControlFlow = false) {
11560   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
11561 }
11562 
11563 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
11564   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
11565       S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
11566 }
11567 
11568 static void adornObjCBoolConversionDiagWithTernaryFixit(
11569     Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
11570   Expr *Ignored = SourceExpr->IgnoreImplicit();
11571   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
11572     Ignored = OVE->getSourceExpr();
11573   bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
11574                      isa<BinaryOperator>(Ignored) ||
11575                      isa<CXXOperatorCallExpr>(Ignored);
11576   SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
11577   if (NeedsParens)
11578     Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
11579             << FixItHint::CreateInsertion(EndLoc, ")");
11580   Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
11581 }
11582 
11583 /// Diagnose an implicit cast from a floating point value to an integer value.
11584 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
11585                                     SourceLocation CContext) {
11586   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
11587   const bool PruneWarnings = S.inTemplateInstantiation();
11588 
11589   Expr *InnerE = E->IgnoreParenImpCasts();
11590   // We also want to warn on, e.g., "int i = -1.234"
11591   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
11592     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
11593       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
11594 
11595   const bool IsLiteral =
11596       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
11597 
11598   llvm::APFloat Value(0.0);
11599   bool IsConstant =
11600     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
11601   if (!IsConstant) {
11602     if (isObjCSignedCharBool(S, T)) {
11603       return adornObjCBoolConversionDiagWithTernaryFixit(
11604           S, E,
11605           S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
11606               << E->getType());
11607     }
11608 
11609     return DiagnoseImpCast(S, E, T, CContext,
11610                            diag::warn_impcast_float_integer, PruneWarnings);
11611   }
11612 
11613   bool isExact = false;
11614 
11615   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
11616                             T->hasUnsignedIntegerRepresentation());
11617   llvm::APFloat::opStatus Result = Value.convertToInteger(
11618       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
11619 
11620   // FIXME: Force the precision of the source value down so we don't print
11621   // digits which are usually useless (we don't really care here if we
11622   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
11623   // would automatically print the shortest representation, but it's a bit
11624   // tricky to implement.
11625   SmallString<16> PrettySourceValue;
11626   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
11627   precision = (precision * 59 + 195) / 196;
11628   Value.toString(PrettySourceValue, precision);
11629 
11630   if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
11631     return adornObjCBoolConversionDiagWithTernaryFixit(
11632         S, E,
11633         S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
11634             << PrettySourceValue);
11635   }
11636 
11637   if (Result == llvm::APFloat::opOK && isExact) {
11638     if (IsLiteral) return;
11639     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
11640                            PruneWarnings);
11641   }
11642 
11643   // Conversion of a floating-point value to a non-bool integer where the
11644   // integral part cannot be represented by the integer type is undefined.
11645   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
11646     return DiagnoseImpCast(
11647         S, E, T, CContext,
11648         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
11649                   : diag::warn_impcast_float_to_integer_out_of_range,
11650         PruneWarnings);
11651 
11652   unsigned DiagID = 0;
11653   if (IsLiteral) {
11654     // Warn on floating point literal to integer.
11655     DiagID = diag::warn_impcast_literal_float_to_integer;
11656   } else if (IntegerValue == 0) {
11657     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
11658       return DiagnoseImpCast(S, E, T, CContext,
11659                              diag::warn_impcast_float_integer, PruneWarnings);
11660     }
11661     // Warn on non-zero to zero conversion.
11662     DiagID = diag::warn_impcast_float_to_integer_zero;
11663   } else {
11664     if (IntegerValue.isUnsigned()) {
11665       if (!IntegerValue.isMaxValue()) {
11666         return DiagnoseImpCast(S, E, T, CContext,
11667                                diag::warn_impcast_float_integer, PruneWarnings);
11668       }
11669     } else {  // IntegerValue.isSigned()
11670       if (!IntegerValue.isMaxSignedValue() &&
11671           !IntegerValue.isMinSignedValue()) {
11672         return DiagnoseImpCast(S, E, T, CContext,
11673                                diag::warn_impcast_float_integer, PruneWarnings);
11674       }
11675     }
11676     // Warn on evaluatable floating point expression to integer conversion.
11677     DiagID = diag::warn_impcast_float_to_integer;
11678   }
11679 
11680   SmallString<16> PrettyTargetValue;
11681   if (IsBool)
11682     PrettyTargetValue = Value.isZero() ? "false" : "true";
11683   else
11684     IntegerValue.toString(PrettyTargetValue);
11685 
11686   if (PruneWarnings) {
11687     S.DiagRuntimeBehavior(E->getExprLoc(), E,
11688                           S.PDiag(DiagID)
11689                               << E->getType() << T.getUnqualifiedType()
11690                               << PrettySourceValue << PrettyTargetValue
11691                               << E->getSourceRange() << SourceRange(CContext));
11692   } else {
11693     S.Diag(E->getExprLoc(), DiagID)
11694         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
11695         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
11696   }
11697 }
11698 
11699 /// Analyze the given compound assignment for the possible losing of
11700 /// floating-point precision.
11701 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
11702   assert(isa<CompoundAssignOperator>(E) &&
11703          "Must be compound assignment operation");
11704   // Recurse on the LHS and RHS in here
11705   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11706   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11707 
11708   if (E->getLHS()->getType()->isAtomicType())
11709     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
11710 
11711   // Now check the outermost expression
11712   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
11713   const auto *RBT = cast<CompoundAssignOperator>(E)
11714                         ->getComputationResultType()
11715                         ->getAs<BuiltinType>();
11716 
11717   // The below checks assume source is floating point.
11718   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
11719 
11720   // If source is floating point but target is an integer.
11721   if (ResultBT->isInteger())
11722     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
11723                            E->getExprLoc(), diag::warn_impcast_float_integer);
11724 
11725   if (!ResultBT->isFloatingPoint())
11726     return;
11727 
11728   // If both source and target are floating points, warn about losing precision.
11729   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
11730       QualType(ResultBT, 0), QualType(RBT, 0));
11731   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
11732     // warn about dropping FP rank.
11733     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
11734                     diag::warn_impcast_float_result_precision);
11735 }
11736 
11737 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
11738                                       IntRange Range) {
11739   if (!Range.Width) return "0";
11740 
11741   llvm::APSInt ValueInRange = Value;
11742   ValueInRange.setIsSigned(!Range.NonNegative);
11743   ValueInRange = ValueInRange.trunc(Range.Width);
11744   return ValueInRange.toString(10);
11745 }
11746 
11747 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
11748   if (!isa<ImplicitCastExpr>(Ex))
11749     return false;
11750 
11751   Expr *InnerE = Ex->IgnoreParenImpCasts();
11752   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
11753   const Type *Source =
11754     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
11755   if (Target->isDependentType())
11756     return false;
11757 
11758   const BuiltinType *FloatCandidateBT =
11759     dyn_cast<BuiltinType>(ToBool ? Source : Target);
11760   const Type *BoolCandidateType = ToBool ? Target : Source;
11761 
11762   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
11763           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
11764 }
11765 
11766 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
11767                                              SourceLocation CC) {
11768   unsigned NumArgs = TheCall->getNumArgs();
11769   for (unsigned i = 0; i < NumArgs; ++i) {
11770     Expr *CurrA = TheCall->getArg(i);
11771     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
11772       continue;
11773 
11774     bool IsSwapped = ((i > 0) &&
11775         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
11776     IsSwapped |= ((i < (NumArgs - 1)) &&
11777         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
11778     if (IsSwapped) {
11779       // Warn on this floating-point to bool conversion.
11780       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
11781                       CurrA->getType(), CC,
11782                       diag::warn_impcast_floating_point_to_bool);
11783     }
11784   }
11785 }
11786 
11787 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
11788                                    SourceLocation CC) {
11789   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
11790                         E->getExprLoc()))
11791     return;
11792 
11793   // Don't warn on functions which have return type nullptr_t.
11794   if (isa<CallExpr>(E))
11795     return;
11796 
11797   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
11798   const Expr::NullPointerConstantKind NullKind =
11799       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
11800   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
11801     return;
11802 
11803   // Return if target type is a safe conversion.
11804   if (T->isAnyPointerType() || T->isBlockPointerType() ||
11805       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
11806     return;
11807 
11808   SourceLocation Loc = E->getSourceRange().getBegin();
11809 
11810   // Venture through the macro stacks to get to the source of macro arguments.
11811   // The new location is a better location than the complete location that was
11812   // passed in.
11813   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
11814   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
11815 
11816   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
11817   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
11818     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
11819         Loc, S.SourceMgr, S.getLangOpts());
11820     if (MacroName == "NULL")
11821       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
11822   }
11823 
11824   // Only warn if the null and context location are in the same macro expansion.
11825   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
11826     return;
11827 
11828   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
11829       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
11830       << FixItHint::CreateReplacement(Loc,
11831                                       S.getFixItZeroLiteralForType(T, Loc));
11832 }
11833 
11834 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
11835                                   ObjCArrayLiteral *ArrayLiteral);
11836 
11837 static void
11838 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
11839                            ObjCDictionaryLiteral *DictionaryLiteral);
11840 
11841 /// Check a single element within a collection literal against the
11842 /// target element type.
11843 static void checkObjCCollectionLiteralElement(Sema &S,
11844                                               QualType TargetElementType,
11845                                               Expr *Element,
11846                                               unsigned ElementKind) {
11847   // Skip a bitcast to 'id' or qualified 'id'.
11848   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
11849     if (ICE->getCastKind() == CK_BitCast &&
11850         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
11851       Element = ICE->getSubExpr();
11852   }
11853 
11854   QualType ElementType = Element->getType();
11855   ExprResult ElementResult(Element);
11856   if (ElementType->getAs<ObjCObjectPointerType>() &&
11857       S.CheckSingleAssignmentConstraints(TargetElementType,
11858                                          ElementResult,
11859                                          false, false)
11860         != Sema::Compatible) {
11861     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
11862         << ElementType << ElementKind << TargetElementType
11863         << Element->getSourceRange();
11864   }
11865 
11866   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
11867     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
11868   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
11869     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
11870 }
11871 
11872 /// Check an Objective-C array literal being converted to the given
11873 /// target type.
11874 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
11875                                   ObjCArrayLiteral *ArrayLiteral) {
11876   if (!S.NSArrayDecl)
11877     return;
11878 
11879   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
11880   if (!TargetObjCPtr)
11881     return;
11882 
11883   if (TargetObjCPtr->isUnspecialized() ||
11884       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
11885         != S.NSArrayDecl->getCanonicalDecl())
11886     return;
11887 
11888   auto TypeArgs = TargetObjCPtr->getTypeArgs();
11889   if (TypeArgs.size() != 1)
11890     return;
11891 
11892   QualType TargetElementType = TypeArgs[0];
11893   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
11894     checkObjCCollectionLiteralElement(S, TargetElementType,
11895                                       ArrayLiteral->getElement(I),
11896                                       0);
11897   }
11898 }
11899 
11900 /// Check an Objective-C dictionary literal being converted to the given
11901 /// target type.
11902 static void
11903 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
11904                            ObjCDictionaryLiteral *DictionaryLiteral) {
11905   if (!S.NSDictionaryDecl)
11906     return;
11907 
11908   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
11909   if (!TargetObjCPtr)
11910     return;
11911 
11912   if (TargetObjCPtr->isUnspecialized() ||
11913       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
11914         != S.NSDictionaryDecl->getCanonicalDecl())
11915     return;
11916 
11917   auto TypeArgs = TargetObjCPtr->getTypeArgs();
11918   if (TypeArgs.size() != 2)
11919     return;
11920 
11921   QualType TargetKeyType = TypeArgs[0];
11922   QualType TargetObjectType = TypeArgs[1];
11923   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
11924     auto Element = DictionaryLiteral->getKeyValueElement(I);
11925     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
11926     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
11927   }
11928 }
11929 
11930 // Helper function to filter out cases for constant width constant conversion.
11931 // Don't warn on char array initialization or for non-decimal values.
11932 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
11933                                           SourceLocation CC) {
11934   // If initializing from a constant, and the constant starts with '0',
11935   // then it is a binary, octal, or hexadecimal.  Allow these constants
11936   // to fill all the bits, even if there is a sign change.
11937   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
11938     const char FirstLiteralCharacter =
11939         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
11940     if (FirstLiteralCharacter == '0')
11941       return false;
11942   }
11943 
11944   // If the CC location points to a '{', and the type is char, then assume
11945   // assume it is an array initialization.
11946   if (CC.isValid() && T->isCharType()) {
11947     const char FirstContextCharacter =
11948         S.getSourceManager().getCharacterData(CC)[0];
11949     if (FirstContextCharacter == '{')
11950       return false;
11951   }
11952 
11953   return true;
11954 }
11955 
11956 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
11957   const auto *IL = dyn_cast<IntegerLiteral>(E);
11958   if (!IL) {
11959     if (auto *UO = dyn_cast<UnaryOperator>(E)) {
11960       if (UO->getOpcode() == UO_Minus)
11961         return dyn_cast<IntegerLiteral>(UO->getSubExpr());
11962     }
11963   }
11964 
11965   return IL;
11966 }
11967 
11968 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
11969   E = E->IgnoreParenImpCasts();
11970   SourceLocation ExprLoc = E->getExprLoc();
11971 
11972   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11973     BinaryOperator::Opcode Opc = BO->getOpcode();
11974     Expr::EvalResult Result;
11975     // Do not diagnose unsigned shifts.
11976     if (Opc == BO_Shl) {
11977       const auto *LHS = getIntegerLiteral(BO->getLHS());
11978       const auto *RHS = getIntegerLiteral(BO->getRHS());
11979       if (LHS && LHS->getValue() == 0)
11980         S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
11981       else if (!E->isValueDependent() && LHS && RHS &&
11982                RHS->getValue().isNonNegative() &&
11983                E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
11984         S.Diag(ExprLoc, diag::warn_left_shift_always)
11985             << (Result.Val.getInt() != 0);
11986       else if (E->getType()->isSignedIntegerType())
11987         S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
11988     }
11989   }
11990 
11991   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11992     const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
11993     const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
11994     if (!LHS || !RHS)
11995       return;
11996     if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
11997         (RHS->getValue() == 0 || RHS->getValue() == 1))
11998       // Do not diagnose common idioms.
11999       return;
12000     if (LHS->getValue() != 0 && RHS->getValue() != 0)
12001       S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
12002   }
12003 }
12004 
12005 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
12006                                     SourceLocation CC,
12007                                     bool *ICContext = nullptr,
12008                                     bool IsListInit = false) {
12009   if (E->isTypeDependent() || E->isValueDependent()) return;
12010 
12011   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
12012   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
12013   if (Source == Target) return;
12014   if (Target->isDependentType()) return;
12015 
12016   // If the conversion context location is invalid don't complain. We also
12017   // don't want to emit a warning if the issue occurs from the expansion of
12018   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
12019   // delay this check as long as possible. Once we detect we are in that
12020   // scenario, we just return.
12021   if (CC.isInvalid())
12022     return;
12023 
12024   if (Source->isAtomicType())
12025     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
12026 
12027   // Diagnose implicit casts to bool.
12028   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
12029     if (isa<StringLiteral>(E))
12030       // Warn on string literal to bool.  Checks for string literals in logical
12031       // and expressions, for instance, assert(0 && "error here"), are
12032       // prevented by a check in AnalyzeImplicitConversions().
12033       return DiagnoseImpCast(S, E, T, CC,
12034                              diag::warn_impcast_string_literal_to_bool);
12035     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
12036         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
12037       // This covers the literal expressions that evaluate to Objective-C
12038       // objects.
12039       return DiagnoseImpCast(S, E, T, CC,
12040                              diag::warn_impcast_objective_c_literal_to_bool);
12041     }
12042     if (Source->isPointerType() || Source->canDecayToPointerType()) {
12043       // Warn on pointer to bool conversion that is always true.
12044       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
12045                                      SourceRange(CC));
12046     }
12047   }
12048 
12049   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
12050   // is a typedef for signed char (macOS), then that constant value has to be 1
12051   // or 0.
12052   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
12053     Expr::EvalResult Result;
12054     if (E->EvaluateAsInt(Result, S.getASTContext(),
12055                          Expr::SE_AllowSideEffects)) {
12056       if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
12057         adornObjCBoolConversionDiagWithTernaryFixit(
12058             S, E,
12059             S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
12060                 << Result.Val.getInt().toString(10));
12061       }
12062       return;
12063     }
12064   }
12065 
12066   // Check implicit casts from Objective-C collection literals to specialized
12067   // collection types, e.g., NSArray<NSString *> *.
12068   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
12069     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
12070   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
12071     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
12072 
12073   // Strip vector types.
12074   if (const auto *SourceVT = dyn_cast<VectorType>(Source)) {
12075     if (Target->isVLSTBuiltinType()) {
12076       auto SourceVectorKind = SourceVT->getVectorKind();
12077       if (SourceVectorKind == VectorType::SveFixedLengthDataVector ||
12078           SourceVectorKind == VectorType::SveFixedLengthPredicateVector ||
12079           (SourceVectorKind == VectorType::GenericVector &&
12080            S.Context.getTypeSize(Source) == S.getLangOpts().ArmSveVectorBits))
12081         return;
12082     }
12083 
12084     if (!isa<VectorType>(Target)) {
12085       if (S.SourceMgr.isInSystemMacro(CC))
12086         return;
12087       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
12088     }
12089 
12090     // If the vector cast is cast between two vectors of the same size, it is
12091     // a bitcast, not a conversion.
12092     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
12093       return;
12094 
12095     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
12096     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
12097   }
12098   if (auto VecTy = dyn_cast<VectorType>(Target))
12099     Target = VecTy->getElementType().getTypePtr();
12100 
12101   // Strip complex types.
12102   if (isa<ComplexType>(Source)) {
12103     if (!isa<ComplexType>(Target)) {
12104       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
12105         return;
12106 
12107       return DiagnoseImpCast(S, E, T, CC,
12108                              S.getLangOpts().CPlusPlus
12109                                  ? diag::err_impcast_complex_scalar
12110                                  : diag::warn_impcast_complex_scalar);
12111     }
12112 
12113     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
12114     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
12115   }
12116 
12117   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
12118   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
12119 
12120   // If the source is floating point...
12121   if (SourceBT && SourceBT->isFloatingPoint()) {
12122     // ...and the target is floating point...
12123     if (TargetBT && TargetBT->isFloatingPoint()) {
12124       // ...then warn if we're dropping FP rank.
12125 
12126       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12127           QualType(SourceBT, 0), QualType(TargetBT, 0));
12128       if (Order > 0) {
12129         // Don't warn about float constants that are precisely
12130         // representable in the target type.
12131         Expr::EvalResult result;
12132         if (E->EvaluateAsRValue(result, S.Context)) {
12133           // Value might be a float, a float vector, or a float complex.
12134           if (IsSameFloatAfterCast(result.Val,
12135                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
12136                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
12137             return;
12138         }
12139 
12140         if (S.SourceMgr.isInSystemMacro(CC))
12141           return;
12142 
12143         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
12144       }
12145       // ... or possibly if we're increasing rank, too
12146       else if (Order < 0) {
12147         if (S.SourceMgr.isInSystemMacro(CC))
12148           return;
12149 
12150         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
12151       }
12152       return;
12153     }
12154 
12155     // If the target is integral, always warn.
12156     if (TargetBT && TargetBT->isInteger()) {
12157       if (S.SourceMgr.isInSystemMacro(CC))
12158         return;
12159 
12160       DiagnoseFloatingImpCast(S, E, T, CC);
12161     }
12162 
12163     // Detect the case where a call result is converted from floating-point to
12164     // to bool, and the final argument to the call is converted from bool, to
12165     // discover this typo:
12166     //
12167     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
12168     //
12169     // FIXME: This is an incredibly special case; is there some more general
12170     // way to detect this class of misplaced-parentheses bug?
12171     if (Target->isBooleanType() && isa<CallExpr>(E)) {
12172       // Check last argument of function call to see if it is an
12173       // implicit cast from a type matching the type the result
12174       // is being cast to.
12175       CallExpr *CEx = cast<CallExpr>(E);
12176       if (unsigned NumArgs = CEx->getNumArgs()) {
12177         Expr *LastA = CEx->getArg(NumArgs - 1);
12178         Expr *InnerE = LastA->IgnoreParenImpCasts();
12179         if (isa<ImplicitCastExpr>(LastA) &&
12180             InnerE->getType()->isBooleanType()) {
12181           // Warn on this floating-point to bool conversion
12182           DiagnoseImpCast(S, E, T, CC,
12183                           diag::warn_impcast_floating_point_to_bool);
12184         }
12185       }
12186     }
12187     return;
12188   }
12189 
12190   // Valid casts involving fixed point types should be accounted for here.
12191   if (Source->isFixedPointType()) {
12192     if (Target->isUnsaturatedFixedPointType()) {
12193       Expr::EvalResult Result;
12194       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
12195                                   S.isConstantEvaluated())) {
12196         llvm::APFixedPoint Value = Result.Val.getFixedPoint();
12197         llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
12198         llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T);
12199         if (Value > MaxVal || Value < MinVal) {
12200           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12201                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12202                                     << Value.toString() << T
12203                                     << E->getSourceRange()
12204                                     << clang::SourceRange(CC));
12205           return;
12206         }
12207       }
12208     } else if (Target->isIntegerType()) {
12209       Expr::EvalResult Result;
12210       if (!S.isConstantEvaluated() &&
12211           E->EvaluateAsFixedPoint(Result, S.Context,
12212                                   Expr::SE_AllowSideEffects)) {
12213         llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
12214 
12215         bool Overflowed;
12216         llvm::APSInt IntResult = FXResult.convertToInt(
12217             S.Context.getIntWidth(T),
12218             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
12219 
12220         if (Overflowed) {
12221           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12222                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12223                                     << FXResult.toString() << T
12224                                     << E->getSourceRange()
12225                                     << clang::SourceRange(CC));
12226           return;
12227         }
12228       }
12229     }
12230   } else if (Target->isUnsaturatedFixedPointType()) {
12231     if (Source->isIntegerType()) {
12232       Expr::EvalResult Result;
12233       if (!S.isConstantEvaluated() &&
12234           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
12235         llvm::APSInt Value = Result.Val.getInt();
12236 
12237         bool Overflowed;
12238         llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
12239             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
12240 
12241         if (Overflowed) {
12242           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12243                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12244                                     << Value.toString(/*Radix=*/10) << T
12245                                     << E->getSourceRange()
12246                                     << clang::SourceRange(CC));
12247           return;
12248         }
12249       }
12250     }
12251   }
12252 
12253   // If we are casting an integer type to a floating point type without
12254   // initialization-list syntax, we might lose accuracy if the floating
12255   // point type has a narrower significand than the integer type.
12256   if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
12257       TargetBT->isFloatingType() && !IsListInit) {
12258     // Determine the number of precision bits in the source integer type.
12259     IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(),
12260                                         /*Approximate*/ true);
12261     unsigned int SourcePrecision = SourceRange.Width;
12262 
12263     // Determine the number of precision bits in the
12264     // target floating point type.
12265     unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
12266         S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12267 
12268     if (SourcePrecision > 0 && TargetPrecision > 0 &&
12269         SourcePrecision > TargetPrecision) {
12270 
12271       if (Optional<llvm::APSInt> SourceInt =
12272               E->getIntegerConstantExpr(S.Context)) {
12273         // If the source integer is a constant, convert it to the target
12274         // floating point type. Issue a warning if the value changes
12275         // during the whole conversion.
12276         llvm::APFloat TargetFloatValue(
12277             S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12278         llvm::APFloat::opStatus ConversionStatus =
12279             TargetFloatValue.convertFromAPInt(
12280                 *SourceInt, SourceBT->isSignedInteger(),
12281                 llvm::APFloat::rmNearestTiesToEven);
12282 
12283         if (ConversionStatus != llvm::APFloat::opOK) {
12284           std::string PrettySourceValue = SourceInt->toString(10);
12285           SmallString<32> PrettyTargetValue;
12286           TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
12287 
12288           S.DiagRuntimeBehavior(
12289               E->getExprLoc(), E,
12290               S.PDiag(diag::warn_impcast_integer_float_precision_constant)
12291                   << PrettySourceValue << PrettyTargetValue << E->getType() << T
12292                   << E->getSourceRange() << clang::SourceRange(CC));
12293         }
12294       } else {
12295         // Otherwise, the implicit conversion may lose precision.
12296         DiagnoseImpCast(S, E, T, CC,
12297                         diag::warn_impcast_integer_float_precision);
12298       }
12299     }
12300   }
12301 
12302   DiagnoseNullConversion(S, E, T, CC);
12303 
12304   S.DiscardMisalignedMemberAddress(Target, E);
12305 
12306   if (Target->isBooleanType())
12307     DiagnoseIntInBoolContext(S, E);
12308 
12309   if (!Source->isIntegerType() || !Target->isIntegerType())
12310     return;
12311 
12312   // TODO: remove this early return once the false positives for constant->bool
12313   // in templates, macros, etc, are reduced or removed.
12314   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
12315     return;
12316 
12317   if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
12318       !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
12319     return adornObjCBoolConversionDiagWithTernaryFixit(
12320         S, E,
12321         S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
12322             << E->getType());
12323   }
12324 
12325   IntRange SourceTypeRange =
12326       IntRange::forTargetOfCanonicalType(S.Context, Source);
12327   IntRange LikelySourceRange =
12328       GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true);
12329   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
12330 
12331   if (LikelySourceRange.Width > TargetRange.Width) {
12332     // If the source is a constant, use a default-on diagnostic.
12333     // TODO: this should happen for bitfield stores, too.
12334     Expr::EvalResult Result;
12335     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
12336                          S.isConstantEvaluated())) {
12337       llvm::APSInt Value(32);
12338       Value = Result.Val.getInt();
12339 
12340       if (S.SourceMgr.isInSystemMacro(CC))
12341         return;
12342 
12343       std::string PrettySourceValue = Value.toString(10);
12344       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
12345 
12346       S.DiagRuntimeBehavior(
12347           E->getExprLoc(), E,
12348           S.PDiag(diag::warn_impcast_integer_precision_constant)
12349               << PrettySourceValue << PrettyTargetValue << E->getType() << T
12350               << E->getSourceRange() << SourceRange(CC));
12351       return;
12352     }
12353 
12354     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
12355     if (S.SourceMgr.isInSystemMacro(CC))
12356       return;
12357 
12358     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
12359       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
12360                              /* pruneControlFlow */ true);
12361     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
12362   }
12363 
12364   if (TargetRange.Width > SourceTypeRange.Width) {
12365     if (auto *UO = dyn_cast<UnaryOperator>(E))
12366       if (UO->getOpcode() == UO_Minus)
12367         if (Source->isUnsignedIntegerType()) {
12368           if (Target->isUnsignedIntegerType())
12369             return DiagnoseImpCast(S, E, T, CC,
12370                                    diag::warn_impcast_high_order_zero_bits);
12371           if (Target->isSignedIntegerType())
12372             return DiagnoseImpCast(S, E, T, CC,
12373                                    diag::warn_impcast_nonnegative_result);
12374         }
12375   }
12376 
12377   if (TargetRange.Width == LikelySourceRange.Width &&
12378       !TargetRange.NonNegative && LikelySourceRange.NonNegative &&
12379       Source->isSignedIntegerType()) {
12380     // Warn when doing a signed to signed conversion, warn if the positive
12381     // source value is exactly the width of the target type, which will
12382     // cause a negative value to be stored.
12383 
12384     Expr::EvalResult Result;
12385     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
12386         !S.SourceMgr.isInSystemMacro(CC)) {
12387       llvm::APSInt Value = Result.Val.getInt();
12388       if (isSameWidthConstantConversion(S, E, T, CC)) {
12389         std::string PrettySourceValue = Value.toString(10);
12390         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
12391 
12392         S.DiagRuntimeBehavior(
12393             E->getExprLoc(), E,
12394             S.PDiag(diag::warn_impcast_integer_precision_constant)
12395                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
12396                 << E->getSourceRange() << SourceRange(CC));
12397         return;
12398       }
12399     }
12400 
12401     // Fall through for non-constants to give a sign conversion warning.
12402   }
12403 
12404   if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) ||
12405       (!TargetRange.NonNegative && LikelySourceRange.NonNegative &&
12406        LikelySourceRange.Width == TargetRange.Width)) {
12407     if (S.SourceMgr.isInSystemMacro(CC))
12408       return;
12409 
12410     unsigned DiagID = diag::warn_impcast_integer_sign;
12411 
12412     // Traditionally, gcc has warned about this under -Wsign-compare.
12413     // We also want to warn about it in -Wconversion.
12414     // So if -Wconversion is off, use a completely identical diagnostic
12415     // in the sign-compare group.
12416     // The conditional-checking code will
12417     if (ICContext) {
12418       DiagID = diag::warn_impcast_integer_sign_conditional;
12419       *ICContext = true;
12420     }
12421 
12422     return DiagnoseImpCast(S, E, T, CC, DiagID);
12423   }
12424 
12425   // Diagnose conversions between different enumeration types.
12426   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
12427   // type, to give us better diagnostics.
12428   QualType SourceType = E->getType();
12429   if (!S.getLangOpts().CPlusPlus) {
12430     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12431       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
12432         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
12433         SourceType = S.Context.getTypeDeclType(Enum);
12434         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
12435       }
12436   }
12437 
12438   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
12439     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
12440       if (SourceEnum->getDecl()->hasNameForLinkage() &&
12441           TargetEnum->getDecl()->hasNameForLinkage() &&
12442           SourceEnum != TargetEnum) {
12443         if (S.SourceMgr.isInSystemMacro(CC))
12444           return;
12445 
12446         return DiagnoseImpCast(S, E, SourceType, T, CC,
12447                                diag::warn_impcast_different_enum_types);
12448       }
12449 }
12450 
12451 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
12452                                      SourceLocation CC, QualType T);
12453 
12454 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
12455                                     SourceLocation CC, bool &ICContext) {
12456   E = E->IgnoreParenImpCasts();
12457 
12458   if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
12459     return CheckConditionalOperator(S, CO, CC, T);
12460 
12461   AnalyzeImplicitConversions(S, E, CC);
12462   if (E->getType() != T)
12463     return CheckImplicitConversion(S, E, T, CC, &ICContext);
12464 }
12465 
12466 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
12467                                      SourceLocation CC, QualType T) {
12468   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
12469 
12470   Expr *TrueExpr = E->getTrueExpr();
12471   if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
12472     TrueExpr = BCO->getCommon();
12473 
12474   bool Suspicious = false;
12475   CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
12476   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
12477 
12478   if (T->isBooleanType())
12479     DiagnoseIntInBoolContext(S, E);
12480 
12481   // If -Wconversion would have warned about either of the candidates
12482   // for a signedness conversion to the context type...
12483   if (!Suspicious) return;
12484 
12485   // ...but it's currently ignored...
12486   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
12487     return;
12488 
12489   // ...then check whether it would have warned about either of the
12490   // candidates for a signedness conversion to the condition type.
12491   if (E->getType() == T) return;
12492 
12493   Suspicious = false;
12494   CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(),
12495                           E->getType(), CC, &Suspicious);
12496   if (!Suspicious)
12497     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
12498                             E->getType(), CC, &Suspicious);
12499 }
12500 
12501 /// Check conversion of given expression to boolean.
12502 /// Input argument E is a logical expression.
12503 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
12504   if (S.getLangOpts().Bool)
12505     return;
12506   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
12507     return;
12508   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
12509 }
12510 
12511 namespace {
12512 struct AnalyzeImplicitConversionsWorkItem {
12513   Expr *E;
12514   SourceLocation CC;
12515   bool IsListInit;
12516 };
12517 }
12518 
12519 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
12520 /// that should be visited are added to WorkList.
12521 static void AnalyzeImplicitConversions(
12522     Sema &S, AnalyzeImplicitConversionsWorkItem Item,
12523     llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
12524   Expr *OrigE = Item.E;
12525   SourceLocation CC = Item.CC;
12526 
12527   QualType T = OrigE->getType();
12528   Expr *E = OrigE->IgnoreParenImpCasts();
12529 
12530   // Propagate whether we are in a C++ list initialization expression.
12531   // If so, we do not issue warnings for implicit int-float conversion
12532   // precision loss, because C++11 narrowing already handles it.
12533   bool IsListInit = Item.IsListInit ||
12534                     (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
12535 
12536   if (E->isTypeDependent() || E->isValueDependent())
12537     return;
12538 
12539   Expr *SourceExpr = E;
12540   // Examine, but don't traverse into the source expression of an
12541   // OpaqueValueExpr, since it may have multiple parents and we don't want to
12542   // emit duplicate diagnostics. Its fine to examine the form or attempt to
12543   // evaluate it in the context of checking the specific conversion to T though.
12544   if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
12545     if (auto *Src = OVE->getSourceExpr())
12546       SourceExpr = Src;
12547 
12548   if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
12549     if (UO->getOpcode() == UO_Not &&
12550         UO->getSubExpr()->isKnownToHaveBooleanValue())
12551       S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
12552           << OrigE->getSourceRange() << T->isBooleanType()
12553           << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
12554 
12555   // For conditional operators, we analyze the arguments as if they
12556   // were being fed directly into the output.
12557   if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
12558     CheckConditionalOperator(S, CO, CC, T);
12559     return;
12560   }
12561 
12562   // Check implicit argument conversions for function calls.
12563   if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
12564     CheckImplicitArgumentConversions(S, Call, CC);
12565 
12566   // Go ahead and check any implicit conversions we might have skipped.
12567   // The non-canonical typecheck is just an optimization;
12568   // CheckImplicitConversion will filter out dead implicit conversions.
12569   if (SourceExpr->getType() != T)
12570     CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit);
12571 
12572   // Now continue drilling into this expression.
12573 
12574   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
12575     // The bound subexpressions in a PseudoObjectExpr are not reachable
12576     // as transitive children.
12577     // FIXME: Use a more uniform representation for this.
12578     for (auto *SE : POE->semantics())
12579       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
12580         WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
12581   }
12582 
12583   // Skip past explicit casts.
12584   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
12585     E = CE->getSubExpr()->IgnoreParenImpCasts();
12586     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
12587       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12588     WorkList.push_back({E, CC, IsListInit});
12589     return;
12590   }
12591 
12592   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12593     // Do a somewhat different check with comparison operators.
12594     if (BO->isComparisonOp())
12595       return AnalyzeComparison(S, BO);
12596 
12597     // And with simple assignments.
12598     if (BO->getOpcode() == BO_Assign)
12599       return AnalyzeAssignment(S, BO);
12600     // And with compound assignments.
12601     if (BO->isAssignmentOp())
12602       return AnalyzeCompoundAssignment(S, BO);
12603   }
12604 
12605   // These break the otherwise-useful invariant below.  Fortunately,
12606   // we don't really need to recurse into them, because any internal
12607   // expressions should have been analyzed already when they were
12608   // built into statements.
12609   if (isa<StmtExpr>(E)) return;
12610 
12611   // Don't descend into unevaluated contexts.
12612   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
12613 
12614   // Now just recurse over the expression's children.
12615   CC = E->getExprLoc();
12616   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
12617   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
12618   for (Stmt *SubStmt : E->children()) {
12619     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
12620     if (!ChildExpr)
12621       continue;
12622 
12623     if (IsLogicalAndOperator &&
12624         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
12625       // Ignore checking string literals that are in logical and operators.
12626       // This is a common pattern for asserts.
12627       continue;
12628     WorkList.push_back({ChildExpr, CC, IsListInit});
12629   }
12630 
12631   if (BO && BO->isLogicalOp()) {
12632     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
12633     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
12634       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
12635 
12636     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
12637     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
12638       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
12639   }
12640 
12641   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
12642     if (U->getOpcode() == UO_LNot) {
12643       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
12644     } else if (U->getOpcode() != UO_AddrOf) {
12645       if (U->getSubExpr()->getType()->isAtomicType())
12646         S.Diag(U->getSubExpr()->getBeginLoc(),
12647                diag::warn_atomic_implicit_seq_cst);
12648     }
12649   }
12650 }
12651 
12652 /// AnalyzeImplicitConversions - Find and report any interesting
12653 /// implicit conversions in the given expression.  There are a couple
12654 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
12655 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
12656                                        bool IsListInit/*= false*/) {
12657   llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
12658   WorkList.push_back({OrigE, CC, IsListInit});
12659   while (!WorkList.empty())
12660     AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
12661 }
12662 
12663 /// Diagnose integer type and any valid implicit conversion to it.
12664 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
12665   // Taking into account implicit conversions,
12666   // allow any integer.
12667   if (!E->getType()->isIntegerType()) {
12668     S.Diag(E->getBeginLoc(),
12669            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
12670     return true;
12671   }
12672   // Potentially emit standard warnings for implicit conversions if enabled
12673   // using -Wconversion.
12674   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
12675   return false;
12676 }
12677 
12678 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
12679 // Returns true when emitting a warning about taking the address of a reference.
12680 static bool CheckForReference(Sema &SemaRef, const Expr *E,
12681                               const PartialDiagnostic &PD) {
12682   E = E->IgnoreParenImpCasts();
12683 
12684   const FunctionDecl *FD = nullptr;
12685 
12686   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12687     if (!DRE->getDecl()->getType()->isReferenceType())
12688       return false;
12689   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
12690     if (!M->getMemberDecl()->getType()->isReferenceType())
12691       return false;
12692   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
12693     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
12694       return false;
12695     FD = Call->getDirectCallee();
12696   } else {
12697     return false;
12698   }
12699 
12700   SemaRef.Diag(E->getExprLoc(), PD);
12701 
12702   // If possible, point to location of function.
12703   if (FD) {
12704     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
12705   }
12706 
12707   return true;
12708 }
12709 
12710 // Returns true if the SourceLocation is expanded from any macro body.
12711 // Returns false if the SourceLocation is invalid, is from not in a macro
12712 // expansion, or is from expanded from a top-level macro argument.
12713 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
12714   if (Loc.isInvalid())
12715     return false;
12716 
12717   while (Loc.isMacroID()) {
12718     if (SM.isMacroBodyExpansion(Loc))
12719       return true;
12720     Loc = SM.getImmediateMacroCallerLoc(Loc);
12721   }
12722 
12723   return false;
12724 }
12725 
12726 /// Diagnose pointers that are always non-null.
12727 /// \param E the expression containing the pointer
12728 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
12729 /// compared to a null pointer
12730 /// \param IsEqual True when the comparison is equal to a null pointer
12731 /// \param Range Extra SourceRange to highlight in the diagnostic
12732 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
12733                                         Expr::NullPointerConstantKind NullKind,
12734                                         bool IsEqual, SourceRange Range) {
12735   if (!E)
12736     return;
12737 
12738   // Don't warn inside macros.
12739   if (E->getExprLoc().isMacroID()) {
12740     const SourceManager &SM = getSourceManager();
12741     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
12742         IsInAnyMacroBody(SM, Range.getBegin()))
12743       return;
12744   }
12745   E = E->IgnoreImpCasts();
12746 
12747   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
12748 
12749   if (isa<CXXThisExpr>(E)) {
12750     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
12751                                 : diag::warn_this_bool_conversion;
12752     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
12753     return;
12754   }
12755 
12756   bool IsAddressOf = false;
12757 
12758   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
12759     if (UO->getOpcode() != UO_AddrOf)
12760       return;
12761     IsAddressOf = true;
12762     E = UO->getSubExpr();
12763   }
12764 
12765   if (IsAddressOf) {
12766     unsigned DiagID = IsCompare
12767                           ? diag::warn_address_of_reference_null_compare
12768                           : diag::warn_address_of_reference_bool_conversion;
12769     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
12770                                          << IsEqual;
12771     if (CheckForReference(*this, E, PD)) {
12772       return;
12773     }
12774   }
12775 
12776   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
12777     bool IsParam = isa<NonNullAttr>(NonnullAttr);
12778     std::string Str;
12779     llvm::raw_string_ostream S(Str);
12780     E->printPretty(S, nullptr, getPrintingPolicy());
12781     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
12782                                 : diag::warn_cast_nonnull_to_bool;
12783     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
12784       << E->getSourceRange() << Range << IsEqual;
12785     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
12786   };
12787 
12788   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
12789   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
12790     if (auto *Callee = Call->getDirectCallee()) {
12791       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
12792         ComplainAboutNonnullParamOrCall(A);
12793         return;
12794       }
12795     }
12796   }
12797 
12798   // Expect to find a single Decl.  Skip anything more complicated.
12799   ValueDecl *D = nullptr;
12800   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
12801     D = R->getDecl();
12802   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
12803     D = M->getMemberDecl();
12804   }
12805 
12806   // Weak Decls can be null.
12807   if (!D || D->isWeak())
12808     return;
12809 
12810   // Check for parameter decl with nonnull attribute
12811   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
12812     if (getCurFunction() &&
12813         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
12814       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
12815         ComplainAboutNonnullParamOrCall(A);
12816         return;
12817       }
12818 
12819       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
12820         // Skip function template not specialized yet.
12821         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
12822           return;
12823         auto ParamIter = llvm::find(FD->parameters(), PV);
12824         assert(ParamIter != FD->param_end());
12825         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
12826 
12827         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
12828           if (!NonNull->args_size()) {
12829               ComplainAboutNonnullParamOrCall(NonNull);
12830               return;
12831           }
12832 
12833           for (const ParamIdx &ArgNo : NonNull->args()) {
12834             if (ArgNo.getASTIndex() == ParamNo) {
12835               ComplainAboutNonnullParamOrCall(NonNull);
12836               return;
12837             }
12838           }
12839         }
12840       }
12841     }
12842   }
12843 
12844   QualType T = D->getType();
12845   const bool IsArray = T->isArrayType();
12846   const bool IsFunction = T->isFunctionType();
12847 
12848   // Address of function is used to silence the function warning.
12849   if (IsAddressOf && IsFunction) {
12850     return;
12851   }
12852 
12853   // Found nothing.
12854   if (!IsAddressOf && !IsFunction && !IsArray)
12855     return;
12856 
12857   // Pretty print the expression for the diagnostic.
12858   std::string Str;
12859   llvm::raw_string_ostream S(Str);
12860   E->printPretty(S, nullptr, getPrintingPolicy());
12861 
12862   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
12863                               : diag::warn_impcast_pointer_to_bool;
12864   enum {
12865     AddressOf,
12866     FunctionPointer,
12867     ArrayPointer
12868   } DiagType;
12869   if (IsAddressOf)
12870     DiagType = AddressOf;
12871   else if (IsFunction)
12872     DiagType = FunctionPointer;
12873   else if (IsArray)
12874     DiagType = ArrayPointer;
12875   else
12876     llvm_unreachable("Could not determine diagnostic.");
12877   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
12878                                 << Range << IsEqual;
12879 
12880   if (!IsFunction)
12881     return;
12882 
12883   // Suggest '&' to silence the function warning.
12884   Diag(E->getExprLoc(), diag::note_function_warning_silence)
12885       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
12886 
12887   // Check to see if '()' fixit should be emitted.
12888   QualType ReturnType;
12889   UnresolvedSet<4> NonTemplateOverloads;
12890   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
12891   if (ReturnType.isNull())
12892     return;
12893 
12894   if (IsCompare) {
12895     // There are two cases here.  If there is null constant, the only suggest
12896     // for a pointer return type.  If the null is 0, then suggest if the return
12897     // type is a pointer or an integer type.
12898     if (!ReturnType->isPointerType()) {
12899       if (NullKind == Expr::NPCK_ZeroExpression ||
12900           NullKind == Expr::NPCK_ZeroLiteral) {
12901         if (!ReturnType->isIntegerType())
12902           return;
12903       } else {
12904         return;
12905       }
12906     }
12907   } else { // !IsCompare
12908     // For function to bool, only suggest if the function pointer has bool
12909     // return type.
12910     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
12911       return;
12912   }
12913   Diag(E->getExprLoc(), diag::note_function_to_function_call)
12914       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
12915 }
12916 
12917 /// Diagnoses "dangerous" implicit conversions within the given
12918 /// expression (which is a full expression).  Implements -Wconversion
12919 /// and -Wsign-compare.
12920 ///
12921 /// \param CC the "context" location of the implicit conversion, i.e.
12922 ///   the most location of the syntactic entity requiring the implicit
12923 ///   conversion
12924 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
12925   // Don't diagnose in unevaluated contexts.
12926   if (isUnevaluatedContext())
12927     return;
12928 
12929   // Don't diagnose for value- or type-dependent expressions.
12930   if (E->isTypeDependent() || E->isValueDependent())
12931     return;
12932 
12933   // Check for array bounds violations in cases where the check isn't triggered
12934   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
12935   // ArraySubscriptExpr is on the RHS of a variable initialization.
12936   CheckArrayAccess(E);
12937 
12938   // This is not the right CC for (e.g.) a variable initialization.
12939   AnalyzeImplicitConversions(*this, E, CC);
12940 }
12941 
12942 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
12943 /// Input argument E is a logical expression.
12944 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
12945   ::CheckBoolLikeConversion(*this, E, CC);
12946 }
12947 
12948 /// Diagnose when expression is an integer constant expression and its evaluation
12949 /// results in integer overflow
12950 void Sema::CheckForIntOverflow (Expr *E) {
12951   // Use a work list to deal with nested struct initializers.
12952   SmallVector<Expr *, 2> Exprs(1, E);
12953 
12954   do {
12955     Expr *OriginalE = Exprs.pop_back_val();
12956     Expr *E = OriginalE->IgnoreParenCasts();
12957 
12958     if (isa<BinaryOperator>(E)) {
12959       E->EvaluateForOverflow(Context);
12960       continue;
12961     }
12962 
12963     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
12964       Exprs.append(InitList->inits().begin(), InitList->inits().end());
12965     else if (isa<ObjCBoxedExpr>(OriginalE))
12966       E->EvaluateForOverflow(Context);
12967     else if (auto Call = dyn_cast<CallExpr>(E))
12968       Exprs.append(Call->arg_begin(), Call->arg_end());
12969     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
12970       Exprs.append(Message->arg_begin(), Message->arg_end());
12971   } while (!Exprs.empty());
12972 }
12973 
12974 namespace {
12975 
12976 /// Visitor for expressions which looks for unsequenced operations on the
12977 /// same object.
12978 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
12979   using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
12980 
12981   /// A tree of sequenced regions within an expression. Two regions are
12982   /// unsequenced if one is an ancestor or a descendent of the other. When we
12983   /// finish processing an expression with sequencing, such as a comma
12984   /// expression, we fold its tree nodes into its parent, since they are
12985   /// unsequenced with respect to nodes we will visit later.
12986   class SequenceTree {
12987     struct Value {
12988       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
12989       unsigned Parent : 31;
12990       unsigned Merged : 1;
12991     };
12992     SmallVector<Value, 8> Values;
12993 
12994   public:
12995     /// A region within an expression which may be sequenced with respect
12996     /// to some other region.
12997     class Seq {
12998       friend class SequenceTree;
12999 
13000       unsigned Index;
13001 
13002       explicit Seq(unsigned N) : Index(N) {}
13003 
13004     public:
13005       Seq() : Index(0) {}
13006     };
13007 
13008     SequenceTree() { Values.push_back(Value(0)); }
13009     Seq root() const { return Seq(0); }
13010 
13011     /// Create a new sequence of operations, which is an unsequenced
13012     /// subset of \p Parent. This sequence of operations is sequenced with
13013     /// respect to other children of \p Parent.
13014     Seq allocate(Seq Parent) {
13015       Values.push_back(Value(Parent.Index));
13016       return Seq(Values.size() - 1);
13017     }
13018 
13019     /// Merge a sequence of operations into its parent.
13020     void merge(Seq S) {
13021       Values[S.Index].Merged = true;
13022     }
13023 
13024     /// Determine whether two operations are unsequenced. This operation
13025     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
13026     /// should have been merged into its parent as appropriate.
13027     bool isUnsequenced(Seq Cur, Seq Old) {
13028       unsigned C = representative(Cur.Index);
13029       unsigned Target = representative(Old.Index);
13030       while (C >= Target) {
13031         if (C == Target)
13032           return true;
13033         C = Values[C].Parent;
13034       }
13035       return false;
13036     }
13037 
13038   private:
13039     /// Pick a representative for a sequence.
13040     unsigned representative(unsigned K) {
13041       if (Values[K].Merged)
13042         // Perform path compression as we go.
13043         return Values[K].Parent = representative(Values[K].Parent);
13044       return K;
13045     }
13046   };
13047 
13048   /// An object for which we can track unsequenced uses.
13049   using Object = const NamedDecl *;
13050 
13051   /// Different flavors of object usage which we track. We only track the
13052   /// least-sequenced usage of each kind.
13053   enum UsageKind {
13054     /// A read of an object. Multiple unsequenced reads are OK.
13055     UK_Use,
13056 
13057     /// A modification of an object which is sequenced before the value
13058     /// computation of the expression, such as ++n in C++.
13059     UK_ModAsValue,
13060 
13061     /// A modification of an object which is not sequenced before the value
13062     /// computation of the expression, such as n++.
13063     UK_ModAsSideEffect,
13064 
13065     UK_Count = UK_ModAsSideEffect + 1
13066   };
13067 
13068   /// Bundle together a sequencing region and the expression corresponding
13069   /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
13070   struct Usage {
13071     const Expr *UsageExpr;
13072     SequenceTree::Seq Seq;
13073 
13074     Usage() : UsageExpr(nullptr), Seq() {}
13075   };
13076 
13077   struct UsageInfo {
13078     Usage Uses[UK_Count];
13079 
13080     /// Have we issued a diagnostic for this object already?
13081     bool Diagnosed;
13082 
13083     UsageInfo() : Uses(), Diagnosed(false) {}
13084   };
13085   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
13086 
13087   Sema &SemaRef;
13088 
13089   /// Sequenced regions within the expression.
13090   SequenceTree Tree;
13091 
13092   /// Declaration modifications and references which we have seen.
13093   UsageInfoMap UsageMap;
13094 
13095   /// The region we are currently within.
13096   SequenceTree::Seq Region;
13097 
13098   /// Filled in with declarations which were modified as a side-effect
13099   /// (that is, post-increment operations).
13100   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
13101 
13102   /// Expressions to check later. We defer checking these to reduce
13103   /// stack usage.
13104   SmallVectorImpl<const Expr *> &WorkList;
13105 
13106   /// RAII object wrapping the visitation of a sequenced subexpression of an
13107   /// expression. At the end of this process, the side-effects of the evaluation
13108   /// become sequenced with respect to the value computation of the result, so
13109   /// we downgrade any UK_ModAsSideEffect within the evaluation to
13110   /// UK_ModAsValue.
13111   struct SequencedSubexpression {
13112     SequencedSubexpression(SequenceChecker &Self)
13113       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
13114       Self.ModAsSideEffect = &ModAsSideEffect;
13115     }
13116 
13117     ~SequencedSubexpression() {
13118       for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
13119         // Add a new usage with usage kind UK_ModAsValue, and then restore
13120         // the previous usage with UK_ModAsSideEffect (thus clearing it if
13121         // the previous one was empty).
13122         UsageInfo &UI = Self.UsageMap[M.first];
13123         auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
13124         Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
13125         SideEffectUsage = M.second;
13126       }
13127       Self.ModAsSideEffect = OldModAsSideEffect;
13128     }
13129 
13130     SequenceChecker &Self;
13131     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
13132     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
13133   };
13134 
13135   /// RAII object wrapping the visitation of a subexpression which we might
13136   /// choose to evaluate as a constant. If any subexpression is evaluated and
13137   /// found to be non-constant, this allows us to suppress the evaluation of
13138   /// the outer expression.
13139   class EvaluationTracker {
13140   public:
13141     EvaluationTracker(SequenceChecker &Self)
13142         : Self(Self), Prev(Self.EvalTracker) {
13143       Self.EvalTracker = this;
13144     }
13145 
13146     ~EvaluationTracker() {
13147       Self.EvalTracker = Prev;
13148       if (Prev)
13149         Prev->EvalOK &= EvalOK;
13150     }
13151 
13152     bool evaluate(const Expr *E, bool &Result) {
13153       if (!EvalOK || E->isValueDependent())
13154         return false;
13155       EvalOK = E->EvaluateAsBooleanCondition(
13156           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
13157       return EvalOK;
13158     }
13159 
13160   private:
13161     SequenceChecker &Self;
13162     EvaluationTracker *Prev;
13163     bool EvalOK = true;
13164   } *EvalTracker = nullptr;
13165 
13166   /// Find the object which is produced by the specified expression,
13167   /// if any.
13168   Object getObject(const Expr *E, bool Mod) const {
13169     E = E->IgnoreParenCasts();
13170     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13171       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
13172         return getObject(UO->getSubExpr(), Mod);
13173     } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13174       if (BO->getOpcode() == BO_Comma)
13175         return getObject(BO->getRHS(), Mod);
13176       if (Mod && BO->isAssignmentOp())
13177         return getObject(BO->getLHS(), Mod);
13178     } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13179       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
13180       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
13181         return ME->getMemberDecl();
13182     } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13183       // FIXME: If this is a reference, map through to its value.
13184       return DRE->getDecl();
13185     return nullptr;
13186   }
13187 
13188   /// Note that an object \p O was modified or used by an expression
13189   /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
13190   /// the object \p O as obtained via the \p UsageMap.
13191   void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
13192     // Get the old usage for the given object and usage kind.
13193     Usage &U = UI.Uses[UK];
13194     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
13195       // If we have a modification as side effect and are in a sequenced
13196       // subexpression, save the old Usage so that we can restore it later
13197       // in SequencedSubexpression::~SequencedSubexpression.
13198       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
13199         ModAsSideEffect->push_back(std::make_pair(O, U));
13200       // Then record the new usage with the current sequencing region.
13201       U.UsageExpr = UsageExpr;
13202       U.Seq = Region;
13203     }
13204   }
13205 
13206   /// Check whether a modification or use of an object \p O in an expression
13207   /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
13208   /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
13209   /// \p IsModMod is true when we are checking for a mod-mod unsequenced
13210   /// usage and false we are checking for a mod-use unsequenced usage.
13211   void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
13212                   UsageKind OtherKind, bool IsModMod) {
13213     if (UI.Diagnosed)
13214       return;
13215 
13216     const Usage &U = UI.Uses[OtherKind];
13217     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
13218       return;
13219 
13220     const Expr *Mod = U.UsageExpr;
13221     const Expr *ModOrUse = UsageExpr;
13222     if (OtherKind == UK_Use)
13223       std::swap(Mod, ModOrUse);
13224 
13225     SemaRef.DiagRuntimeBehavior(
13226         Mod->getExprLoc(), {Mod, ModOrUse},
13227         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
13228                                : diag::warn_unsequenced_mod_use)
13229             << O << SourceRange(ModOrUse->getExprLoc()));
13230     UI.Diagnosed = true;
13231   }
13232 
13233   // A note on note{Pre, Post}{Use, Mod}:
13234   //
13235   // (It helps to follow the algorithm with an expression such as
13236   //  "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
13237   //  operations before C++17 and both are well-defined in C++17).
13238   //
13239   // When visiting a node which uses/modify an object we first call notePreUse
13240   // or notePreMod before visiting its sub-expression(s). At this point the
13241   // children of the current node have not yet been visited and so the eventual
13242   // uses/modifications resulting from the children of the current node have not
13243   // been recorded yet.
13244   //
13245   // We then visit the children of the current node. After that notePostUse or
13246   // notePostMod is called. These will 1) detect an unsequenced modification
13247   // as side effect (as in "k++ + k") and 2) add a new usage with the
13248   // appropriate usage kind.
13249   //
13250   // We also have to be careful that some operation sequences modification as
13251   // side effect as well (for example: || or ,). To account for this we wrap
13252   // the visitation of such a sub-expression (for example: the LHS of || or ,)
13253   // with SequencedSubexpression. SequencedSubexpression is an RAII object
13254   // which record usages which are modifications as side effect, and then
13255   // downgrade them (or more accurately restore the previous usage which was a
13256   // modification as side effect) when exiting the scope of the sequenced
13257   // subexpression.
13258 
13259   void notePreUse(Object O, const Expr *UseExpr) {
13260     UsageInfo &UI = UsageMap[O];
13261     // Uses conflict with other modifications.
13262     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
13263   }
13264 
13265   void notePostUse(Object O, const Expr *UseExpr) {
13266     UsageInfo &UI = UsageMap[O];
13267     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
13268                /*IsModMod=*/false);
13269     addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
13270   }
13271 
13272   void notePreMod(Object O, const Expr *ModExpr) {
13273     UsageInfo &UI = UsageMap[O];
13274     // Modifications conflict with other modifications and with uses.
13275     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
13276     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
13277   }
13278 
13279   void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
13280     UsageInfo &UI = UsageMap[O];
13281     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
13282                /*IsModMod=*/true);
13283     addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
13284   }
13285 
13286 public:
13287   SequenceChecker(Sema &S, const Expr *E,
13288                   SmallVectorImpl<const Expr *> &WorkList)
13289       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
13290     Visit(E);
13291     // Silence a -Wunused-private-field since WorkList is now unused.
13292     // TODO: Evaluate if it can be used, and if not remove it.
13293     (void)this->WorkList;
13294   }
13295 
13296   void VisitStmt(const Stmt *S) {
13297     // Skip all statements which aren't expressions for now.
13298   }
13299 
13300   void VisitExpr(const Expr *E) {
13301     // By default, just recurse to evaluated subexpressions.
13302     Base::VisitStmt(E);
13303   }
13304 
13305   void VisitCastExpr(const CastExpr *E) {
13306     Object O = Object();
13307     if (E->getCastKind() == CK_LValueToRValue)
13308       O = getObject(E->getSubExpr(), false);
13309 
13310     if (O)
13311       notePreUse(O, E);
13312     VisitExpr(E);
13313     if (O)
13314       notePostUse(O, E);
13315   }
13316 
13317   void VisitSequencedExpressions(const Expr *SequencedBefore,
13318                                  const Expr *SequencedAfter) {
13319     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
13320     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
13321     SequenceTree::Seq OldRegion = Region;
13322 
13323     {
13324       SequencedSubexpression SeqBefore(*this);
13325       Region = BeforeRegion;
13326       Visit(SequencedBefore);
13327     }
13328 
13329     Region = AfterRegion;
13330     Visit(SequencedAfter);
13331 
13332     Region = OldRegion;
13333 
13334     Tree.merge(BeforeRegion);
13335     Tree.merge(AfterRegion);
13336   }
13337 
13338   void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
13339     // C++17 [expr.sub]p1:
13340     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
13341     //   expression E1 is sequenced before the expression E2.
13342     if (SemaRef.getLangOpts().CPlusPlus17)
13343       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
13344     else {
13345       Visit(ASE->getLHS());
13346       Visit(ASE->getRHS());
13347     }
13348   }
13349 
13350   void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
13351   void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
13352   void VisitBinPtrMem(const BinaryOperator *BO) {
13353     // C++17 [expr.mptr.oper]p4:
13354     //  Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
13355     //  the expression E1 is sequenced before the expression E2.
13356     if (SemaRef.getLangOpts().CPlusPlus17)
13357       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13358     else {
13359       Visit(BO->getLHS());
13360       Visit(BO->getRHS());
13361     }
13362   }
13363 
13364   void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
13365   void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
13366   void VisitBinShlShr(const BinaryOperator *BO) {
13367     // C++17 [expr.shift]p4:
13368     //  The expression E1 is sequenced before the expression E2.
13369     if (SemaRef.getLangOpts().CPlusPlus17)
13370       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13371     else {
13372       Visit(BO->getLHS());
13373       Visit(BO->getRHS());
13374     }
13375   }
13376 
13377   void VisitBinComma(const BinaryOperator *BO) {
13378     // C++11 [expr.comma]p1:
13379     //   Every value computation and side effect associated with the left
13380     //   expression is sequenced before every value computation and side
13381     //   effect associated with the right expression.
13382     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13383   }
13384 
13385   void VisitBinAssign(const BinaryOperator *BO) {
13386     SequenceTree::Seq RHSRegion;
13387     SequenceTree::Seq LHSRegion;
13388     if (SemaRef.getLangOpts().CPlusPlus17) {
13389       RHSRegion = Tree.allocate(Region);
13390       LHSRegion = Tree.allocate(Region);
13391     } else {
13392       RHSRegion = Region;
13393       LHSRegion = Region;
13394     }
13395     SequenceTree::Seq OldRegion = Region;
13396 
13397     // C++11 [expr.ass]p1:
13398     //  [...] the assignment is sequenced after the value computation
13399     //  of the right and left operands, [...]
13400     //
13401     // so check it before inspecting the operands and update the
13402     // map afterwards.
13403     Object O = getObject(BO->getLHS(), /*Mod=*/true);
13404     if (O)
13405       notePreMod(O, BO);
13406 
13407     if (SemaRef.getLangOpts().CPlusPlus17) {
13408       // C++17 [expr.ass]p1:
13409       //  [...] The right operand is sequenced before the left operand. [...]
13410       {
13411         SequencedSubexpression SeqBefore(*this);
13412         Region = RHSRegion;
13413         Visit(BO->getRHS());
13414       }
13415 
13416       Region = LHSRegion;
13417       Visit(BO->getLHS());
13418 
13419       if (O && isa<CompoundAssignOperator>(BO))
13420         notePostUse(O, BO);
13421 
13422     } else {
13423       // C++11 does not specify any sequencing between the LHS and RHS.
13424       Region = LHSRegion;
13425       Visit(BO->getLHS());
13426 
13427       if (O && isa<CompoundAssignOperator>(BO))
13428         notePostUse(O, BO);
13429 
13430       Region = RHSRegion;
13431       Visit(BO->getRHS());
13432     }
13433 
13434     // C++11 [expr.ass]p1:
13435     //  the assignment is sequenced [...] before the value computation of the
13436     //  assignment expression.
13437     // C11 6.5.16/3 has no such rule.
13438     Region = OldRegion;
13439     if (O)
13440       notePostMod(O, BO,
13441                   SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
13442                                                   : UK_ModAsSideEffect);
13443     if (SemaRef.getLangOpts().CPlusPlus17) {
13444       Tree.merge(RHSRegion);
13445       Tree.merge(LHSRegion);
13446     }
13447   }
13448 
13449   void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
13450     VisitBinAssign(CAO);
13451   }
13452 
13453   void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
13454   void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
13455   void VisitUnaryPreIncDec(const UnaryOperator *UO) {
13456     Object O = getObject(UO->getSubExpr(), true);
13457     if (!O)
13458       return VisitExpr(UO);
13459 
13460     notePreMod(O, UO);
13461     Visit(UO->getSubExpr());
13462     // C++11 [expr.pre.incr]p1:
13463     //   the expression ++x is equivalent to x+=1
13464     notePostMod(O, UO,
13465                 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
13466                                                 : UK_ModAsSideEffect);
13467   }
13468 
13469   void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
13470   void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
13471   void VisitUnaryPostIncDec(const UnaryOperator *UO) {
13472     Object O = getObject(UO->getSubExpr(), true);
13473     if (!O)
13474       return VisitExpr(UO);
13475 
13476     notePreMod(O, UO);
13477     Visit(UO->getSubExpr());
13478     notePostMod(O, UO, UK_ModAsSideEffect);
13479   }
13480 
13481   void VisitBinLOr(const BinaryOperator *BO) {
13482     // C++11 [expr.log.or]p2:
13483     //  If the second expression is evaluated, every value computation and
13484     //  side effect associated with the first expression is sequenced before
13485     //  every value computation and side effect associated with the
13486     //  second expression.
13487     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
13488     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
13489     SequenceTree::Seq OldRegion = Region;
13490 
13491     EvaluationTracker Eval(*this);
13492     {
13493       SequencedSubexpression Sequenced(*this);
13494       Region = LHSRegion;
13495       Visit(BO->getLHS());
13496     }
13497 
13498     // C++11 [expr.log.or]p1:
13499     //  [...] the second operand is not evaluated if the first operand
13500     //  evaluates to true.
13501     bool EvalResult = false;
13502     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
13503     bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
13504     if (ShouldVisitRHS) {
13505       Region = RHSRegion;
13506       Visit(BO->getRHS());
13507     }
13508 
13509     Region = OldRegion;
13510     Tree.merge(LHSRegion);
13511     Tree.merge(RHSRegion);
13512   }
13513 
13514   void VisitBinLAnd(const BinaryOperator *BO) {
13515     // C++11 [expr.log.and]p2:
13516     //  If the second expression is evaluated, every value computation and
13517     //  side effect associated with the first expression is sequenced before
13518     //  every value computation and side effect associated with the
13519     //  second expression.
13520     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
13521     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
13522     SequenceTree::Seq OldRegion = Region;
13523 
13524     EvaluationTracker Eval(*this);
13525     {
13526       SequencedSubexpression Sequenced(*this);
13527       Region = LHSRegion;
13528       Visit(BO->getLHS());
13529     }
13530 
13531     // C++11 [expr.log.and]p1:
13532     //  [...] the second operand is not evaluated if the first operand is false.
13533     bool EvalResult = false;
13534     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
13535     bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
13536     if (ShouldVisitRHS) {
13537       Region = RHSRegion;
13538       Visit(BO->getRHS());
13539     }
13540 
13541     Region = OldRegion;
13542     Tree.merge(LHSRegion);
13543     Tree.merge(RHSRegion);
13544   }
13545 
13546   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
13547     // C++11 [expr.cond]p1:
13548     //  [...] Every value computation and side effect associated with the first
13549     //  expression is sequenced before every value computation and side effect
13550     //  associated with the second or third expression.
13551     SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
13552 
13553     // No sequencing is specified between the true and false expression.
13554     // However since exactly one of both is going to be evaluated we can
13555     // consider them to be sequenced. This is needed to avoid warning on
13556     // something like "x ? y+= 1 : y += 2;" in the case where we will visit
13557     // both the true and false expressions because we can't evaluate x.
13558     // This will still allow us to detect an expression like (pre C++17)
13559     // "(x ? y += 1 : y += 2) = y".
13560     //
13561     // We don't wrap the visitation of the true and false expression with
13562     // SequencedSubexpression because we don't want to downgrade modifications
13563     // as side effect in the true and false expressions after the visition
13564     // is done. (for example in the expression "(x ? y++ : y++) + y" we should
13565     // not warn between the two "y++", but we should warn between the "y++"
13566     // and the "y".
13567     SequenceTree::Seq TrueRegion = Tree.allocate(Region);
13568     SequenceTree::Seq FalseRegion = Tree.allocate(Region);
13569     SequenceTree::Seq OldRegion = Region;
13570 
13571     EvaluationTracker Eval(*this);
13572     {
13573       SequencedSubexpression Sequenced(*this);
13574       Region = ConditionRegion;
13575       Visit(CO->getCond());
13576     }
13577 
13578     // C++11 [expr.cond]p1:
13579     // [...] The first expression is contextually converted to bool (Clause 4).
13580     // It is evaluated and if it is true, the result of the conditional
13581     // expression is the value of the second expression, otherwise that of the
13582     // third expression. Only one of the second and third expressions is
13583     // evaluated. [...]
13584     bool EvalResult = false;
13585     bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
13586     bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
13587     bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
13588     if (ShouldVisitTrueExpr) {
13589       Region = TrueRegion;
13590       Visit(CO->getTrueExpr());
13591     }
13592     if (ShouldVisitFalseExpr) {
13593       Region = FalseRegion;
13594       Visit(CO->getFalseExpr());
13595     }
13596 
13597     Region = OldRegion;
13598     Tree.merge(ConditionRegion);
13599     Tree.merge(TrueRegion);
13600     Tree.merge(FalseRegion);
13601   }
13602 
13603   void VisitCallExpr(const CallExpr *CE) {
13604     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
13605 
13606     if (CE->isUnevaluatedBuiltinCall(Context))
13607       return;
13608 
13609     // C++11 [intro.execution]p15:
13610     //   When calling a function [...], every value computation and side effect
13611     //   associated with any argument expression, or with the postfix expression
13612     //   designating the called function, is sequenced before execution of every
13613     //   expression or statement in the body of the function [and thus before
13614     //   the value computation of its result].
13615     SequencedSubexpression Sequenced(*this);
13616     SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
13617       // C++17 [expr.call]p5
13618       //   The postfix-expression is sequenced before each expression in the
13619       //   expression-list and any default argument. [...]
13620       SequenceTree::Seq CalleeRegion;
13621       SequenceTree::Seq OtherRegion;
13622       if (SemaRef.getLangOpts().CPlusPlus17) {
13623         CalleeRegion = Tree.allocate(Region);
13624         OtherRegion = Tree.allocate(Region);
13625       } else {
13626         CalleeRegion = Region;
13627         OtherRegion = Region;
13628       }
13629       SequenceTree::Seq OldRegion = Region;
13630 
13631       // Visit the callee expression first.
13632       Region = CalleeRegion;
13633       if (SemaRef.getLangOpts().CPlusPlus17) {
13634         SequencedSubexpression Sequenced(*this);
13635         Visit(CE->getCallee());
13636       } else {
13637         Visit(CE->getCallee());
13638       }
13639 
13640       // Then visit the argument expressions.
13641       Region = OtherRegion;
13642       for (const Expr *Argument : CE->arguments())
13643         Visit(Argument);
13644 
13645       Region = OldRegion;
13646       if (SemaRef.getLangOpts().CPlusPlus17) {
13647         Tree.merge(CalleeRegion);
13648         Tree.merge(OtherRegion);
13649       }
13650     });
13651   }
13652 
13653   void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
13654     // C++17 [over.match.oper]p2:
13655     //   [...] the operator notation is first transformed to the equivalent
13656     //   function-call notation as summarized in Table 12 (where @ denotes one
13657     //   of the operators covered in the specified subclause). However, the
13658     //   operands are sequenced in the order prescribed for the built-in
13659     //   operator (Clause 8).
13660     //
13661     // From the above only overloaded binary operators and overloaded call
13662     // operators have sequencing rules in C++17 that we need to handle
13663     // separately.
13664     if (!SemaRef.getLangOpts().CPlusPlus17 ||
13665         (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
13666       return VisitCallExpr(CXXOCE);
13667 
13668     enum {
13669       NoSequencing,
13670       LHSBeforeRHS,
13671       RHSBeforeLHS,
13672       LHSBeforeRest
13673     } SequencingKind;
13674     switch (CXXOCE->getOperator()) {
13675     case OO_Equal:
13676     case OO_PlusEqual:
13677     case OO_MinusEqual:
13678     case OO_StarEqual:
13679     case OO_SlashEqual:
13680     case OO_PercentEqual:
13681     case OO_CaretEqual:
13682     case OO_AmpEqual:
13683     case OO_PipeEqual:
13684     case OO_LessLessEqual:
13685     case OO_GreaterGreaterEqual:
13686       SequencingKind = RHSBeforeLHS;
13687       break;
13688 
13689     case OO_LessLess:
13690     case OO_GreaterGreater:
13691     case OO_AmpAmp:
13692     case OO_PipePipe:
13693     case OO_Comma:
13694     case OO_ArrowStar:
13695     case OO_Subscript:
13696       SequencingKind = LHSBeforeRHS;
13697       break;
13698 
13699     case OO_Call:
13700       SequencingKind = LHSBeforeRest;
13701       break;
13702 
13703     default:
13704       SequencingKind = NoSequencing;
13705       break;
13706     }
13707 
13708     if (SequencingKind == NoSequencing)
13709       return VisitCallExpr(CXXOCE);
13710 
13711     // This is a call, so all subexpressions are sequenced before the result.
13712     SequencedSubexpression Sequenced(*this);
13713 
13714     SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
13715       assert(SemaRef.getLangOpts().CPlusPlus17 &&
13716              "Should only get there with C++17 and above!");
13717       assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
13718              "Should only get there with an overloaded binary operator"
13719              " or an overloaded call operator!");
13720 
13721       if (SequencingKind == LHSBeforeRest) {
13722         assert(CXXOCE->getOperator() == OO_Call &&
13723                "We should only have an overloaded call operator here!");
13724 
13725         // This is very similar to VisitCallExpr, except that we only have the
13726         // C++17 case. The postfix-expression is the first argument of the
13727         // CXXOperatorCallExpr. The expressions in the expression-list, if any,
13728         // are in the following arguments.
13729         //
13730         // Note that we intentionally do not visit the callee expression since
13731         // it is just a decayed reference to a function.
13732         SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
13733         SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
13734         SequenceTree::Seq OldRegion = Region;
13735 
13736         assert(CXXOCE->getNumArgs() >= 1 &&
13737                "An overloaded call operator must have at least one argument"
13738                " for the postfix-expression!");
13739         const Expr *PostfixExpr = CXXOCE->getArgs()[0];
13740         llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
13741                                           CXXOCE->getNumArgs() - 1);
13742 
13743         // Visit the postfix-expression first.
13744         {
13745           Region = PostfixExprRegion;
13746           SequencedSubexpression Sequenced(*this);
13747           Visit(PostfixExpr);
13748         }
13749 
13750         // Then visit the argument expressions.
13751         Region = ArgsRegion;
13752         for (const Expr *Arg : Args)
13753           Visit(Arg);
13754 
13755         Region = OldRegion;
13756         Tree.merge(PostfixExprRegion);
13757         Tree.merge(ArgsRegion);
13758       } else {
13759         assert(CXXOCE->getNumArgs() == 2 &&
13760                "Should only have two arguments here!");
13761         assert((SequencingKind == LHSBeforeRHS ||
13762                 SequencingKind == RHSBeforeLHS) &&
13763                "Unexpected sequencing kind!");
13764 
13765         // We do not visit the callee expression since it is just a decayed
13766         // reference to a function.
13767         const Expr *E1 = CXXOCE->getArg(0);
13768         const Expr *E2 = CXXOCE->getArg(1);
13769         if (SequencingKind == RHSBeforeLHS)
13770           std::swap(E1, E2);
13771 
13772         return VisitSequencedExpressions(E1, E2);
13773       }
13774     });
13775   }
13776 
13777   void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
13778     // This is a call, so all subexpressions are sequenced before the result.
13779     SequencedSubexpression Sequenced(*this);
13780 
13781     if (!CCE->isListInitialization())
13782       return VisitExpr(CCE);
13783 
13784     // In C++11, list initializations are sequenced.
13785     SmallVector<SequenceTree::Seq, 32> Elts;
13786     SequenceTree::Seq Parent = Region;
13787     for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
13788                                               E = CCE->arg_end();
13789          I != E; ++I) {
13790       Region = Tree.allocate(Parent);
13791       Elts.push_back(Region);
13792       Visit(*I);
13793     }
13794 
13795     // Forget that the initializers are sequenced.
13796     Region = Parent;
13797     for (unsigned I = 0; I < Elts.size(); ++I)
13798       Tree.merge(Elts[I]);
13799   }
13800 
13801   void VisitInitListExpr(const InitListExpr *ILE) {
13802     if (!SemaRef.getLangOpts().CPlusPlus11)
13803       return VisitExpr(ILE);
13804 
13805     // In C++11, list initializations are sequenced.
13806     SmallVector<SequenceTree::Seq, 32> Elts;
13807     SequenceTree::Seq Parent = Region;
13808     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
13809       const Expr *E = ILE->getInit(I);
13810       if (!E)
13811         continue;
13812       Region = Tree.allocate(Parent);
13813       Elts.push_back(Region);
13814       Visit(E);
13815     }
13816 
13817     // Forget that the initializers are sequenced.
13818     Region = Parent;
13819     for (unsigned I = 0; I < Elts.size(); ++I)
13820       Tree.merge(Elts[I]);
13821   }
13822 };
13823 
13824 } // namespace
13825 
13826 void Sema::CheckUnsequencedOperations(const Expr *E) {
13827   SmallVector<const Expr *, 8> WorkList;
13828   WorkList.push_back(E);
13829   while (!WorkList.empty()) {
13830     const Expr *Item = WorkList.pop_back_val();
13831     SequenceChecker(*this, Item, WorkList);
13832   }
13833 }
13834 
13835 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
13836                               bool IsConstexpr) {
13837   llvm::SaveAndRestore<bool> ConstantContext(
13838       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
13839   CheckImplicitConversions(E, CheckLoc);
13840   if (!E->isInstantiationDependent())
13841     CheckUnsequencedOperations(E);
13842   if (!IsConstexpr && !E->isValueDependent())
13843     CheckForIntOverflow(E);
13844   DiagnoseMisalignedMembers();
13845 }
13846 
13847 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
13848                                        FieldDecl *BitField,
13849                                        Expr *Init) {
13850   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
13851 }
13852 
13853 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
13854                                          SourceLocation Loc) {
13855   if (!PType->isVariablyModifiedType())
13856     return;
13857   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
13858     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
13859     return;
13860   }
13861   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
13862     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
13863     return;
13864   }
13865   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
13866     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
13867     return;
13868   }
13869 
13870   const ArrayType *AT = S.Context.getAsArrayType(PType);
13871   if (!AT)
13872     return;
13873 
13874   if (AT->getSizeModifier() != ArrayType::Star) {
13875     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
13876     return;
13877   }
13878 
13879   S.Diag(Loc, diag::err_array_star_in_function_definition);
13880 }
13881 
13882 /// CheckParmsForFunctionDef - Check that the parameters of the given
13883 /// function are appropriate for the definition of a function. This
13884 /// takes care of any checks that cannot be performed on the
13885 /// declaration itself, e.g., that the types of each of the function
13886 /// parameters are complete.
13887 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
13888                                     bool CheckParameterNames) {
13889   bool HasInvalidParm = false;
13890   for (ParmVarDecl *Param : Parameters) {
13891     // C99 6.7.5.3p4: the parameters in a parameter type list in a
13892     // function declarator that is part of a function definition of
13893     // that function shall not have incomplete type.
13894     //
13895     // This is also C++ [dcl.fct]p6.
13896     if (!Param->isInvalidDecl() &&
13897         RequireCompleteType(Param->getLocation(), Param->getType(),
13898                             diag::err_typecheck_decl_incomplete_type)) {
13899       Param->setInvalidDecl();
13900       HasInvalidParm = true;
13901     }
13902 
13903     // C99 6.9.1p5: If the declarator includes a parameter type list, the
13904     // declaration of each parameter shall include an identifier.
13905     if (CheckParameterNames && Param->getIdentifier() == nullptr &&
13906         !Param->isImplicit() && !getLangOpts().CPlusPlus) {
13907       // Diagnose this as an extension in C17 and earlier.
13908       if (!getLangOpts().C2x)
13909         Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
13910     }
13911 
13912     // C99 6.7.5.3p12:
13913     //   If the function declarator is not part of a definition of that
13914     //   function, parameters may have incomplete type and may use the [*]
13915     //   notation in their sequences of declarator specifiers to specify
13916     //   variable length array types.
13917     QualType PType = Param->getOriginalType();
13918     // FIXME: This diagnostic should point the '[*]' if source-location
13919     // information is added for it.
13920     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
13921 
13922     // If the parameter is a c++ class type and it has to be destructed in the
13923     // callee function, declare the destructor so that it can be called by the
13924     // callee function. Do not perform any direct access check on the dtor here.
13925     if (!Param->isInvalidDecl()) {
13926       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
13927         if (!ClassDecl->isInvalidDecl() &&
13928             !ClassDecl->hasIrrelevantDestructor() &&
13929             !ClassDecl->isDependentContext() &&
13930             ClassDecl->isParamDestroyedInCallee()) {
13931           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
13932           MarkFunctionReferenced(Param->getLocation(), Destructor);
13933           DiagnoseUseOfDecl(Destructor, Param->getLocation());
13934         }
13935       }
13936     }
13937 
13938     // Parameters with the pass_object_size attribute only need to be marked
13939     // constant at function definitions. Because we lack information about
13940     // whether we're on a declaration or definition when we're instantiating the
13941     // attribute, we need to check for constness here.
13942     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
13943       if (!Param->getType().isConstQualified())
13944         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
13945             << Attr->getSpelling() << 1;
13946 
13947     // Check for parameter names shadowing fields from the class.
13948     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
13949       // The owning context for the parameter should be the function, but we
13950       // want to see if this function's declaration context is a record.
13951       DeclContext *DC = Param->getDeclContext();
13952       if (DC && DC->isFunctionOrMethod()) {
13953         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
13954           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
13955                                      RD, /*DeclIsField*/ false);
13956       }
13957     }
13958   }
13959 
13960   return HasInvalidParm;
13961 }
13962 
13963 Optional<std::pair<CharUnits, CharUnits>>
13964 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx);
13965 
13966 /// Compute the alignment and offset of the base class object given the
13967 /// derived-to-base cast expression and the alignment and offset of the derived
13968 /// class object.
13969 static std::pair<CharUnits, CharUnits>
13970 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
13971                                    CharUnits BaseAlignment, CharUnits Offset,
13972                                    ASTContext &Ctx) {
13973   for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
13974        ++PathI) {
13975     const CXXBaseSpecifier *Base = *PathI;
13976     const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
13977     if (Base->isVirtual()) {
13978       // The complete object may have a lower alignment than the non-virtual
13979       // alignment of the base, in which case the base may be misaligned. Choose
13980       // the smaller of the non-virtual alignment and BaseAlignment, which is a
13981       // conservative lower bound of the complete object alignment.
13982       CharUnits NonVirtualAlignment =
13983           Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment();
13984       BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
13985       Offset = CharUnits::Zero();
13986     } else {
13987       const ASTRecordLayout &RL =
13988           Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
13989       Offset += RL.getBaseClassOffset(BaseDecl);
13990     }
13991     DerivedType = Base->getType();
13992   }
13993 
13994   return std::make_pair(BaseAlignment, Offset);
13995 }
13996 
13997 /// Compute the alignment and offset of a binary additive operator.
13998 static Optional<std::pair<CharUnits, CharUnits>>
13999 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
14000                                      bool IsSub, ASTContext &Ctx) {
14001   QualType PointeeType = PtrE->getType()->getPointeeType();
14002 
14003   if (!PointeeType->isConstantSizeType())
14004     return llvm::None;
14005 
14006   auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
14007 
14008   if (!P)
14009     return llvm::None;
14010 
14011   CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
14012   if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
14013     CharUnits Offset = EltSize * IdxRes->getExtValue();
14014     if (IsSub)
14015       Offset = -Offset;
14016     return std::make_pair(P->first, P->second + Offset);
14017   }
14018 
14019   // If the integer expression isn't a constant expression, compute the lower
14020   // bound of the alignment using the alignment and offset of the pointer
14021   // expression and the element size.
14022   return std::make_pair(
14023       P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
14024       CharUnits::Zero());
14025 }
14026 
14027 /// This helper function takes an lvalue expression and returns the alignment of
14028 /// a VarDecl and a constant offset from the VarDecl.
14029 Optional<std::pair<CharUnits, CharUnits>>
14030 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) {
14031   E = E->IgnoreParens();
14032   switch (E->getStmtClass()) {
14033   default:
14034     break;
14035   case Stmt::CStyleCastExprClass:
14036   case Stmt::CXXStaticCastExprClass:
14037   case Stmt::ImplicitCastExprClass: {
14038     auto *CE = cast<CastExpr>(E);
14039     const Expr *From = CE->getSubExpr();
14040     switch (CE->getCastKind()) {
14041     default:
14042       break;
14043     case CK_NoOp:
14044       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14045     case CK_UncheckedDerivedToBase:
14046     case CK_DerivedToBase: {
14047       auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14048       if (!P)
14049         break;
14050       return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
14051                                                 P->second, Ctx);
14052     }
14053     }
14054     break;
14055   }
14056   case Stmt::ArraySubscriptExprClass: {
14057     auto *ASE = cast<ArraySubscriptExpr>(E);
14058     return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(),
14059                                                 false, Ctx);
14060   }
14061   case Stmt::DeclRefExprClass: {
14062     if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
14063       // FIXME: If VD is captured by copy or is an escaping __block variable,
14064       // use the alignment of VD's type.
14065       if (!VD->getType()->isReferenceType())
14066         return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
14067       if (VD->hasInit())
14068         return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
14069     }
14070     break;
14071   }
14072   case Stmt::MemberExprClass: {
14073     auto *ME = cast<MemberExpr>(E);
14074     auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
14075     if (!FD || FD->getType()->isReferenceType())
14076       break;
14077     Optional<std::pair<CharUnits, CharUnits>> P;
14078     if (ME->isArrow())
14079       P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
14080     else
14081       P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
14082     if (!P)
14083       break;
14084     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
14085     uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
14086     return std::make_pair(P->first,
14087                           P->second + CharUnits::fromQuantity(Offset));
14088   }
14089   case Stmt::UnaryOperatorClass: {
14090     auto *UO = cast<UnaryOperator>(E);
14091     switch (UO->getOpcode()) {
14092     default:
14093       break;
14094     case UO_Deref:
14095       return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx);
14096     }
14097     break;
14098   }
14099   case Stmt::BinaryOperatorClass: {
14100     auto *BO = cast<BinaryOperator>(E);
14101     auto Opcode = BO->getOpcode();
14102     switch (Opcode) {
14103     default:
14104       break;
14105     case BO_Comma:
14106       return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx);
14107     }
14108     break;
14109   }
14110   }
14111   return llvm::None;
14112 }
14113 
14114 /// This helper function takes a pointer expression and returns the alignment of
14115 /// a VarDecl and a constant offset from the VarDecl.
14116 Optional<std::pair<CharUnits, CharUnits>>
14117 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) {
14118   E = E->IgnoreParens();
14119   switch (E->getStmtClass()) {
14120   default:
14121     break;
14122   case Stmt::CStyleCastExprClass:
14123   case Stmt::CXXStaticCastExprClass:
14124   case Stmt::ImplicitCastExprClass: {
14125     auto *CE = cast<CastExpr>(E);
14126     const Expr *From = CE->getSubExpr();
14127     switch (CE->getCastKind()) {
14128     default:
14129       break;
14130     case CK_NoOp:
14131       return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14132     case CK_ArrayToPointerDecay:
14133       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14134     case CK_UncheckedDerivedToBase:
14135     case CK_DerivedToBase: {
14136       auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14137       if (!P)
14138         break;
14139       return getDerivedToBaseAlignmentAndOffset(
14140           CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
14141     }
14142     }
14143     break;
14144   }
14145   case Stmt::CXXThisExprClass: {
14146     auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
14147     CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment();
14148     return std::make_pair(Alignment, CharUnits::Zero());
14149   }
14150   case Stmt::UnaryOperatorClass: {
14151     auto *UO = cast<UnaryOperator>(E);
14152     if (UO->getOpcode() == UO_AddrOf)
14153       return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx);
14154     break;
14155   }
14156   case Stmt::BinaryOperatorClass: {
14157     auto *BO = cast<BinaryOperator>(E);
14158     auto Opcode = BO->getOpcode();
14159     switch (Opcode) {
14160     default:
14161       break;
14162     case BO_Add:
14163     case BO_Sub: {
14164       const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
14165       if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
14166         std::swap(LHS, RHS);
14167       return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
14168                                                   Ctx);
14169     }
14170     case BO_Comma:
14171       return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
14172     }
14173     break;
14174   }
14175   }
14176   return llvm::None;
14177 }
14178 
14179 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
14180   // See if we can compute the alignment of a VarDecl and an offset from it.
14181   Optional<std::pair<CharUnits, CharUnits>> P =
14182       getBaseAlignmentAndOffsetFromPtr(E, S.Context);
14183 
14184   if (P)
14185     return P->first.alignmentAtOffset(P->second);
14186 
14187   // If that failed, return the type's alignment.
14188   return S.Context.getTypeAlignInChars(E->getType()->getPointeeType());
14189 }
14190 
14191 /// CheckCastAlign - Implements -Wcast-align, which warns when a
14192 /// pointer cast increases the alignment requirements.
14193 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
14194   // This is actually a lot of work to potentially be doing on every
14195   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
14196   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
14197     return;
14198 
14199   // Ignore dependent types.
14200   if (T->isDependentType() || Op->getType()->isDependentType())
14201     return;
14202 
14203   // Require that the destination be a pointer type.
14204   const PointerType *DestPtr = T->getAs<PointerType>();
14205   if (!DestPtr) return;
14206 
14207   // If the destination has alignment 1, we're done.
14208   QualType DestPointee = DestPtr->getPointeeType();
14209   if (DestPointee->isIncompleteType()) return;
14210   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
14211   if (DestAlign.isOne()) return;
14212 
14213   // Require that the source be a pointer type.
14214   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
14215   if (!SrcPtr) return;
14216   QualType SrcPointee = SrcPtr->getPointeeType();
14217 
14218   // Explicitly allow casts from cv void*.  We already implicitly
14219   // allowed casts to cv void*, since they have alignment 1.
14220   // Also allow casts involving incomplete types, which implicitly
14221   // includes 'void'.
14222   if (SrcPointee->isIncompleteType()) return;
14223 
14224   CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
14225 
14226   if (SrcAlign >= DestAlign) return;
14227 
14228   Diag(TRange.getBegin(), diag::warn_cast_align)
14229     << Op->getType() << T
14230     << static_cast<unsigned>(SrcAlign.getQuantity())
14231     << static_cast<unsigned>(DestAlign.getQuantity())
14232     << TRange << Op->getSourceRange();
14233 }
14234 
14235 /// Check whether this array fits the idiom of a size-one tail padded
14236 /// array member of a struct.
14237 ///
14238 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
14239 /// commonly used to emulate flexible arrays in C89 code.
14240 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
14241                                     const NamedDecl *ND) {
14242   if (Size != 1 || !ND) return false;
14243 
14244   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
14245   if (!FD) return false;
14246 
14247   // Don't consider sizes resulting from macro expansions or template argument
14248   // substitution to form C89 tail-padded arrays.
14249 
14250   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
14251   while (TInfo) {
14252     TypeLoc TL = TInfo->getTypeLoc();
14253     // Look through typedefs.
14254     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
14255       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
14256       TInfo = TDL->getTypeSourceInfo();
14257       continue;
14258     }
14259     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
14260       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
14261       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
14262         return false;
14263     }
14264     break;
14265   }
14266 
14267   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
14268   if (!RD) return false;
14269   if (RD->isUnion()) return false;
14270   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
14271     if (!CRD->isStandardLayout()) return false;
14272   }
14273 
14274   // See if this is the last field decl in the record.
14275   const Decl *D = FD;
14276   while ((D = D->getNextDeclInContext()))
14277     if (isa<FieldDecl>(D))
14278       return false;
14279   return true;
14280 }
14281 
14282 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
14283                             const ArraySubscriptExpr *ASE,
14284                             bool AllowOnePastEnd, bool IndexNegated) {
14285   // Already diagnosed by the constant evaluator.
14286   if (isConstantEvaluated())
14287     return;
14288 
14289   IndexExpr = IndexExpr->IgnoreParenImpCasts();
14290   if (IndexExpr->isValueDependent())
14291     return;
14292 
14293   const Type *EffectiveType =
14294       BaseExpr->getType()->getPointeeOrArrayElementType();
14295   BaseExpr = BaseExpr->IgnoreParenCasts();
14296   const ConstantArrayType *ArrayTy =
14297       Context.getAsConstantArrayType(BaseExpr->getType());
14298 
14299   if (!ArrayTy)
14300     return;
14301 
14302   const Type *BaseType = ArrayTy->getElementType().getTypePtr();
14303   if (EffectiveType->isDependentType() || BaseType->isDependentType())
14304     return;
14305 
14306   Expr::EvalResult Result;
14307   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
14308     return;
14309 
14310   llvm::APSInt index = Result.Val.getInt();
14311   if (IndexNegated)
14312     index = -index;
14313 
14314   const NamedDecl *ND = nullptr;
14315   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14316     ND = DRE->getDecl();
14317   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
14318     ND = ME->getMemberDecl();
14319 
14320   if (index.isUnsigned() || !index.isNegative()) {
14321     // It is possible that the type of the base expression after
14322     // IgnoreParenCasts is incomplete, even though the type of the base
14323     // expression before IgnoreParenCasts is complete (see PR39746 for an
14324     // example). In this case we have no information about whether the array
14325     // access exceeds the array bounds. However we can still diagnose an array
14326     // access which precedes the array bounds.
14327     if (BaseType->isIncompleteType())
14328       return;
14329 
14330     llvm::APInt size = ArrayTy->getSize();
14331     if (!size.isStrictlyPositive())
14332       return;
14333 
14334     if (BaseType != EffectiveType) {
14335       // Make sure we're comparing apples to apples when comparing index to size
14336       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
14337       uint64_t array_typesize = Context.getTypeSize(BaseType);
14338       // Handle ptrarith_typesize being zero, such as when casting to void*
14339       if (!ptrarith_typesize) ptrarith_typesize = 1;
14340       if (ptrarith_typesize != array_typesize) {
14341         // There's a cast to a different size type involved
14342         uint64_t ratio = array_typesize / ptrarith_typesize;
14343         // TODO: Be smarter about handling cases where array_typesize is not a
14344         // multiple of ptrarith_typesize
14345         if (ptrarith_typesize * ratio == array_typesize)
14346           size *= llvm::APInt(size.getBitWidth(), ratio);
14347       }
14348     }
14349 
14350     if (size.getBitWidth() > index.getBitWidth())
14351       index = index.zext(size.getBitWidth());
14352     else if (size.getBitWidth() < index.getBitWidth())
14353       size = size.zext(index.getBitWidth());
14354 
14355     // For array subscripting the index must be less than size, but for pointer
14356     // arithmetic also allow the index (offset) to be equal to size since
14357     // computing the next address after the end of the array is legal and
14358     // commonly done e.g. in C++ iterators and range-based for loops.
14359     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
14360       return;
14361 
14362     // Also don't warn for arrays of size 1 which are members of some
14363     // structure. These are often used to approximate flexible arrays in C89
14364     // code.
14365     if (IsTailPaddedMemberArray(*this, size, ND))
14366       return;
14367 
14368     // Suppress the warning if the subscript expression (as identified by the
14369     // ']' location) and the index expression are both from macro expansions
14370     // within a system header.
14371     if (ASE) {
14372       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
14373           ASE->getRBracketLoc());
14374       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
14375         SourceLocation IndexLoc =
14376             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
14377         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
14378           return;
14379       }
14380     }
14381 
14382     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
14383     if (ASE)
14384       DiagID = diag::warn_array_index_exceeds_bounds;
14385 
14386     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
14387                         PDiag(DiagID) << index.toString(10, true)
14388                                       << size.toString(10, true)
14389                                       << (unsigned)size.getLimitedValue(~0U)
14390                                       << IndexExpr->getSourceRange());
14391   } else {
14392     unsigned DiagID = diag::warn_array_index_precedes_bounds;
14393     if (!ASE) {
14394       DiagID = diag::warn_ptr_arith_precedes_bounds;
14395       if (index.isNegative()) index = -index;
14396     }
14397 
14398     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
14399                         PDiag(DiagID) << index.toString(10, true)
14400                                       << IndexExpr->getSourceRange());
14401   }
14402 
14403   if (!ND) {
14404     // Try harder to find a NamedDecl to point at in the note.
14405     while (const ArraySubscriptExpr *ASE =
14406            dyn_cast<ArraySubscriptExpr>(BaseExpr))
14407       BaseExpr = ASE->getBase()->IgnoreParenCasts();
14408     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14409       ND = DRE->getDecl();
14410     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
14411       ND = ME->getMemberDecl();
14412   }
14413 
14414   if (ND)
14415     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
14416                         PDiag(diag::note_array_declared_here) << ND);
14417 }
14418 
14419 void Sema::CheckArrayAccess(const Expr *expr) {
14420   int AllowOnePastEnd = 0;
14421   while (expr) {
14422     expr = expr->IgnoreParenImpCasts();
14423     switch (expr->getStmtClass()) {
14424       case Stmt::ArraySubscriptExprClass: {
14425         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
14426         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
14427                          AllowOnePastEnd > 0);
14428         expr = ASE->getBase();
14429         break;
14430       }
14431       case Stmt::MemberExprClass: {
14432         expr = cast<MemberExpr>(expr)->getBase();
14433         break;
14434       }
14435       case Stmt::OMPArraySectionExprClass: {
14436         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
14437         if (ASE->getLowerBound())
14438           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
14439                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
14440         return;
14441       }
14442       case Stmt::UnaryOperatorClass: {
14443         // Only unwrap the * and & unary operators
14444         const UnaryOperator *UO = cast<UnaryOperator>(expr);
14445         expr = UO->getSubExpr();
14446         switch (UO->getOpcode()) {
14447           case UO_AddrOf:
14448             AllowOnePastEnd++;
14449             break;
14450           case UO_Deref:
14451             AllowOnePastEnd--;
14452             break;
14453           default:
14454             return;
14455         }
14456         break;
14457       }
14458       case Stmt::ConditionalOperatorClass: {
14459         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
14460         if (const Expr *lhs = cond->getLHS())
14461           CheckArrayAccess(lhs);
14462         if (const Expr *rhs = cond->getRHS())
14463           CheckArrayAccess(rhs);
14464         return;
14465       }
14466       case Stmt::CXXOperatorCallExprClass: {
14467         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
14468         for (const auto *Arg : OCE->arguments())
14469           CheckArrayAccess(Arg);
14470         return;
14471       }
14472       default:
14473         return;
14474     }
14475   }
14476 }
14477 
14478 //===--- CHECK: Objective-C retain cycles ----------------------------------//
14479 
14480 namespace {
14481 
14482 struct RetainCycleOwner {
14483   VarDecl *Variable = nullptr;
14484   SourceRange Range;
14485   SourceLocation Loc;
14486   bool Indirect = false;
14487 
14488   RetainCycleOwner() = default;
14489 
14490   void setLocsFrom(Expr *e) {
14491     Loc = e->getExprLoc();
14492     Range = e->getSourceRange();
14493   }
14494 };
14495 
14496 } // namespace
14497 
14498 /// Consider whether capturing the given variable can possibly lead to
14499 /// a retain cycle.
14500 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
14501   // In ARC, it's captured strongly iff the variable has __strong
14502   // lifetime.  In MRR, it's captured strongly if the variable is
14503   // __block and has an appropriate type.
14504   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
14505     return false;
14506 
14507   owner.Variable = var;
14508   if (ref)
14509     owner.setLocsFrom(ref);
14510   return true;
14511 }
14512 
14513 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
14514   while (true) {
14515     e = e->IgnoreParens();
14516     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
14517       switch (cast->getCastKind()) {
14518       case CK_BitCast:
14519       case CK_LValueBitCast:
14520       case CK_LValueToRValue:
14521       case CK_ARCReclaimReturnedObject:
14522         e = cast->getSubExpr();
14523         continue;
14524 
14525       default:
14526         return false;
14527       }
14528     }
14529 
14530     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
14531       ObjCIvarDecl *ivar = ref->getDecl();
14532       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
14533         return false;
14534 
14535       // Try to find a retain cycle in the base.
14536       if (!findRetainCycleOwner(S, ref->getBase(), owner))
14537         return false;
14538 
14539       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
14540       owner.Indirect = true;
14541       return true;
14542     }
14543 
14544     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
14545       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
14546       if (!var) return false;
14547       return considerVariable(var, ref, owner);
14548     }
14549 
14550     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
14551       if (member->isArrow()) return false;
14552 
14553       // Don't count this as an indirect ownership.
14554       e = member->getBase();
14555       continue;
14556     }
14557 
14558     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
14559       // Only pay attention to pseudo-objects on property references.
14560       ObjCPropertyRefExpr *pre
14561         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
14562                                               ->IgnoreParens());
14563       if (!pre) return false;
14564       if (pre->isImplicitProperty()) return false;
14565       ObjCPropertyDecl *property = pre->getExplicitProperty();
14566       if (!property->isRetaining() &&
14567           !(property->getPropertyIvarDecl() &&
14568             property->getPropertyIvarDecl()->getType()
14569               .getObjCLifetime() == Qualifiers::OCL_Strong))
14570           return false;
14571 
14572       owner.Indirect = true;
14573       if (pre->isSuperReceiver()) {
14574         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
14575         if (!owner.Variable)
14576           return false;
14577         owner.Loc = pre->getLocation();
14578         owner.Range = pre->getSourceRange();
14579         return true;
14580       }
14581       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
14582                               ->getSourceExpr());
14583       continue;
14584     }
14585 
14586     // Array ivars?
14587 
14588     return false;
14589   }
14590 }
14591 
14592 namespace {
14593 
14594   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
14595     ASTContext &Context;
14596     VarDecl *Variable;
14597     Expr *Capturer = nullptr;
14598     bool VarWillBeReased = false;
14599 
14600     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
14601         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
14602           Context(Context), Variable(variable) {}
14603 
14604     void VisitDeclRefExpr(DeclRefExpr *ref) {
14605       if (ref->getDecl() == Variable && !Capturer)
14606         Capturer = ref;
14607     }
14608 
14609     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
14610       if (Capturer) return;
14611       Visit(ref->getBase());
14612       if (Capturer && ref->isFreeIvar())
14613         Capturer = ref;
14614     }
14615 
14616     void VisitBlockExpr(BlockExpr *block) {
14617       // Look inside nested blocks
14618       if (block->getBlockDecl()->capturesVariable(Variable))
14619         Visit(block->getBlockDecl()->getBody());
14620     }
14621 
14622     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
14623       if (Capturer) return;
14624       if (OVE->getSourceExpr())
14625         Visit(OVE->getSourceExpr());
14626     }
14627 
14628     void VisitBinaryOperator(BinaryOperator *BinOp) {
14629       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
14630         return;
14631       Expr *LHS = BinOp->getLHS();
14632       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
14633         if (DRE->getDecl() != Variable)
14634           return;
14635         if (Expr *RHS = BinOp->getRHS()) {
14636           RHS = RHS->IgnoreParenCasts();
14637           Optional<llvm::APSInt> Value;
14638           VarWillBeReased =
14639               (RHS && (Value = RHS->getIntegerConstantExpr(Context)) &&
14640                *Value == 0);
14641         }
14642       }
14643     }
14644   };
14645 
14646 } // namespace
14647 
14648 /// Check whether the given argument is a block which captures a
14649 /// variable.
14650 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
14651   assert(owner.Variable && owner.Loc.isValid());
14652 
14653   e = e->IgnoreParenCasts();
14654 
14655   // Look through [^{...} copy] and Block_copy(^{...}).
14656   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
14657     Selector Cmd = ME->getSelector();
14658     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
14659       e = ME->getInstanceReceiver();
14660       if (!e)
14661         return nullptr;
14662       e = e->IgnoreParenCasts();
14663     }
14664   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
14665     if (CE->getNumArgs() == 1) {
14666       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
14667       if (Fn) {
14668         const IdentifierInfo *FnI = Fn->getIdentifier();
14669         if (FnI && FnI->isStr("_Block_copy")) {
14670           e = CE->getArg(0)->IgnoreParenCasts();
14671         }
14672       }
14673     }
14674   }
14675 
14676   BlockExpr *block = dyn_cast<BlockExpr>(e);
14677   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
14678     return nullptr;
14679 
14680   FindCaptureVisitor visitor(S.Context, owner.Variable);
14681   visitor.Visit(block->getBlockDecl()->getBody());
14682   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
14683 }
14684 
14685 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
14686                                 RetainCycleOwner &owner) {
14687   assert(capturer);
14688   assert(owner.Variable && owner.Loc.isValid());
14689 
14690   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
14691     << owner.Variable << capturer->getSourceRange();
14692   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
14693     << owner.Indirect << owner.Range;
14694 }
14695 
14696 /// Check for a keyword selector that starts with the word 'add' or
14697 /// 'set'.
14698 static bool isSetterLikeSelector(Selector sel) {
14699   if (sel.isUnarySelector()) return false;
14700 
14701   StringRef str = sel.getNameForSlot(0);
14702   while (!str.empty() && str.front() == '_') str = str.substr(1);
14703   if (str.startswith("set"))
14704     str = str.substr(3);
14705   else if (str.startswith("add")) {
14706     // Specially allow 'addOperationWithBlock:'.
14707     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
14708       return false;
14709     str = str.substr(3);
14710   }
14711   else
14712     return false;
14713 
14714   if (str.empty()) return true;
14715   return !isLowercase(str.front());
14716 }
14717 
14718 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
14719                                                     ObjCMessageExpr *Message) {
14720   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
14721                                                 Message->getReceiverInterface(),
14722                                                 NSAPI::ClassId_NSMutableArray);
14723   if (!IsMutableArray) {
14724     return None;
14725   }
14726 
14727   Selector Sel = Message->getSelector();
14728 
14729   Optional<NSAPI::NSArrayMethodKind> MKOpt =
14730     S.NSAPIObj->getNSArrayMethodKind(Sel);
14731   if (!MKOpt) {
14732     return None;
14733   }
14734 
14735   NSAPI::NSArrayMethodKind MK = *MKOpt;
14736 
14737   switch (MK) {
14738     case NSAPI::NSMutableArr_addObject:
14739     case NSAPI::NSMutableArr_insertObjectAtIndex:
14740     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
14741       return 0;
14742     case NSAPI::NSMutableArr_replaceObjectAtIndex:
14743       return 1;
14744 
14745     default:
14746       return None;
14747   }
14748 
14749   return None;
14750 }
14751 
14752 static
14753 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
14754                                                   ObjCMessageExpr *Message) {
14755   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
14756                                             Message->getReceiverInterface(),
14757                                             NSAPI::ClassId_NSMutableDictionary);
14758   if (!IsMutableDictionary) {
14759     return None;
14760   }
14761 
14762   Selector Sel = Message->getSelector();
14763 
14764   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
14765     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
14766   if (!MKOpt) {
14767     return None;
14768   }
14769 
14770   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
14771 
14772   switch (MK) {
14773     case NSAPI::NSMutableDict_setObjectForKey:
14774     case NSAPI::NSMutableDict_setValueForKey:
14775     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
14776       return 0;
14777 
14778     default:
14779       return None;
14780   }
14781 
14782   return None;
14783 }
14784 
14785 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
14786   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
14787                                                 Message->getReceiverInterface(),
14788                                                 NSAPI::ClassId_NSMutableSet);
14789 
14790   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
14791                                             Message->getReceiverInterface(),
14792                                             NSAPI::ClassId_NSMutableOrderedSet);
14793   if (!IsMutableSet && !IsMutableOrderedSet) {
14794     return None;
14795   }
14796 
14797   Selector Sel = Message->getSelector();
14798 
14799   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
14800   if (!MKOpt) {
14801     return None;
14802   }
14803 
14804   NSAPI::NSSetMethodKind MK = *MKOpt;
14805 
14806   switch (MK) {
14807     case NSAPI::NSMutableSet_addObject:
14808     case NSAPI::NSOrderedSet_setObjectAtIndex:
14809     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
14810     case NSAPI::NSOrderedSet_insertObjectAtIndex:
14811       return 0;
14812     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
14813       return 1;
14814   }
14815 
14816   return None;
14817 }
14818 
14819 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
14820   if (!Message->isInstanceMessage()) {
14821     return;
14822   }
14823 
14824   Optional<int> ArgOpt;
14825 
14826   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
14827       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
14828       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
14829     return;
14830   }
14831 
14832   int ArgIndex = *ArgOpt;
14833 
14834   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
14835   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
14836     Arg = OE->getSourceExpr()->IgnoreImpCasts();
14837   }
14838 
14839   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
14840     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
14841       if (ArgRE->isObjCSelfExpr()) {
14842         Diag(Message->getSourceRange().getBegin(),
14843              diag::warn_objc_circular_container)
14844           << ArgRE->getDecl() << StringRef("'super'");
14845       }
14846     }
14847   } else {
14848     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
14849 
14850     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
14851       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
14852     }
14853 
14854     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
14855       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
14856         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
14857           ValueDecl *Decl = ReceiverRE->getDecl();
14858           Diag(Message->getSourceRange().getBegin(),
14859                diag::warn_objc_circular_container)
14860             << Decl << Decl;
14861           if (!ArgRE->isObjCSelfExpr()) {
14862             Diag(Decl->getLocation(),
14863                  diag::note_objc_circular_container_declared_here)
14864               << Decl;
14865           }
14866         }
14867       }
14868     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
14869       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
14870         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
14871           ObjCIvarDecl *Decl = IvarRE->getDecl();
14872           Diag(Message->getSourceRange().getBegin(),
14873                diag::warn_objc_circular_container)
14874             << Decl << Decl;
14875           Diag(Decl->getLocation(),
14876                diag::note_objc_circular_container_declared_here)
14877             << Decl;
14878         }
14879       }
14880     }
14881   }
14882 }
14883 
14884 /// Check a message send to see if it's likely to cause a retain cycle.
14885 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
14886   // Only check instance methods whose selector looks like a setter.
14887   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
14888     return;
14889 
14890   // Try to find a variable that the receiver is strongly owned by.
14891   RetainCycleOwner owner;
14892   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
14893     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
14894       return;
14895   } else {
14896     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
14897     owner.Variable = getCurMethodDecl()->getSelfDecl();
14898     owner.Loc = msg->getSuperLoc();
14899     owner.Range = msg->getSuperLoc();
14900   }
14901 
14902   // Check whether the receiver is captured by any of the arguments.
14903   const ObjCMethodDecl *MD = msg->getMethodDecl();
14904   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
14905     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
14906       // noescape blocks should not be retained by the method.
14907       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
14908         continue;
14909       return diagnoseRetainCycle(*this, capturer, owner);
14910     }
14911   }
14912 }
14913 
14914 /// Check a property assign to see if it's likely to cause a retain cycle.
14915 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
14916   RetainCycleOwner owner;
14917   if (!findRetainCycleOwner(*this, receiver, owner))
14918     return;
14919 
14920   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
14921     diagnoseRetainCycle(*this, capturer, owner);
14922 }
14923 
14924 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
14925   RetainCycleOwner Owner;
14926   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
14927     return;
14928 
14929   // Because we don't have an expression for the variable, we have to set the
14930   // location explicitly here.
14931   Owner.Loc = Var->getLocation();
14932   Owner.Range = Var->getSourceRange();
14933 
14934   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
14935     diagnoseRetainCycle(*this, Capturer, Owner);
14936 }
14937 
14938 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
14939                                      Expr *RHS, bool isProperty) {
14940   // Check if RHS is an Objective-C object literal, which also can get
14941   // immediately zapped in a weak reference.  Note that we explicitly
14942   // allow ObjCStringLiterals, since those are designed to never really die.
14943   RHS = RHS->IgnoreParenImpCasts();
14944 
14945   // This enum needs to match with the 'select' in
14946   // warn_objc_arc_literal_assign (off-by-1).
14947   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
14948   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
14949     return false;
14950 
14951   S.Diag(Loc, diag::warn_arc_literal_assign)
14952     << (unsigned) Kind
14953     << (isProperty ? 0 : 1)
14954     << RHS->getSourceRange();
14955 
14956   return true;
14957 }
14958 
14959 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
14960                                     Qualifiers::ObjCLifetime LT,
14961                                     Expr *RHS, bool isProperty) {
14962   // Strip off any implicit cast added to get to the one ARC-specific.
14963   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
14964     if (cast->getCastKind() == CK_ARCConsumeObject) {
14965       S.Diag(Loc, diag::warn_arc_retained_assign)
14966         << (LT == Qualifiers::OCL_ExplicitNone)
14967         << (isProperty ? 0 : 1)
14968         << RHS->getSourceRange();
14969       return true;
14970     }
14971     RHS = cast->getSubExpr();
14972   }
14973 
14974   if (LT == Qualifiers::OCL_Weak &&
14975       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
14976     return true;
14977 
14978   return false;
14979 }
14980 
14981 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
14982                               QualType LHS, Expr *RHS) {
14983   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
14984 
14985   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
14986     return false;
14987 
14988   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
14989     return true;
14990 
14991   return false;
14992 }
14993 
14994 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
14995                               Expr *LHS, Expr *RHS) {
14996   QualType LHSType;
14997   // PropertyRef on LHS type need be directly obtained from
14998   // its declaration as it has a PseudoType.
14999   ObjCPropertyRefExpr *PRE
15000     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
15001   if (PRE && !PRE->isImplicitProperty()) {
15002     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15003     if (PD)
15004       LHSType = PD->getType();
15005   }
15006 
15007   if (LHSType.isNull())
15008     LHSType = LHS->getType();
15009 
15010   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
15011 
15012   if (LT == Qualifiers::OCL_Weak) {
15013     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
15014       getCurFunction()->markSafeWeakUse(LHS);
15015   }
15016 
15017   if (checkUnsafeAssigns(Loc, LHSType, RHS))
15018     return;
15019 
15020   // FIXME. Check for other life times.
15021   if (LT != Qualifiers::OCL_None)
15022     return;
15023 
15024   if (PRE) {
15025     if (PRE->isImplicitProperty())
15026       return;
15027     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15028     if (!PD)
15029       return;
15030 
15031     unsigned Attributes = PD->getPropertyAttributes();
15032     if (Attributes & ObjCPropertyAttribute::kind_assign) {
15033       // when 'assign' attribute was not explicitly specified
15034       // by user, ignore it and rely on property type itself
15035       // for lifetime info.
15036       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
15037       if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
15038           LHSType->isObjCRetainableType())
15039         return;
15040 
15041       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15042         if (cast->getCastKind() == CK_ARCConsumeObject) {
15043           Diag(Loc, diag::warn_arc_retained_property_assign)
15044           << RHS->getSourceRange();
15045           return;
15046         }
15047         RHS = cast->getSubExpr();
15048       }
15049     } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
15050       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
15051         return;
15052     }
15053   }
15054 }
15055 
15056 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
15057 
15058 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
15059                                         SourceLocation StmtLoc,
15060                                         const NullStmt *Body) {
15061   // Do not warn if the body is a macro that expands to nothing, e.g:
15062   //
15063   // #define CALL(x)
15064   // if (condition)
15065   //   CALL(0);
15066   if (Body->hasLeadingEmptyMacro())
15067     return false;
15068 
15069   // Get line numbers of statement and body.
15070   bool StmtLineInvalid;
15071   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
15072                                                       &StmtLineInvalid);
15073   if (StmtLineInvalid)
15074     return false;
15075 
15076   bool BodyLineInvalid;
15077   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
15078                                                       &BodyLineInvalid);
15079   if (BodyLineInvalid)
15080     return false;
15081 
15082   // Warn if null statement and body are on the same line.
15083   if (StmtLine != BodyLine)
15084     return false;
15085 
15086   return true;
15087 }
15088 
15089 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
15090                                  const Stmt *Body,
15091                                  unsigned DiagID) {
15092   // Since this is a syntactic check, don't emit diagnostic for template
15093   // instantiations, this just adds noise.
15094   if (CurrentInstantiationScope)
15095     return;
15096 
15097   // The body should be a null statement.
15098   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15099   if (!NBody)
15100     return;
15101 
15102   // Do the usual checks.
15103   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15104     return;
15105 
15106   Diag(NBody->getSemiLoc(), DiagID);
15107   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15108 }
15109 
15110 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
15111                                  const Stmt *PossibleBody) {
15112   assert(!CurrentInstantiationScope); // Ensured by caller
15113 
15114   SourceLocation StmtLoc;
15115   const Stmt *Body;
15116   unsigned DiagID;
15117   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
15118     StmtLoc = FS->getRParenLoc();
15119     Body = FS->getBody();
15120     DiagID = diag::warn_empty_for_body;
15121   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
15122     StmtLoc = WS->getCond()->getSourceRange().getEnd();
15123     Body = WS->getBody();
15124     DiagID = diag::warn_empty_while_body;
15125   } else
15126     return; // Neither `for' nor `while'.
15127 
15128   // The body should be a null statement.
15129   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15130   if (!NBody)
15131     return;
15132 
15133   // Skip expensive checks if diagnostic is disabled.
15134   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
15135     return;
15136 
15137   // Do the usual checks.
15138   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15139     return;
15140 
15141   // `for(...);' and `while(...);' are popular idioms, so in order to keep
15142   // noise level low, emit diagnostics only if for/while is followed by a
15143   // CompoundStmt, e.g.:
15144   //    for (int i = 0; i < n; i++);
15145   //    {
15146   //      a(i);
15147   //    }
15148   // or if for/while is followed by a statement with more indentation
15149   // than for/while itself:
15150   //    for (int i = 0; i < n; i++);
15151   //      a(i);
15152   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
15153   if (!ProbableTypo) {
15154     bool BodyColInvalid;
15155     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
15156         PossibleBody->getBeginLoc(), &BodyColInvalid);
15157     if (BodyColInvalid)
15158       return;
15159 
15160     bool StmtColInvalid;
15161     unsigned StmtCol =
15162         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
15163     if (StmtColInvalid)
15164       return;
15165 
15166     if (BodyCol > StmtCol)
15167       ProbableTypo = true;
15168   }
15169 
15170   if (ProbableTypo) {
15171     Diag(NBody->getSemiLoc(), DiagID);
15172     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15173   }
15174 }
15175 
15176 //===--- CHECK: Warn on self move with std::move. -------------------------===//
15177 
15178 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
15179 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
15180                              SourceLocation OpLoc) {
15181   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
15182     return;
15183 
15184   if (inTemplateInstantiation())
15185     return;
15186 
15187   // Strip parens and casts away.
15188   LHSExpr = LHSExpr->IgnoreParenImpCasts();
15189   RHSExpr = RHSExpr->IgnoreParenImpCasts();
15190 
15191   // Check for a call expression
15192   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
15193   if (!CE || CE->getNumArgs() != 1)
15194     return;
15195 
15196   // Check for a call to std::move
15197   if (!CE->isCallToStdMove())
15198     return;
15199 
15200   // Get argument from std::move
15201   RHSExpr = CE->getArg(0);
15202 
15203   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
15204   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
15205 
15206   // Two DeclRefExpr's, check that the decls are the same.
15207   if (LHSDeclRef && RHSDeclRef) {
15208     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15209       return;
15210     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15211         RHSDeclRef->getDecl()->getCanonicalDecl())
15212       return;
15213 
15214     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15215                                         << LHSExpr->getSourceRange()
15216                                         << RHSExpr->getSourceRange();
15217     return;
15218   }
15219 
15220   // Member variables require a different approach to check for self moves.
15221   // MemberExpr's are the same if every nested MemberExpr refers to the same
15222   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
15223   // the base Expr's are CXXThisExpr's.
15224   const Expr *LHSBase = LHSExpr;
15225   const Expr *RHSBase = RHSExpr;
15226   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
15227   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
15228   if (!LHSME || !RHSME)
15229     return;
15230 
15231   while (LHSME && RHSME) {
15232     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
15233         RHSME->getMemberDecl()->getCanonicalDecl())
15234       return;
15235 
15236     LHSBase = LHSME->getBase();
15237     RHSBase = RHSME->getBase();
15238     LHSME = dyn_cast<MemberExpr>(LHSBase);
15239     RHSME = dyn_cast<MemberExpr>(RHSBase);
15240   }
15241 
15242   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
15243   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
15244   if (LHSDeclRef && RHSDeclRef) {
15245     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15246       return;
15247     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15248         RHSDeclRef->getDecl()->getCanonicalDecl())
15249       return;
15250 
15251     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15252                                         << LHSExpr->getSourceRange()
15253                                         << RHSExpr->getSourceRange();
15254     return;
15255   }
15256 
15257   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
15258     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15259                                         << LHSExpr->getSourceRange()
15260                                         << RHSExpr->getSourceRange();
15261 }
15262 
15263 //===--- Layout compatibility ----------------------------------------------//
15264 
15265 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
15266 
15267 /// Check if two enumeration types are layout-compatible.
15268 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
15269   // C++11 [dcl.enum] p8:
15270   // Two enumeration types are layout-compatible if they have the same
15271   // underlying type.
15272   return ED1->isComplete() && ED2->isComplete() &&
15273          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
15274 }
15275 
15276 /// Check if two fields are layout-compatible.
15277 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
15278                                FieldDecl *Field2) {
15279   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
15280     return false;
15281 
15282   if (Field1->isBitField() != Field2->isBitField())
15283     return false;
15284 
15285   if (Field1->isBitField()) {
15286     // Make sure that the bit-fields are the same length.
15287     unsigned Bits1 = Field1->getBitWidthValue(C);
15288     unsigned Bits2 = Field2->getBitWidthValue(C);
15289 
15290     if (Bits1 != Bits2)
15291       return false;
15292   }
15293 
15294   return true;
15295 }
15296 
15297 /// Check if two standard-layout structs are layout-compatible.
15298 /// (C++11 [class.mem] p17)
15299 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
15300                                      RecordDecl *RD2) {
15301   // If both records are C++ classes, check that base classes match.
15302   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
15303     // If one of records is a CXXRecordDecl we are in C++ mode,
15304     // thus the other one is a CXXRecordDecl, too.
15305     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
15306     // Check number of base classes.
15307     if (D1CXX->getNumBases() != D2CXX->getNumBases())
15308       return false;
15309 
15310     // Check the base classes.
15311     for (CXXRecordDecl::base_class_const_iterator
15312                Base1 = D1CXX->bases_begin(),
15313            BaseEnd1 = D1CXX->bases_end(),
15314               Base2 = D2CXX->bases_begin();
15315          Base1 != BaseEnd1;
15316          ++Base1, ++Base2) {
15317       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
15318         return false;
15319     }
15320   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
15321     // If only RD2 is a C++ class, it should have zero base classes.
15322     if (D2CXX->getNumBases() > 0)
15323       return false;
15324   }
15325 
15326   // Check the fields.
15327   RecordDecl::field_iterator Field2 = RD2->field_begin(),
15328                              Field2End = RD2->field_end(),
15329                              Field1 = RD1->field_begin(),
15330                              Field1End = RD1->field_end();
15331   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
15332     if (!isLayoutCompatible(C, *Field1, *Field2))
15333       return false;
15334   }
15335   if (Field1 != Field1End || Field2 != Field2End)
15336     return false;
15337 
15338   return true;
15339 }
15340 
15341 /// Check if two standard-layout unions are layout-compatible.
15342 /// (C++11 [class.mem] p18)
15343 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
15344                                     RecordDecl *RD2) {
15345   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
15346   for (auto *Field2 : RD2->fields())
15347     UnmatchedFields.insert(Field2);
15348 
15349   for (auto *Field1 : RD1->fields()) {
15350     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
15351         I = UnmatchedFields.begin(),
15352         E = UnmatchedFields.end();
15353 
15354     for ( ; I != E; ++I) {
15355       if (isLayoutCompatible(C, Field1, *I)) {
15356         bool Result = UnmatchedFields.erase(*I);
15357         (void) Result;
15358         assert(Result);
15359         break;
15360       }
15361     }
15362     if (I == E)
15363       return false;
15364   }
15365 
15366   return UnmatchedFields.empty();
15367 }
15368 
15369 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
15370                                RecordDecl *RD2) {
15371   if (RD1->isUnion() != RD2->isUnion())
15372     return false;
15373 
15374   if (RD1->isUnion())
15375     return isLayoutCompatibleUnion(C, RD1, RD2);
15376   else
15377     return isLayoutCompatibleStruct(C, RD1, RD2);
15378 }
15379 
15380 /// Check if two types are layout-compatible in C++11 sense.
15381 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
15382   if (T1.isNull() || T2.isNull())
15383     return false;
15384 
15385   // C++11 [basic.types] p11:
15386   // If two types T1 and T2 are the same type, then T1 and T2 are
15387   // layout-compatible types.
15388   if (C.hasSameType(T1, T2))
15389     return true;
15390 
15391   T1 = T1.getCanonicalType().getUnqualifiedType();
15392   T2 = T2.getCanonicalType().getUnqualifiedType();
15393 
15394   const Type::TypeClass TC1 = T1->getTypeClass();
15395   const Type::TypeClass TC2 = T2->getTypeClass();
15396 
15397   if (TC1 != TC2)
15398     return false;
15399 
15400   if (TC1 == Type::Enum) {
15401     return isLayoutCompatible(C,
15402                               cast<EnumType>(T1)->getDecl(),
15403                               cast<EnumType>(T2)->getDecl());
15404   } else if (TC1 == Type::Record) {
15405     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
15406       return false;
15407 
15408     return isLayoutCompatible(C,
15409                               cast<RecordType>(T1)->getDecl(),
15410                               cast<RecordType>(T2)->getDecl());
15411   }
15412 
15413   return false;
15414 }
15415 
15416 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
15417 
15418 /// Given a type tag expression find the type tag itself.
15419 ///
15420 /// \param TypeExpr Type tag expression, as it appears in user's code.
15421 ///
15422 /// \param VD Declaration of an identifier that appears in a type tag.
15423 ///
15424 /// \param MagicValue Type tag magic value.
15425 ///
15426 /// \param isConstantEvaluated wether the evalaution should be performed in
15427 
15428 /// constant context.
15429 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
15430                             const ValueDecl **VD, uint64_t *MagicValue,
15431                             bool isConstantEvaluated) {
15432   while(true) {
15433     if (!TypeExpr)
15434       return false;
15435 
15436     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
15437 
15438     switch (TypeExpr->getStmtClass()) {
15439     case Stmt::UnaryOperatorClass: {
15440       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
15441       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
15442         TypeExpr = UO->getSubExpr();
15443         continue;
15444       }
15445       return false;
15446     }
15447 
15448     case Stmt::DeclRefExprClass: {
15449       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
15450       *VD = DRE->getDecl();
15451       return true;
15452     }
15453 
15454     case Stmt::IntegerLiteralClass: {
15455       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
15456       llvm::APInt MagicValueAPInt = IL->getValue();
15457       if (MagicValueAPInt.getActiveBits() <= 64) {
15458         *MagicValue = MagicValueAPInt.getZExtValue();
15459         return true;
15460       } else
15461         return false;
15462     }
15463 
15464     case Stmt::BinaryConditionalOperatorClass:
15465     case Stmt::ConditionalOperatorClass: {
15466       const AbstractConditionalOperator *ACO =
15467           cast<AbstractConditionalOperator>(TypeExpr);
15468       bool Result;
15469       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
15470                                                      isConstantEvaluated)) {
15471         if (Result)
15472           TypeExpr = ACO->getTrueExpr();
15473         else
15474           TypeExpr = ACO->getFalseExpr();
15475         continue;
15476       }
15477       return false;
15478     }
15479 
15480     case Stmt::BinaryOperatorClass: {
15481       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
15482       if (BO->getOpcode() == BO_Comma) {
15483         TypeExpr = BO->getRHS();
15484         continue;
15485       }
15486       return false;
15487     }
15488 
15489     default:
15490       return false;
15491     }
15492   }
15493 }
15494 
15495 /// Retrieve the C type corresponding to type tag TypeExpr.
15496 ///
15497 /// \param TypeExpr Expression that specifies a type tag.
15498 ///
15499 /// \param MagicValues Registered magic values.
15500 ///
15501 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
15502 ///        kind.
15503 ///
15504 /// \param TypeInfo Information about the corresponding C type.
15505 ///
15506 /// \param isConstantEvaluated wether the evalaution should be performed in
15507 /// constant context.
15508 ///
15509 /// \returns true if the corresponding C type was found.
15510 static bool GetMatchingCType(
15511     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
15512     const ASTContext &Ctx,
15513     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
15514         *MagicValues,
15515     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
15516     bool isConstantEvaluated) {
15517   FoundWrongKind = false;
15518 
15519   // Variable declaration that has type_tag_for_datatype attribute.
15520   const ValueDecl *VD = nullptr;
15521 
15522   uint64_t MagicValue;
15523 
15524   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
15525     return false;
15526 
15527   if (VD) {
15528     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
15529       if (I->getArgumentKind() != ArgumentKind) {
15530         FoundWrongKind = true;
15531         return false;
15532       }
15533       TypeInfo.Type = I->getMatchingCType();
15534       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
15535       TypeInfo.MustBeNull = I->getMustBeNull();
15536       return true;
15537     }
15538     return false;
15539   }
15540 
15541   if (!MagicValues)
15542     return false;
15543 
15544   llvm::DenseMap<Sema::TypeTagMagicValue,
15545                  Sema::TypeTagData>::const_iterator I =
15546       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
15547   if (I == MagicValues->end())
15548     return false;
15549 
15550   TypeInfo = I->second;
15551   return true;
15552 }
15553 
15554 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
15555                                       uint64_t MagicValue, QualType Type,
15556                                       bool LayoutCompatible,
15557                                       bool MustBeNull) {
15558   if (!TypeTagForDatatypeMagicValues)
15559     TypeTagForDatatypeMagicValues.reset(
15560         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
15561 
15562   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
15563   (*TypeTagForDatatypeMagicValues)[Magic] =
15564       TypeTagData(Type, LayoutCompatible, MustBeNull);
15565 }
15566 
15567 static bool IsSameCharType(QualType T1, QualType T2) {
15568   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
15569   if (!BT1)
15570     return false;
15571 
15572   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
15573   if (!BT2)
15574     return false;
15575 
15576   BuiltinType::Kind T1Kind = BT1->getKind();
15577   BuiltinType::Kind T2Kind = BT2->getKind();
15578 
15579   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
15580          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
15581          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
15582          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
15583 }
15584 
15585 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
15586                                     const ArrayRef<const Expr *> ExprArgs,
15587                                     SourceLocation CallSiteLoc) {
15588   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
15589   bool IsPointerAttr = Attr->getIsPointer();
15590 
15591   // Retrieve the argument representing the 'type_tag'.
15592   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
15593   if (TypeTagIdxAST >= ExprArgs.size()) {
15594     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
15595         << 0 << Attr->getTypeTagIdx().getSourceIndex();
15596     return;
15597   }
15598   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
15599   bool FoundWrongKind;
15600   TypeTagData TypeInfo;
15601   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
15602                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
15603                         TypeInfo, isConstantEvaluated())) {
15604     if (FoundWrongKind)
15605       Diag(TypeTagExpr->getExprLoc(),
15606            diag::warn_type_tag_for_datatype_wrong_kind)
15607         << TypeTagExpr->getSourceRange();
15608     return;
15609   }
15610 
15611   // Retrieve the argument representing the 'arg_idx'.
15612   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
15613   if (ArgumentIdxAST >= ExprArgs.size()) {
15614     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
15615         << 1 << Attr->getArgumentIdx().getSourceIndex();
15616     return;
15617   }
15618   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
15619   if (IsPointerAttr) {
15620     // Skip implicit cast of pointer to `void *' (as a function argument).
15621     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
15622       if (ICE->getType()->isVoidPointerType() &&
15623           ICE->getCastKind() == CK_BitCast)
15624         ArgumentExpr = ICE->getSubExpr();
15625   }
15626   QualType ArgumentType = ArgumentExpr->getType();
15627 
15628   // Passing a `void*' pointer shouldn't trigger a warning.
15629   if (IsPointerAttr && ArgumentType->isVoidPointerType())
15630     return;
15631 
15632   if (TypeInfo.MustBeNull) {
15633     // Type tag with matching void type requires a null pointer.
15634     if (!ArgumentExpr->isNullPointerConstant(Context,
15635                                              Expr::NPC_ValueDependentIsNotNull)) {
15636       Diag(ArgumentExpr->getExprLoc(),
15637            diag::warn_type_safety_null_pointer_required)
15638           << ArgumentKind->getName()
15639           << ArgumentExpr->getSourceRange()
15640           << TypeTagExpr->getSourceRange();
15641     }
15642     return;
15643   }
15644 
15645   QualType RequiredType = TypeInfo.Type;
15646   if (IsPointerAttr)
15647     RequiredType = Context.getPointerType(RequiredType);
15648 
15649   bool mismatch = false;
15650   if (!TypeInfo.LayoutCompatible) {
15651     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
15652 
15653     // C++11 [basic.fundamental] p1:
15654     // Plain char, signed char, and unsigned char are three distinct types.
15655     //
15656     // But we treat plain `char' as equivalent to `signed char' or `unsigned
15657     // char' depending on the current char signedness mode.
15658     if (mismatch)
15659       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
15660                                            RequiredType->getPointeeType())) ||
15661           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
15662         mismatch = false;
15663   } else
15664     if (IsPointerAttr)
15665       mismatch = !isLayoutCompatible(Context,
15666                                      ArgumentType->getPointeeType(),
15667                                      RequiredType->getPointeeType());
15668     else
15669       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
15670 
15671   if (mismatch)
15672     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
15673         << ArgumentType << ArgumentKind
15674         << TypeInfo.LayoutCompatible << RequiredType
15675         << ArgumentExpr->getSourceRange()
15676         << TypeTagExpr->getSourceRange();
15677 }
15678 
15679 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
15680                                          CharUnits Alignment) {
15681   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
15682 }
15683 
15684 void Sema::DiagnoseMisalignedMembers() {
15685   for (MisalignedMember &m : MisalignedMembers) {
15686     const NamedDecl *ND = m.RD;
15687     if (ND->getName().empty()) {
15688       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
15689         ND = TD;
15690     }
15691     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
15692         << m.MD << ND << m.E->getSourceRange();
15693   }
15694   MisalignedMembers.clear();
15695 }
15696 
15697 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
15698   E = E->IgnoreParens();
15699   if (!T->isPointerType() && !T->isIntegerType())
15700     return;
15701   if (isa<UnaryOperator>(E) &&
15702       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
15703     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
15704     if (isa<MemberExpr>(Op)) {
15705       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
15706       if (MA != MisalignedMembers.end() &&
15707           (T->isIntegerType() ||
15708            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
15709                                    Context.getTypeAlignInChars(
15710                                        T->getPointeeType()) <= MA->Alignment))))
15711         MisalignedMembers.erase(MA);
15712     }
15713   }
15714 }
15715 
15716 void Sema::RefersToMemberWithReducedAlignment(
15717     Expr *E,
15718     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
15719         Action) {
15720   const auto *ME = dyn_cast<MemberExpr>(E);
15721   if (!ME)
15722     return;
15723 
15724   // No need to check expressions with an __unaligned-qualified type.
15725   if (E->getType().getQualifiers().hasUnaligned())
15726     return;
15727 
15728   // For a chain of MemberExpr like "a.b.c.d" this list
15729   // will keep FieldDecl's like [d, c, b].
15730   SmallVector<FieldDecl *, 4> ReverseMemberChain;
15731   const MemberExpr *TopME = nullptr;
15732   bool AnyIsPacked = false;
15733   do {
15734     QualType BaseType = ME->getBase()->getType();
15735     if (BaseType->isDependentType())
15736       return;
15737     if (ME->isArrow())
15738       BaseType = BaseType->getPointeeType();
15739     RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
15740     if (RD->isInvalidDecl())
15741       return;
15742 
15743     ValueDecl *MD = ME->getMemberDecl();
15744     auto *FD = dyn_cast<FieldDecl>(MD);
15745     // We do not care about non-data members.
15746     if (!FD || FD->isInvalidDecl())
15747       return;
15748 
15749     AnyIsPacked =
15750         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
15751     ReverseMemberChain.push_back(FD);
15752 
15753     TopME = ME;
15754     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
15755   } while (ME);
15756   assert(TopME && "We did not compute a topmost MemberExpr!");
15757 
15758   // Not the scope of this diagnostic.
15759   if (!AnyIsPacked)
15760     return;
15761 
15762   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
15763   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
15764   // TODO: The innermost base of the member expression may be too complicated.
15765   // For now, just disregard these cases. This is left for future
15766   // improvement.
15767   if (!DRE && !isa<CXXThisExpr>(TopBase))
15768       return;
15769 
15770   // Alignment expected by the whole expression.
15771   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
15772 
15773   // No need to do anything else with this case.
15774   if (ExpectedAlignment.isOne())
15775     return;
15776 
15777   // Synthesize offset of the whole access.
15778   CharUnits Offset;
15779   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
15780        I++) {
15781     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
15782   }
15783 
15784   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
15785   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
15786       ReverseMemberChain.back()->getParent()->getTypeForDecl());
15787 
15788   // The base expression of the innermost MemberExpr may give
15789   // stronger guarantees than the class containing the member.
15790   if (DRE && !TopME->isArrow()) {
15791     const ValueDecl *VD = DRE->getDecl();
15792     if (!VD->getType()->isReferenceType())
15793       CompleteObjectAlignment =
15794           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
15795   }
15796 
15797   // Check if the synthesized offset fulfills the alignment.
15798   if (Offset % ExpectedAlignment != 0 ||
15799       // It may fulfill the offset it but the effective alignment may still be
15800       // lower than the expected expression alignment.
15801       CompleteObjectAlignment < ExpectedAlignment) {
15802     // If this happens, we want to determine a sensible culprit of this.
15803     // Intuitively, watching the chain of member expressions from right to
15804     // left, we start with the required alignment (as required by the field
15805     // type) but some packed attribute in that chain has reduced the alignment.
15806     // It may happen that another packed structure increases it again. But if
15807     // we are here such increase has not been enough. So pointing the first
15808     // FieldDecl that either is packed or else its RecordDecl is,
15809     // seems reasonable.
15810     FieldDecl *FD = nullptr;
15811     CharUnits Alignment;
15812     for (FieldDecl *FDI : ReverseMemberChain) {
15813       if (FDI->hasAttr<PackedAttr>() ||
15814           FDI->getParent()->hasAttr<PackedAttr>()) {
15815         FD = FDI;
15816         Alignment = std::min(
15817             Context.getTypeAlignInChars(FD->getType()),
15818             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
15819         break;
15820       }
15821     }
15822     assert(FD && "We did not find a packed FieldDecl!");
15823     Action(E, FD->getParent(), FD, Alignment);
15824   }
15825 }
15826 
15827 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
15828   using namespace std::placeholders;
15829 
15830   RefersToMemberWithReducedAlignment(
15831       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
15832                      _2, _3, _4));
15833 }
15834 
15835 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall,
15836                                             ExprResult CallResult) {
15837   if (checkArgCount(*this, TheCall, 1))
15838     return ExprError();
15839 
15840   ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
15841   if (MatrixArg.isInvalid())
15842     return MatrixArg;
15843   Expr *Matrix = MatrixArg.get();
15844 
15845   auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
15846   if (!MType) {
15847     Diag(Matrix->getBeginLoc(), diag::err_builtin_matrix_arg);
15848     return ExprError();
15849   }
15850 
15851   // Create returned matrix type by swapping rows and columns of the argument
15852   // matrix type.
15853   QualType ResultType = Context.getConstantMatrixType(
15854       MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
15855 
15856   // Change the return type to the type of the returned matrix.
15857   TheCall->setType(ResultType);
15858 
15859   // Update call argument to use the possibly converted matrix argument.
15860   TheCall->setArg(0, Matrix);
15861   return CallResult;
15862 }
15863 
15864 // Get and verify the matrix dimensions.
15865 static llvm::Optional<unsigned>
15866 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {
15867   SourceLocation ErrorPos;
15868   Optional<llvm::APSInt> Value =
15869       Expr->getIntegerConstantExpr(S.Context, &ErrorPos);
15870   if (!Value) {
15871     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
15872         << Name;
15873     return {};
15874   }
15875   uint64_t Dim = Value->getZExtValue();
15876   if (!ConstantMatrixType::isDimensionValid(Dim)) {
15877     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
15878         << Name << ConstantMatrixType::getMaxElementsPerDimension();
15879     return {};
15880   }
15881   return Dim;
15882 }
15883 
15884 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
15885                                                   ExprResult CallResult) {
15886   if (!getLangOpts().MatrixTypes) {
15887     Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
15888     return ExprError();
15889   }
15890 
15891   if (checkArgCount(*this, TheCall, 4))
15892     return ExprError();
15893 
15894   unsigned PtrArgIdx = 0;
15895   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
15896   Expr *RowsExpr = TheCall->getArg(1);
15897   Expr *ColumnsExpr = TheCall->getArg(2);
15898   Expr *StrideExpr = TheCall->getArg(3);
15899 
15900   bool ArgError = false;
15901 
15902   // Check pointer argument.
15903   {
15904     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
15905     if (PtrConv.isInvalid())
15906       return PtrConv;
15907     PtrExpr = PtrConv.get();
15908     TheCall->setArg(0, PtrExpr);
15909     if (PtrExpr->isTypeDependent()) {
15910       TheCall->setType(Context.DependentTy);
15911       return TheCall;
15912     }
15913   }
15914 
15915   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
15916   QualType ElementTy;
15917   if (!PtrTy) {
15918     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
15919         << PtrArgIdx + 1;
15920     ArgError = true;
15921   } else {
15922     ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
15923 
15924     if (!ConstantMatrixType::isValidElementType(ElementTy)) {
15925       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
15926           << PtrArgIdx + 1;
15927       ArgError = true;
15928     }
15929   }
15930 
15931   // Apply default Lvalue conversions and convert the expression to size_t.
15932   auto ApplyArgumentConversions = [this](Expr *E) {
15933     ExprResult Conv = DefaultLvalueConversion(E);
15934     if (Conv.isInvalid())
15935       return Conv;
15936 
15937     return tryConvertExprToType(Conv.get(), Context.getSizeType());
15938   };
15939 
15940   // Apply conversion to row and column expressions.
15941   ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
15942   if (!RowsConv.isInvalid()) {
15943     RowsExpr = RowsConv.get();
15944     TheCall->setArg(1, RowsExpr);
15945   } else
15946     RowsExpr = nullptr;
15947 
15948   ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
15949   if (!ColumnsConv.isInvalid()) {
15950     ColumnsExpr = ColumnsConv.get();
15951     TheCall->setArg(2, ColumnsExpr);
15952   } else
15953     ColumnsExpr = nullptr;
15954 
15955   // If any any part of the result matrix type is still pending, just use
15956   // Context.DependentTy, until all parts are resolved.
15957   if ((RowsExpr && RowsExpr->isTypeDependent()) ||
15958       (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
15959     TheCall->setType(Context.DependentTy);
15960     return CallResult;
15961   }
15962 
15963   // Check row and column dimenions.
15964   llvm::Optional<unsigned> MaybeRows;
15965   if (RowsExpr)
15966     MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
15967 
15968   llvm::Optional<unsigned> MaybeColumns;
15969   if (ColumnsExpr)
15970     MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
15971 
15972   // Check stride argument.
15973   ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
15974   if (StrideConv.isInvalid())
15975     return ExprError();
15976   StrideExpr = StrideConv.get();
15977   TheCall->setArg(3, StrideExpr);
15978 
15979   if (MaybeRows) {
15980     if (Optional<llvm::APSInt> Value =
15981             StrideExpr->getIntegerConstantExpr(Context)) {
15982       uint64_t Stride = Value->getZExtValue();
15983       if (Stride < *MaybeRows) {
15984         Diag(StrideExpr->getBeginLoc(),
15985              diag::err_builtin_matrix_stride_too_small);
15986         ArgError = true;
15987       }
15988     }
15989   }
15990 
15991   if (ArgError || !MaybeRows || !MaybeColumns)
15992     return ExprError();
15993 
15994   TheCall->setType(
15995       Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
15996   return CallResult;
15997 }
15998 
15999 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
16000                                                    ExprResult CallResult) {
16001   if (checkArgCount(*this, TheCall, 3))
16002     return ExprError();
16003 
16004   unsigned PtrArgIdx = 1;
16005   Expr *MatrixExpr = TheCall->getArg(0);
16006   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16007   Expr *StrideExpr = TheCall->getArg(2);
16008 
16009   bool ArgError = false;
16010 
16011   {
16012     ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
16013     if (MatrixConv.isInvalid())
16014       return MatrixConv;
16015     MatrixExpr = MatrixConv.get();
16016     TheCall->setArg(0, MatrixExpr);
16017   }
16018   if (MatrixExpr->isTypeDependent()) {
16019     TheCall->setType(Context.DependentTy);
16020     return TheCall;
16021   }
16022 
16023   auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
16024   if (!MatrixTy) {
16025     Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_matrix_arg) << 0;
16026     ArgError = true;
16027   }
16028 
16029   {
16030     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
16031     if (PtrConv.isInvalid())
16032       return PtrConv;
16033     PtrExpr = PtrConv.get();
16034     TheCall->setArg(1, PtrExpr);
16035     if (PtrExpr->isTypeDependent()) {
16036       TheCall->setType(Context.DependentTy);
16037       return TheCall;
16038     }
16039   }
16040 
16041   // Check pointer argument.
16042   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16043   if (!PtrTy) {
16044     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
16045         << PtrArgIdx + 1;
16046     ArgError = true;
16047   } else {
16048     QualType ElementTy = PtrTy->getPointeeType();
16049     if (ElementTy.isConstQualified()) {
16050       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
16051       ArgError = true;
16052     }
16053     ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
16054     if (MatrixTy &&
16055         !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
16056       Diag(PtrExpr->getBeginLoc(),
16057            diag::err_builtin_matrix_pointer_arg_mismatch)
16058           << ElementTy << MatrixTy->getElementType();
16059       ArgError = true;
16060     }
16061   }
16062 
16063   // Apply default Lvalue conversions and convert the stride expression to
16064   // size_t.
16065   {
16066     ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
16067     if (StrideConv.isInvalid())
16068       return StrideConv;
16069 
16070     StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
16071     if (StrideConv.isInvalid())
16072       return StrideConv;
16073     StrideExpr = StrideConv.get();
16074     TheCall->setArg(2, StrideExpr);
16075   }
16076 
16077   // Check stride argument.
16078   if (MatrixTy) {
16079     if (Optional<llvm::APSInt> Value =
16080             StrideExpr->getIntegerConstantExpr(Context)) {
16081       uint64_t Stride = Value->getZExtValue();
16082       if (Stride < MatrixTy->getNumRows()) {
16083         Diag(StrideExpr->getBeginLoc(),
16084              diag::err_builtin_matrix_stride_too_small);
16085         ArgError = true;
16086       }
16087     }
16088   }
16089 
16090   if (ArgError)
16091     return ExprError();
16092 
16093   return CallResult;
16094 }
16095 
16096 /// \brief Enforce the bounds of a TCB
16097 /// CheckTCBEnforcement - Enforces that every function in a named TCB only
16098 /// directly calls other functions in the same TCB as marked by the enforce_tcb
16099 /// and enforce_tcb_leaf attributes.
16100 void Sema::CheckTCBEnforcement(const CallExpr *TheCall,
16101                                const FunctionDecl *Callee) {
16102   const FunctionDecl *Caller = getCurFunctionDecl();
16103 
16104   // Calls to builtins are not enforced.
16105   if (!Caller || !Caller->hasAttr<EnforceTCBAttr>() ||
16106       Callee->getBuiltinID() != 0)
16107     return;
16108 
16109   // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
16110   // all TCBs the callee is a part of.
16111   llvm::StringSet<> CalleeTCBs;
16112   for_each(Callee->specific_attrs<EnforceTCBAttr>(),
16113            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
16114   for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(),
16115            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
16116 
16117   // Go through the TCBs the caller is a part of and emit warnings if Caller
16118   // is in a TCB that the Callee is not.
16119   for_each(
16120       Caller->specific_attrs<EnforceTCBAttr>(),
16121       [&](const auto *A) {
16122         StringRef CallerTCB = A->getTCBName();
16123         if (CalleeTCBs.count(CallerTCB) == 0) {
16124           this->Diag(TheCall->getExprLoc(),
16125                      diag::warn_tcb_enforcement_violation) << Callee
16126                                                            << CallerTCB;
16127         }
16128       });
16129 }
16130