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 <cctype>
95 #include <cstddef>
96 #include <cstdint>
97 #include <functional>
98 #include <limits>
99 #include <string>
100 #include <tuple>
101 #include <utility>
102 
103 using namespace clang;
104 using namespace sema;
105 
106 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
107                                                     unsigned ByteNo) const {
108   return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
109                                Context.getTargetInfo());
110 }
111 
112 static constexpr unsigned short combineFAPK(Sema::FormatArgumentPassingKind A,
113                                             Sema::FormatArgumentPassingKind B) {
114   return (A << 8) | B;
115 }
116 
117 /// Checks that a call expression's argument count is at least the desired
118 /// number. This is useful when doing custom type-checking on a variadic
119 /// function. Returns true on error.
120 static bool checkArgCountAtLeast(Sema &S, CallExpr *Call,
121                                  unsigned MinArgCount) {
122   unsigned ArgCount = Call->getNumArgs();
123   if (ArgCount >= MinArgCount)
124     return false;
125 
126   return S.Diag(Call->getEndLoc(), diag::err_typecheck_call_too_few_args)
127          << 0 /*function call*/ << MinArgCount << ArgCount
128          << Call->getSourceRange();
129 }
130 
131 /// Checks that a call expression's argument count is the desired number.
132 /// This is useful when doing custom type-checking.  Returns true on error.
133 static bool checkArgCount(Sema &S, CallExpr *Call, unsigned DesiredArgCount) {
134   unsigned ArgCount = Call->getNumArgs();
135   if (ArgCount == DesiredArgCount)
136     return false;
137 
138   if (checkArgCountAtLeast(S, Call, DesiredArgCount))
139     return true;
140   assert(ArgCount > DesiredArgCount && "should have diagnosed this");
141 
142   // Highlight all the excess arguments.
143   SourceRange Range(Call->getArg(DesiredArgCount)->getBeginLoc(),
144                     Call->getArg(ArgCount - 1)->getEndLoc());
145 
146   return S.Diag(Range.getBegin(), diag::err_typecheck_call_too_many_args)
147          << 0 /*function call*/ << DesiredArgCount << ArgCount
148          << Call->getArg(1)->getSourceRange();
149 }
150 
151 /// Check that the first argument to __builtin_annotation is an integer
152 /// and the second argument is a non-wide string literal.
153 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
154   if (checkArgCount(S, TheCall, 2))
155     return true;
156 
157   // First argument should be an integer.
158   Expr *ValArg = TheCall->getArg(0);
159   QualType Ty = ValArg->getType();
160   if (!Ty->isIntegerType()) {
161     S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
162         << ValArg->getSourceRange();
163     return true;
164   }
165 
166   // Second argument should be a constant string.
167   Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
168   StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
169   if (!Literal || !Literal->isOrdinary()) {
170     S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
171         << StrArg->getSourceRange();
172     return true;
173   }
174 
175   TheCall->setType(Ty);
176   return false;
177 }
178 
179 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
180   // We need at least one argument.
181   if (TheCall->getNumArgs() < 1) {
182     S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
183         << 0 << 1 << TheCall->getNumArgs()
184         << TheCall->getCallee()->getSourceRange();
185     return true;
186   }
187 
188   // All arguments should be wide string literals.
189   for (Expr *Arg : TheCall->arguments()) {
190     auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
191     if (!Literal || !Literal->isWide()) {
192       S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
193           << Arg->getSourceRange();
194       return true;
195     }
196   }
197 
198   return false;
199 }
200 
201 /// Check that the argument to __builtin_addressof is a glvalue, and set the
202 /// result type to the corresponding pointer type.
203 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
204   if (checkArgCount(S, TheCall, 1))
205     return true;
206 
207   ExprResult Arg(TheCall->getArg(0));
208   QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
209   if (ResultType.isNull())
210     return true;
211 
212   TheCall->setArg(0, Arg.get());
213   TheCall->setType(ResultType);
214   return false;
215 }
216 
217 /// Check that the argument to __builtin_function_start is a function.
218 static bool SemaBuiltinFunctionStart(Sema &S, CallExpr *TheCall) {
219   if (checkArgCount(S, TheCall, 1))
220     return true;
221 
222   ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
223   if (Arg.isInvalid())
224     return true;
225 
226   TheCall->setArg(0, Arg.get());
227   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(
228       Arg.get()->getAsBuiltinConstantDeclRef(S.getASTContext()));
229 
230   if (!FD) {
231     S.Diag(TheCall->getBeginLoc(), diag::err_function_start_invalid_type)
232         << TheCall->getSourceRange();
233     return true;
234   }
235 
236   return !S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
237                                               TheCall->getBeginLoc());
238 }
239 
240 /// Check the number of arguments and set the result type to
241 /// the argument type.
242 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
243   if (checkArgCount(S, TheCall, 1))
244     return true;
245 
246   TheCall->setType(TheCall->getArg(0)->getType());
247   return false;
248 }
249 
250 /// Check that the value argument for __builtin_is_aligned(value, alignment) and
251 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
252 /// type (but not a function pointer) and that the alignment is a power-of-two.
253 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
254   if (checkArgCount(S, TheCall, 2))
255     return true;
256 
257   clang::Expr *Source = TheCall->getArg(0);
258   bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
259 
260   auto IsValidIntegerType = [](QualType Ty) {
261     return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
262   };
263   QualType SrcTy = Source->getType();
264   // We should also be able to use it with arrays (but not functions!).
265   if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
266     SrcTy = S.Context.getDecayedType(SrcTy);
267   }
268   if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
269       SrcTy->isFunctionPointerType()) {
270     // FIXME: this is not quite the right error message since we don't allow
271     // floating point types, or member pointers.
272     S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand)
273         << SrcTy;
274     return true;
275   }
276 
277   clang::Expr *AlignOp = TheCall->getArg(1);
278   if (!IsValidIntegerType(AlignOp->getType())) {
279     S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int)
280         << AlignOp->getType();
281     return true;
282   }
283   Expr::EvalResult AlignResult;
284   unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1;
285   // We can't check validity of alignment if it is value dependent.
286   if (!AlignOp->isValueDependent() &&
287       AlignOp->EvaluateAsInt(AlignResult, S.Context,
288                              Expr::SE_AllowSideEffects)) {
289     llvm::APSInt AlignValue = AlignResult.Val.getInt();
290     llvm::APSInt MaxValue(
291         llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits));
292     if (AlignValue < 1) {
293       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1;
294       return true;
295     }
296     if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) {
297       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big)
298           << toString(MaxValue, 10);
299       return true;
300     }
301     if (!AlignValue.isPowerOf2()) {
302       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two);
303       return true;
304     }
305     if (AlignValue == 1) {
306       S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless)
307           << IsBooleanAlignBuiltin;
308     }
309   }
310 
311   ExprResult SrcArg = S.PerformCopyInitialization(
312       InitializedEntity::InitializeParameter(S.Context, SrcTy, false),
313       SourceLocation(), Source);
314   if (SrcArg.isInvalid())
315     return true;
316   TheCall->setArg(0, SrcArg.get());
317   ExprResult AlignArg =
318       S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
319                                       S.Context, AlignOp->getType(), false),
320                                   SourceLocation(), AlignOp);
321   if (AlignArg.isInvalid())
322     return true;
323   TheCall->setArg(1, AlignArg.get());
324   // For align_up/align_down, the return type is the same as the (potentially
325   // decayed) argument type including qualifiers. For is_aligned(), the result
326   // is always bool.
327   TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
328   return false;
329 }
330 
331 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall,
332                                 unsigned BuiltinID) {
333   if (checkArgCount(S, TheCall, 3))
334     return true;
335 
336   // First two arguments should be integers.
337   for (unsigned I = 0; I < 2; ++I) {
338     ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I));
339     if (Arg.isInvalid()) return true;
340     TheCall->setArg(I, Arg.get());
341 
342     QualType Ty = Arg.get()->getType();
343     if (!Ty->isIntegerType()) {
344       S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
345           << Ty << Arg.get()->getSourceRange();
346       return true;
347     }
348   }
349 
350   // Third argument should be a pointer to a non-const integer.
351   // IRGen correctly handles volatile, restrict, and address spaces, and
352   // the other qualifiers aren't possible.
353   {
354     ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(2));
355     if (Arg.isInvalid()) return true;
356     TheCall->setArg(2, Arg.get());
357 
358     QualType Ty = Arg.get()->getType();
359     const auto *PtrTy = Ty->getAs<PointerType>();
360     if (!PtrTy ||
361         !PtrTy->getPointeeType()->isIntegerType() ||
362         PtrTy->getPointeeType().isConstQualified()) {
363       S.Diag(Arg.get()->getBeginLoc(),
364              diag::err_overflow_builtin_must_be_ptr_int)
365         << Ty << Arg.get()->getSourceRange();
366       return true;
367     }
368   }
369 
370   // Disallow signed bit-precise integer args larger than 128 bits to mul
371   // function until we improve backend support.
372   if (BuiltinID == Builtin::BI__builtin_mul_overflow) {
373     for (unsigned I = 0; I < 3; ++I) {
374       const auto Arg = TheCall->getArg(I);
375       // Third argument will be a pointer.
376       auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType();
377       if (Ty->isBitIntType() && Ty->isSignedIntegerType() &&
378           S.getASTContext().getIntWidth(Ty) > 128)
379         return S.Diag(Arg->getBeginLoc(),
380                       diag::err_overflow_builtin_bit_int_max_size)
381                << 128;
382     }
383   }
384 
385   return false;
386 }
387 
388 namespace {
389 struct BuiltinDumpStructGenerator {
390   Sema &S;
391   CallExpr *TheCall;
392   SourceLocation Loc = TheCall->getBeginLoc();
393   SmallVector<Expr *, 32> Actions;
394   DiagnosticErrorTrap ErrorTracker;
395   PrintingPolicy Policy;
396 
397   BuiltinDumpStructGenerator(Sema &S, CallExpr *TheCall)
398       : S(S), TheCall(TheCall), ErrorTracker(S.getDiagnostics()),
399         Policy(S.Context.getPrintingPolicy()) {
400     Policy.AnonymousTagLocations = false;
401   }
402 
403   Expr *makeOpaqueValueExpr(Expr *Inner) {
404     auto *OVE = new (S.Context)
405         OpaqueValueExpr(Loc, Inner->getType(), Inner->getValueKind(),
406                         Inner->getObjectKind(), Inner);
407     Actions.push_back(OVE);
408     return OVE;
409   }
410 
411   Expr *getStringLiteral(llvm::StringRef Str) {
412     Expr *Lit = S.Context.getPredefinedStringLiteralFromCache(Str);
413     // Wrap the literal in parentheses to attach a source location.
414     return new (S.Context) ParenExpr(Loc, Loc, Lit);
415   }
416 
417   bool callPrintFunction(llvm::StringRef Format,
418                          llvm::ArrayRef<Expr *> Exprs = {}) {
419     SmallVector<Expr *, 8> Args;
420     assert(TheCall->getNumArgs() >= 2);
421     Args.reserve((TheCall->getNumArgs() - 2) + /*Format*/ 1 + Exprs.size());
422     Args.assign(TheCall->arg_begin() + 2, TheCall->arg_end());
423     Args.push_back(getStringLiteral(Format));
424     Args.insert(Args.end(), Exprs.begin(), Exprs.end());
425 
426     // Register a note to explain why we're performing the call.
427     Sema::CodeSynthesisContext Ctx;
428     Ctx.Kind = Sema::CodeSynthesisContext::BuildingBuiltinDumpStructCall;
429     Ctx.PointOfInstantiation = Loc;
430     Ctx.CallArgs = Args.data();
431     Ctx.NumCallArgs = Args.size();
432     S.pushCodeSynthesisContext(Ctx);
433 
434     ExprResult RealCall =
435         S.BuildCallExpr(/*Scope=*/nullptr, TheCall->getArg(1),
436                         TheCall->getBeginLoc(), Args, TheCall->getRParenLoc());
437 
438     S.popCodeSynthesisContext();
439     if (!RealCall.isInvalid())
440       Actions.push_back(RealCall.get());
441     // Bail out if we've hit any errors, even if we managed to build the
442     // call. We don't want to produce more than one error.
443     return RealCall.isInvalid() || ErrorTracker.hasErrorOccurred();
444   }
445 
446   Expr *getIndentString(unsigned Depth) {
447     if (!Depth)
448       return nullptr;
449 
450     llvm::SmallString<32> Indent;
451     Indent.resize(Depth * Policy.Indentation, ' ');
452     return getStringLiteral(Indent);
453   }
454 
455   Expr *getTypeString(QualType T) {
456     return getStringLiteral(T.getAsString(Policy));
457   }
458 
459   bool appendFormatSpecifier(QualType T, llvm::SmallVectorImpl<char> &Str) {
460     llvm::raw_svector_ostream OS(Str);
461 
462     // Format 'bool', 'char', 'signed char', 'unsigned char' as numbers, rather
463     // than trying to print a single character.
464     if (auto *BT = T->getAs<BuiltinType>()) {
465       switch (BT->getKind()) {
466       case BuiltinType::Bool:
467         OS << "%d";
468         return true;
469       case BuiltinType::Char_U:
470       case BuiltinType::UChar:
471         OS << "%hhu";
472         return true;
473       case BuiltinType::Char_S:
474       case BuiltinType::SChar:
475         OS << "%hhd";
476         return true;
477       default:
478         break;
479       }
480     }
481 
482     analyze_printf::PrintfSpecifier Specifier;
483     if (Specifier.fixType(T, S.getLangOpts(), S.Context, /*IsObjCLiteral=*/false)) {
484       // We were able to guess how to format this.
485       if (Specifier.getConversionSpecifier().getKind() ==
486           analyze_printf::PrintfConversionSpecifier::sArg) {
487         // Wrap double-quotes around a '%s' specifier and limit its maximum
488         // length. Ideally we'd also somehow escape special characters in the
489         // contents but printf doesn't support that.
490         // FIXME: '%s' formatting is not safe in general.
491         OS << '"';
492         Specifier.setPrecision(analyze_printf::OptionalAmount(32u));
493         Specifier.toString(OS);
494         OS << '"';
495         // FIXME: It would be nice to include a '...' if the string doesn't fit
496         // in the length limit.
497       } else {
498         Specifier.toString(OS);
499       }
500       return true;
501     }
502 
503     if (T->isPointerType()) {
504       // Format all pointers with '%p'.
505       OS << "%p";
506       return true;
507     }
508 
509     return false;
510   }
511 
512   bool dumpUnnamedRecord(const RecordDecl *RD, Expr *E, unsigned Depth) {
513     Expr *IndentLit = getIndentString(Depth);
514     Expr *TypeLit = getTypeString(S.Context.getRecordType(RD));
515     if (IndentLit ? callPrintFunction("%s%s", {IndentLit, TypeLit})
516                   : callPrintFunction("%s", {TypeLit}))
517       return true;
518 
519     return dumpRecordValue(RD, E, IndentLit, Depth);
520   }
521 
522   // Dump a record value. E should be a pointer or lvalue referring to an RD.
523   bool dumpRecordValue(const RecordDecl *RD, Expr *E, Expr *RecordIndent,
524                        unsigned Depth) {
525     // FIXME: Decide what to do if RD is a union. At least we should probably
526     // turn off printing `const char*` members with `%s`, because that is very
527     // likely to crash if that's not the active member. Whatever we decide, we
528     // should document it.
529 
530     // Build an OpaqueValueExpr so we can refer to E more than once without
531     // triggering re-evaluation.
532     Expr *RecordArg = makeOpaqueValueExpr(E);
533     bool RecordArgIsPtr = RecordArg->getType()->isPointerType();
534 
535     if (callPrintFunction(" {\n"))
536       return true;
537 
538     // Dump each base class, regardless of whether they're aggregates.
539     if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
540       for (const auto &Base : CXXRD->bases()) {
541         QualType BaseType =
542             RecordArgIsPtr ? S.Context.getPointerType(Base.getType())
543                            : S.Context.getLValueReferenceType(Base.getType());
544         ExprResult BasePtr = S.BuildCStyleCastExpr(
545             Loc, S.Context.getTrivialTypeSourceInfo(BaseType, Loc), Loc,
546             RecordArg);
547         if (BasePtr.isInvalid() ||
548             dumpUnnamedRecord(Base.getType()->getAsRecordDecl(), BasePtr.get(),
549                               Depth + 1))
550           return true;
551       }
552     }
553 
554     Expr *FieldIndentArg = getIndentString(Depth + 1);
555 
556     // Dump each field.
557     for (auto *D : RD->decls()) {
558       auto *IFD = dyn_cast<IndirectFieldDecl>(D);
559       auto *FD = IFD ? IFD->getAnonField() : dyn_cast<FieldDecl>(D);
560       if (!FD || FD->isUnnamedBitfield() || FD->isAnonymousStructOrUnion())
561         continue;
562 
563       llvm::SmallString<20> Format = llvm::StringRef("%s%s %s ");
564       llvm::SmallVector<Expr *, 5> Args = {FieldIndentArg,
565                                            getTypeString(FD->getType()),
566                                            getStringLiteral(FD->getName())};
567 
568       if (FD->isBitField()) {
569         Format += ": %zu ";
570         QualType SizeT = S.Context.getSizeType();
571         llvm::APInt BitWidth(S.Context.getIntWidth(SizeT),
572                              FD->getBitWidthValue(S.Context));
573         Args.push_back(IntegerLiteral::Create(S.Context, BitWidth, SizeT, Loc));
574       }
575 
576       Format += "=";
577 
578       ExprResult Field =
579           IFD ? S.BuildAnonymousStructUnionMemberReference(
580                     CXXScopeSpec(), Loc, IFD,
581                     DeclAccessPair::make(IFD, AS_public), RecordArg, Loc)
582               : S.BuildFieldReferenceExpr(
583                     RecordArg, RecordArgIsPtr, Loc, CXXScopeSpec(), FD,
584                     DeclAccessPair::make(FD, AS_public),
585                     DeclarationNameInfo(FD->getDeclName(), Loc));
586       if (Field.isInvalid())
587         return true;
588 
589       auto *InnerRD = FD->getType()->getAsRecordDecl();
590       auto *InnerCXXRD = dyn_cast_or_null<CXXRecordDecl>(InnerRD);
591       if (InnerRD && (!InnerCXXRD || InnerCXXRD->isAggregate())) {
592         // Recursively print the values of members of aggregate record type.
593         if (callPrintFunction(Format, Args) ||
594             dumpRecordValue(InnerRD, Field.get(), FieldIndentArg, Depth + 1))
595           return true;
596       } else {
597         Format += " ";
598         if (appendFormatSpecifier(FD->getType(), Format)) {
599           // We know how to print this field.
600           Args.push_back(Field.get());
601         } else {
602           // We don't know how to print this field. Print out its address
603           // with a format specifier that a smart tool will be able to
604           // recognize and treat specially.
605           Format += "*%p";
606           ExprResult FieldAddr =
607               S.BuildUnaryOp(nullptr, Loc, UO_AddrOf, Field.get());
608           if (FieldAddr.isInvalid())
609             return true;
610           Args.push_back(FieldAddr.get());
611         }
612         Format += "\n";
613         if (callPrintFunction(Format, Args))
614           return true;
615       }
616     }
617 
618     return RecordIndent ? callPrintFunction("%s}\n", RecordIndent)
619                         : callPrintFunction("}\n");
620   }
621 
622   Expr *buildWrapper() {
623     auto *Wrapper = PseudoObjectExpr::Create(S.Context, TheCall, Actions,
624                                              PseudoObjectExpr::NoResult);
625     TheCall->setType(Wrapper->getType());
626     TheCall->setValueKind(Wrapper->getValueKind());
627     return Wrapper;
628   }
629 };
630 } // namespace
631 
632 static ExprResult SemaBuiltinDumpStruct(Sema &S, CallExpr *TheCall) {
633   if (checkArgCountAtLeast(S, TheCall, 2))
634     return ExprError();
635 
636   ExprResult PtrArgResult = S.DefaultLvalueConversion(TheCall->getArg(0));
637   if (PtrArgResult.isInvalid())
638     return ExprError();
639   TheCall->setArg(0, PtrArgResult.get());
640 
641   // First argument should be a pointer to a struct.
642   QualType PtrArgType = PtrArgResult.get()->getType();
643   if (!PtrArgType->isPointerType() ||
644       !PtrArgType->getPointeeType()->isRecordType()) {
645     S.Diag(PtrArgResult.get()->getBeginLoc(),
646            diag::err_expected_struct_pointer_argument)
647         << 1 << TheCall->getDirectCallee() << PtrArgType;
648     return ExprError();
649   }
650   const RecordDecl *RD = PtrArgType->getPointeeType()->getAsRecordDecl();
651 
652   // Second argument is a callable, but we can't fully validate it until we try
653   // calling it.
654   QualType FnArgType = TheCall->getArg(1)->getType();
655   if (!FnArgType->isFunctionType() && !FnArgType->isFunctionPointerType() &&
656       !FnArgType->isBlockPointerType() &&
657       !(S.getLangOpts().CPlusPlus && FnArgType->isRecordType())) {
658     auto *BT = FnArgType->getAs<BuiltinType>();
659     switch (BT ? BT->getKind() : BuiltinType::Void) {
660     case BuiltinType::Dependent:
661     case BuiltinType::Overload:
662     case BuiltinType::BoundMember:
663     case BuiltinType::PseudoObject:
664     case BuiltinType::UnknownAny:
665     case BuiltinType::BuiltinFn:
666       // This might be a callable.
667       break;
668 
669     default:
670       S.Diag(TheCall->getArg(1)->getBeginLoc(),
671              diag::err_expected_callable_argument)
672           << 2 << TheCall->getDirectCallee() << FnArgType;
673       return ExprError();
674     }
675   }
676 
677   BuiltinDumpStructGenerator Generator(S, TheCall);
678 
679   // Wrap parentheses around the given pointer. This is not necessary for
680   // correct code generation, but it means that when we pretty-print the call
681   // arguments in our diagnostics we will produce '(&s)->n' instead of the
682   // incorrect '&s->n'.
683   Expr *PtrArg = PtrArgResult.get();
684   PtrArg = new (S.Context)
685       ParenExpr(PtrArg->getBeginLoc(),
686                 S.getLocForEndOfToken(PtrArg->getEndLoc()), PtrArg);
687   if (Generator.dumpUnnamedRecord(RD, PtrArg, 0))
688     return ExprError();
689 
690   return Generator.buildWrapper();
691 }
692 
693 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
694   if (checkArgCount(S, BuiltinCall, 2))
695     return true;
696 
697   SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
698   Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
699   Expr *Call = BuiltinCall->getArg(0);
700   Expr *Chain = BuiltinCall->getArg(1);
701 
702   if (Call->getStmtClass() != Stmt::CallExprClass) {
703     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
704         << Call->getSourceRange();
705     return true;
706   }
707 
708   auto CE = cast<CallExpr>(Call);
709   if (CE->getCallee()->getType()->isBlockPointerType()) {
710     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
711         << Call->getSourceRange();
712     return true;
713   }
714 
715   const Decl *TargetDecl = CE->getCalleeDecl();
716   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
717     if (FD->getBuiltinID()) {
718       S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
719           << Call->getSourceRange();
720       return true;
721     }
722 
723   if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
724     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
725         << Call->getSourceRange();
726     return true;
727   }
728 
729   ExprResult ChainResult = S.UsualUnaryConversions(Chain);
730   if (ChainResult.isInvalid())
731     return true;
732   if (!ChainResult.get()->getType()->isPointerType()) {
733     S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
734         << Chain->getSourceRange();
735     return true;
736   }
737 
738   QualType ReturnTy = CE->getCallReturnType(S.Context);
739   QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
740   QualType BuiltinTy = S.Context.getFunctionType(
741       ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
742   QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
743 
744   Builtin =
745       S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
746 
747   BuiltinCall->setType(CE->getType());
748   BuiltinCall->setValueKind(CE->getValueKind());
749   BuiltinCall->setObjectKind(CE->getObjectKind());
750   BuiltinCall->setCallee(Builtin);
751   BuiltinCall->setArg(1, ChainResult.get());
752 
753   return false;
754 }
755 
756 namespace {
757 
758 class ScanfDiagnosticFormatHandler
759     : public analyze_format_string::FormatStringHandler {
760   // Accepts the argument index (relative to the first destination index) of the
761   // argument whose size we want.
762   using ComputeSizeFunction =
763       llvm::function_ref<Optional<llvm::APSInt>(unsigned)>;
764 
765   // Accepts the argument index (relative to the first destination index), the
766   // destination size, and the source size).
767   using DiagnoseFunction =
768       llvm::function_ref<void(unsigned, unsigned, unsigned)>;
769 
770   ComputeSizeFunction ComputeSizeArgument;
771   DiagnoseFunction Diagnose;
772 
773 public:
774   ScanfDiagnosticFormatHandler(ComputeSizeFunction ComputeSizeArgument,
775                                DiagnoseFunction Diagnose)
776       : ComputeSizeArgument(ComputeSizeArgument), Diagnose(Diagnose) {}
777 
778   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
779                             const char *StartSpecifier,
780                             unsigned specifierLen) override {
781     if (!FS.consumesDataArgument())
782       return true;
783 
784     unsigned NulByte = 0;
785     switch ((FS.getConversionSpecifier().getKind())) {
786     default:
787       return true;
788     case analyze_format_string::ConversionSpecifier::sArg:
789     case analyze_format_string::ConversionSpecifier::ScanListArg:
790       NulByte = 1;
791       break;
792     case analyze_format_string::ConversionSpecifier::cArg:
793       break;
794     }
795 
796     analyze_format_string::OptionalAmount FW = FS.getFieldWidth();
797     if (FW.getHowSpecified() !=
798         analyze_format_string::OptionalAmount::HowSpecified::Constant)
799       return true;
800 
801     unsigned SourceSize = FW.getConstantAmount() + NulByte;
802 
803     Optional<llvm::APSInt> DestSizeAPS = ComputeSizeArgument(FS.getArgIndex());
804     if (!DestSizeAPS)
805       return true;
806 
807     unsigned DestSize = DestSizeAPS->getZExtValue();
808 
809     if (DestSize < SourceSize)
810       Diagnose(FS.getArgIndex(), DestSize, SourceSize);
811 
812     return true;
813   }
814 };
815 
816 class EstimateSizeFormatHandler
817     : public analyze_format_string::FormatStringHandler {
818   size_t Size;
819 
820 public:
821   EstimateSizeFormatHandler(StringRef Format)
822       : Size(std::min(Format.find(0), Format.size()) +
823              1 /* null byte always written by sprintf */) {}
824 
825   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
826                              const char *, unsigned SpecifierLen,
827                              const TargetInfo &) override {
828 
829     const size_t FieldWidth = computeFieldWidth(FS);
830     const size_t Precision = computePrecision(FS);
831 
832     // The actual format.
833     switch (FS.getConversionSpecifier().getKind()) {
834     // Just a char.
835     case analyze_format_string::ConversionSpecifier::cArg:
836     case analyze_format_string::ConversionSpecifier::CArg:
837       Size += std::max(FieldWidth, (size_t)1);
838       break;
839     // Just an integer.
840     case analyze_format_string::ConversionSpecifier::dArg:
841     case analyze_format_string::ConversionSpecifier::DArg:
842     case analyze_format_string::ConversionSpecifier::iArg:
843     case analyze_format_string::ConversionSpecifier::oArg:
844     case analyze_format_string::ConversionSpecifier::OArg:
845     case analyze_format_string::ConversionSpecifier::uArg:
846     case analyze_format_string::ConversionSpecifier::UArg:
847     case analyze_format_string::ConversionSpecifier::xArg:
848     case analyze_format_string::ConversionSpecifier::XArg:
849       Size += std::max(FieldWidth, Precision);
850       break;
851 
852     // %g style conversion switches between %f or %e style dynamically.
853     // %f always takes less space, so default to it.
854     case analyze_format_string::ConversionSpecifier::gArg:
855     case analyze_format_string::ConversionSpecifier::GArg:
856 
857     // Floating point number in the form '[+]ddd.ddd'.
858     case analyze_format_string::ConversionSpecifier::fArg:
859     case analyze_format_string::ConversionSpecifier::FArg:
860       Size += std::max(FieldWidth, 1 /* integer part */ +
861                                        (Precision ? 1 + Precision
862                                                   : 0) /* period + decimal */);
863       break;
864 
865     // Floating point number in the form '[-]d.ddde[+-]dd'.
866     case analyze_format_string::ConversionSpecifier::eArg:
867     case analyze_format_string::ConversionSpecifier::EArg:
868       Size +=
869           std::max(FieldWidth,
870                    1 /* integer part */ +
871                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
872                        1 /* e or E letter */ + 2 /* exponent */);
873       break;
874 
875     // Floating point number in the form '[-]0xh.hhhhp±dd'.
876     case analyze_format_string::ConversionSpecifier::aArg:
877     case analyze_format_string::ConversionSpecifier::AArg:
878       Size +=
879           std::max(FieldWidth,
880                    2 /* 0x */ + 1 /* integer part */ +
881                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
882                        1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
883       break;
884 
885     // Just a string.
886     case analyze_format_string::ConversionSpecifier::sArg:
887     case analyze_format_string::ConversionSpecifier::SArg:
888       Size += FieldWidth;
889       break;
890 
891     // Just a pointer in the form '0xddd'.
892     case analyze_format_string::ConversionSpecifier::pArg:
893       Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
894       break;
895 
896     // A plain percent.
897     case analyze_format_string::ConversionSpecifier::PercentArg:
898       Size += 1;
899       break;
900 
901     default:
902       break;
903     }
904 
905     Size += FS.hasPlusPrefix() || FS.hasSpacePrefix();
906 
907     if (FS.hasAlternativeForm()) {
908       switch (FS.getConversionSpecifier().getKind()) {
909       default:
910         break;
911       // Force a leading '0'.
912       case analyze_format_string::ConversionSpecifier::oArg:
913         Size += 1;
914         break;
915       // Force a leading '0x'.
916       case analyze_format_string::ConversionSpecifier::xArg:
917       case analyze_format_string::ConversionSpecifier::XArg:
918         Size += 2;
919         break;
920       // Force a period '.' before decimal, even if precision is 0.
921       case analyze_format_string::ConversionSpecifier::aArg:
922       case analyze_format_string::ConversionSpecifier::AArg:
923       case analyze_format_string::ConversionSpecifier::eArg:
924       case analyze_format_string::ConversionSpecifier::EArg:
925       case analyze_format_string::ConversionSpecifier::fArg:
926       case analyze_format_string::ConversionSpecifier::FArg:
927       case analyze_format_string::ConversionSpecifier::gArg:
928       case analyze_format_string::ConversionSpecifier::GArg:
929         Size += (Precision ? 0 : 1);
930         break;
931       }
932     }
933     assert(SpecifierLen <= Size && "no underflow");
934     Size -= SpecifierLen;
935     return true;
936   }
937 
938   size_t getSizeLowerBound() const { return Size; }
939 
940 private:
941   static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
942     const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
943     size_t FieldWidth = 0;
944     if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant)
945       FieldWidth = FW.getConstantAmount();
946     return FieldWidth;
947   }
948 
949   static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
950     const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
951     size_t Precision = 0;
952 
953     // See man 3 printf for default precision value based on the specifier.
954     switch (FW.getHowSpecified()) {
955     case analyze_format_string::OptionalAmount::NotSpecified:
956       switch (FS.getConversionSpecifier().getKind()) {
957       default:
958         break;
959       case analyze_format_string::ConversionSpecifier::dArg: // %d
960       case analyze_format_string::ConversionSpecifier::DArg: // %D
961       case analyze_format_string::ConversionSpecifier::iArg: // %i
962         Precision = 1;
963         break;
964       case analyze_format_string::ConversionSpecifier::oArg: // %d
965       case analyze_format_string::ConversionSpecifier::OArg: // %D
966       case analyze_format_string::ConversionSpecifier::uArg: // %d
967       case analyze_format_string::ConversionSpecifier::UArg: // %D
968       case analyze_format_string::ConversionSpecifier::xArg: // %d
969       case analyze_format_string::ConversionSpecifier::XArg: // %D
970         Precision = 1;
971         break;
972       case analyze_format_string::ConversionSpecifier::fArg: // %f
973       case analyze_format_string::ConversionSpecifier::FArg: // %F
974       case analyze_format_string::ConversionSpecifier::eArg: // %e
975       case analyze_format_string::ConversionSpecifier::EArg: // %E
976       case analyze_format_string::ConversionSpecifier::gArg: // %g
977       case analyze_format_string::ConversionSpecifier::GArg: // %G
978         Precision = 6;
979         break;
980       case analyze_format_string::ConversionSpecifier::pArg: // %d
981         Precision = 1;
982         break;
983       }
984       break;
985     case analyze_format_string::OptionalAmount::Constant:
986       Precision = FW.getConstantAmount();
987       break;
988     default:
989       break;
990     }
991     return Precision;
992   }
993 };
994 
995 } // namespace
996 
997 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
998                                                CallExpr *TheCall) {
999   if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
1000       isConstantEvaluated())
1001     return;
1002 
1003   bool UseDABAttr = false;
1004   const FunctionDecl *UseDecl = FD;
1005 
1006   const auto *DABAttr = FD->getAttr<DiagnoseAsBuiltinAttr>();
1007   if (DABAttr) {
1008     UseDecl = DABAttr->getFunction();
1009     assert(UseDecl && "Missing FunctionDecl in DiagnoseAsBuiltin attribute!");
1010     UseDABAttr = true;
1011   }
1012 
1013   unsigned BuiltinID = UseDecl->getBuiltinID(/*ConsiderWrappers=*/true);
1014 
1015   if (!BuiltinID)
1016     return;
1017 
1018   const TargetInfo &TI = getASTContext().getTargetInfo();
1019   unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
1020 
1021   auto TranslateIndex = [&](unsigned Index) -> Optional<unsigned> {
1022     // If we refer to a diagnose_as_builtin attribute, we need to change the
1023     // argument index to refer to the arguments of the called function. Unless
1024     // the index is out of bounds, which presumably means it's a variadic
1025     // function.
1026     if (!UseDABAttr)
1027       return Index;
1028     unsigned DABIndices = DABAttr->argIndices_size();
1029     unsigned NewIndex = Index < DABIndices
1030                             ? DABAttr->argIndices_begin()[Index]
1031                             : Index - DABIndices + FD->getNumParams();
1032     if (NewIndex >= TheCall->getNumArgs())
1033       return llvm::None;
1034     return NewIndex;
1035   };
1036 
1037   auto ComputeExplicitObjectSizeArgument =
1038       [&](unsigned Index) -> Optional<llvm::APSInt> {
1039     Optional<unsigned> IndexOptional = TranslateIndex(Index);
1040     if (!IndexOptional)
1041       return llvm::None;
1042     unsigned NewIndex = *IndexOptional;
1043     Expr::EvalResult Result;
1044     Expr *SizeArg = TheCall->getArg(NewIndex);
1045     if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
1046       return llvm::None;
1047     llvm::APSInt Integer = Result.Val.getInt();
1048     Integer.setIsUnsigned(true);
1049     return Integer;
1050   };
1051 
1052   auto ComputeSizeArgument = [&](unsigned Index) -> Optional<llvm::APSInt> {
1053     // If the parameter has a pass_object_size attribute, then we should use its
1054     // (potentially) more strict checking mode. Otherwise, conservatively assume
1055     // type 0.
1056     int BOSType = 0;
1057     // This check can fail for variadic functions.
1058     if (Index < FD->getNumParams()) {
1059       if (const auto *POS =
1060               FD->getParamDecl(Index)->getAttr<PassObjectSizeAttr>())
1061         BOSType = POS->getType();
1062     }
1063 
1064     Optional<unsigned> IndexOptional = TranslateIndex(Index);
1065     if (!IndexOptional)
1066       return llvm::None;
1067     unsigned NewIndex = *IndexOptional;
1068 
1069     const Expr *ObjArg = TheCall->getArg(NewIndex);
1070     uint64_t Result;
1071     if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
1072       return llvm::None;
1073 
1074     // Get the object size in the target's size_t width.
1075     return llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
1076   };
1077 
1078   auto ComputeStrLenArgument = [&](unsigned Index) -> Optional<llvm::APSInt> {
1079     Optional<unsigned> IndexOptional = TranslateIndex(Index);
1080     if (!IndexOptional)
1081       return llvm::None;
1082     unsigned NewIndex = *IndexOptional;
1083 
1084     const Expr *ObjArg = TheCall->getArg(NewIndex);
1085     uint64_t Result;
1086     if (!ObjArg->tryEvaluateStrLen(Result, getASTContext()))
1087       return llvm::None;
1088     // Add 1 for null byte.
1089     return llvm::APSInt::getUnsigned(Result + 1).extOrTrunc(SizeTypeWidth);
1090   };
1091 
1092   Optional<llvm::APSInt> SourceSize;
1093   Optional<llvm::APSInt> DestinationSize;
1094   unsigned DiagID = 0;
1095   bool IsChkVariant = false;
1096 
1097   auto GetFunctionName = [&]() {
1098     StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
1099     // Skim off the details of whichever builtin was called to produce a better
1100     // diagnostic, as it's unlikely that the user wrote the __builtin
1101     // explicitly.
1102     if (IsChkVariant) {
1103       FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
1104       FunctionName = FunctionName.drop_back(std::strlen("_chk"));
1105     } else if (FunctionName.startswith("__builtin_")) {
1106       FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
1107     }
1108     return FunctionName;
1109   };
1110 
1111   switch (BuiltinID) {
1112   default:
1113     return;
1114   case Builtin::BI__builtin_strcpy:
1115   case Builtin::BIstrcpy: {
1116     DiagID = diag::warn_fortify_strlen_overflow;
1117     SourceSize = ComputeStrLenArgument(1);
1118     DestinationSize = ComputeSizeArgument(0);
1119     break;
1120   }
1121 
1122   case Builtin::BI__builtin___strcpy_chk: {
1123     DiagID = diag::warn_fortify_strlen_overflow;
1124     SourceSize = ComputeStrLenArgument(1);
1125     DestinationSize = ComputeExplicitObjectSizeArgument(2);
1126     IsChkVariant = true;
1127     break;
1128   }
1129 
1130   case Builtin::BIscanf:
1131   case Builtin::BIfscanf:
1132   case Builtin::BIsscanf: {
1133     unsigned FormatIndex = 1;
1134     unsigned DataIndex = 2;
1135     if (BuiltinID == Builtin::BIscanf) {
1136       FormatIndex = 0;
1137       DataIndex = 1;
1138     }
1139 
1140     const auto *FormatExpr =
1141         TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
1142 
1143     const auto *Format = dyn_cast<StringLiteral>(FormatExpr);
1144     if (!Format)
1145       return;
1146 
1147     if (!Format->isOrdinary() && !Format->isUTF8())
1148       return;
1149 
1150     auto Diagnose = [&](unsigned ArgIndex, unsigned DestSize,
1151                         unsigned SourceSize) {
1152       DiagID = diag::warn_fortify_scanf_overflow;
1153       unsigned Index = ArgIndex + DataIndex;
1154       StringRef FunctionName = GetFunctionName();
1155       DiagRuntimeBehavior(TheCall->getArg(Index)->getBeginLoc(), TheCall,
1156                           PDiag(DiagID) << FunctionName << (Index + 1)
1157                                         << DestSize << SourceSize);
1158     };
1159 
1160     StringRef FormatStrRef = Format->getString();
1161     auto ShiftedComputeSizeArgument = [&](unsigned Index) {
1162       return ComputeSizeArgument(Index + DataIndex);
1163     };
1164     ScanfDiagnosticFormatHandler H(ShiftedComputeSizeArgument, Diagnose);
1165     const char *FormatBytes = FormatStrRef.data();
1166     const ConstantArrayType *T =
1167         Context.getAsConstantArrayType(Format->getType());
1168     assert(T && "String literal not of constant array type!");
1169     size_t TypeSize = T->getSize().getZExtValue();
1170 
1171     // In case there's a null byte somewhere.
1172     size_t StrLen =
1173         std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
1174 
1175     analyze_format_string::ParseScanfString(H, FormatBytes,
1176                                             FormatBytes + StrLen, getLangOpts(),
1177                                             Context.getTargetInfo());
1178 
1179     // Unlike the other cases, in this one we have already issued the diagnostic
1180     // here, so no need to continue (because unlike the other cases, here the
1181     // diagnostic refers to the argument number).
1182     return;
1183   }
1184 
1185   case Builtin::BIsprintf:
1186   case Builtin::BI__builtin___sprintf_chk: {
1187     size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
1188     auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
1189 
1190     if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) {
1191 
1192       if (!Format->isOrdinary() && !Format->isUTF8())
1193         return;
1194 
1195       StringRef FormatStrRef = Format->getString();
1196       EstimateSizeFormatHandler H(FormatStrRef);
1197       const char *FormatBytes = FormatStrRef.data();
1198       const ConstantArrayType *T =
1199           Context.getAsConstantArrayType(Format->getType());
1200       assert(T && "String literal not of constant array type!");
1201       size_t TypeSize = T->getSize().getZExtValue();
1202 
1203       // In case there's a null byte somewhere.
1204       size_t StrLen =
1205           std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
1206       if (!analyze_format_string::ParsePrintfString(
1207               H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
1208               Context.getTargetInfo(), false)) {
1209         DiagID = diag::warn_fortify_source_format_overflow;
1210         SourceSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
1211                          .extOrTrunc(SizeTypeWidth);
1212         if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
1213           DestinationSize = ComputeExplicitObjectSizeArgument(2);
1214           IsChkVariant = true;
1215         } else {
1216           DestinationSize = ComputeSizeArgument(0);
1217         }
1218         break;
1219       }
1220     }
1221     return;
1222   }
1223   case Builtin::BI__builtin___memcpy_chk:
1224   case Builtin::BI__builtin___memmove_chk:
1225   case Builtin::BI__builtin___memset_chk:
1226   case Builtin::BI__builtin___strlcat_chk:
1227   case Builtin::BI__builtin___strlcpy_chk:
1228   case Builtin::BI__builtin___strncat_chk:
1229   case Builtin::BI__builtin___strncpy_chk:
1230   case Builtin::BI__builtin___stpncpy_chk:
1231   case Builtin::BI__builtin___memccpy_chk:
1232   case Builtin::BI__builtin___mempcpy_chk: {
1233     DiagID = diag::warn_builtin_chk_overflow;
1234     SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 2);
1235     DestinationSize =
1236         ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1237     IsChkVariant = true;
1238     break;
1239   }
1240 
1241   case Builtin::BI__builtin___snprintf_chk:
1242   case Builtin::BI__builtin___vsnprintf_chk: {
1243     DiagID = diag::warn_builtin_chk_overflow;
1244     SourceSize = ComputeExplicitObjectSizeArgument(1);
1245     DestinationSize = ComputeExplicitObjectSizeArgument(3);
1246     IsChkVariant = true;
1247     break;
1248   }
1249 
1250   case Builtin::BIstrncat:
1251   case Builtin::BI__builtin_strncat:
1252   case Builtin::BIstrncpy:
1253   case Builtin::BI__builtin_strncpy:
1254   case Builtin::BIstpncpy:
1255   case Builtin::BI__builtin_stpncpy: {
1256     // Whether these functions overflow depends on the runtime strlen of the
1257     // string, not just the buffer size, so emitting the "always overflow"
1258     // diagnostic isn't quite right. We should still diagnose passing a buffer
1259     // size larger than the destination buffer though; this is a runtime abort
1260     // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
1261     DiagID = diag::warn_fortify_source_size_mismatch;
1262     SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1263     DestinationSize = ComputeSizeArgument(0);
1264     break;
1265   }
1266 
1267   case Builtin::BImemcpy:
1268   case Builtin::BI__builtin_memcpy:
1269   case Builtin::BImemmove:
1270   case Builtin::BI__builtin_memmove:
1271   case Builtin::BImemset:
1272   case Builtin::BI__builtin_memset:
1273   case Builtin::BImempcpy:
1274   case Builtin::BI__builtin_mempcpy: {
1275     DiagID = diag::warn_fortify_source_overflow;
1276     SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1277     DestinationSize = ComputeSizeArgument(0);
1278     break;
1279   }
1280   case Builtin::BIsnprintf:
1281   case Builtin::BI__builtin_snprintf:
1282   case Builtin::BIvsnprintf:
1283   case Builtin::BI__builtin_vsnprintf: {
1284     DiagID = diag::warn_fortify_source_size_mismatch;
1285     SourceSize = ComputeExplicitObjectSizeArgument(1);
1286     DestinationSize = ComputeSizeArgument(0);
1287     break;
1288   }
1289   }
1290 
1291   if (!SourceSize || !DestinationSize ||
1292       llvm::APSInt::compareValues(*SourceSize, *DestinationSize) <= 0)
1293     return;
1294 
1295   StringRef FunctionName = GetFunctionName();
1296 
1297   SmallString<16> DestinationStr;
1298   SmallString<16> SourceStr;
1299   DestinationSize->toString(DestinationStr, /*Radix=*/10);
1300   SourceSize->toString(SourceStr, /*Radix=*/10);
1301   DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
1302                       PDiag(DiagID)
1303                           << FunctionName << DestinationStr << SourceStr);
1304 }
1305 
1306 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
1307                                      Scope::ScopeFlags NeededScopeFlags,
1308                                      unsigned DiagID) {
1309   // Scopes aren't available during instantiation. Fortunately, builtin
1310   // functions cannot be template args so they cannot be formed through template
1311   // instantiation. Therefore checking once during the parse is sufficient.
1312   if (SemaRef.inTemplateInstantiation())
1313     return false;
1314 
1315   Scope *S = SemaRef.getCurScope();
1316   while (S && !S->isSEHExceptScope())
1317     S = S->getParent();
1318   if (!S || !(S->getFlags() & NeededScopeFlags)) {
1319     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1320     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
1321         << DRE->getDecl()->getIdentifier();
1322     return true;
1323   }
1324 
1325   return false;
1326 }
1327 
1328 static inline bool isBlockPointer(Expr *Arg) {
1329   return Arg->getType()->isBlockPointerType();
1330 }
1331 
1332 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
1333 /// void*, which is a requirement of device side enqueue.
1334 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
1335   const BlockPointerType *BPT =
1336       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
1337   ArrayRef<QualType> Params =
1338       BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes();
1339   unsigned ArgCounter = 0;
1340   bool IllegalParams = false;
1341   // Iterate through the block parameters until either one is found that is not
1342   // a local void*, or the block is valid.
1343   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
1344        I != E; ++I, ++ArgCounter) {
1345     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
1346         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
1347             LangAS::opencl_local) {
1348       // Get the location of the error. If a block literal has been passed
1349       // (BlockExpr) then we can point straight to the offending argument,
1350       // else we just point to the variable reference.
1351       SourceLocation ErrorLoc;
1352       if (isa<BlockExpr>(BlockArg)) {
1353         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
1354         ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
1355       } else if (isa<DeclRefExpr>(BlockArg)) {
1356         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
1357       }
1358       S.Diag(ErrorLoc,
1359              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
1360       IllegalParams = true;
1361     }
1362   }
1363 
1364   return IllegalParams;
1365 }
1366 
1367 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
1368   // OpenCL device can support extension but not the feature as extension
1369   // requires subgroup independent forward progress, but subgroup independent
1370   // forward progress is optional in OpenCL C 3.0 __opencl_c_subgroups feature.
1371   if (!S.getOpenCLOptions().isSupported("cl_khr_subgroups", S.getLangOpts()) &&
1372       !S.getOpenCLOptions().isSupported("__opencl_c_subgroups",
1373                                         S.getLangOpts())) {
1374     S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
1375         << 1 << Call->getDirectCallee()
1376         << "cl_khr_subgroups or __opencl_c_subgroups";
1377     return true;
1378   }
1379   return false;
1380 }
1381 
1382 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
1383   if (checkArgCount(S, TheCall, 2))
1384     return true;
1385 
1386   if (checkOpenCLSubgroupExt(S, TheCall))
1387     return true;
1388 
1389   // First argument is an ndrange_t type.
1390   Expr *NDRangeArg = TheCall->getArg(0);
1391   if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
1392     S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1393         << TheCall->getDirectCallee() << "'ndrange_t'";
1394     return true;
1395   }
1396 
1397   Expr *BlockArg = TheCall->getArg(1);
1398   if (!isBlockPointer(BlockArg)) {
1399     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1400         << TheCall->getDirectCallee() << "block";
1401     return true;
1402   }
1403   return checkOpenCLBlockArgs(S, BlockArg);
1404 }
1405 
1406 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
1407 /// get_kernel_work_group_size
1408 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
1409 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
1410   if (checkArgCount(S, TheCall, 1))
1411     return true;
1412 
1413   Expr *BlockArg = TheCall->getArg(0);
1414   if (!isBlockPointer(BlockArg)) {
1415     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1416         << TheCall->getDirectCallee() << "block";
1417     return true;
1418   }
1419   return checkOpenCLBlockArgs(S, BlockArg);
1420 }
1421 
1422 /// Diagnose integer type and any valid implicit conversion to it.
1423 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
1424                                       const QualType &IntType);
1425 
1426 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
1427                                             unsigned Start, unsigned End) {
1428   bool IllegalParams = false;
1429   for (unsigned I = Start; I <= End; ++I)
1430     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
1431                                               S.Context.getSizeType());
1432   return IllegalParams;
1433 }
1434 
1435 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
1436 /// 'local void*' parameter of passed block.
1437 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
1438                                            Expr *BlockArg,
1439                                            unsigned NumNonVarArgs) {
1440   const BlockPointerType *BPT =
1441       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
1442   unsigned NumBlockParams =
1443       BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams();
1444   unsigned TotalNumArgs = TheCall->getNumArgs();
1445 
1446   // For each argument passed to the block, a corresponding uint needs to
1447   // be passed to describe the size of the local memory.
1448   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
1449     S.Diag(TheCall->getBeginLoc(),
1450            diag::err_opencl_enqueue_kernel_local_size_args);
1451     return true;
1452   }
1453 
1454   // Check that the sizes of the local memory are specified by integers.
1455   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
1456                                          TotalNumArgs - 1);
1457 }
1458 
1459 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
1460 /// overload formats specified in Table 6.13.17.1.
1461 /// int enqueue_kernel(queue_t queue,
1462 ///                    kernel_enqueue_flags_t flags,
1463 ///                    const ndrange_t ndrange,
1464 ///                    void (^block)(void))
1465 /// int enqueue_kernel(queue_t queue,
1466 ///                    kernel_enqueue_flags_t flags,
1467 ///                    const ndrange_t ndrange,
1468 ///                    uint num_events_in_wait_list,
1469 ///                    clk_event_t *event_wait_list,
1470 ///                    clk_event_t *event_ret,
1471 ///                    void (^block)(void))
1472 /// int enqueue_kernel(queue_t queue,
1473 ///                    kernel_enqueue_flags_t flags,
1474 ///                    const ndrange_t ndrange,
1475 ///                    void (^block)(local void*, ...),
1476 ///                    uint size0, ...)
1477 /// int enqueue_kernel(queue_t queue,
1478 ///                    kernel_enqueue_flags_t flags,
1479 ///                    const ndrange_t ndrange,
1480 ///                    uint num_events_in_wait_list,
1481 ///                    clk_event_t *event_wait_list,
1482 ///                    clk_event_t *event_ret,
1483 ///                    void (^block)(local void*, ...),
1484 ///                    uint size0, ...)
1485 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
1486   unsigned NumArgs = TheCall->getNumArgs();
1487 
1488   if (NumArgs < 4) {
1489     S.Diag(TheCall->getBeginLoc(),
1490            diag::err_typecheck_call_too_few_args_at_least)
1491         << 0 << 4 << NumArgs;
1492     return true;
1493   }
1494 
1495   Expr *Arg0 = TheCall->getArg(0);
1496   Expr *Arg1 = TheCall->getArg(1);
1497   Expr *Arg2 = TheCall->getArg(2);
1498   Expr *Arg3 = TheCall->getArg(3);
1499 
1500   // First argument always needs to be a queue_t type.
1501   if (!Arg0->getType()->isQueueT()) {
1502     S.Diag(TheCall->getArg(0)->getBeginLoc(),
1503            diag::err_opencl_builtin_expected_type)
1504         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
1505     return true;
1506   }
1507 
1508   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
1509   if (!Arg1->getType()->isIntegerType()) {
1510     S.Diag(TheCall->getArg(1)->getBeginLoc(),
1511            diag::err_opencl_builtin_expected_type)
1512         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
1513     return true;
1514   }
1515 
1516   // Third argument is always an ndrange_t type.
1517   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
1518     S.Diag(TheCall->getArg(2)->getBeginLoc(),
1519            diag::err_opencl_builtin_expected_type)
1520         << TheCall->getDirectCallee() << "'ndrange_t'";
1521     return true;
1522   }
1523 
1524   // With four arguments, there is only one form that the function could be
1525   // called in: no events and no variable arguments.
1526   if (NumArgs == 4) {
1527     // check that the last argument is the right block type.
1528     if (!isBlockPointer(Arg3)) {
1529       S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1530           << TheCall->getDirectCallee() << "block";
1531       return true;
1532     }
1533     // we have a block type, check the prototype
1534     const BlockPointerType *BPT =
1535         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
1536     if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) {
1537       S.Diag(Arg3->getBeginLoc(),
1538              diag::err_opencl_enqueue_kernel_blocks_no_args);
1539       return true;
1540     }
1541     return false;
1542   }
1543   // we can have block + varargs.
1544   if (isBlockPointer(Arg3))
1545     return (checkOpenCLBlockArgs(S, Arg3) ||
1546             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
1547   // last two cases with either exactly 7 args or 7 args and varargs.
1548   if (NumArgs >= 7) {
1549     // check common block argument.
1550     Expr *Arg6 = TheCall->getArg(6);
1551     if (!isBlockPointer(Arg6)) {
1552       S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1553           << TheCall->getDirectCallee() << "block";
1554       return true;
1555     }
1556     if (checkOpenCLBlockArgs(S, Arg6))
1557       return true;
1558 
1559     // Forth argument has to be any integer type.
1560     if (!Arg3->getType()->isIntegerType()) {
1561       S.Diag(TheCall->getArg(3)->getBeginLoc(),
1562              diag::err_opencl_builtin_expected_type)
1563           << TheCall->getDirectCallee() << "integer";
1564       return true;
1565     }
1566     // check remaining common arguments.
1567     Expr *Arg4 = TheCall->getArg(4);
1568     Expr *Arg5 = TheCall->getArg(5);
1569 
1570     // Fifth argument is always passed as a pointer to clk_event_t.
1571     if (!Arg4->isNullPointerConstant(S.Context,
1572                                      Expr::NPC_ValueDependentIsNotNull) &&
1573         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
1574       S.Diag(TheCall->getArg(4)->getBeginLoc(),
1575              diag::err_opencl_builtin_expected_type)
1576           << TheCall->getDirectCallee()
1577           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1578       return true;
1579     }
1580 
1581     // Sixth argument is always passed as a pointer to clk_event_t.
1582     if (!Arg5->isNullPointerConstant(S.Context,
1583                                      Expr::NPC_ValueDependentIsNotNull) &&
1584         !(Arg5->getType()->isPointerType() &&
1585           Arg5->getType()->getPointeeType()->isClkEventT())) {
1586       S.Diag(TheCall->getArg(5)->getBeginLoc(),
1587              diag::err_opencl_builtin_expected_type)
1588           << TheCall->getDirectCallee()
1589           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1590       return true;
1591     }
1592 
1593     if (NumArgs == 7)
1594       return false;
1595 
1596     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
1597   }
1598 
1599   // None of the specific case has been detected, give generic error
1600   S.Diag(TheCall->getBeginLoc(),
1601          diag::err_opencl_enqueue_kernel_incorrect_args);
1602   return true;
1603 }
1604 
1605 /// Returns OpenCL access qual.
1606 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
1607     return D->getAttr<OpenCLAccessAttr>();
1608 }
1609 
1610 /// Returns true if pipe element type is different from the pointer.
1611 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
1612   const Expr *Arg0 = Call->getArg(0);
1613   // First argument type should always be pipe.
1614   if (!Arg0->getType()->isPipeType()) {
1615     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1616         << Call->getDirectCallee() << Arg0->getSourceRange();
1617     return true;
1618   }
1619   OpenCLAccessAttr *AccessQual =
1620       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
1621   // Validates the access qualifier is compatible with the call.
1622   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
1623   // read_only and write_only, and assumed to be read_only if no qualifier is
1624   // specified.
1625   switch (Call->getDirectCallee()->getBuiltinID()) {
1626   case Builtin::BIread_pipe:
1627   case Builtin::BIreserve_read_pipe:
1628   case Builtin::BIcommit_read_pipe:
1629   case Builtin::BIwork_group_reserve_read_pipe:
1630   case Builtin::BIsub_group_reserve_read_pipe:
1631   case Builtin::BIwork_group_commit_read_pipe:
1632   case Builtin::BIsub_group_commit_read_pipe:
1633     if (!(!AccessQual || AccessQual->isReadOnly())) {
1634       S.Diag(Arg0->getBeginLoc(),
1635              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1636           << "read_only" << Arg0->getSourceRange();
1637       return true;
1638     }
1639     break;
1640   case Builtin::BIwrite_pipe:
1641   case Builtin::BIreserve_write_pipe:
1642   case Builtin::BIcommit_write_pipe:
1643   case Builtin::BIwork_group_reserve_write_pipe:
1644   case Builtin::BIsub_group_reserve_write_pipe:
1645   case Builtin::BIwork_group_commit_write_pipe:
1646   case Builtin::BIsub_group_commit_write_pipe:
1647     if (!(AccessQual && AccessQual->isWriteOnly())) {
1648       S.Diag(Arg0->getBeginLoc(),
1649              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1650           << "write_only" << Arg0->getSourceRange();
1651       return true;
1652     }
1653     break;
1654   default:
1655     break;
1656   }
1657   return false;
1658 }
1659 
1660 /// Returns true if pipe element type is different from the pointer.
1661 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
1662   const Expr *Arg0 = Call->getArg(0);
1663   const Expr *ArgIdx = Call->getArg(Idx);
1664   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
1665   const QualType EltTy = PipeTy->getElementType();
1666   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
1667   // The Idx argument should be a pointer and the type of the pointer and
1668   // the type of pipe element should also be the same.
1669   if (!ArgTy ||
1670       !S.Context.hasSameType(
1671           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
1672     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1673         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
1674         << ArgIdx->getType() << ArgIdx->getSourceRange();
1675     return true;
1676   }
1677   return false;
1678 }
1679 
1680 // Performs semantic analysis for the read/write_pipe call.
1681 // \param S Reference to the semantic analyzer.
1682 // \param Call A pointer to the builtin call.
1683 // \return True if a semantic error has been found, false otherwise.
1684 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
1685   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
1686   // functions have two forms.
1687   switch (Call->getNumArgs()) {
1688   case 2:
1689     if (checkOpenCLPipeArg(S, Call))
1690       return true;
1691     // The call with 2 arguments should be
1692     // read/write_pipe(pipe T, T*).
1693     // Check packet type T.
1694     if (checkOpenCLPipePacketType(S, Call, 1))
1695       return true;
1696     break;
1697 
1698   case 4: {
1699     if (checkOpenCLPipeArg(S, Call))
1700       return true;
1701     // The call with 4 arguments should be
1702     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
1703     // Check reserve_id_t.
1704     if (!Call->getArg(1)->getType()->isReserveIDT()) {
1705       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1706           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1707           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1708       return true;
1709     }
1710 
1711     // Check the index.
1712     const Expr *Arg2 = Call->getArg(2);
1713     if (!Arg2->getType()->isIntegerType() &&
1714         !Arg2->getType()->isUnsignedIntegerType()) {
1715       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1716           << Call->getDirectCallee() << S.Context.UnsignedIntTy
1717           << Arg2->getType() << Arg2->getSourceRange();
1718       return true;
1719     }
1720 
1721     // Check packet type T.
1722     if (checkOpenCLPipePacketType(S, Call, 3))
1723       return true;
1724   } break;
1725   default:
1726     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
1727         << Call->getDirectCallee() << Call->getSourceRange();
1728     return true;
1729   }
1730 
1731   return false;
1732 }
1733 
1734 // Performs a semantic analysis on the {work_group_/sub_group_
1735 //        /_}reserve_{read/write}_pipe
1736 // \param S Reference to the semantic analyzer.
1737 // \param Call The call to the builtin function to be analyzed.
1738 // \return True if a semantic error was found, false otherwise.
1739 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
1740   if (checkArgCount(S, Call, 2))
1741     return true;
1742 
1743   if (checkOpenCLPipeArg(S, Call))
1744     return true;
1745 
1746   // Check the reserve size.
1747   if (!Call->getArg(1)->getType()->isIntegerType() &&
1748       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
1749     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1750         << Call->getDirectCallee() << S.Context.UnsignedIntTy
1751         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1752     return true;
1753   }
1754 
1755   // Since return type of reserve_read/write_pipe built-in function is
1756   // reserve_id_t, which is not defined in the builtin def file , we used int
1757   // as return type and need to override the return type of these functions.
1758   Call->setType(S.Context.OCLReserveIDTy);
1759 
1760   return false;
1761 }
1762 
1763 // Performs a semantic analysis on {work_group_/sub_group_
1764 //        /_}commit_{read/write}_pipe
1765 // \param S Reference to the semantic analyzer.
1766 // \param Call The call to the builtin function to be analyzed.
1767 // \return True if a semantic error was found, false otherwise.
1768 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
1769   if (checkArgCount(S, Call, 2))
1770     return true;
1771 
1772   if (checkOpenCLPipeArg(S, Call))
1773     return true;
1774 
1775   // Check reserve_id_t.
1776   if (!Call->getArg(1)->getType()->isReserveIDT()) {
1777     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1778         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1779         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1780     return true;
1781   }
1782 
1783   return false;
1784 }
1785 
1786 // Performs a semantic analysis on the call to built-in Pipe
1787 //        Query Functions.
1788 // \param S Reference to the semantic analyzer.
1789 // \param Call The call to the builtin function to be analyzed.
1790 // \return True if a semantic error was found, false otherwise.
1791 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
1792   if (checkArgCount(S, Call, 1))
1793     return true;
1794 
1795   if (!Call->getArg(0)->getType()->isPipeType()) {
1796     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1797         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
1798     return true;
1799   }
1800 
1801   return false;
1802 }
1803 
1804 // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
1805 // Performs semantic analysis for the to_global/local/private call.
1806 // \param S Reference to the semantic analyzer.
1807 // \param BuiltinID ID of the builtin function.
1808 // \param Call A pointer to the builtin call.
1809 // \return True if a semantic error has been found, false otherwise.
1810 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
1811                                     CallExpr *Call) {
1812   if (checkArgCount(S, Call, 1))
1813     return true;
1814 
1815   auto RT = Call->getArg(0)->getType();
1816   if (!RT->isPointerType() || RT->getPointeeType()
1817       .getAddressSpace() == LangAS::opencl_constant) {
1818     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
1819         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
1820     return true;
1821   }
1822 
1823   if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
1824     S.Diag(Call->getArg(0)->getBeginLoc(),
1825            diag::warn_opencl_generic_address_space_arg)
1826         << Call->getDirectCallee()->getNameInfo().getAsString()
1827         << Call->getArg(0)->getSourceRange();
1828   }
1829 
1830   RT = RT->getPointeeType();
1831   auto Qual = RT.getQualifiers();
1832   switch (BuiltinID) {
1833   case Builtin::BIto_global:
1834     Qual.setAddressSpace(LangAS::opencl_global);
1835     break;
1836   case Builtin::BIto_local:
1837     Qual.setAddressSpace(LangAS::opencl_local);
1838     break;
1839   case Builtin::BIto_private:
1840     Qual.setAddressSpace(LangAS::opencl_private);
1841     break;
1842   default:
1843     llvm_unreachable("Invalid builtin function");
1844   }
1845   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
1846       RT.getUnqualifiedType(), Qual)));
1847 
1848   return false;
1849 }
1850 
1851 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
1852   if (checkArgCount(S, TheCall, 1))
1853     return ExprError();
1854 
1855   // Compute __builtin_launder's parameter type from the argument.
1856   // The parameter type is:
1857   //  * The type of the argument if it's not an array or function type,
1858   //  Otherwise,
1859   //  * The decayed argument type.
1860   QualType ParamTy = [&]() {
1861     QualType ArgTy = TheCall->getArg(0)->getType();
1862     if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1863       return S.Context.getPointerType(Ty->getElementType());
1864     if (ArgTy->isFunctionType()) {
1865       return S.Context.getPointerType(ArgTy);
1866     }
1867     return ArgTy;
1868   }();
1869 
1870   TheCall->setType(ParamTy);
1871 
1872   auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
1873     if (!ParamTy->isPointerType())
1874       return 0;
1875     if (ParamTy->isFunctionPointerType())
1876       return 1;
1877     if (ParamTy->isVoidPointerType())
1878       return 2;
1879     return llvm::Optional<unsigned>{};
1880   }();
1881   if (DiagSelect) {
1882     S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1883         << DiagSelect.getValue() << TheCall->getSourceRange();
1884     return ExprError();
1885   }
1886 
1887   // We either have an incomplete class type, or we have a class template
1888   // whose instantiation has not been forced. Example:
1889   //
1890   //   template <class T> struct Foo { T value; };
1891   //   Foo<int> *p = nullptr;
1892   //   auto *d = __builtin_launder(p);
1893   if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1894                             diag::err_incomplete_type))
1895     return ExprError();
1896 
1897   assert(ParamTy->getPointeeType()->isObjectType() &&
1898          "Unhandled non-object pointer case");
1899 
1900   InitializedEntity Entity =
1901       InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
1902   ExprResult Arg =
1903       S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1904   if (Arg.isInvalid())
1905     return ExprError();
1906   TheCall->setArg(0, Arg.get());
1907 
1908   return TheCall;
1909 }
1910 
1911 // Emit an error and return true if the current object format type is in the
1912 // list of unsupported types.
1913 static bool CheckBuiltinTargetNotInUnsupported(
1914     Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1915     ArrayRef<llvm::Triple::ObjectFormatType> UnsupportedObjectFormatTypes) {
1916   llvm::Triple::ObjectFormatType CurObjFormat =
1917       S.getASTContext().getTargetInfo().getTriple().getObjectFormat();
1918   if (llvm::is_contained(UnsupportedObjectFormatTypes, CurObjFormat)) {
1919     S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1920         << TheCall->getSourceRange();
1921     return true;
1922   }
1923   return false;
1924 }
1925 
1926 // Emit an error and return true if the current architecture is not in the list
1927 // of supported architectures.
1928 static bool
1929 CheckBuiltinTargetInSupported(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1930                               ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
1931   llvm::Triple::ArchType CurArch =
1932       S.getASTContext().getTargetInfo().getTriple().getArch();
1933   if (llvm::is_contained(SupportedArchs, CurArch))
1934     return false;
1935   S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1936       << TheCall->getSourceRange();
1937   return true;
1938 }
1939 
1940 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
1941                                  SourceLocation CallSiteLoc);
1942 
1943 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
1944                                       CallExpr *TheCall) {
1945   switch (TI.getTriple().getArch()) {
1946   default:
1947     // Some builtins don't require additional checking, so just consider these
1948     // acceptable.
1949     return false;
1950   case llvm::Triple::arm:
1951   case llvm::Triple::armeb:
1952   case llvm::Triple::thumb:
1953   case llvm::Triple::thumbeb:
1954     return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
1955   case llvm::Triple::aarch64:
1956   case llvm::Triple::aarch64_32:
1957   case llvm::Triple::aarch64_be:
1958     return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
1959   case llvm::Triple::bpfeb:
1960   case llvm::Triple::bpfel:
1961     return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
1962   case llvm::Triple::hexagon:
1963     return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
1964   case llvm::Triple::mips:
1965   case llvm::Triple::mipsel:
1966   case llvm::Triple::mips64:
1967   case llvm::Triple::mips64el:
1968     return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
1969   case llvm::Triple::systemz:
1970     return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
1971   case llvm::Triple::x86:
1972   case llvm::Triple::x86_64:
1973     return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall);
1974   case llvm::Triple::ppc:
1975   case llvm::Triple::ppcle:
1976   case llvm::Triple::ppc64:
1977   case llvm::Triple::ppc64le:
1978     return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
1979   case llvm::Triple::amdgcn:
1980     return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
1981   case llvm::Triple::riscv32:
1982   case llvm::Triple::riscv64:
1983     return CheckRISCVBuiltinFunctionCall(TI, BuiltinID, TheCall);
1984   }
1985 }
1986 
1987 ExprResult
1988 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
1989                                CallExpr *TheCall) {
1990   ExprResult TheCallResult(TheCall);
1991 
1992   // Find out if any arguments are required to be integer constant expressions.
1993   unsigned ICEArguments = 0;
1994   ASTContext::GetBuiltinTypeError Error;
1995   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
1996   if (Error != ASTContext::GE_None)
1997     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
1998 
1999   // If any arguments are required to be ICE's, check and diagnose.
2000   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
2001     // Skip arguments not required to be ICE's.
2002     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
2003 
2004     llvm::APSInt Result;
2005     // If we don't have enough arguments, continue so we can issue better
2006     // diagnostic in checkArgCount(...)
2007     if (ArgNo < TheCall->getNumArgs() &&
2008         SemaBuiltinConstantArg(TheCall, ArgNo, Result))
2009       return true;
2010     ICEArguments &= ~(1 << ArgNo);
2011   }
2012 
2013   switch (BuiltinID) {
2014   case Builtin::BI__builtin___CFStringMakeConstantString:
2015     // CFStringMakeConstantString is currently not implemented for GOFF (i.e.,
2016     // on z/OS) and for XCOFF (i.e., on AIX). Emit unsupported
2017     if (CheckBuiltinTargetNotInUnsupported(
2018             *this, BuiltinID, TheCall,
2019             {llvm::Triple::GOFF, llvm::Triple::XCOFF}))
2020       return ExprError();
2021     assert(TheCall->getNumArgs() == 1 &&
2022            "Wrong # arguments to builtin CFStringMakeConstantString");
2023     if (CheckObjCString(TheCall->getArg(0)))
2024       return ExprError();
2025     break;
2026   case Builtin::BI__builtin_ms_va_start:
2027   case Builtin::BI__builtin_stdarg_start:
2028   case Builtin::BI__builtin_va_start:
2029     if (SemaBuiltinVAStart(BuiltinID, TheCall))
2030       return ExprError();
2031     break;
2032   case Builtin::BI__va_start: {
2033     switch (Context.getTargetInfo().getTriple().getArch()) {
2034     case llvm::Triple::aarch64:
2035     case llvm::Triple::arm:
2036     case llvm::Triple::thumb:
2037       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
2038         return ExprError();
2039       break;
2040     default:
2041       if (SemaBuiltinVAStart(BuiltinID, TheCall))
2042         return ExprError();
2043       break;
2044     }
2045     break;
2046   }
2047 
2048   // The acquire, release, and no fence variants are ARM and AArch64 only.
2049   case Builtin::BI_interlockedbittestandset_acq:
2050   case Builtin::BI_interlockedbittestandset_rel:
2051   case Builtin::BI_interlockedbittestandset_nf:
2052   case Builtin::BI_interlockedbittestandreset_acq:
2053   case Builtin::BI_interlockedbittestandreset_rel:
2054   case Builtin::BI_interlockedbittestandreset_nf:
2055     if (CheckBuiltinTargetInSupported(
2056             *this, BuiltinID, TheCall,
2057             {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
2058       return ExprError();
2059     break;
2060 
2061   // The 64-bit bittest variants are x64, ARM, and AArch64 only.
2062   case Builtin::BI_bittest64:
2063   case Builtin::BI_bittestandcomplement64:
2064   case Builtin::BI_bittestandreset64:
2065   case Builtin::BI_bittestandset64:
2066   case Builtin::BI_interlockedbittestandreset64:
2067   case Builtin::BI_interlockedbittestandset64:
2068     if (CheckBuiltinTargetInSupported(*this, BuiltinID, TheCall,
2069                                       {llvm::Triple::x86_64, llvm::Triple::arm,
2070                                        llvm::Triple::thumb,
2071                                        llvm::Triple::aarch64}))
2072       return ExprError();
2073     break;
2074 
2075   case Builtin::BI__builtin_isgreater:
2076   case Builtin::BI__builtin_isgreaterequal:
2077   case Builtin::BI__builtin_isless:
2078   case Builtin::BI__builtin_islessequal:
2079   case Builtin::BI__builtin_islessgreater:
2080   case Builtin::BI__builtin_isunordered:
2081     if (SemaBuiltinUnorderedCompare(TheCall))
2082       return ExprError();
2083     break;
2084   case Builtin::BI__builtin_fpclassify:
2085     if (SemaBuiltinFPClassification(TheCall, 6))
2086       return ExprError();
2087     break;
2088   case Builtin::BI__builtin_isfinite:
2089   case Builtin::BI__builtin_isinf:
2090   case Builtin::BI__builtin_isinf_sign:
2091   case Builtin::BI__builtin_isnan:
2092   case Builtin::BI__builtin_isnormal:
2093   case Builtin::BI__builtin_signbit:
2094   case Builtin::BI__builtin_signbitf:
2095   case Builtin::BI__builtin_signbitl:
2096     if (SemaBuiltinFPClassification(TheCall, 1))
2097       return ExprError();
2098     break;
2099   case Builtin::BI__builtin_shufflevector:
2100     return SemaBuiltinShuffleVector(TheCall);
2101     // TheCall will be freed by the smart pointer here, but that's fine, since
2102     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
2103   case Builtin::BI__builtin_prefetch:
2104     if (SemaBuiltinPrefetch(TheCall))
2105       return ExprError();
2106     break;
2107   case Builtin::BI__builtin_alloca_with_align:
2108   case Builtin::BI__builtin_alloca_with_align_uninitialized:
2109     if (SemaBuiltinAllocaWithAlign(TheCall))
2110       return ExprError();
2111     LLVM_FALLTHROUGH;
2112   case Builtin::BI__builtin_alloca:
2113   case Builtin::BI__builtin_alloca_uninitialized:
2114     Diag(TheCall->getBeginLoc(), diag::warn_alloca)
2115         << TheCall->getDirectCallee();
2116     break;
2117   case Builtin::BI__arithmetic_fence:
2118     if (SemaBuiltinArithmeticFence(TheCall))
2119       return ExprError();
2120     break;
2121   case Builtin::BI__assume:
2122   case Builtin::BI__builtin_assume:
2123     if (SemaBuiltinAssume(TheCall))
2124       return ExprError();
2125     break;
2126   case Builtin::BI__builtin_assume_aligned:
2127     if (SemaBuiltinAssumeAligned(TheCall))
2128       return ExprError();
2129     break;
2130   case Builtin::BI__builtin_dynamic_object_size:
2131   case Builtin::BI__builtin_object_size:
2132     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
2133       return ExprError();
2134     break;
2135   case Builtin::BI__builtin_longjmp:
2136     if (SemaBuiltinLongjmp(TheCall))
2137       return ExprError();
2138     break;
2139   case Builtin::BI__builtin_setjmp:
2140     if (SemaBuiltinSetjmp(TheCall))
2141       return ExprError();
2142     break;
2143   case Builtin::BI__builtin_classify_type:
2144     if (checkArgCount(*this, TheCall, 1)) return true;
2145     TheCall->setType(Context.IntTy);
2146     break;
2147   case Builtin::BI__builtin_complex:
2148     if (SemaBuiltinComplex(TheCall))
2149       return ExprError();
2150     break;
2151   case Builtin::BI__builtin_constant_p: {
2152     if (checkArgCount(*this, TheCall, 1)) return true;
2153     ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
2154     if (Arg.isInvalid()) return true;
2155     TheCall->setArg(0, Arg.get());
2156     TheCall->setType(Context.IntTy);
2157     break;
2158   }
2159   case Builtin::BI__builtin_launder:
2160     return SemaBuiltinLaunder(*this, TheCall);
2161   case Builtin::BI__sync_fetch_and_add:
2162   case Builtin::BI__sync_fetch_and_add_1:
2163   case Builtin::BI__sync_fetch_and_add_2:
2164   case Builtin::BI__sync_fetch_and_add_4:
2165   case Builtin::BI__sync_fetch_and_add_8:
2166   case Builtin::BI__sync_fetch_and_add_16:
2167   case Builtin::BI__sync_fetch_and_sub:
2168   case Builtin::BI__sync_fetch_and_sub_1:
2169   case Builtin::BI__sync_fetch_and_sub_2:
2170   case Builtin::BI__sync_fetch_and_sub_4:
2171   case Builtin::BI__sync_fetch_and_sub_8:
2172   case Builtin::BI__sync_fetch_and_sub_16:
2173   case Builtin::BI__sync_fetch_and_or:
2174   case Builtin::BI__sync_fetch_and_or_1:
2175   case Builtin::BI__sync_fetch_and_or_2:
2176   case Builtin::BI__sync_fetch_and_or_4:
2177   case Builtin::BI__sync_fetch_and_or_8:
2178   case Builtin::BI__sync_fetch_and_or_16:
2179   case Builtin::BI__sync_fetch_and_and:
2180   case Builtin::BI__sync_fetch_and_and_1:
2181   case Builtin::BI__sync_fetch_and_and_2:
2182   case Builtin::BI__sync_fetch_and_and_4:
2183   case Builtin::BI__sync_fetch_and_and_8:
2184   case Builtin::BI__sync_fetch_and_and_16:
2185   case Builtin::BI__sync_fetch_and_xor:
2186   case Builtin::BI__sync_fetch_and_xor_1:
2187   case Builtin::BI__sync_fetch_and_xor_2:
2188   case Builtin::BI__sync_fetch_and_xor_4:
2189   case Builtin::BI__sync_fetch_and_xor_8:
2190   case Builtin::BI__sync_fetch_and_xor_16:
2191   case Builtin::BI__sync_fetch_and_nand:
2192   case Builtin::BI__sync_fetch_and_nand_1:
2193   case Builtin::BI__sync_fetch_and_nand_2:
2194   case Builtin::BI__sync_fetch_and_nand_4:
2195   case Builtin::BI__sync_fetch_and_nand_8:
2196   case Builtin::BI__sync_fetch_and_nand_16:
2197   case Builtin::BI__sync_add_and_fetch:
2198   case Builtin::BI__sync_add_and_fetch_1:
2199   case Builtin::BI__sync_add_and_fetch_2:
2200   case Builtin::BI__sync_add_and_fetch_4:
2201   case Builtin::BI__sync_add_and_fetch_8:
2202   case Builtin::BI__sync_add_and_fetch_16:
2203   case Builtin::BI__sync_sub_and_fetch:
2204   case Builtin::BI__sync_sub_and_fetch_1:
2205   case Builtin::BI__sync_sub_and_fetch_2:
2206   case Builtin::BI__sync_sub_and_fetch_4:
2207   case Builtin::BI__sync_sub_and_fetch_8:
2208   case Builtin::BI__sync_sub_and_fetch_16:
2209   case Builtin::BI__sync_and_and_fetch:
2210   case Builtin::BI__sync_and_and_fetch_1:
2211   case Builtin::BI__sync_and_and_fetch_2:
2212   case Builtin::BI__sync_and_and_fetch_4:
2213   case Builtin::BI__sync_and_and_fetch_8:
2214   case Builtin::BI__sync_and_and_fetch_16:
2215   case Builtin::BI__sync_or_and_fetch:
2216   case Builtin::BI__sync_or_and_fetch_1:
2217   case Builtin::BI__sync_or_and_fetch_2:
2218   case Builtin::BI__sync_or_and_fetch_4:
2219   case Builtin::BI__sync_or_and_fetch_8:
2220   case Builtin::BI__sync_or_and_fetch_16:
2221   case Builtin::BI__sync_xor_and_fetch:
2222   case Builtin::BI__sync_xor_and_fetch_1:
2223   case Builtin::BI__sync_xor_and_fetch_2:
2224   case Builtin::BI__sync_xor_and_fetch_4:
2225   case Builtin::BI__sync_xor_and_fetch_8:
2226   case Builtin::BI__sync_xor_and_fetch_16:
2227   case Builtin::BI__sync_nand_and_fetch:
2228   case Builtin::BI__sync_nand_and_fetch_1:
2229   case Builtin::BI__sync_nand_and_fetch_2:
2230   case Builtin::BI__sync_nand_and_fetch_4:
2231   case Builtin::BI__sync_nand_and_fetch_8:
2232   case Builtin::BI__sync_nand_and_fetch_16:
2233   case Builtin::BI__sync_val_compare_and_swap:
2234   case Builtin::BI__sync_val_compare_and_swap_1:
2235   case Builtin::BI__sync_val_compare_and_swap_2:
2236   case Builtin::BI__sync_val_compare_and_swap_4:
2237   case Builtin::BI__sync_val_compare_and_swap_8:
2238   case Builtin::BI__sync_val_compare_and_swap_16:
2239   case Builtin::BI__sync_bool_compare_and_swap:
2240   case Builtin::BI__sync_bool_compare_and_swap_1:
2241   case Builtin::BI__sync_bool_compare_and_swap_2:
2242   case Builtin::BI__sync_bool_compare_and_swap_4:
2243   case Builtin::BI__sync_bool_compare_and_swap_8:
2244   case Builtin::BI__sync_bool_compare_and_swap_16:
2245   case Builtin::BI__sync_lock_test_and_set:
2246   case Builtin::BI__sync_lock_test_and_set_1:
2247   case Builtin::BI__sync_lock_test_and_set_2:
2248   case Builtin::BI__sync_lock_test_and_set_4:
2249   case Builtin::BI__sync_lock_test_and_set_8:
2250   case Builtin::BI__sync_lock_test_and_set_16:
2251   case Builtin::BI__sync_lock_release:
2252   case Builtin::BI__sync_lock_release_1:
2253   case Builtin::BI__sync_lock_release_2:
2254   case Builtin::BI__sync_lock_release_4:
2255   case Builtin::BI__sync_lock_release_8:
2256   case Builtin::BI__sync_lock_release_16:
2257   case Builtin::BI__sync_swap:
2258   case Builtin::BI__sync_swap_1:
2259   case Builtin::BI__sync_swap_2:
2260   case Builtin::BI__sync_swap_4:
2261   case Builtin::BI__sync_swap_8:
2262   case Builtin::BI__sync_swap_16:
2263     return SemaBuiltinAtomicOverloaded(TheCallResult);
2264   case Builtin::BI__sync_synchronize:
2265     Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
2266         << TheCall->getCallee()->getSourceRange();
2267     break;
2268   case Builtin::BI__builtin_nontemporal_load:
2269   case Builtin::BI__builtin_nontemporal_store:
2270     return SemaBuiltinNontemporalOverloaded(TheCallResult);
2271   case Builtin::BI__builtin_memcpy_inline: {
2272     clang::Expr *SizeOp = TheCall->getArg(2);
2273     // We warn about copying to or from `nullptr` pointers when `size` is
2274     // greater than 0. When `size` is value dependent we cannot evaluate its
2275     // value so we bail out.
2276     if (SizeOp->isValueDependent())
2277       break;
2278     if (!SizeOp->EvaluateKnownConstInt(Context).isZero()) {
2279       CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
2280       CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
2281     }
2282     break;
2283   }
2284   case Builtin::BI__builtin_memset_inline: {
2285     clang::Expr *SizeOp = TheCall->getArg(2);
2286     // We warn about filling to `nullptr` pointers when `size` is greater than
2287     // 0. When `size` is value dependent we cannot evaluate its value so we bail
2288     // out.
2289     if (SizeOp->isValueDependent())
2290       break;
2291     if (!SizeOp->EvaluateKnownConstInt(Context).isZero())
2292       CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
2293     break;
2294   }
2295 #define BUILTIN(ID, TYPE, ATTRS)
2296 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
2297   case Builtin::BI##ID: \
2298     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
2299 #include "clang/Basic/Builtins.def"
2300   case Builtin::BI__annotation:
2301     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
2302       return ExprError();
2303     break;
2304   case Builtin::BI__builtin_annotation:
2305     if (SemaBuiltinAnnotation(*this, TheCall))
2306       return ExprError();
2307     break;
2308   case Builtin::BI__builtin_addressof:
2309     if (SemaBuiltinAddressof(*this, TheCall))
2310       return ExprError();
2311     break;
2312   case Builtin::BI__builtin_function_start:
2313     if (SemaBuiltinFunctionStart(*this, TheCall))
2314       return ExprError();
2315     break;
2316   case Builtin::BI__builtin_is_aligned:
2317   case Builtin::BI__builtin_align_up:
2318   case Builtin::BI__builtin_align_down:
2319     if (SemaBuiltinAlignment(*this, TheCall, BuiltinID))
2320       return ExprError();
2321     break;
2322   case Builtin::BI__builtin_add_overflow:
2323   case Builtin::BI__builtin_sub_overflow:
2324   case Builtin::BI__builtin_mul_overflow:
2325     if (SemaBuiltinOverflow(*this, TheCall, BuiltinID))
2326       return ExprError();
2327     break;
2328   case Builtin::BI__builtin_operator_new:
2329   case Builtin::BI__builtin_operator_delete: {
2330     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
2331     ExprResult Res =
2332         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
2333     if (Res.isInvalid())
2334       CorrectDelayedTyposInExpr(TheCallResult.get());
2335     return Res;
2336   }
2337   case Builtin::BI__builtin_dump_struct:
2338     return SemaBuiltinDumpStruct(*this, TheCall);
2339   case Builtin::BI__builtin_expect_with_probability: {
2340     // We first want to ensure we are called with 3 arguments
2341     if (checkArgCount(*this, TheCall, 3))
2342       return ExprError();
2343     // then check probability is constant float in range [0.0, 1.0]
2344     const Expr *ProbArg = TheCall->getArg(2);
2345     SmallVector<PartialDiagnosticAt, 8> Notes;
2346     Expr::EvalResult Eval;
2347     Eval.Diag = &Notes;
2348     if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
2349         !Eval.Val.isFloat()) {
2350       Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
2351           << ProbArg->getSourceRange();
2352       for (const PartialDiagnosticAt &PDiag : Notes)
2353         Diag(PDiag.first, PDiag.second);
2354       return ExprError();
2355     }
2356     llvm::APFloat Probability = Eval.Val.getFloat();
2357     bool LoseInfo = false;
2358     Probability.convert(llvm::APFloat::IEEEdouble(),
2359                         llvm::RoundingMode::Dynamic, &LoseInfo);
2360     if (!(Probability >= llvm::APFloat(0.0) &&
2361           Probability <= llvm::APFloat(1.0))) {
2362       Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
2363           << ProbArg->getSourceRange();
2364       return ExprError();
2365     }
2366     break;
2367   }
2368   case Builtin::BI__builtin_preserve_access_index:
2369     if (SemaBuiltinPreserveAI(*this, TheCall))
2370       return ExprError();
2371     break;
2372   case Builtin::BI__builtin_call_with_static_chain:
2373     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
2374       return ExprError();
2375     break;
2376   case Builtin::BI__exception_code:
2377   case Builtin::BI_exception_code:
2378     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
2379                                  diag::err_seh___except_block))
2380       return ExprError();
2381     break;
2382   case Builtin::BI__exception_info:
2383   case Builtin::BI_exception_info:
2384     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
2385                                  diag::err_seh___except_filter))
2386       return ExprError();
2387     break;
2388   case Builtin::BI__GetExceptionInfo:
2389     if (checkArgCount(*this, TheCall, 1))
2390       return ExprError();
2391 
2392     if (CheckCXXThrowOperand(
2393             TheCall->getBeginLoc(),
2394             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
2395             TheCall))
2396       return ExprError();
2397 
2398     TheCall->setType(Context.VoidPtrTy);
2399     break;
2400   case Builtin::BIaddressof:
2401   case Builtin::BI__addressof:
2402   case Builtin::BIforward:
2403   case Builtin::BImove:
2404   case Builtin::BImove_if_noexcept:
2405   case Builtin::BIas_const: {
2406     // These are all expected to be of the form
2407     //   T &/&&/* f(U &/&&)
2408     // where T and U only differ in qualification.
2409     if (checkArgCount(*this, TheCall, 1))
2410       return ExprError();
2411     QualType Param = FDecl->getParamDecl(0)->getType();
2412     QualType Result = FDecl->getReturnType();
2413     bool ReturnsPointer = BuiltinID == Builtin::BIaddressof ||
2414                           BuiltinID == Builtin::BI__addressof;
2415     if (!(Param->isReferenceType() &&
2416           (ReturnsPointer ? Result->isAnyPointerType()
2417                           : Result->isReferenceType()) &&
2418           Context.hasSameUnqualifiedType(Param->getPointeeType(),
2419                                          Result->getPointeeType()))) {
2420       Diag(TheCall->getBeginLoc(), diag::err_builtin_move_forward_unsupported)
2421           << FDecl;
2422       return ExprError();
2423     }
2424     break;
2425   }
2426   // OpenCL v2.0, s6.13.16 - Pipe functions
2427   case Builtin::BIread_pipe:
2428   case Builtin::BIwrite_pipe:
2429     // Since those two functions are declared with var args, we need a semantic
2430     // check for the argument.
2431     if (SemaBuiltinRWPipe(*this, TheCall))
2432       return ExprError();
2433     break;
2434   case Builtin::BIreserve_read_pipe:
2435   case Builtin::BIreserve_write_pipe:
2436   case Builtin::BIwork_group_reserve_read_pipe:
2437   case Builtin::BIwork_group_reserve_write_pipe:
2438     if (SemaBuiltinReserveRWPipe(*this, TheCall))
2439       return ExprError();
2440     break;
2441   case Builtin::BIsub_group_reserve_read_pipe:
2442   case Builtin::BIsub_group_reserve_write_pipe:
2443     if (checkOpenCLSubgroupExt(*this, TheCall) ||
2444         SemaBuiltinReserveRWPipe(*this, TheCall))
2445       return ExprError();
2446     break;
2447   case Builtin::BIcommit_read_pipe:
2448   case Builtin::BIcommit_write_pipe:
2449   case Builtin::BIwork_group_commit_read_pipe:
2450   case Builtin::BIwork_group_commit_write_pipe:
2451     if (SemaBuiltinCommitRWPipe(*this, TheCall))
2452       return ExprError();
2453     break;
2454   case Builtin::BIsub_group_commit_read_pipe:
2455   case Builtin::BIsub_group_commit_write_pipe:
2456     if (checkOpenCLSubgroupExt(*this, TheCall) ||
2457         SemaBuiltinCommitRWPipe(*this, TheCall))
2458       return ExprError();
2459     break;
2460   case Builtin::BIget_pipe_num_packets:
2461   case Builtin::BIget_pipe_max_packets:
2462     if (SemaBuiltinPipePackets(*this, TheCall))
2463       return ExprError();
2464     break;
2465   case Builtin::BIto_global:
2466   case Builtin::BIto_local:
2467   case Builtin::BIto_private:
2468     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
2469       return ExprError();
2470     break;
2471   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
2472   case Builtin::BIenqueue_kernel:
2473     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
2474       return ExprError();
2475     break;
2476   case Builtin::BIget_kernel_work_group_size:
2477   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
2478     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
2479       return ExprError();
2480     break;
2481   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
2482   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
2483     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
2484       return ExprError();
2485     break;
2486   case Builtin::BI__builtin_os_log_format:
2487     Cleanup.setExprNeedsCleanups(true);
2488     LLVM_FALLTHROUGH;
2489   case Builtin::BI__builtin_os_log_format_buffer_size:
2490     if (SemaBuiltinOSLogFormat(TheCall))
2491       return ExprError();
2492     break;
2493   case Builtin::BI__builtin_frame_address:
2494   case Builtin::BI__builtin_return_address: {
2495     if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
2496       return ExprError();
2497 
2498     // -Wframe-address warning if non-zero passed to builtin
2499     // return/frame address.
2500     Expr::EvalResult Result;
2501     if (!TheCall->getArg(0)->isValueDependent() &&
2502         TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
2503         Result.Val.getInt() != 0)
2504       Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
2505           << ((BuiltinID == Builtin::BI__builtin_return_address)
2506                   ? "__builtin_return_address"
2507                   : "__builtin_frame_address")
2508           << TheCall->getSourceRange();
2509     break;
2510   }
2511 
2512   // __builtin_elementwise_abs restricts the element type to signed integers or
2513   // floating point types only.
2514   case Builtin::BI__builtin_elementwise_abs: {
2515     if (PrepareBuiltinElementwiseMathOneArgCall(TheCall))
2516       return ExprError();
2517 
2518     QualType ArgTy = TheCall->getArg(0)->getType();
2519     QualType EltTy = ArgTy;
2520 
2521     if (auto *VecTy = EltTy->getAs<VectorType>())
2522       EltTy = VecTy->getElementType();
2523     if (EltTy->isUnsignedIntegerType()) {
2524       Diag(TheCall->getArg(0)->getBeginLoc(),
2525            diag::err_builtin_invalid_arg_type)
2526           << 1 << /* signed integer or float ty*/ 3 << ArgTy;
2527       return ExprError();
2528     }
2529     break;
2530   }
2531 
2532   // These builtins restrict the element type to floating point
2533   // types only.
2534   case Builtin::BI__builtin_elementwise_ceil:
2535   case Builtin::BI__builtin_elementwise_floor:
2536   case Builtin::BI__builtin_elementwise_roundeven:
2537   case Builtin::BI__builtin_elementwise_trunc: {
2538     if (PrepareBuiltinElementwiseMathOneArgCall(TheCall))
2539       return ExprError();
2540 
2541     QualType ArgTy = TheCall->getArg(0)->getType();
2542     QualType EltTy = ArgTy;
2543 
2544     if (auto *VecTy = EltTy->getAs<VectorType>())
2545       EltTy = VecTy->getElementType();
2546     if (!EltTy->isFloatingType()) {
2547       Diag(TheCall->getArg(0)->getBeginLoc(),
2548            diag::err_builtin_invalid_arg_type)
2549           << 1 << /* float ty*/ 5 << ArgTy;
2550 
2551       return ExprError();
2552     }
2553     break;
2554   }
2555 
2556   // These builtins restrict the element type to integer
2557   // types only.
2558   case Builtin::BI__builtin_elementwise_add_sat:
2559   case Builtin::BI__builtin_elementwise_sub_sat: {
2560     if (SemaBuiltinElementwiseMath(TheCall))
2561       return ExprError();
2562 
2563     const Expr *Arg = TheCall->getArg(0);
2564     QualType ArgTy = Arg->getType();
2565     QualType EltTy = ArgTy;
2566 
2567     if (auto *VecTy = EltTy->getAs<VectorType>())
2568       EltTy = VecTy->getElementType();
2569 
2570     if (!EltTy->isIntegerType()) {
2571       Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2572           << 1 << /* integer ty */ 6 << ArgTy;
2573       return ExprError();
2574     }
2575     break;
2576   }
2577 
2578   case Builtin::BI__builtin_elementwise_min:
2579   case Builtin::BI__builtin_elementwise_max:
2580     if (SemaBuiltinElementwiseMath(TheCall))
2581       return ExprError();
2582     break;
2583   case Builtin::BI__builtin_reduce_max:
2584   case Builtin::BI__builtin_reduce_min: {
2585     if (PrepareBuiltinReduceMathOneArgCall(TheCall))
2586       return ExprError();
2587 
2588     const Expr *Arg = TheCall->getArg(0);
2589     const auto *TyA = Arg->getType()->getAs<VectorType>();
2590     if (!TyA) {
2591       Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2592           << 1 << /* vector ty*/ 4 << Arg->getType();
2593       return ExprError();
2594     }
2595 
2596     TheCall->setType(TyA->getElementType());
2597     break;
2598   }
2599 
2600   // These builtins support vectors of integers only.
2601   // TODO: ADD/MUL should support floating-point types.
2602   case Builtin::BI__builtin_reduce_add:
2603   case Builtin::BI__builtin_reduce_mul:
2604   case Builtin::BI__builtin_reduce_xor:
2605   case Builtin::BI__builtin_reduce_or:
2606   case Builtin::BI__builtin_reduce_and: {
2607     if (PrepareBuiltinReduceMathOneArgCall(TheCall))
2608       return ExprError();
2609 
2610     const Expr *Arg = TheCall->getArg(0);
2611     const auto *TyA = Arg->getType()->getAs<VectorType>();
2612     if (!TyA || !TyA->getElementType()->isIntegerType()) {
2613       Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2614           << 1  << /* vector of integers */ 6 << Arg->getType();
2615       return ExprError();
2616     }
2617     TheCall->setType(TyA->getElementType());
2618     break;
2619   }
2620 
2621   case Builtin::BI__builtin_matrix_transpose:
2622     return SemaBuiltinMatrixTranspose(TheCall, TheCallResult);
2623 
2624   case Builtin::BI__builtin_matrix_column_major_load:
2625     return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
2626 
2627   case Builtin::BI__builtin_matrix_column_major_store:
2628     return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
2629 
2630   case Builtin::BI__builtin_get_device_side_mangled_name: {
2631     auto Check = [](CallExpr *TheCall) {
2632       if (TheCall->getNumArgs() != 1)
2633         return false;
2634       auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());
2635       if (!DRE)
2636         return false;
2637       auto *D = DRE->getDecl();
2638       if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D))
2639         return false;
2640       return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
2641              D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
2642     };
2643     if (!Check(TheCall)) {
2644       Diag(TheCall->getBeginLoc(),
2645            diag::err_hip_invalid_args_builtin_mangled_name);
2646       return ExprError();
2647     }
2648   }
2649   }
2650 
2651   // Since the target specific builtins for each arch overlap, only check those
2652   // of the arch we are compiling for.
2653   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
2654     if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
2655       assert(Context.getAuxTargetInfo() &&
2656              "Aux Target Builtin, but not an aux target?");
2657 
2658       if (CheckTSBuiltinFunctionCall(
2659               *Context.getAuxTargetInfo(),
2660               Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
2661         return ExprError();
2662     } else {
2663       if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
2664                                      TheCall))
2665         return ExprError();
2666     }
2667   }
2668 
2669   return TheCallResult;
2670 }
2671 
2672 // Get the valid immediate range for the specified NEON type code.
2673 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
2674   NeonTypeFlags Type(t);
2675   int IsQuad = ForceQuad ? true : Type.isQuad();
2676   switch (Type.getEltType()) {
2677   case NeonTypeFlags::Int8:
2678   case NeonTypeFlags::Poly8:
2679     return shift ? 7 : (8 << IsQuad) - 1;
2680   case NeonTypeFlags::Int16:
2681   case NeonTypeFlags::Poly16:
2682     return shift ? 15 : (4 << IsQuad) - 1;
2683   case NeonTypeFlags::Int32:
2684     return shift ? 31 : (2 << IsQuad) - 1;
2685   case NeonTypeFlags::Int64:
2686   case NeonTypeFlags::Poly64:
2687     return shift ? 63 : (1 << IsQuad) - 1;
2688   case NeonTypeFlags::Poly128:
2689     return shift ? 127 : (1 << IsQuad) - 1;
2690   case NeonTypeFlags::Float16:
2691     assert(!shift && "cannot shift float types!");
2692     return (4 << IsQuad) - 1;
2693   case NeonTypeFlags::Float32:
2694     assert(!shift && "cannot shift float types!");
2695     return (2 << IsQuad) - 1;
2696   case NeonTypeFlags::Float64:
2697     assert(!shift && "cannot shift float types!");
2698     return (1 << IsQuad) - 1;
2699   case NeonTypeFlags::BFloat16:
2700     assert(!shift && "cannot shift float types!");
2701     return (4 << IsQuad) - 1;
2702   }
2703   llvm_unreachable("Invalid NeonTypeFlag!");
2704 }
2705 
2706 /// getNeonEltType - Return the QualType corresponding to the elements of
2707 /// the vector type specified by the NeonTypeFlags.  This is used to check
2708 /// the pointer arguments for Neon load/store intrinsics.
2709 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
2710                                bool IsPolyUnsigned, bool IsInt64Long) {
2711   switch (Flags.getEltType()) {
2712   case NeonTypeFlags::Int8:
2713     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
2714   case NeonTypeFlags::Int16:
2715     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
2716   case NeonTypeFlags::Int32:
2717     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
2718   case NeonTypeFlags::Int64:
2719     if (IsInt64Long)
2720       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
2721     else
2722       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
2723                                 : Context.LongLongTy;
2724   case NeonTypeFlags::Poly8:
2725     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
2726   case NeonTypeFlags::Poly16:
2727     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
2728   case NeonTypeFlags::Poly64:
2729     if (IsInt64Long)
2730       return Context.UnsignedLongTy;
2731     else
2732       return Context.UnsignedLongLongTy;
2733   case NeonTypeFlags::Poly128:
2734     break;
2735   case NeonTypeFlags::Float16:
2736     return Context.HalfTy;
2737   case NeonTypeFlags::Float32:
2738     return Context.FloatTy;
2739   case NeonTypeFlags::Float64:
2740     return Context.DoubleTy;
2741   case NeonTypeFlags::BFloat16:
2742     return Context.BFloat16Ty;
2743   }
2744   llvm_unreachable("Invalid NeonTypeFlag!");
2745 }
2746 
2747 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2748   // Range check SVE intrinsics that take immediate values.
2749   SmallVector<std::tuple<int,int,int>, 3> ImmChecks;
2750 
2751   switch (BuiltinID) {
2752   default:
2753     return false;
2754 #define GET_SVE_IMMEDIATE_CHECK
2755 #include "clang/Basic/arm_sve_sema_rangechecks.inc"
2756 #undef GET_SVE_IMMEDIATE_CHECK
2757   }
2758 
2759   // Perform all the immediate checks for this builtin call.
2760   bool HasError = false;
2761   for (auto &I : ImmChecks) {
2762     int ArgNum, CheckTy, ElementSizeInBits;
2763     std::tie(ArgNum, CheckTy, ElementSizeInBits) = I;
2764 
2765     typedef bool(*OptionSetCheckFnTy)(int64_t Value);
2766 
2767     // Function that checks whether the operand (ArgNum) is an immediate
2768     // that is one of the predefined values.
2769     auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm,
2770                                    int ErrDiag) -> bool {
2771       // We can't check the value of a dependent argument.
2772       Expr *Arg = TheCall->getArg(ArgNum);
2773       if (Arg->isTypeDependent() || Arg->isValueDependent())
2774         return false;
2775 
2776       // Check constant-ness first.
2777       llvm::APSInt Imm;
2778       if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm))
2779         return true;
2780 
2781       if (!CheckImm(Imm.getSExtValue()))
2782         return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange();
2783       return false;
2784     };
2785 
2786     switch ((SVETypeFlags::ImmCheckType)CheckTy) {
2787     case SVETypeFlags::ImmCheck0_31:
2788       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31))
2789         HasError = true;
2790       break;
2791     case SVETypeFlags::ImmCheck0_13:
2792       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13))
2793         HasError = true;
2794       break;
2795     case SVETypeFlags::ImmCheck1_16:
2796       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16))
2797         HasError = true;
2798       break;
2799     case SVETypeFlags::ImmCheck0_7:
2800       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7))
2801         HasError = true;
2802       break;
2803     case SVETypeFlags::ImmCheckExtract:
2804       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2805                                       (2048 / ElementSizeInBits) - 1))
2806         HasError = true;
2807       break;
2808     case SVETypeFlags::ImmCheckShiftRight:
2809       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits))
2810         HasError = true;
2811       break;
2812     case SVETypeFlags::ImmCheckShiftRightNarrow:
2813       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1,
2814                                       ElementSizeInBits / 2))
2815         HasError = true;
2816       break;
2817     case SVETypeFlags::ImmCheckShiftLeft:
2818       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2819                                       ElementSizeInBits - 1))
2820         HasError = true;
2821       break;
2822     case SVETypeFlags::ImmCheckLaneIndex:
2823       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2824                                       (128 / (1 * ElementSizeInBits)) - 1))
2825         HasError = true;
2826       break;
2827     case SVETypeFlags::ImmCheckLaneIndexCompRotate:
2828       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2829                                       (128 / (2 * ElementSizeInBits)) - 1))
2830         HasError = true;
2831       break;
2832     case SVETypeFlags::ImmCheckLaneIndexDot:
2833       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2834                                       (128 / (4 * ElementSizeInBits)) - 1))
2835         HasError = true;
2836       break;
2837     case SVETypeFlags::ImmCheckComplexRot90_270:
2838       if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; },
2839                               diag::err_rotation_argument_to_cadd))
2840         HasError = true;
2841       break;
2842     case SVETypeFlags::ImmCheckComplexRotAll90:
2843       if (CheckImmediateInSet(
2844               [](int64_t V) {
2845                 return V == 0 || V == 90 || V == 180 || V == 270;
2846               },
2847               diag::err_rotation_argument_to_cmla))
2848         HasError = true;
2849       break;
2850     case SVETypeFlags::ImmCheck0_1:
2851       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1))
2852         HasError = true;
2853       break;
2854     case SVETypeFlags::ImmCheck0_2:
2855       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2))
2856         HasError = true;
2857       break;
2858     case SVETypeFlags::ImmCheck0_3:
2859       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3))
2860         HasError = true;
2861       break;
2862     }
2863   }
2864 
2865   return HasError;
2866 }
2867 
2868 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI,
2869                                         unsigned BuiltinID, CallExpr *TheCall) {
2870   llvm::APSInt Result;
2871   uint64_t mask = 0;
2872   unsigned TV = 0;
2873   int PtrArgNum = -1;
2874   bool HasConstPtr = false;
2875   switch (BuiltinID) {
2876 #define GET_NEON_OVERLOAD_CHECK
2877 #include "clang/Basic/arm_neon.inc"
2878 #include "clang/Basic/arm_fp16.inc"
2879 #undef GET_NEON_OVERLOAD_CHECK
2880   }
2881 
2882   // For NEON intrinsics which are overloaded on vector element type, validate
2883   // the immediate which specifies which variant to emit.
2884   unsigned ImmArg = TheCall->getNumArgs()-1;
2885   if (mask) {
2886     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
2887       return true;
2888 
2889     TV = Result.getLimitedValue(64);
2890     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
2891       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
2892              << TheCall->getArg(ImmArg)->getSourceRange();
2893   }
2894 
2895   if (PtrArgNum >= 0) {
2896     // Check that pointer arguments have the specified type.
2897     Expr *Arg = TheCall->getArg(PtrArgNum);
2898     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
2899       Arg = ICE->getSubExpr();
2900     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
2901     QualType RHSTy = RHS.get()->getType();
2902 
2903     llvm::Triple::ArchType Arch = TI.getTriple().getArch();
2904     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
2905                           Arch == llvm::Triple::aarch64_32 ||
2906                           Arch == llvm::Triple::aarch64_be;
2907     bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong;
2908     QualType EltTy =
2909         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
2910     if (HasConstPtr)
2911       EltTy = EltTy.withConst();
2912     QualType LHSTy = Context.getPointerType(EltTy);
2913     AssignConvertType ConvTy;
2914     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
2915     if (RHS.isInvalid())
2916       return true;
2917     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
2918                                  RHS.get(), AA_Assigning))
2919       return true;
2920   }
2921 
2922   // For NEON intrinsics which take an immediate value as part of the
2923   // instruction, range check them here.
2924   unsigned i = 0, l = 0, u = 0;
2925   switch (BuiltinID) {
2926   default:
2927     return false;
2928   #define GET_NEON_IMMEDIATE_CHECK
2929   #include "clang/Basic/arm_neon.inc"
2930   #include "clang/Basic/arm_fp16.inc"
2931   #undef GET_NEON_IMMEDIATE_CHECK
2932   }
2933 
2934   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2935 }
2936 
2937 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2938   switch (BuiltinID) {
2939   default:
2940     return false;
2941   #include "clang/Basic/arm_mve_builtin_sema.inc"
2942   }
2943 }
2944 
2945 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2946                                        CallExpr *TheCall) {
2947   bool Err = false;
2948   switch (BuiltinID) {
2949   default:
2950     return false;
2951 #include "clang/Basic/arm_cde_builtin_sema.inc"
2952   }
2953 
2954   if (Err)
2955     return true;
2956 
2957   return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true);
2958 }
2959 
2960 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI,
2961                                         const Expr *CoprocArg, bool WantCDE) {
2962   if (isConstantEvaluated())
2963     return false;
2964 
2965   // We can't check the value of a dependent argument.
2966   if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent())
2967     return false;
2968 
2969   llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context);
2970   int64_t CoprocNo = CoprocNoAP.getExtValue();
2971   assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative");
2972 
2973   uint32_t CDECoprocMask = TI.getARMCDECoprocMask();
2974   bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo));
2975 
2976   if (IsCDECoproc != WantCDE)
2977     return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc)
2978            << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange();
2979 
2980   return false;
2981 }
2982 
2983 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
2984                                         unsigned MaxWidth) {
2985   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
2986           BuiltinID == ARM::BI__builtin_arm_ldaex ||
2987           BuiltinID == ARM::BI__builtin_arm_strex ||
2988           BuiltinID == ARM::BI__builtin_arm_stlex ||
2989           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2990           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2991           BuiltinID == AArch64::BI__builtin_arm_strex ||
2992           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
2993          "unexpected ARM builtin");
2994   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
2995                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
2996                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2997                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
2998 
2999   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3000 
3001   // Ensure that we have the proper number of arguments.
3002   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
3003     return true;
3004 
3005   // Inspect the pointer argument of the atomic builtin.  This should always be
3006   // a pointer type, whose element is an integral scalar or pointer type.
3007   // Because it is a pointer type, we don't have to worry about any implicit
3008   // casts here.
3009   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
3010   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
3011   if (PointerArgRes.isInvalid())
3012     return true;
3013   PointerArg = PointerArgRes.get();
3014 
3015   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
3016   if (!pointerType) {
3017     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
3018         << PointerArg->getType() << PointerArg->getSourceRange();
3019     return true;
3020   }
3021 
3022   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
3023   // task is to insert the appropriate casts into the AST. First work out just
3024   // what the appropriate type is.
3025   QualType ValType = pointerType->getPointeeType();
3026   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
3027   if (IsLdrex)
3028     AddrType.addConst();
3029 
3030   // Issue a warning if the cast is dodgy.
3031   CastKind CastNeeded = CK_NoOp;
3032   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
3033     CastNeeded = CK_BitCast;
3034     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
3035         << PointerArg->getType() << Context.getPointerType(AddrType)
3036         << AA_Passing << PointerArg->getSourceRange();
3037   }
3038 
3039   // Finally, do the cast and replace the argument with the corrected version.
3040   AddrType = Context.getPointerType(AddrType);
3041   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
3042   if (PointerArgRes.isInvalid())
3043     return true;
3044   PointerArg = PointerArgRes.get();
3045 
3046   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
3047 
3048   // In general, we allow ints, floats and pointers to be loaded and stored.
3049   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3050       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
3051     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
3052         << PointerArg->getType() << PointerArg->getSourceRange();
3053     return true;
3054   }
3055 
3056   // But ARM doesn't have instructions to deal with 128-bit versions.
3057   if (Context.getTypeSize(ValType) > MaxWidth) {
3058     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
3059     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
3060         << PointerArg->getType() << PointerArg->getSourceRange();
3061     return true;
3062   }
3063 
3064   switch (ValType.getObjCLifetime()) {
3065   case Qualifiers::OCL_None:
3066   case Qualifiers::OCL_ExplicitNone:
3067     // okay
3068     break;
3069 
3070   case Qualifiers::OCL_Weak:
3071   case Qualifiers::OCL_Strong:
3072   case Qualifiers::OCL_Autoreleasing:
3073     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
3074         << ValType << PointerArg->getSourceRange();
3075     return true;
3076   }
3077 
3078   if (IsLdrex) {
3079     TheCall->setType(ValType);
3080     return false;
3081   }
3082 
3083   // Initialize the argument to be stored.
3084   ExprResult ValArg = TheCall->getArg(0);
3085   InitializedEntity Entity = InitializedEntity::InitializeParameter(
3086       Context, ValType, /*consume*/ false);
3087   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
3088   if (ValArg.isInvalid())
3089     return true;
3090   TheCall->setArg(0, ValArg.get());
3091 
3092   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
3093   // but the custom checker bypasses all default analysis.
3094   TheCall->setType(Context.IntTy);
3095   return false;
3096 }
3097 
3098 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3099                                        CallExpr *TheCall) {
3100   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
3101       BuiltinID == ARM::BI__builtin_arm_ldaex ||
3102       BuiltinID == ARM::BI__builtin_arm_strex ||
3103       BuiltinID == ARM::BI__builtin_arm_stlex) {
3104     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
3105   }
3106 
3107   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
3108     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3109       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
3110   }
3111 
3112   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
3113       BuiltinID == ARM::BI__builtin_arm_wsr64)
3114     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
3115 
3116   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
3117       BuiltinID == ARM::BI__builtin_arm_rsrp ||
3118       BuiltinID == ARM::BI__builtin_arm_wsr ||
3119       BuiltinID == ARM::BI__builtin_arm_wsrp)
3120     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
3121 
3122   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
3123     return true;
3124   if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
3125     return true;
3126   if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall))
3127     return true;
3128 
3129   // For intrinsics which take an immediate value as part of the instruction,
3130   // range check them here.
3131   // FIXME: VFP Intrinsics should error if VFP not present.
3132   switch (BuiltinID) {
3133   default: return false;
3134   case ARM::BI__builtin_arm_ssat:
3135     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
3136   case ARM::BI__builtin_arm_usat:
3137     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
3138   case ARM::BI__builtin_arm_ssat16:
3139     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
3140   case ARM::BI__builtin_arm_usat16:
3141     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
3142   case ARM::BI__builtin_arm_vcvtr_f:
3143   case ARM::BI__builtin_arm_vcvtr_d:
3144     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3145   case ARM::BI__builtin_arm_dmb:
3146   case ARM::BI__builtin_arm_dsb:
3147   case ARM::BI__builtin_arm_isb:
3148   case ARM::BI__builtin_arm_dbg:
3149     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
3150   case ARM::BI__builtin_arm_cdp:
3151   case ARM::BI__builtin_arm_cdp2:
3152   case ARM::BI__builtin_arm_mcr:
3153   case ARM::BI__builtin_arm_mcr2:
3154   case ARM::BI__builtin_arm_mrc:
3155   case ARM::BI__builtin_arm_mrc2:
3156   case ARM::BI__builtin_arm_mcrr:
3157   case ARM::BI__builtin_arm_mcrr2:
3158   case ARM::BI__builtin_arm_mrrc:
3159   case ARM::BI__builtin_arm_mrrc2:
3160   case ARM::BI__builtin_arm_ldc:
3161   case ARM::BI__builtin_arm_ldcl:
3162   case ARM::BI__builtin_arm_ldc2:
3163   case ARM::BI__builtin_arm_ldc2l:
3164   case ARM::BI__builtin_arm_stc:
3165   case ARM::BI__builtin_arm_stcl:
3166   case ARM::BI__builtin_arm_stc2:
3167   case ARM::BI__builtin_arm_stc2l:
3168     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) ||
3169            CheckARMCoprocessorImmediate(TI, TheCall->getArg(0),
3170                                         /*WantCDE*/ false);
3171   }
3172 }
3173 
3174 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI,
3175                                            unsigned BuiltinID,
3176                                            CallExpr *TheCall) {
3177   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
3178       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
3179       BuiltinID == AArch64::BI__builtin_arm_strex ||
3180       BuiltinID == AArch64::BI__builtin_arm_stlex) {
3181     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
3182   }
3183 
3184   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
3185     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3186       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
3187       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
3188       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
3189   }
3190 
3191   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
3192       BuiltinID == AArch64::BI__builtin_arm_wsr64)
3193     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
3194 
3195   // Memory Tagging Extensions (MTE) Intrinsics
3196   if (BuiltinID == AArch64::BI__builtin_arm_irg ||
3197       BuiltinID == AArch64::BI__builtin_arm_addg ||
3198       BuiltinID == AArch64::BI__builtin_arm_gmi ||
3199       BuiltinID == AArch64::BI__builtin_arm_ldg ||
3200       BuiltinID == AArch64::BI__builtin_arm_stg ||
3201       BuiltinID == AArch64::BI__builtin_arm_subp) {
3202     return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
3203   }
3204 
3205   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
3206       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
3207       BuiltinID == AArch64::BI__builtin_arm_wsr ||
3208       BuiltinID == AArch64::BI__builtin_arm_wsrp)
3209     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
3210 
3211   // Only check the valid encoding range. Any constant in this range would be
3212   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
3213   // an exception for incorrect registers. This matches MSVC behavior.
3214   if (BuiltinID == AArch64::BI_ReadStatusReg ||
3215       BuiltinID == AArch64::BI_WriteStatusReg)
3216     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
3217 
3218   if (BuiltinID == AArch64::BI__getReg)
3219     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
3220 
3221   if (BuiltinID == AArch64::BI__break)
3222     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xffff);
3223 
3224   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
3225     return true;
3226 
3227   if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall))
3228     return true;
3229 
3230   // For intrinsics which take an immediate value as part of the instruction,
3231   // range check them here.
3232   unsigned i = 0, l = 0, u = 0;
3233   switch (BuiltinID) {
3234   default: return false;
3235   case AArch64::BI__builtin_arm_dmb:
3236   case AArch64::BI__builtin_arm_dsb:
3237   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
3238   case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
3239   }
3240 
3241   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
3242 }
3243 
3244 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) {
3245   if (Arg->getType()->getAsPlaceholderType())
3246     return false;
3247 
3248   // The first argument needs to be a record field access.
3249   // If it is an array element access, we delay decision
3250   // to BPF backend to check whether the access is a
3251   // field access or not.
3252   return (Arg->IgnoreParens()->getObjectKind() == OK_BitField ||
3253           isa<MemberExpr>(Arg->IgnoreParens()) ||
3254           isa<ArraySubscriptExpr>(Arg->IgnoreParens()));
3255 }
3256 
3257 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) {
3258   QualType ArgType = Arg->getType();
3259   if (ArgType->getAsPlaceholderType())
3260     return false;
3261 
3262   // for TYPE_EXISTENCE/TYPE_MATCH/TYPE_SIZEOF reloc type
3263   // format:
3264   //   1. __builtin_preserve_type_info(*(<type> *)0, flag);
3265   //   2. <type> var;
3266   //      __builtin_preserve_type_info(var, flag);
3267   if (!isa<DeclRefExpr>(Arg->IgnoreParens()) &&
3268       !isa<UnaryOperator>(Arg->IgnoreParens()))
3269     return false;
3270 
3271   // Typedef type.
3272   if (ArgType->getAs<TypedefType>())
3273     return true;
3274 
3275   // Record type or Enum type.
3276   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
3277   if (const auto *RT = Ty->getAs<RecordType>()) {
3278     if (!RT->getDecl()->getDeclName().isEmpty())
3279       return true;
3280   } else if (const auto *ET = Ty->getAs<EnumType>()) {
3281     if (!ET->getDecl()->getDeclName().isEmpty())
3282       return true;
3283   }
3284 
3285   return false;
3286 }
3287 
3288 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) {
3289   QualType ArgType = Arg->getType();
3290   if (ArgType->getAsPlaceholderType())
3291     return false;
3292 
3293   // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type
3294   // format:
3295   //   __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>,
3296   //                                 flag);
3297   const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens());
3298   if (!UO)
3299     return false;
3300 
3301   const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr());
3302   if (!CE)
3303     return false;
3304   if (CE->getCastKind() != CK_IntegralToPointer &&
3305       CE->getCastKind() != CK_NullToPointer)
3306     return false;
3307 
3308   // The integer must be from an EnumConstantDecl.
3309   const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr());
3310   if (!DR)
3311     return false;
3312 
3313   const EnumConstantDecl *Enumerator =
3314       dyn_cast<EnumConstantDecl>(DR->getDecl());
3315   if (!Enumerator)
3316     return false;
3317 
3318   // The type must be EnumType.
3319   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
3320   const auto *ET = Ty->getAs<EnumType>();
3321   if (!ET)
3322     return false;
3323 
3324   // The enum value must be supported.
3325   return llvm::is_contained(ET->getDecl()->enumerators(), Enumerator);
3326 }
3327 
3328 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
3329                                        CallExpr *TheCall) {
3330   assert((BuiltinID == BPF::BI__builtin_preserve_field_info ||
3331           BuiltinID == BPF::BI__builtin_btf_type_id ||
3332           BuiltinID == BPF::BI__builtin_preserve_type_info ||
3333           BuiltinID == BPF::BI__builtin_preserve_enum_value) &&
3334          "unexpected BPF builtin");
3335 
3336   if (checkArgCount(*this, TheCall, 2))
3337     return true;
3338 
3339   // The second argument needs to be a constant int
3340   Expr *Arg = TheCall->getArg(1);
3341   Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context);
3342   diag::kind kind;
3343   if (!Value) {
3344     if (BuiltinID == BPF::BI__builtin_preserve_field_info)
3345       kind = diag::err_preserve_field_info_not_const;
3346     else if (BuiltinID == BPF::BI__builtin_btf_type_id)
3347       kind = diag::err_btf_type_id_not_const;
3348     else if (BuiltinID == BPF::BI__builtin_preserve_type_info)
3349       kind = diag::err_preserve_type_info_not_const;
3350     else
3351       kind = diag::err_preserve_enum_value_not_const;
3352     Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange();
3353     return true;
3354   }
3355 
3356   // The first argument
3357   Arg = TheCall->getArg(0);
3358   bool InvalidArg = false;
3359   bool ReturnUnsignedInt = true;
3360   if (BuiltinID == BPF::BI__builtin_preserve_field_info) {
3361     if (!isValidBPFPreserveFieldInfoArg(Arg)) {
3362       InvalidArg = true;
3363       kind = diag::err_preserve_field_info_not_field;
3364     }
3365   } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) {
3366     if (!isValidBPFPreserveTypeInfoArg(Arg)) {
3367       InvalidArg = true;
3368       kind = diag::err_preserve_type_info_invalid;
3369     }
3370   } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) {
3371     if (!isValidBPFPreserveEnumValueArg(Arg)) {
3372       InvalidArg = true;
3373       kind = diag::err_preserve_enum_value_invalid;
3374     }
3375     ReturnUnsignedInt = false;
3376   } else if (BuiltinID == BPF::BI__builtin_btf_type_id) {
3377     ReturnUnsignedInt = false;
3378   }
3379 
3380   if (InvalidArg) {
3381     Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange();
3382     return true;
3383   }
3384 
3385   if (ReturnUnsignedInt)
3386     TheCall->setType(Context.UnsignedIntTy);
3387   else
3388     TheCall->setType(Context.UnsignedLongTy);
3389   return false;
3390 }
3391 
3392 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
3393   struct ArgInfo {
3394     uint8_t OpNum;
3395     bool IsSigned;
3396     uint8_t BitWidth;
3397     uint8_t Align;
3398   };
3399   struct BuiltinInfo {
3400     unsigned BuiltinID;
3401     ArgInfo Infos[2];
3402   };
3403 
3404   static BuiltinInfo Infos[] = {
3405     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
3406     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
3407     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
3408     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  1 }} },
3409     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
3410     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
3411     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
3412     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
3413     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
3414     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
3415     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
3416 
3417     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
3418     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
3419     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
3420     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
3421     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
3422     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
3423     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
3424     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
3425     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
3426     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
3427     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
3428 
3429     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
3430     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
3431     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
3432     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
3433     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
3434     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
3435     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
3436     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
3437     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
3438     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
3439     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
3440     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
3441     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
3442     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
3443     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
3444     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
3445     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
3446     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
3447     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
3448     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
3449     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
3450     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
3451     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
3452     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
3453     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
3454     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
3455     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
3456     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
3457     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
3458     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
3459     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
3460     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
3461     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
3462     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
3463     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
3464     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
3465     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
3466     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
3467     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
3468     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
3469     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
3470     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
3471     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
3472     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
3473     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
3474     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
3475     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
3476     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
3477     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
3478     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
3479     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
3480     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
3481                                                       {{ 1, false, 6,  0 }} },
3482     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
3483     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
3484     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
3485     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
3486     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
3487     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
3488     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
3489                                                       {{ 1, false, 5,  0 }} },
3490     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
3491     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
3492     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
3493     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
3494     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
3495     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
3496                                                        { 2, false, 5,  0 }} },
3497     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
3498                                                        { 2, false, 6,  0 }} },
3499     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
3500                                                        { 3, false, 5,  0 }} },
3501     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
3502                                                        { 3, false, 6,  0 }} },
3503     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
3504     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
3505     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
3506     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
3507     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
3508     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
3509     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
3510     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
3511     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
3512     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
3513     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
3514     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
3515     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
3516     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
3517     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
3518     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
3519                                                       {{ 2, false, 4,  0 },
3520                                                        { 3, false, 5,  0 }} },
3521     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
3522                                                       {{ 2, false, 4,  0 },
3523                                                        { 3, false, 5,  0 }} },
3524     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
3525                                                       {{ 2, false, 4,  0 },
3526                                                        { 3, false, 5,  0 }} },
3527     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
3528                                                       {{ 2, false, 4,  0 },
3529                                                        { 3, false, 5,  0 }} },
3530     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
3531     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
3532     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
3533     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
3534     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
3535     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
3536     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
3537     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
3538     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
3539     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
3540     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
3541                                                        { 2, false, 5,  0 }} },
3542     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
3543                                                        { 2, false, 6,  0 }} },
3544     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
3545     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
3546     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
3547     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
3548     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
3549     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
3550     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
3551     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
3552     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
3553                                                       {{ 1, false, 4,  0 }} },
3554     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
3555     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
3556                                                       {{ 1, false, 4,  0 }} },
3557     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
3558     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
3559     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
3560     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
3561     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
3562     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
3563     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
3564     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
3565     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
3566     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
3567     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
3568     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
3569     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
3570     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
3571     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
3572     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
3573     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
3574     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
3575     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
3576     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
3577                                                       {{ 3, false, 1,  0 }} },
3578     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
3579     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
3580     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
3581     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
3582                                                       {{ 3, false, 1,  0 }} },
3583     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
3584     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
3585     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
3586     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
3587                                                       {{ 3, false, 1,  0 }} },
3588   };
3589 
3590   // Use a dynamically initialized static to sort the table exactly once on
3591   // first run.
3592   static const bool SortOnce =
3593       (llvm::sort(Infos,
3594                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
3595                    return LHS.BuiltinID < RHS.BuiltinID;
3596                  }),
3597        true);
3598   (void)SortOnce;
3599 
3600   const BuiltinInfo *F = llvm::partition_point(
3601       Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
3602   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
3603     return false;
3604 
3605   bool Error = false;
3606 
3607   for (const ArgInfo &A : F->Infos) {
3608     // Ignore empty ArgInfo elements.
3609     if (A.BitWidth == 0)
3610       continue;
3611 
3612     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
3613     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
3614     if (!A.Align) {
3615       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
3616     } else {
3617       unsigned M = 1 << A.Align;
3618       Min *= M;
3619       Max *= M;
3620       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
3621       Error |= SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
3622     }
3623   }
3624   return Error;
3625 }
3626 
3627 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
3628                                            CallExpr *TheCall) {
3629   return CheckHexagonBuiltinArgument(BuiltinID, TheCall);
3630 }
3631 
3632 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI,
3633                                         unsigned BuiltinID, CallExpr *TheCall) {
3634   return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) ||
3635          CheckMipsBuiltinArgument(BuiltinID, TheCall);
3636 }
3637 
3638 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
3639                                CallExpr *TheCall) {
3640 
3641   if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
3642       BuiltinID <= Mips::BI__builtin_mips_lwx) {
3643     if (!TI.hasFeature("dsp"))
3644       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
3645   }
3646 
3647   if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
3648       BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
3649     if (!TI.hasFeature("dspr2"))
3650       return Diag(TheCall->getBeginLoc(),
3651                   diag::err_mips_builtin_requires_dspr2);
3652   }
3653 
3654   if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
3655       BuiltinID <= Mips::BI__builtin_msa_xori_b) {
3656     if (!TI.hasFeature("msa"))
3657       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
3658   }
3659 
3660   return false;
3661 }
3662 
3663 // CheckMipsBuiltinArgument - Checks the constant value passed to the
3664 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
3665 // ordering for DSP is unspecified. MSA is ordered by the data format used
3666 // by the underlying instruction i.e., df/m, df/n and then by size.
3667 //
3668 // FIXME: The size tests here should instead be tablegen'd along with the
3669 //        definitions from include/clang/Basic/BuiltinsMips.def.
3670 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
3671 //        be too.
3672 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
3673   unsigned i = 0, l = 0, u = 0, m = 0;
3674   switch (BuiltinID) {
3675   default: return false;
3676   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
3677   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
3678   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
3679   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
3680   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
3681   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
3682   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
3683   // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
3684   // df/m field.
3685   // These intrinsics take an unsigned 3 bit immediate.
3686   case Mips::BI__builtin_msa_bclri_b:
3687   case Mips::BI__builtin_msa_bnegi_b:
3688   case Mips::BI__builtin_msa_bseti_b:
3689   case Mips::BI__builtin_msa_sat_s_b:
3690   case Mips::BI__builtin_msa_sat_u_b:
3691   case Mips::BI__builtin_msa_slli_b:
3692   case Mips::BI__builtin_msa_srai_b:
3693   case Mips::BI__builtin_msa_srari_b:
3694   case Mips::BI__builtin_msa_srli_b:
3695   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
3696   case Mips::BI__builtin_msa_binsli_b:
3697   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
3698   // These intrinsics take an unsigned 4 bit immediate.
3699   case Mips::BI__builtin_msa_bclri_h:
3700   case Mips::BI__builtin_msa_bnegi_h:
3701   case Mips::BI__builtin_msa_bseti_h:
3702   case Mips::BI__builtin_msa_sat_s_h:
3703   case Mips::BI__builtin_msa_sat_u_h:
3704   case Mips::BI__builtin_msa_slli_h:
3705   case Mips::BI__builtin_msa_srai_h:
3706   case Mips::BI__builtin_msa_srari_h:
3707   case Mips::BI__builtin_msa_srli_h:
3708   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
3709   case Mips::BI__builtin_msa_binsli_h:
3710   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
3711   // These intrinsics take an unsigned 5 bit immediate.
3712   // The first block of intrinsics actually have an unsigned 5 bit field,
3713   // not a df/n field.
3714   case Mips::BI__builtin_msa_cfcmsa:
3715   case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
3716   case Mips::BI__builtin_msa_clei_u_b:
3717   case Mips::BI__builtin_msa_clei_u_h:
3718   case Mips::BI__builtin_msa_clei_u_w:
3719   case Mips::BI__builtin_msa_clei_u_d:
3720   case Mips::BI__builtin_msa_clti_u_b:
3721   case Mips::BI__builtin_msa_clti_u_h:
3722   case Mips::BI__builtin_msa_clti_u_w:
3723   case Mips::BI__builtin_msa_clti_u_d:
3724   case Mips::BI__builtin_msa_maxi_u_b:
3725   case Mips::BI__builtin_msa_maxi_u_h:
3726   case Mips::BI__builtin_msa_maxi_u_w:
3727   case Mips::BI__builtin_msa_maxi_u_d:
3728   case Mips::BI__builtin_msa_mini_u_b:
3729   case Mips::BI__builtin_msa_mini_u_h:
3730   case Mips::BI__builtin_msa_mini_u_w:
3731   case Mips::BI__builtin_msa_mini_u_d:
3732   case Mips::BI__builtin_msa_addvi_b:
3733   case Mips::BI__builtin_msa_addvi_h:
3734   case Mips::BI__builtin_msa_addvi_w:
3735   case Mips::BI__builtin_msa_addvi_d:
3736   case Mips::BI__builtin_msa_bclri_w:
3737   case Mips::BI__builtin_msa_bnegi_w:
3738   case Mips::BI__builtin_msa_bseti_w:
3739   case Mips::BI__builtin_msa_sat_s_w:
3740   case Mips::BI__builtin_msa_sat_u_w:
3741   case Mips::BI__builtin_msa_slli_w:
3742   case Mips::BI__builtin_msa_srai_w:
3743   case Mips::BI__builtin_msa_srari_w:
3744   case Mips::BI__builtin_msa_srli_w:
3745   case Mips::BI__builtin_msa_srlri_w:
3746   case Mips::BI__builtin_msa_subvi_b:
3747   case Mips::BI__builtin_msa_subvi_h:
3748   case Mips::BI__builtin_msa_subvi_w:
3749   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
3750   case Mips::BI__builtin_msa_binsli_w:
3751   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
3752   // These intrinsics take an unsigned 6 bit immediate.
3753   case Mips::BI__builtin_msa_bclri_d:
3754   case Mips::BI__builtin_msa_bnegi_d:
3755   case Mips::BI__builtin_msa_bseti_d:
3756   case Mips::BI__builtin_msa_sat_s_d:
3757   case Mips::BI__builtin_msa_sat_u_d:
3758   case Mips::BI__builtin_msa_slli_d:
3759   case Mips::BI__builtin_msa_srai_d:
3760   case Mips::BI__builtin_msa_srari_d:
3761   case Mips::BI__builtin_msa_srli_d:
3762   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
3763   case Mips::BI__builtin_msa_binsli_d:
3764   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
3765   // These intrinsics take a signed 5 bit immediate.
3766   case Mips::BI__builtin_msa_ceqi_b:
3767   case Mips::BI__builtin_msa_ceqi_h:
3768   case Mips::BI__builtin_msa_ceqi_w:
3769   case Mips::BI__builtin_msa_ceqi_d:
3770   case Mips::BI__builtin_msa_clti_s_b:
3771   case Mips::BI__builtin_msa_clti_s_h:
3772   case Mips::BI__builtin_msa_clti_s_w:
3773   case Mips::BI__builtin_msa_clti_s_d:
3774   case Mips::BI__builtin_msa_clei_s_b:
3775   case Mips::BI__builtin_msa_clei_s_h:
3776   case Mips::BI__builtin_msa_clei_s_w:
3777   case Mips::BI__builtin_msa_clei_s_d:
3778   case Mips::BI__builtin_msa_maxi_s_b:
3779   case Mips::BI__builtin_msa_maxi_s_h:
3780   case Mips::BI__builtin_msa_maxi_s_w:
3781   case Mips::BI__builtin_msa_maxi_s_d:
3782   case Mips::BI__builtin_msa_mini_s_b:
3783   case Mips::BI__builtin_msa_mini_s_h:
3784   case Mips::BI__builtin_msa_mini_s_w:
3785   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
3786   // These intrinsics take an unsigned 8 bit immediate.
3787   case Mips::BI__builtin_msa_andi_b:
3788   case Mips::BI__builtin_msa_nori_b:
3789   case Mips::BI__builtin_msa_ori_b:
3790   case Mips::BI__builtin_msa_shf_b:
3791   case Mips::BI__builtin_msa_shf_h:
3792   case Mips::BI__builtin_msa_shf_w:
3793   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
3794   case Mips::BI__builtin_msa_bseli_b:
3795   case Mips::BI__builtin_msa_bmnzi_b:
3796   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
3797   // df/n format
3798   // These intrinsics take an unsigned 4 bit immediate.
3799   case Mips::BI__builtin_msa_copy_s_b:
3800   case Mips::BI__builtin_msa_copy_u_b:
3801   case Mips::BI__builtin_msa_insve_b:
3802   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
3803   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
3804   // These intrinsics take an unsigned 3 bit immediate.
3805   case Mips::BI__builtin_msa_copy_s_h:
3806   case Mips::BI__builtin_msa_copy_u_h:
3807   case Mips::BI__builtin_msa_insve_h:
3808   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
3809   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3810   // These intrinsics take an unsigned 2 bit immediate.
3811   case Mips::BI__builtin_msa_copy_s_w:
3812   case Mips::BI__builtin_msa_copy_u_w:
3813   case Mips::BI__builtin_msa_insve_w:
3814   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
3815   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3816   // These intrinsics take an unsigned 1 bit immediate.
3817   case Mips::BI__builtin_msa_copy_s_d:
3818   case Mips::BI__builtin_msa_copy_u_d:
3819   case Mips::BI__builtin_msa_insve_d:
3820   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
3821   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3822   // Memory offsets and immediate loads.
3823   // These intrinsics take a signed 10 bit immediate.
3824   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
3825   case Mips::BI__builtin_msa_ldi_h:
3826   case Mips::BI__builtin_msa_ldi_w:
3827   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
3828   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3829   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3830   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3831   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3832   case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break;
3833   case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break;
3834   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3835   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3836   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3837   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
3838   case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break;
3839   case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break;
3840   }
3841 
3842   if (!m)
3843     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3844 
3845   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3846          SemaBuiltinConstantArgMultiple(TheCall, i, m);
3847 }
3848 
3849 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str,
3850 /// advancing the pointer over the consumed characters. The decoded type is
3851 /// returned. If the decoded type represents a constant integer with a
3852 /// constraint on its value then Mask is set to that value. The type descriptors
3853 /// used in Str are specific to PPC MMA builtins and are documented in the file
3854 /// defining the PPC builtins.
3855 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str,
3856                                         unsigned &Mask) {
3857   bool RequireICE = false;
3858   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3859   switch (*Str++) {
3860   case 'V':
3861     return Context.getVectorType(Context.UnsignedCharTy, 16,
3862                                  VectorType::VectorKind::AltiVecVector);
3863   case 'i': {
3864     char *End;
3865     unsigned size = strtoul(Str, &End, 10);
3866     assert(End != Str && "Missing constant parameter constraint");
3867     Str = End;
3868     Mask = size;
3869     return Context.IntTy;
3870   }
3871   case 'W': {
3872     char *End;
3873     unsigned size = strtoul(Str, &End, 10);
3874     assert(End != Str && "Missing PowerPC MMA type size");
3875     Str = End;
3876     QualType Type;
3877     switch (size) {
3878   #define PPC_VECTOR_TYPE(typeName, Id, size) \
3879     case size: Type = Context.Id##Ty; break;
3880   #include "clang/Basic/PPCTypes.def"
3881     default: llvm_unreachable("Invalid PowerPC MMA vector type");
3882     }
3883     bool CheckVectorArgs = false;
3884     while (!CheckVectorArgs) {
3885       switch (*Str++) {
3886       case '*':
3887         Type = Context.getPointerType(Type);
3888         break;
3889       case 'C':
3890         Type = Type.withConst();
3891         break;
3892       default:
3893         CheckVectorArgs = true;
3894         --Str;
3895         break;
3896       }
3897     }
3898     return Type;
3899   }
3900   default:
3901     return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true);
3902   }
3903 }
3904 
3905 static bool isPPC_64Builtin(unsigned BuiltinID) {
3906   // These builtins only work on PPC 64bit targets.
3907   switch (BuiltinID) {
3908   case PPC::BI__builtin_divde:
3909   case PPC::BI__builtin_divdeu:
3910   case PPC::BI__builtin_bpermd:
3911   case PPC::BI__builtin_pdepd:
3912   case PPC::BI__builtin_pextd:
3913   case PPC::BI__builtin_ppc_ldarx:
3914   case PPC::BI__builtin_ppc_stdcx:
3915   case PPC::BI__builtin_ppc_tdw:
3916   case PPC::BI__builtin_ppc_trapd:
3917   case PPC::BI__builtin_ppc_cmpeqb:
3918   case PPC::BI__builtin_ppc_setb:
3919   case PPC::BI__builtin_ppc_mulhd:
3920   case PPC::BI__builtin_ppc_mulhdu:
3921   case PPC::BI__builtin_ppc_maddhd:
3922   case PPC::BI__builtin_ppc_maddhdu:
3923   case PPC::BI__builtin_ppc_maddld:
3924   case PPC::BI__builtin_ppc_load8r:
3925   case PPC::BI__builtin_ppc_store8r:
3926   case PPC::BI__builtin_ppc_insert_exp:
3927   case PPC::BI__builtin_ppc_extract_sig:
3928   case PPC::BI__builtin_ppc_addex:
3929   case PPC::BI__builtin_darn:
3930   case PPC::BI__builtin_darn_raw:
3931   case PPC::BI__builtin_ppc_compare_and_swaplp:
3932   case PPC::BI__builtin_ppc_fetch_and_addlp:
3933   case PPC::BI__builtin_ppc_fetch_and_andlp:
3934   case PPC::BI__builtin_ppc_fetch_and_orlp:
3935   case PPC::BI__builtin_ppc_fetch_and_swaplp:
3936     return true;
3937   }
3938   return false;
3939 }
3940 
3941 static bool SemaFeatureCheck(Sema &S, CallExpr *TheCall,
3942                              StringRef FeatureToCheck, unsigned DiagID,
3943                              StringRef DiagArg = "") {
3944   if (S.Context.getTargetInfo().hasFeature(FeatureToCheck))
3945     return false;
3946 
3947   if (DiagArg.empty())
3948     S.Diag(TheCall->getBeginLoc(), DiagID) << TheCall->getSourceRange();
3949   else
3950     S.Diag(TheCall->getBeginLoc(), DiagID)
3951         << DiagArg << TheCall->getSourceRange();
3952 
3953   return true;
3954 }
3955 
3956 /// Returns true if the argument consists of one contiguous run of 1s with any
3957 /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB, so
3958 /// 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not,
3959 /// since all 1s are not contiguous.
3960 bool Sema::SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
3961   llvm::APSInt Result;
3962   // We can't check the value of a dependent argument.
3963   Expr *Arg = TheCall->getArg(ArgNum);
3964   if (Arg->isTypeDependent() || Arg->isValueDependent())
3965     return false;
3966 
3967   // Check constant-ness first.
3968   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3969     return true;
3970 
3971   // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
3972   if (Result.isShiftedMask() || (~Result).isShiftedMask())
3973     return false;
3974 
3975   return Diag(TheCall->getBeginLoc(),
3976               diag::err_argument_not_contiguous_bit_field)
3977          << ArgNum << Arg->getSourceRange();
3978 }
3979 
3980 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3981                                        CallExpr *TheCall) {
3982   unsigned i = 0, l = 0, u = 0;
3983   bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64;
3984   llvm::APSInt Result;
3985 
3986   if (isPPC_64Builtin(BuiltinID) && !IsTarget64Bit)
3987     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3988            << TheCall->getSourceRange();
3989 
3990   switch (BuiltinID) {
3991   default: return false;
3992   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3993   case PPC::BI__builtin_altivec_crypto_vshasigmad:
3994     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3995            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3996   case PPC::BI__builtin_altivec_dss:
3997     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
3998   case PPC::BI__builtin_tbegin:
3999   case PPC::BI__builtin_tend:
4000     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 1) ||
4001            SemaFeatureCheck(*this, TheCall, "htm",
4002                             diag::err_ppc_builtin_requires_htm);
4003   case PPC::BI__builtin_tsr:
4004     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) ||
4005            SemaFeatureCheck(*this, TheCall, "htm",
4006                             diag::err_ppc_builtin_requires_htm);
4007   case PPC::BI__builtin_tabortwc:
4008   case PPC::BI__builtin_tabortdc:
4009     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
4010            SemaFeatureCheck(*this, TheCall, "htm",
4011                             diag::err_ppc_builtin_requires_htm);
4012   case PPC::BI__builtin_tabortwci:
4013   case PPC::BI__builtin_tabortdci:
4014     return SemaFeatureCheck(*this, TheCall, "htm",
4015                             diag::err_ppc_builtin_requires_htm) ||
4016            (SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
4017             SemaBuiltinConstantArgRange(TheCall, 2, 0, 31));
4018   case PPC::BI__builtin_tabort:
4019   case PPC::BI__builtin_tcheck:
4020   case PPC::BI__builtin_treclaim:
4021   case PPC::BI__builtin_trechkpt:
4022   case PPC::BI__builtin_tendall:
4023   case PPC::BI__builtin_tresume:
4024   case PPC::BI__builtin_tsuspend:
4025   case PPC::BI__builtin_get_texasr:
4026   case PPC::BI__builtin_get_texasru:
4027   case PPC::BI__builtin_get_tfhar:
4028   case PPC::BI__builtin_get_tfiar:
4029   case PPC::BI__builtin_set_texasr:
4030   case PPC::BI__builtin_set_texasru:
4031   case PPC::BI__builtin_set_tfhar:
4032   case PPC::BI__builtin_set_tfiar:
4033   case PPC::BI__builtin_ttest:
4034     return SemaFeatureCheck(*this, TheCall, "htm",
4035                             diag::err_ppc_builtin_requires_htm);
4036   // According to GCC 'Basic PowerPC Built-in Functions Available on ISA 2.05',
4037   // __builtin_(un)pack_longdouble are available only if long double uses IBM
4038   // extended double representation.
4039   case PPC::BI__builtin_unpack_longdouble:
4040     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 1))
4041       return true;
4042     LLVM_FALLTHROUGH;
4043   case PPC::BI__builtin_pack_longdouble:
4044     if (&TI.getLongDoubleFormat() != &llvm::APFloat::PPCDoubleDouble())
4045       return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_requires_abi)
4046              << "ibmlongdouble";
4047     return false;
4048   case PPC::BI__builtin_altivec_dst:
4049   case PPC::BI__builtin_altivec_dstt:
4050   case PPC::BI__builtin_altivec_dstst:
4051   case PPC::BI__builtin_altivec_dststt:
4052     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
4053   case PPC::BI__builtin_vsx_xxpermdi:
4054   case PPC::BI__builtin_vsx_xxsldwi:
4055     return SemaBuiltinVSX(TheCall);
4056   case PPC::BI__builtin_divwe:
4057   case PPC::BI__builtin_divweu:
4058   case PPC::BI__builtin_divde:
4059   case PPC::BI__builtin_divdeu:
4060     return SemaFeatureCheck(*this, TheCall, "extdiv",
4061                             diag::err_ppc_builtin_only_on_arch, "7");
4062   case PPC::BI__builtin_bpermd:
4063     return SemaFeatureCheck(*this, TheCall, "bpermd",
4064                             diag::err_ppc_builtin_only_on_arch, "7");
4065   case PPC::BI__builtin_unpack_vector_int128:
4066     return SemaFeatureCheck(*this, TheCall, "vsx",
4067                             diag::err_ppc_builtin_only_on_arch, "7") ||
4068            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
4069   case PPC::BI__builtin_pack_vector_int128:
4070     return SemaFeatureCheck(*this, TheCall, "vsx",
4071                             diag::err_ppc_builtin_only_on_arch, "7");
4072   case PPC::BI__builtin_pdepd:
4073   case PPC::BI__builtin_pextd:
4074     return SemaFeatureCheck(*this, TheCall, "isa-v31-instructions",
4075                             diag::err_ppc_builtin_only_on_arch, "10");
4076   case PPC::BI__builtin_altivec_vgnb:
4077      return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7);
4078   case PPC::BI__builtin_vsx_xxeval:
4079      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255);
4080   case PPC::BI__builtin_altivec_vsldbi:
4081      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
4082   case PPC::BI__builtin_altivec_vsrdbi:
4083      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
4084   case PPC::BI__builtin_vsx_xxpermx:
4085      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7);
4086   case PPC::BI__builtin_ppc_tw:
4087   case PPC::BI__builtin_ppc_tdw:
4088     return SemaBuiltinConstantArgRange(TheCall, 2, 1, 31);
4089   case PPC::BI__builtin_ppc_cmpeqb:
4090   case PPC::BI__builtin_ppc_setb:
4091   case PPC::BI__builtin_ppc_maddhd:
4092   case PPC::BI__builtin_ppc_maddhdu:
4093   case PPC::BI__builtin_ppc_maddld:
4094     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
4095                             diag::err_ppc_builtin_only_on_arch, "9");
4096   case PPC::BI__builtin_ppc_cmprb:
4097     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
4098                             diag::err_ppc_builtin_only_on_arch, "9") ||
4099            SemaBuiltinConstantArgRange(TheCall, 0, 0, 1);
4100   // For __rlwnm, __rlwimi and __rldimi, the last parameter mask must
4101   // be a constant that represents a contiguous bit field.
4102   case PPC::BI__builtin_ppc_rlwnm:
4103     return SemaValueIsRunOfOnes(TheCall, 2);
4104   case PPC::BI__builtin_ppc_rlwimi:
4105   case PPC::BI__builtin_ppc_rldimi:
4106     return SemaBuiltinConstantArg(TheCall, 2, Result) ||
4107            SemaValueIsRunOfOnes(TheCall, 3);
4108   case PPC::BI__builtin_ppc_extract_exp:
4109   case PPC::BI__builtin_ppc_extract_sig:
4110   case PPC::BI__builtin_ppc_insert_exp:
4111     return SemaFeatureCheck(*this, TheCall, "power9-vector",
4112                             diag::err_ppc_builtin_only_on_arch, "9");
4113   case PPC::BI__builtin_ppc_addex: {
4114     if (SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
4115                          diag::err_ppc_builtin_only_on_arch, "9") ||
4116         SemaBuiltinConstantArgRange(TheCall, 2, 0, 3))
4117       return true;
4118     // Output warning for reserved values 1 to 3.
4119     int ArgValue =
4120         TheCall->getArg(2)->getIntegerConstantExpr(Context)->getSExtValue();
4121     if (ArgValue != 0)
4122       Diag(TheCall->getBeginLoc(), diag::warn_argument_undefined_behaviour)
4123           << ArgValue;
4124     return false;
4125   }
4126   case PPC::BI__builtin_ppc_mtfsb0:
4127   case PPC::BI__builtin_ppc_mtfsb1:
4128     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
4129   case PPC::BI__builtin_ppc_mtfsf:
4130     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 255);
4131   case PPC::BI__builtin_ppc_mtfsfi:
4132     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) ||
4133            SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
4134   case PPC::BI__builtin_ppc_alignx:
4135     return SemaBuiltinConstantArgPower2(TheCall, 0);
4136   case PPC::BI__builtin_ppc_rdlam:
4137     return SemaValueIsRunOfOnes(TheCall, 2);
4138   case PPC::BI__builtin_ppc_icbt:
4139   case PPC::BI__builtin_ppc_sthcx:
4140   case PPC::BI__builtin_ppc_stbcx:
4141   case PPC::BI__builtin_ppc_lharx:
4142   case PPC::BI__builtin_ppc_lbarx:
4143     return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions",
4144                             diag::err_ppc_builtin_only_on_arch, "8");
4145   case PPC::BI__builtin_vsx_ldrmb:
4146   case PPC::BI__builtin_vsx_strmb:
4147     return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions",
4148                             diag::err_ppc_builtin_only_on_arch, "8") ||
4149            SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
4150   case PPC::BI__builtin_altivec_vcntmbb:
4151   case PPC::BI__builtin_altivec_vcntmbh:
4152   case PPC::BI__builtin_altivec_vcntmbw:
4153   case PPC::BI__builtin_altivec_vcntmbd:
4154     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
4155   case PPC::BI__builtin_darn:
4156   case PPC::BI__builtin_darn_raw:
4157   case PPC::BI__builtin_darn_32:
4158     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
4159                             diag::err_ppc_builtin_only_on_arch, "9");
4160   case PPC::BI__builtin_vsx_xxgenpcvbm:
4161   case PPC::BI__builtin_vsx_xxgenpcvhm:
4162   case PPC::BI__builtin_vsx_xxgenpcvwm:
4163   case PPC::BI__builtin_vsx_xxgenpcvdm:
4164     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
4165   case PPC::BI__builtin_ppc_compare_exp_uo:
4166   case PPC::BI__builtin_ppc_compare_exp_lt:
4167   case PPC::BI__builtin_ppc_compare_exp_gt:
4168   case PPC::BI__builtin_ppc_compare_exp_eq:
4169     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
4170                             diag::err_ppc_builtin_only_on_arch, "9") ||
4171            SemaFeatureCheck(*this, TheCall, "vsx",
4172                             diag::err_ppc_builtin_requires_vsx);
4173   case PPC::BI__builtin_ppc_test_data_class: {
4174     // Check if the first argument of the __builtin_ppc_test_data_class call is
4175     // valid. The argument must be either a 'float' or a 'double'.
4176     QualType ArgType = TheCall->getArg(0)->getType();
4177     if (ArgType != QualType(Context.FloatTy) &&
4178         ArgType != QualType(Context.DoubleTy))
4179       return Diag(TheCall->getBeginLoc(),
4180                   diag::err_ppc_invalid_test_data_class_type);
4181     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
4182                             diag::err_ppc_builtin_only_on_arch, "9") ||
4183            SemaFeatureCheck(*this, TheCall, "vsx",
4184                             diag::err_ppc_builtin_requires_vsx) ||
4185            SemaBuiltinConstantArgRange(TheCall, 1, 0, 127);
4186   }
4187   case PPC::BI__builtin_ppc_maxfe:
4188   case PPC::BI__builtin_ppc_minfe:
4189   case PPC::BI__builtin_ppc_maxfl:
4190   case PPC::BI__builtin_ppc_minfl:
4191   case PPC::BI__builtin_ppc_maxfs:
4192   case PPC::BI__builtin_ppc_minfs: {
4193     if (Context.getTargetInfo().getTriple().isOSAIX() &&
4194         (BuiltinID == PPC::BI__builtin_ppc_maxfe ||
4195          BuiltinID == PPC::BI__builtin_ppc_minfe))
4196       return Diag(TheCall->getBeginLoc(), diag::err_target_unsupported_type)
4197              << "builtin" << true << 128 << QualType(Context.LongDoubleTy)
4198              << false << Context.getTargetInfo().getTriple().str();
4199     // Argument type should be exact.
4200     QualType ArgType = QualType(Context.LongDoubleTy);
4201     if (BuiltinID == PPC::BI__builtin_ppc_maxfl ||
4202         BuiltinID == PPC::BI__builtin_ppc_minfl)
4203       ArgType = QualType(Context.DoubleTy);
4204     else if (BuiltinID == PPC::BI__builtin_ppc_maxfs ||
4205              BuiltinID == PPC::BI__builtin_ppc_minfs)
4206       ArgType = QualType(Context.FloatTy);
4207     for (unsigned I = 0, E = TheCall->getNumArgs(); I < E; ++I)
4208       if (TheCall->getArg(I)->getType() != ArgType)
4209         return Diag(TheCall->getBeginLoc(),
4210                     diag::err_typecheck_convert_incompatible)
4211                << TheCall->getArg(I)->getType() << ArgType << 1 << 0 << 0;
4212     return false;
4213   }
4214   case PPC::BI__builtin_ppc_load8r:
4215   case PPC::BI__builtin_ppc_store8r:
4216     return SemaFeatureCheck(*this, TheCall, "isa-v206-instructions",
4217                             diag::err_ppc_builtin_only_on_arch, "7");
4218 #define CUSTOM_BUILTIN(Name, Intr, Types, Acc)                                 \
4219   case PPC::BI__builtin_##Name:                                                \
4220     return SemaBuiltinPPCMMACall(TheCall, BuiltinID, Types);
4221 #include "clang/Basic/BuiltinsPPC.def"
4222   }
4223   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
4224 }
4225 
4226 // Check if the given type is a non-pointer PPC MMA type. This function is used
4227 // in Sema to prevent invalid uses of restricted PPC MMA types.
4228 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) {
4229   if (Type->isPointerType() || Type->isArrayType())
4230     return false;
4231 
4232   QualType CoreType = Type.getCanonicalType().getUnqualifiedType();
4233 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty
4234   if (false
4235 #include "clang/Basic/PPCTypes.def"
4236      ) {
4237     Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type);
4238     return true;
4239   }
4240   return false;
4241 }
4242 
4243 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID,
4244                                           CallExpr *TheCall) {
4245   // position of memory order and scope arguments in the builtin
4246   unsigned OrderIndex, ScopeIndex;
4247   switch (BuiltinID) {
4248   case AMDGPU::BI__builtin_amdgcn_atomic_inc32:
4249   case AMDGPU::BI__builtin_amdgcn_atomic_inc64:
4250   case AMDGPU::BI__builtin_amdgcn_atomic_dec32:
4251   case AMDGPU::BI__builtin_amdgcn_atomic_dec64:
4252     OrderIndex = 2;
4253     ScopeIndex = 3;
4254     break;
4255   case AMDGPU::BI__builtin_amdgcn_fence:
4256     OrderIndex = 0;
4257     ScopeIndex = 1;
4258     break;
4259   default:
4260     return false;
4261   }
4262 
4263   ExprResult Arg = TheCall->getArg(OrderIndex);
4264   auto ArgExpr = Arg.get();
4265   Expr::EvalResult ArgResult;
4266 
4267   if (!ArgExpr->EvaluateAsInt(ArgResult, Context))
4268     return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int)
4269            << ArgExpr->getType();
4270   auto Ord = ArgResult.Val.getInt().getZExtValue();
4271 
4272   // Check validity of memory ordering as per C11 / C++11's memody model.
4273   // Only fence needs check. Atomic dec/inc allow all memory orders.
4274   if (!llvm::isValidAtomicOrderingCABI(Ord))
4275     return Diag(ArgExpr->getBeginLoc(),
4276                 diag::warn_atomic_op_has_invalid_memory_order)
4277            << ArgExpr->getSourceRange();
4278   switch (static_cast<llvm::AtomicOrderingCABI>(Ord)) {
4279   case llvm::AtomicOrderingCABI::relaxed:
4280   case llvm::AtomicOrderingCABI::consume:
4281     if (BuiltinID == AMDGPU::BI__builtin_amdgcn_fence)
4282       return Diag(ArgExpr->getBeginLoc(),
4283                   diag::warn_atomic_op_has_invalid_memory_order)
4284              << ArgExpr->getSourceRange();
4285     break;
4286   case llvm::AtomicOrderingCABI::acquire:
4287   case llvm::AtomicOrderingCABI::release:
4288   case llvm::AtomicOrderingCABI::acq_rel:
4289   case llvm::AtomicOrderingCABI::seq_cst:
4290     break;
4291   }
4292 
4293   Arg = TheCall->getArg(ScopeIndex);
4294   ArgExpr = Arg.get();
4295   Expr::EvalResult ArgResult1;
4296   // Check that sync scope is a constant literal
4297   if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context))
4298     return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal)
4299            << ArgExpr->getType();
4300 
4301   return false;
4302 }
4303 
4304 bool Sema::CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum) {
4305   llvm::APSInt Result;
4306 
4307   // We can't check the value of a dependent argument.
4308   Expr *Arg = TheCall->getArg(ArgNum);
4309   if (Arg->isTypeDependent() || Arg->isValueDependent())
4310     return false;
4311 
4312   // Check constant-ness first.
4313   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4314     return true;
4315 
4316   int64_t Val = Result.getSExtValue();
4317   if ((Val >= 0 && Val <= 3) || (Val >= 5 && Val <= 7))
4318     return false;
4319 
4320   return Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_invalid_lmul)
4321          << Arg->getSourceRange();
4322 }
4323 
4324 static bool isRISCV32Builtin(unsigned BuiltinID) {
4325   // These builtins only work on riscv32 targets.
4326   switch (BuiltinID) {
4327   case RISCV::BI__builtin_riscv_zip_32:
4328   case RISCV::BI__builtin_riscv_unzip_32:
4329   case RISCV::BI__builtin_riscv_aes32dsi_32:
4330   case RISCV::BI__builtin_riscv_aes32dsmi_32:
4331   case RISCV::BI__builtin_riscv_aes32esi_32:
4332   case RISCV::BI__builtin_riscv_aes32esmi_32:
4333   case RISCV::BI__builtin_riscv_sha512sig0h_32:
4334   case RISCV::BI__builtin_riscv_sha512sig0l_32:
4335   case RISCV::BI__builtin_riscv_sha512sig1h_32:
4336   case RISCV::BI__builtin_riscv_sha512sig1l_32:
4337   case RISCV::BI__builtin_riscv_sha512sum0r_32:
4338   case RISCV::BI__builtin_riscv_sha512sum1r_32:
4339     return true;
4340   }
4341 
4342   return false;
4343 }
4344 
4345 bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI,
4346                                          unsigned BuiltinID,
4347                                          CallExpr *TheCall) {
4348   // CodeGenFunction can also detect this, but this gives a better error
4349   // message.
4350   bool FeatureMissing = false;
4351   SmallVector<StringRef> ReqFeatures;
4352   StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID);
4353   Features.split(ReqFeatures, ',');
4354 
4355   // Check for 32-bit only builtins on a 64-bit target.
4356   const llvm::Triple &TT = TI.getTriple();
4357   if (TT.getArch() != llvm::Triple::riscv32 && isRISCV32Builtin(BuiltinID))
4358     return Diag(TheCall->getCallee()->getBeginLoc(),
4359                 diag::err_32_bit_builtin_64_bit_tgt);
4360 
4361   // Check if each required feature is included
4362   for (StringRef F : ReqFeatures) {
4363     SmallVector<StringRef> ReqOpFeatures;
4364     F.split(ReqOpFeatures, '|');
4365     bool HasFeature = false;
4366     for (StringRef OF : ReqOpFeatures) {
4367       if (TI.hasFeature(OF)) {
4368         HasFeature = true;
4369         continue;
4370       }
4371     }
4372 
4373     if (!HasFeature) {
4374       std::string FeatureStrs;
4375       for (StringRef OF : ReqOpFeatures) {
4376         // If the feature is 64bit, alter the string so it will print better in
4377         // the diagnostic.
4378         if (OF == "64bit")
4379           OF = "RV64";
4380 
4381         // Convert features like "zbr" and "experimental-zbr" to "Zbr".
4382         OF.consume_front("experimental-");
4383         std::string FeatureStr = OF.str();
4384         FeatureStr[0] = std::toupper(FeatureStr[0]);
4385         // Combine strings.
4386         FeatureStrs += FeatureStrs == "" ? "" : ", ";
4387         FeatureStrs += "'";
4388         FeatureStrs += FeatureStr;
4389         FeatureStrs += "'";
4390       }
4391       // Error message
4392       FeatureMissing = true;
4393       Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_requires_extension)
4394           << TheCall->getSourceRange() << StringRef(FeatureStrs);
4395     }
4396   }
4397 
4398   if (FeatureMissing)
4399     return true;
4400 
4401   switch (BuiltinID) {
4402   case RISCVVector::BI__builtin_rvv_vsetvli:
4403     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3) ||
4404            CheckRISCVLMUL(TheCall, 2);
4405   case RISCVVector::BI__builtin_rvv_vsetvlimax:
4406     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3) ||
4407            CheckRISCVLMUL(TheCall, 1);
4408   case RISCVVector::BI__builtin_rvv_vget_v: {
4409     ASTContext::BuiltinVectorTypeInfo ResVecInfo =
4410         Context.getBuiltinVectorTypeInfo(cast<BuiltinType>(
4411             TheCall->getType().getCanonicalType().getTypePtr()));
4412     ASTContext::BuiltinVectorTypeInfo VecInfo =
4413         Context.getBuiltinVectorTypeInfo(cast<BuiltinType>(
4414             TheCall->getArg(0)->getType().getCanonicalType().getTypePtr()));
4415     unsigned MaxIndex =
4416         (VecInfo.EC.getKnownMinValue() * VecInfo.NumVectors) /
4417         (ResVecInfo.EC.getKnownMinValue() * ResVecInfo.NumVectors);
4418     return SemaBuiltinConstantArgRange(TheCall, 1, 0, MaxIndex - 1);
4419   }
4420   case RISCVVector::BI__builtin_rvv_vset_v: {
4421     ASTContext::BuiltinVectorTypeInfo ResVecInfo =
4422         Context.getBuiltinVectorTypeInfo(cast<BuiltinType>(
4423             TheCall->getType().getCanonicalType().getTypePtr()));
4424     ASTContext::BuiltinVectorTypeInfo VecInfo =
4425         Context.getBuiltinVectorTypeInfo(cast<BuiltinType>(
4426             TheCall->getArg(2)->getType().getCanonicalType().getTypePtr()));
4427     unsigned MaxIndex =
4428         (ResVecInfo.EC.getKnownMinValue() * ResVecInfo.NumVectors) /
4429         (VecInfo.EC.getKnownMinValue() * VecInfo.NumVectors);
4430     return SemaBuiltinConstantArgRange(TheCall, 1, 0, MaxIndex - 1);
4431   }
4432   // Check if byteselect is in [0, 3]
4433   case RISCV::BI__builtin_riscv_aes32dsi_32:
4434   case RISCV::BI__builtin_riscv_aes32dsmi_32:
4435   case RISCV::BI__builtin_riscv_aes32esi_32:
4436   case RISCV::BI__builtin_riscv_aes32esmi_32:
4437   case RISCV::BI__builtin_riscv_sm4ks:
4438   case RISCV::BI__builtin_riscv_sm4ed:
4439     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
4440   // Check if rnum is in [0, 10]
4441   case RISCV::BI__builtin_riscv_aes64ks1i_64:
4442     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 10);
4443   }
4444 
4445   return false;
4446 }
4447 
4448 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
4449                                            CallExpr *TheCall) {
4450   if (BuiltinID == SystemZ::BI__builtin_tabort) {
4451     Expr *Arg = TheCall->getArg(0);
4452     if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context))
4453       if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256)
4454         return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
4455                << Arg->getSourceRange();
4456   }
4457 
4458   // For intrinsics which take an immediate value as part of the instruction,
4459   // range check them here.
4460   unsigned i = 0, l = 0, u = 0;
4461   switch (BuiltinID) {
4462   default: return false;
4463   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
4464   case SystemZ::BI__builtin_s390_verimb:
4465   case SystemZ::BI__builtin_s390_verimh:
4466   case SystemZ::BI__builtin_s390_verimf:
4467   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
4468   case SystemZ::BI__builtin_s390_vfaeb:
4469   case SystemZ::BI__builtin_s390_vfaeh:
4470   case SystemZ::BI__builtin_s390_vfaef:
4471   case SystemZ::BI__builtin_s390_vfaebs:
4472   case SystemZ::BI__builtin_s390_vfaehs:
4473   case SystemZ::BI__builtin_s390_vfaefs:
4474   case SystemZ::BI__builtin_s390_vfaezb:
4475   case SystemZ::BI__builtin_s390_vfaezh:
4476   case SystemZ::BI__builtin_s390_vfaezf:
4477   case SystemZ::BI__builtin_s390_vfaezbs:
4478   case SystemZ::BI__builtin_s390_vfaezhs:
4479   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
4480   case SystemZ::BI__builtin_s390_vfisb:
4481   case SystemZ::BI__builtin_s390_vfidb:
4482     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
4483            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
4484   case SystemZ::BI__builtin_s390_vftcisb:
4485   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
4486   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
4487   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
4488   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
4489   case SystemZ::BI__builtin_s390_vstrcb:
4490   case SystemZ::BI__builtin_s390_vstrch:
4491   case SystemZ::BI__builtin_s390_vstrcf:
4492   case SystemZ::BI__builtin_s390_vstrczb:
4493   case SystemZ::BI__builtin_s390_vstrczh:
4494   case SystemZ::BI__builtin_s390_vstrczf:
4495   case SystemZ::BI__builtin_s390_vstrcbs:
4496   case SystemZ::BI__builtin_s390_vstrchs:
4497   case SystemZ::BI__builtin_s390_vstrcfs:
4498   case SystemZ::BI__builtin_s390_vstrczbs:
4499   case SystemZ::BI__builtin_s390_vstrczhs:
4500   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
4501   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
4502   case SystemZ::BI__builtin_s390_vfminsb:
4503   case SystemZ::BI__builtin_s390_vfmaxsb:
4504   case SystemZ::BI__builtin_s390_vfmindb:
4505   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
4506   case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
4507   case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
4508   case SystemZ::BI__builtin_s390_vclfnhs:
4509   case SystemZ::BI__builtin_s390_vclfnls:
4510   case SystemZ::BI__builtin_s390_vcfn:
4511   case SystemZ::BI__builtin_s390_vcnf: i = 1; l = 0; u = 15; break;
4512   case SystemZ::BI__builtin_s390_vcrnfs: i = 2; l = 0; u = 15; break;
4513   }
4514   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
4515 }
4516 
4517 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
4518 /// This checks that the target supports __builtin_cpu_supports and
4519 /// that the string argument is constant and valid.
4520 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI,
4521                                    CallExpr *TheCall) {
4522   Expr *Arg = TheCall->getArg(0);
4523 
4524   // Check if the argument is a string literal.
4525   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4526     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
4527            << Arg->getSourceRange();
4528 
4529   // Check the contents of the string.
4530   StringRef Feature =
4531       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4532   if (!TI.validateCpuSupports(Feature))
4533     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
4534            << Arg->getSourceRange();
4535   return false;
4536 }
4537 
4538 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
4539 /// This checks that the target supports __builtin_cpu_is and
4540 /// that the string argument is constant and valid.
4541 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) {
4542   Expr *Arg = TheCall->getArg(0);
4543 
4544   // Check if the argument is a string literal.
4545   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4546     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
4547            << Arg->getSourceRange();
4548 
4549   // Check the contents of the string.
4550   StringRef Feature =
4551       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4552   if (!TI.validateCpuIs(Feature))
4553     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
4554            << Arg->getSourceRange();
4555   return false;
4556 }
4557 
4558 // Check if the rounding mode is legal.
4559 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
4560   // Indicates if this instruction has rounding control or just SAE.
4561   bool HasRC = false;
4562 
4563   unsigned ArgNum = 0;
4564   switch (BuiltinID) {
4565   default:
4566     return false;
4567   case X86::BI__builtin_ia32_vcvttsd2si32:
4568   case X86::BI__builtin_ia32_vcvttsd2si64:
4569   case X86::BI__builtin_ia32_vcvttsd2usi32:
4570   case X86::BI__builtin_ia32_vcvttsd2usi64:
4571   case X86::BI__builtin_ia32_vcvttss2si32:
4572   case X86::BI__builtin_ia32_vcvttss2si64:
4573   case X86::BI__builtin_ia32_vcvttss2usi32:
4574   case X86::BI__builtin_ia32_vcvttss2usi64:
4575   case X86::BI__builtin_ia32_vcvttsh2si32:
4576   case X86::BI__builtin_ia32_vcvttsh2si64:
4577   case X86::BI__builtin_ia32_vcvttsh2usi32:
4578   case X86::BI__builtin_ia32_vcvttsh2usi64:
4579     ArgNum = 1;
4580     break;
4581   case X86::BI__builtin_ia32_maxpd512:
4582   case X86::BI__builtin_ia32_maxps512:
4583   case X86::BI__builtin_ia32_minpd512:
4584   case X86::BI__builtin_ia32_minps512:
4585   case X86::BI__builtin_ia32_maxph512:
4586   case X86::BI__builtin_ia32_minph512:
4587     ArgNum = 2;
4588     break;
4589   case X86::BI__builtin_ia32_vcvtph2pd512_mask:
4590   case X86::BI__builtin_ia32_vcvtph2psx512_mask:
4591   case X86::BI__builtin_ia32_cvtps2pd512_mask:
4592   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
4593   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
4594   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
4595   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
4596   case X86::BI__builtin_ia32_cvttps2dq512_mask:
4597   case X86::BI__builtin_ia32_cvttps2qq512_mask:
4598   case X86::BI__builtin_ia32_cvttps2udq512_mask:
4599   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
4600   case X86::BI__builtin_ia32_vcvttph2w512_mask:
4601   case X86::BI__builtin_ia32_vcvttph2uw512_mask:
4602   case X86::BI__builtin_ia32_vcvttph2dq512_mask:
4603   case X86::BI__builtin_ia32_vcvttph2udq512_mask:
4604   case X86::BI__builtin_ia32_vcvttph2qq512_mask:
4605   case X86::BI__builtin_ia32_vcvttph2uqq512_mask:
4606   case X86::BI__builtin_ia32_exp2pd_mask:
4607   case X86::BI__builtin_ia32_exp2ps_mask:
4608   case X86::BI__builtin_ia32_getexppd512_mask:
4609   case X86::BI__builtin_ia32_getexpps512_mask:
4610   case X86::BI__builtin_ia32_getexpph512_mask:
4611   case X86::BI__builtin_ia32_rcp28pd_mask:
4612   case X86::BI__builtin_ia32_rcp28ps_mask:
4613   case X86::BI__builtin_ia32_rsqrt28pd_mask:
4614   case X86::BI__builtin_ia32_rsqrt28ps_mask:
4615   case X86::BI__builtin_ia32_vcomisd:
4616   case X86::BI__builtin_ia32_vcomiss:
4617   case X86::BI__builtin_ia32_vcomish:
4618   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
4619     ArgNum = 3;
4620     break;
4621   case X86::BI__builtin_ia32_cmppd512_mask:
4622   case X86::BI__builtin_ia32_cmpps512_mask:
4623   case X86::BI__builtin_ia32_cmpsd_mask:
4624   case X86::BI__builtin_ia32_cmpss_mask:
4625   case X86::BI__builtin_ia32_cmpsh_mask:
4626   case X86::BI__builtin_ia32_vcvtsh2sd_round_mask:
4627   case X86::BI__builtin_ia32_vcvtsh2ss_round_mask:
4628   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
4629   case X86::BI__builtin_ia32_getexpsd128_round_mask:
4630   case X86::BI__builtin_ia32_getexpss128_round_mask:
4631   case X86::BI__builtin_ia32_getexpsh128_round_mask:
4632   case X86::BI__builtin_ia32_getmantpd512_mask:
4633   case X86::BI__builtin_ia32_getmantps512_mask:
4634   case X86::BI__builtin_ia32_getmantph512_mask:
4635   case X86::BI__builtin_ia32_maxsd_round_mask:
4636   case X86::BI__builtin_ia32_maxss_round_mask:
4637   case X86::BI__builtin_ia32_maxsh_round_mask:
4638   case X86::BI__builtin_ia32_minsd_round_mask:
4639   case X86::BI__builtin_ia32_minss_round_mask:
4640   case X86::BI__builtin_ia32_minsh_round_mask:
4641   case X86::BI__builtin_ia32_rcp28sd_round_mask:
4642   case X86::BI__builtin_ia32_rcp28ss_round_mask:
4643   case X86::BI__builtin_ia32_reducepd512_mask:
4644   case X86::BI__builtin_ia32_reduceps512_mask:
4645   case X86::BI__builtin_ia32_reduceph512_mask:
4646   case X86::BI__builtin_ia32_rndscalepd_mask:
4647   case X86::BI__builtin_ia32_rndscaleps_mask:
4648   case X86::BI__builtin_ia32_rndscaleph_mask:
4649   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
4650   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
4651     ArgNum = 4;
4652     break;
4653   case X86::BI__builtin_ia32_fixupimmpd512_mask:
4654   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
4655   case X86::BI__builtin_ia32_fixupimmps512_mask:
4656   case X86::BI__builtin_ia32_fixupimmps512_maskz:
4657   case X86::BI__builtin_ia32_fixupimmsd_mask:
4658   case X86::BI__builtin_ia32_fixupimmsd_maskz:
4659   case X86::BI__builtin_ia32_fixupimmss_mask:
4660   case X86::BI__builtin_ia32_fixupimmss_maskz:
4661   case X86::BI__builtin_ia32_getmantsd_round_mask:
4662   case X86::BI__builtin_ia32_getmantss_round_mask:
4663   case X86::BI__builtin_ia32_getmantsh_round_mask:
4664   case X86::BI__builtin_ia32_rangepd512_mask:
4665   case X86::BI__builtin_ia32_rangeps512_mask:
4666   case X86::BI__builtin_ia32_rangesd128_round_mask:
4667   case X86::BI__builtin_ia32_rangess128_round_mask:
4668   case X86::BI__builtin_ia32_reducesd_mask:
4669   case X86::BI__builtin_ia32_reducess_mask:
4670   case X86::BI__builtin_ia32_reducesh_mask:
4671   case X86::BI__builtin_ia32_rndscalesd_round_mask:
4672   case X86::BI__builtin_ia32_rndscaless_round_mask:
4673   case X86::BI__builtin_ia32_rndscalesh_round_mask:
4674     ArgNum = 5;
4675     break;
4676   case X86::BI__builtin_ia32_vcvtsd2si64:
4677   case X86::BI__builtin_ia32_vcvtsd2si32:
4678   case X86::BI__builtin_ia32_vcvtsd2usi32:
4679   case X86::BI__builtin_ia32_vcvtsd2usi64:
4680   case X86::BI__builtin_ia32_vcvtss2si32:
4681   case X86::BI__builtin_ia32_vcvtss2si64:
4682   case X86::BI__builtin_ia32_vcvtss2usi32:
4683   case X86::BI__builtin_ia32_vcvtss2usi64:
4684   case X86::BI__builtin_ia32_vcvtsh2si32:
4685   case X86::BI__builtin_ia32_vcvtsh2si64:
4686   case X86::BI__builtin_ia32_vcvtsh2usi32:
4687   case X86::BI__builtin_ia32_vcvtsh2usi64:
4688   case X86::BI__builtin_ia32_sqrtpd512:
4689   case X86::BI__builtin_ia32_sqrtps512:
4690   case X86::BI__builtin_ia32_sqrtph512:
4691     ArgNum = 1;
4692     HasRC = true;
4693     break;
4694   case X86::BI__builtin_ia32_addph512:
4695   case X86::BI__builtin_ia32_divph512:
4696   case X86::BI__builtin_ia32_mulph512:
4697   case X86::BI__builtin_ia32_subph512:
4698   case X86::BI__builtin_ia32_addpd512:
4699   case X86::BI__builtin_ia32_addps512:
4700   case X86::BI__builtin_ia32_divpd512:
4701   case X86::BI__builtin_ia32_divps512:
4702   case X86::BI__builtin_ia32_mulpd512:
4703   case X86::BI__builtin_ia32_mulps512:
4704   case X86::BI__builtin_ia32_subpd512:
4705   case X86::BI__builtin_ia32_subps512:
4706   case X86::BI__builtin_ia32_cvtsi2sd64:
4707   case X86::BI__builtin_ia32_cvtsi2ss32:
4708   case X86::BI__builtin_ia32_cvtsi2ss64:
4709   case X86::BI__builtin_ia32_cvtusi2sd64:
4710   case X86::BI__builtin_ia32_cvtusi2ss32:
4711   case X86::BI__builtin_ia32_cvtusi2ss64:
4712   case X86::BI__builtin_ia32_vcvtusi2sh:
4713   case X86::BI__builtin_ia32_vcvtusi642sh:
4714   case X86::BI__builtin_ia32_vcvtsi2sh:
4715   case X86::BI__builtin_ia32_vcvtsi642sh:
4716     ArgNum = 2;
4717     HasRC = true;
4718     break;
4719   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
4720   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
4721   case X86::BI__builtin_ia32_vcvtpd2ph512_mask:
4722   case X86::BI__builtin_ia32_vcvtps2phx512_mask:
4723   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
4724   case X86::BI__builtin_ia32_cvtpd2dq512_mask:
4725   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
4726   case X86::BI__builtin_ia32_cvtpd2udq512_mask:
4727   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
4728   case X86::BI__builtin_ia32_cvtps2dq512_mask:
4729   case X86::BI__builtin_ia32_cvtps2qq512_mask:
4730   case X86::BI__builtin_ia32_cvtps2udq512_mask:
4731   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
4732   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
4733   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
4734   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
4735   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
4736   case X86::BI__builtin_ia32_vcvtdq2ph512_mask:
4737   case X86::BI__builtin_ia32_vcvtudq2ph512_mask:
4738   case X86::BI__builtin_ia32_vcvtw2ph512_mask:
4739   case X86::BI__builtin_ia32_vcvtuw2ph512_mask:
4740   case X86::BI__builtin_ia32_vcvtph2w512_mask:
4741   case X86::BI__builtin_ia32_vcvtph2uw512_mask:
4742   case X86::BI__builtin_ia32_vcvtph2dq512_mask:
4743   case X86::BI__builtin_ia32_vcvtph2udq512_mask:
4744   case X86::BI__builtin_ia32_vcvtph2qq512_mask:
4745   case X86::BI__builtin_ia32_vcvtph2uqq512_mask:
4746   case X86::BI__builtin_ia32_vcvtqq2ph512_mask:
4747   case X86::BI__builtin_ia32_vcvtuqq2ph512_mask:
4748     ArgNum = 3;
4749     HasRC = true;
4750     break;
4751   case X86::BI__builtin_ia32_addsh_round_mask:
4752   case X86::BI__builtin_ia32_addss_round_mask:
4753   case X86::BI__builtin_ia32_addsd_round_mask:
4754   case X86::BI__builtin_ia32_divsh_round_mask:
4755   case X86::BI__builtin_ia32_divss_round_mask:
4756   case X86::BI__builtin_ia32_divsd_round_mask:
4757   case X86::BI__builtin_ia32_mulsh_round_mask:
4758   case X86::BI__builtin_ia32_mulss_round_mask:
4759   case X86::BI__builtin_ia32_mulsd_round_mask:
4760   case X86::BI__builtin_ia32_subsh_round_mask:
4761   case X86::BI__builtin_ia32_subss_round_mask:
4762   case X86::BI__builtin_ia32_subsd_round_mask:
4763   case X86::BI__builtin_ia32_scalefph512_mask:
4764   case X86::BI__builtin_ia32_scalefpd512_mask:
4765   case X86::BI__builtin_ia32_scalefps512_mask:
4766   case X86::BI__builtin_ia32_scalefsd_round_mask:
4767   case X86::BI__builtin_ia32_scalefss_round_mask:
4768   case X86::BI__builtin_ia32_scalefsh_round_mask:
4769   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
4770   case X86::BI__builtin_ia32_vcvtss2sh_round_mask:
4771   case X86::BI__builtin_ia32_vcvtsd2sh_round_mask:
4772   case X86::BI__builtin_ia32_sqrtsd_round_mask:
4773   case X86::BI__builtin_ia32_sqrtss_round_mask:
4774   case X86::BI__builtin_ia32_sqrtsh_round_mask:
4775   case X86::BI__builtin_ia32_vfmaddsd3_mask:
4776   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
4777   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
4778   case X86::BI__builtin_ia32_vfmaddss3_mask:
4779   case X86::BI__builtin_ia32_vfmaddss3_maskz:
4780   case X86::BI__builtin_ia32_vfmaddss3_mask3:
4781   case X86::BI__builtin_ia32_vfmaddsh3_mask:
4782   case X86::BI__builtin_ia32_vfmaddsh3_maskz:
4783   case X86::BI__builtin_ia32_vfmaddsh3_mask3:
4784   case X86::BI__builtin_ia32_vfmaddpd512_mask:
4785   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
4786   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
4787   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
4788   case X86::BI__builtin_ia32_vfmaddps512_mask:
4789   case X86::BI__builtin_ia32_vfmaddps512_maskz:
4790   case X86::BI__builtin_ia32_vfmaddps512_mask3:
4791   case X86::BI__builtin_ia32_vfmsubps512_mask3:
4792   case X86::BI__builtin_ia32_vfmaddph512_mask:
4793   case X86::BI__builtin_ia32_vfmaddph512_maskz:
4794   case X86::BI__builtin_ia32_vfmaddph512_mask3:
4795   case X86::BI__builtin_ia32_vfmsubph512_mask3:
4796   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
4797   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
4798   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
4799   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
4800   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
4801   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
4802   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
4803   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
4804   case X86::BI__builtin_ia32_vfmaddsubph512_mask:
4805   case X86::BI__builtin_ia32_vfmaddsubph512_maskz:
4806   case X86::BI__builtin_ia32_vfmaddsubph512_mask3:
4807   case X86::BI__builtin_ia32_vfmsubaddph512_mask3:
4808   case X86::BI__builtin_ia32_vfmaddcsh_mask:
4809   case X86::BI__builtin_ia32_vfmaddcsh_round_mask:
4810   case X86::BI__builtin_ia32_vfmaddcsh_round_mask3:
4811   case X86::BI__builtin_ia32_vfmaddcph512_mask:
4812   case X86::BI__builtin_ia32_vfmaddcph512_maskz:
4813   case X86::BI__builtin_ia32_vfmaddcph512_mask3:
4814   case X86::BI__builtin_ia32_vfcmaddcsh_mask:
4815   case X86::BI__builtin_ia32_vfcmaddcsh_round_mask:
4816   case X86::BI__builtin_ia32_vfcmaddcsh_round_mask3:
4817   case X86::BI__builtin_ia32_vfcmaddcph512_mask:
4818   case X86::BI__builtin_ia32_vfcmaddcph512_maskz:
4819   case X86::BI__builtin_ia32_vfcmaddcph512_mask3:
4820   case X86::BI__builtin_ia32_vfmulcsh_mask:
4821   case X86::BI__builtin_ia32_vfmulcph512_mask:
4822   case X86::BI__builtin_ia32_vfcmulcsh_mask:
4823   case X86::BI__builtin_ia32_vfcmulcph512_mask:
4824     ArgNum = 4;
4825     HasRC = true;
4826     break;
4827   }
4828 
4829   llvm::APSInt Result;
4830 
4831   // We can't check the value of a dependent argument.
4832   Expr *Arg = TheCall->getArg(ArgNum);
4833   if (Arg->isTypeDependent() || Arg->isValueDependent())
4834     return false;
4835 
4836   // Check constant-ness first.
4837   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4838     return true;
4839 
4840   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
4841   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
4842   // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
4843   // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
4844   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
4845       Result == 8/*ROUND_NO_EXC*/ ||
4846       (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
4847       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
4848     return false;
4849 
4850   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
4851          << Arg->getSourceRange();
4852 }
4853 
4854 // Check if the gather/scatter scale is legal.
4855 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
4856                                              CallExpr *TheCall) {
4857   unsigned ArgNum = 0;
4858   switch (BuiltinID) {
4859   default:
4860     return false;
4861   case X86::BI__builtin_ia32_gatherpfdpd:
4862   case X86::BI__builtin_ia32_gatherpfdps:
4863   case X86::BI__builtin_ia32_gatherpfqpd:
4864   case X86::BI__builtin_ia32_gatherpfqps:
4865   case X86::BI__builtin_ia32_scatterpfdpd:
4866   case X86::BI__builtin_ia32_scatterpfdps:
4867   case X86::BI__builtin_ia32_scatterpfqpd:
4868   case X86::BI__builtin_ia32_scatterpfqps:
4869     ArgNum = 3;
4870     break;
4871   case X86::BI__builtin_ia32_gatherd_pd:
4872   case X86::BI__builtin_ia32_gatherd_pd256:
4873   case X86::BI__builtin_ia32_gatherq_pd:
4874   case X86::BI__builtin_ia32_gatherq_pd256:
4875   case X86::BI__builtin_ia32_gatherd_ps:
4876   case X86::BI__builtin_ia32_gatherd_ps256:
4877   case X86::BI__builtin_ia32_gatherq_ps:
4878   case X86::BI__builtin_ia32_gatherq_ps256:
4879   case X86::BI__builtin_ia32_gatherd_q:
4880   case X86::BI__builtin_ia32_gatherd_q256:
4881   case X86::BI__builtin_ia32_gatherq_q:
4882   case X86::BI__builtin_ia32_gatherq_q256:
4883   case X86::BI__builtin_ia32_gatherd_d:
4884   case X86::BI__builtin_ia32_gatherd_d256:
4885   case X86::BI__builtin_ia32_gatherq_d:
4886   case X86::BI__builtin_ia32_gatherq_d256:
4887   case X86::BI__builtin_ia32_gather3div2df:
4888   case X86::BI__builtin_ia32_gather3div2di:
4889   case X86::BI__builtin_ia32_gather3div4df:
4890   case X86::BI__builtin_ia32_gather3div4di:
4891   case X86::BI__builtin_ia32_gather3div4sf:
4892   case X86::BI__builtin_ia32_gather3div4si:
4893   case X86::BI__builtin_ia32_gather3div8sf:
4894   case X86::BI__builtin_ia32_gather3div8si:
4895   case X86::BI__builtin_ia32_gather3siv2df:
4896   case X86::BI__builtin_ia32_gather3siv2di:
4897   case X86::BI__builtin_ia32_gather3siv4df:
4898   case X86::BI__builtin_ia32_gather3siv4di:
4899   case X86::BI__builtin_ia32_gather3siv4sf:
4900   case X86::BI__builtin_ia32_gather3siv4si:
4901   case X86::BI__builtin_ia32_gather3siv8sf:
4902   case X86::BI__builtin_ia32_gather3siv8si:
4903   case X86::BI__builtin_ia32_gathersiv8df:
4904   case X86::BI__builtin_ia32_gathersiv16sf:
4905   case X86::BI__builtin_ia32_gatherdiv8df:
4906   case X86::BI__builtin_ia32_gatherdiv16sf:
4907   case X86::BI__builtin_ia32_gathersiv8di:
4908   case X86::BI__builtin_ia32_gathersiv16si:
4909   case X86::BI__builtin_ia32_gatherdiv8di:
4910   case X86::BI__builtin_ia32_gatherdiv16si:
4911   case X86::BI__builtin_ia32_scatterdiv2df:
4912   case X86::BI__builtin_ia32_scatterdiv2di:
4913   case X86::BI__builtin_ia32_scatterdiv4df:
4914   case X86::BI__builtin_ia32_scatterdiv4di:
4915   case X86::BI__builtin_ia32_scatterdiv4sf:
4916   case X86::BI__builtin_ia32_scatterdiv4si:
4917   case X86::BI__builtin_ia32_scatterdiv8sf:
4918   case X86::BI__builtin_ia32_scatterdiv8si:
4919   case X86::BI__builtin_ia32_scattersiv2df:
4920   case X86::BI__builtin_ia32_scattersiv2di:
4921   case X86::BI__builtin_ia32_scattersiv4df:
4922   case X86::BI__builtin_ia32_scattersiv4di:
4923   case X86::BI__builtin_ia32_scattersiv4sf:
4924   case X86::BI__builtin_ia32_scattersiv4si:
4925   case X86::BI__builtin_ia32_scattersiv8sf:
4926   case X86::BI__builtin_ia32_scattersiv8si:
4927   case X86::BI__builtin_ia32_scattersiv8df:
4928   case X86::BI__builtin_ia32_scattersiv16sf:
4929   case X86::BI__builtin_ia32_scatterdiv8df:
4930   case X86::BI__builtin_ia32_scatterdiv16sf:
4931   case X86::BI__builtin_ia32_scattersiv8di:
4932   case X86::BI__builtin_ia32_scattersiv16si:
4933   case X86::BI__builtin_ia32_scatterdiv8di:
4934   case X86::BI__builtin_ia32_scatterdiv16si:
4935     ArgNum = 4;
4936     break;
4937   }
4938 
4939   llvm::APSInt Result;
4940 
4941   // We can't check the value of a dependent argument.
4942   Expr *Arg = TheCall->getArg(ArgNum);
4943   if (Arg->isTypeDependent() || Arg->isValueDependent())
4944     return false;
4945 
4946   // Check constant-ness first.
4947   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4948     return true;
4949 
4950   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
4951     return false;
4952 
4953   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
4954          << Arg->getSourceRange();
4955 }
4956 
4957 enum { TileRegLow = 0, TileRegHigh = 7 };
4958 
4959 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
4960                                              ArrayRef<int> ArgNums) {
4961   for (int ArgNum : ArgNums) {
4962     if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh))
4963       return true;
4964   }
4965   return false;
4966 }
4967 
4968 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall,
4969                                         ArrayRef<int> ArgNums) {
4970   // Because the max number of tile register is TileRegHigh + 1, so here we use
4971   // each bit to represent the usage of them in bitset.
4972   std::bitset<TileRegHigh + 1> ArgValues;
4973   for (int ArgNum : ArgNums) {
4974     Expr *Arg = TheCall->getArg(ArgNum);
4975     if (Arg->isTypeDependent() || Arg->isValueDependent())
4976       continue;
4977 
4978     llvm::APSInt Result;
4979     if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4980       return true;
4981     int ArgExtValue = Result.getExtValue();
4982     assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) &&
4983            "Incorrect tile register num.");
4984     if (ArgValues.test(ArgExtValue))
4985       return Diag(TheCall->getBeginLoc(),
4986                   diag::err_x86_builtin_tile_arg_duplicate)
4987              << TheCall->getArg(ArgNum)->getSourceRange();
4988     ArgValues.set(ArgExtValue);
4989   }
4990   return false;
4991 }
4992 
4993 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
4994                                                 ArrayRef<int> ArgNums) {
4995   return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) ||
4996          CheckX86BuiltinTileDuplicate(TheCall, ArgNums);
4997 }
4998 
4999 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) {
5000   switch (BuiltinID) {
5001   default:
5002     return false;
5003   case X86::BI__builtin_ia32_tileloadd64:
5004   case X86::BI__builtin_ia32_tileloaddt164:
5005   case X86::BI__builtin_ia32_tilestored64:
5006   case X86::BI__builtin_ia32_tilezero:
5007     return CheckX86BuiltinTileArgumentsRange(TheCall, 0);
5008   case X86::BI__builtin_ia32_tdpbssd:
5009   case X86::BI__builtin_ia32_tdpbsud:
5010   case X86::BI__builtin_ia32_tdpbusd:
5011   case X86::BI__builtin_ia32_tdpbuud:
5012   case X86::BI__builtin_ia32_tdpbf16ps:
5013     return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2});
5014   }
5015 }
5016 static bool isX86_32Builtin(unsigned BuiltinID) {
5017   // These builtins only work on x86-32 targets.
5018   switch (BuiltinID) {
5019   case X86::BI__builtin_ia32_readeflags_u32:
5020   case X86::BI__builtin_ia32_writeeflags_u32:
5021     return true;
5022   }
5023 
5024   return false;
5025 }
5026 
5027 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
5028                                        CallExpr *TheCall) {
5029   if (BuiltinID == X86::BI__builtin_cpu_supports)
5030     return SemaBuiltinCpuSupports(*this, TI, TheCall);
5031 
5032   if (BuiltinID == X86::BI__builtin_cpu_is)
5033     return SemaBuiltinCpuIs(*this, TI, TheCall);
5034 
5035   // Check for 32-bit only builtins on a 64-bit target.
5036   const llvm::Triple &TT = TI.getTriple();
5037   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
5038     return Diag(TheCall->getCallee()->getBeginLoc(),
5039                 diag::err_32_bit_builtin_64_bit_tgt);
5040 
5041   // If the intrinsic has rounding or SAE make sure its valid.
5042   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
5043     return true;
5044 
5045   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
5046   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
5047     return true;
5048 
5049   // If the intrinsic has a tile arguments, make sure they are valid.
5050   if (CheckX86BuiltinTileArguments(BuiltinID, TheCall))
5051     return true;
5052 
5053   // For intrinsics which take an immediate value as part of the instruction,
5054   // range check them here.
5055   int i = 0, l = 0, u = 0;
5056   switch (BuiltinID) {
5057   default:
5058     return false;
5059   case X86::BI__builtin_ia32_vec_ext_v2si:
5060   case X86::BI__builtin_ia32_vec_ext_v2di:
5061   case X86::BI__builtin_ia32_vextractf128_pd256:
5062   case X86::BI__builtin_ia32_vextractf128_ps256:
5063   case X86::BI__builtin_ia32_vextractf128_si256:
5064   case X86::BI__builtin_ia32_extract128i256:
5065   case X86::BI__builtin_ia32_extractf64x4_mask:
5066   case X86::BI__builtin_ia32_extracti64x4_mask:
5067   case X86::BI__builtin_ia32_extractf32x8_mask:
5068   case X86::BI__builtin_ia32_extracti32x8_mask:
5069   case X86::BI__builtin_ia32_extractf64x2_256_mask:
5070   case X86::BI__builtin_ia32_extracti64x2_256_mask:
5071   case X86::BI__builtin_ia32_extractf32x4_256_mask:
5072   case X86::BI__builtin_ia32_extracti32x4_256_mask:
5073     i = 1; l = 0; u = 1;
5074     break;
5075   case X86::BI__builtin_ia32_vec_set_v2di:
5076   case X86::BI__builtin_ia32_vinsertf128_pd256:
5077   case X86::BI__builtin_ia32_vinsertf128_ps256:
5078   case X86::BI__builtin_ia32_vinsertf128_si256:
5079   case X86::BI__builtin_ia32_insert128i256:
5080   case X86::BI__builtin_ia32_insertf32x8:
5081   case X86::BI__builtin_ia32_inserti32x8:
5082   case X86::BI__builtin_ia32_insertf64x4:
5083   case X86::BI__builtin_ia32_inserti64x4:
5084   case X86::BI__builtin_ia32_insertf64x2_256:
5085   case X86::BI__builtin_ia32_inserti64x2_256:
5086   case X86::BI__builtin_ia32_insertf32x4_256:
5087   case X86::BI__builtin_ia32_inserti32x4_256:
5088     i = 2; l = 0; u = 1;
5089     break;
5090   case X86::BI__builtin_ia32_vpermilpd:
5091   case X86::BI__builtin_ia32_vec_ext_v4hi:
5092   case X86::BI__builtin_ia32_vec_ext_v4si:
5093   case X86::BI__builtin_ia32_vec_ext_v4sf:
5094   case X86::BI__builtin_ia32_vec_ext_v4di:
5095   case X86::BI__builtin_ia32_extractf32x4_mask:
5096   case X86::BI__builtin_ia32_extracti32x4_mask:
5097   case X86::BI__builtin_ia32_extractf64x2_512_mask:
5098   case X86::BI__builtin_ia32_extracti64x2_512_mask:
5099     i = 1; l = 0; u = 3;
5100     break;
5101   case X86::BI_mm_prefetch:
5102   case X86::BI__builtin_ia32_vec_ext_v8hi:
5103   case X86::BI__builtin_ia32_vec_ext_v8si:
5104     i = 1; l = 0; u = 7;
5105     break;
5106   case X86::BI__builtin_ia32_sha1rnds4:
5107   case X86::BI__builtin_ia32_blendpd:
5108   case X86::BI__builtin_ia32_shufpd:
5109   case X86::BI__builtin_ia32_vec_set_v4hi:
5110   case X86::BI__builtin_ia32_vec_set_v4si:
5111   case X86::BI__builtin_ia32_vec_set_v4di:
5112   case X86::BI__builtin_ia32_shuf_f32x4_256:
5113   case X86::BI__builtin_ia32_shuf_f64x2_256:
5114   case X86::BI__builtin_ia32_shuf_i32x4_256:
5115   case X86::BI__builtin_ia32_shuf_i64x2_256:
5116   case X86::BI__builtin_ia32_insertf64x2_512:
5117   case X86::BI__builtin_ia32_inserti64x2_512:
5118   case X86::BI__builtin_ia32_insertf32x4:
5119   case X86::BI__builtin_ia32_inserti32x4:
5120     i = 2; l = 0; u = 3;
5121     break;
5122   case X86::BI__builtin_ia32_vpermil2pd:
5123   case X86::BI__builtin_ia32_vpermil2pd256:
5124   case X86::BI__builtin_ia32_vpermil2ps:
5125   case X86::BI__builtin_ia32_vpermil2ps256:
5126     i = 3; l = 0; u = 3;
5127     break;
5128   case X86::BI__builtin_ia32_cmpb128_mask:
5129   case X86::BI__builtin_ia32_cmpw128_mask:
5130   case X86::BI__builtin_ia32_cmpd128_mask:
5131   case X86::BI__builtin_ia32_cmpq128_mask:
5132   case X86::BI__builtin_ia32_cmpb256_mask:
5133   case X86::BI__builtin_ia32_cmpw256_mask:
5134   case X86::BI__builtin_ia32_cmpd256_mask:
5135   case X86::BI__builtin_ia32_cmpq256_mask:
5136   case X86::BI__builtin_ia32_cmpb512_mask:
5137   case X86::BI__builtin_ia32_cmpw512_mask:
5138   case X86::BI__builtin_ia32_cmpd512_mask:
5139   case X86::BI__builtin_ia32_cmpq512_mask:
5140   case X86::BI__builtin_ia32_ucmpb128_mask:
5141   case X86::BI__builtin_ia32_ucmpw128_mask:
5142   case X86::BI__builtin_ia32_ucmpd128_mask:
5143   case X86::BI__builtin_ia32_ucmpq128_mask:
5144   case X86::BI__builtin_ia32_ucmpb256_mask:
5145   case X86::BI__builtin_ia32_ucmpw256_mask:
5146   case X86::BI__builtin_ia32_ucmpd256_mask:
5147   case X86::BI__builtin_ia32_ucmpq256_mask:
5148   case X86::BI__builtin_ia32_ucmpb512_mask:
5149   case X86::BI__builtin_ia32_ucmpw512_mask:
5150   case X86::BI__builtin_ia32_ucmpd512_mask:
5151   case X86::BI__builtin_ia32_ucmpq512_mask:
5152   case X86::BI__builtin_ia32_vpcomub:
5153   case X86::BI__builtin_ia32_vpcomuw:
5154   case X86::BI__builtin_ia32_vpcomud:
5155   case X86::BI__builtin_ia32_vpcomuq:
5156   case X86::BI__builtin_ia32_vpcomb:
5157   case X86::BI__builtin_ia32_vpcomw:
5158   case X86::BI__builtin_ia32_vpcomd:
5159   case X86::BI__builtin_ia32_vpcomq:
5160   case X86::BI__builtin_ia32_vec_set_v8hi:
5161   case X86::BI__builtin_ia32_vec_set_v8si:
5162     i = 2; l = 0; u = 7;
5163     break;
5164   case X86::BI__builtin_ia32_vpermilpd256:
5165   case X86::BI__builtin_ia32_roundps:
5166   case X86::BI__builtin_ia32_roundpd:
5167   case X86::BI__builtin_ia32_roundps256:
5168   case X86::BI__builtin_ia32_roundpd256:
5169   case X86::BI__builtin_ia32_getmantpd128_mask:
5170   case X86::BI__builtin_ia32_getmantpd256_mask:
5171   case X86::BI__builtin_ia32_getmantps128_mask:
5172   case X86::BI__builtin_ia32_getmantps256_mask:
5173   case X86::BI__builtin_ia32_getmantpd512_mask:
5174   case X86::BI__builtin_ia32_getmantps512_mask:
5175   case X86::BI__builtin_ia32_getmantph128_mask:
5176   case X86::BI__builtin_ia32_getmantph256_mask:
5177   case X86::BI__builtin_ia32_getmantph512_mask:
5178   case X86::BI__builtin_ia32_vec_ext_v16qi:
5179   case X86::BI__builtin_ia32_vec_ext_v16hi:
5180     i = 1; l = 0; u = 15;
5181     break;
5182   case X86::BI__builtin_ia32_pblendd128:
5183   case X86::BI__builtin_ia32_blendps:
5184   case X86::BI__builtin_ia32_blendpd256:
5185   case X86::BI__builtin_ia32_shufpd256:
5186   case X86::BI__builtin_ia32_roundss:
5187   case X86::BI__builtin_ia32_roundsd:
5188   case X86::BI__builtin_ia32_rangepd128_mask:
5189   case X86::BI__builtin_ia32_rangepd256_mask:
5190   case X86::BI__builtin_ia32_rangepd512_mask:
5191   case X86::BI__builtin_ia32_rangeps128_mask:
5192   case X86::BI__builtin_ia32_rangeps256_mask:
5193   case X86::BI__builtin_ia32_rangeps512_mask:
5194   case X86::BI__builtin_ia32_getmantsd_round_mask:
5195   case X86::BI__builtin_ia32_getmantss_round_mask:
5196   case X86::BI__builtin_ia32_getmantsh_round_mask:
5197   case X86::BI__builtin_ia32_vec_set_v16qi:
5198   case X86::BI__builtin_ia32_vec_set_v16hi:
5199     i = 2; l = 0; u = 15;
5200     break;
5201   case X86::BI__builtin_ia32_vec_ext_v32qi:
5202     i = 1; l = 0; u = 31;
5203     break;
5204   case X86::BI__builtin_ia32_cmpps:
5205   case X86::BI__builtin_ia32_cmpss:
5206   case X86::BI__builtin_ia32_cmppd:
5207   case X86::BI__builtin_ia32_cmpsd:
5208   case X86::BI__builtin_ia32_cmpps256:
5209   case X86::BI__builtin_ia32_cmppd256:
5210   case X86::BI__builtin_ia32_cmpps128_mask:
5211   case X86::BI__builtin_ia32_cmppd128_mask:
5212   case X86::BI__builtin_ia32_cmpps256_mask:
5213   case X86::BI__builtin_ia32_cmppd256_mask:
5214   case X86::BI__builtin_ia32_cmpps512_mask:
5215   case X86::BI__builtin_ia32_cmppd512_mask:
5216   case X86::BI__builtin_ia32_cmpsd_mask:
5217   case X86::BI__builtin_ia32_cmpss_mask:
5218   case X86::BI__builtin_ia32_vec_set_v32qi:
5219     i = 2; l = 0; u = 31;
5220     break;
5221   case X86::BI__builtin_ia32_permdf256:
5222   case X86::BI__builtin_ia32_permdi256:
5223   case X86::BI__builtin_ia32_permdf512:
5224   case X86::BI__builtin_ia32_permdi512:
5225   case X86::BI__builtin_ia32_vpermilps:
5226   case X86::BI__builtin_ia32_vpermilps256:
5227   case X86::BI__builtin_ia32_vpermilpd512:
5228   case X86::BI__builtin_ia32_vpermilps512:
5229   case X86::BI__builtin_ia32_pshufd:
5230   case X86::BI__builtin_ia32_pshufd256:
5231   case X86::BI__builtin_ia32_pshufd512:
5232   case X86::BI__builtin_ia32_pshufhw:
5233   case X86::BI__builtin_ia32_pshufhw256:
5234   case X86::BI__builtin_ia32_pshufhw512:
5235   case X86::BI__builtin_ia32_pshuflw:
5236   case X86::BI__builtin_ia32_pshuflw256:
5237   case X86::BI__builtin_ia32_pshuflw512:
5238   case X86::BI__builtin_ia32_vcvtps2ph:
5239   case X86::BI__builtin_ia32_vcvtps2ph_mask:
5240   case X86::BI__builtin_ia32_vcvtps2ph256:
5241   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
5242   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
5243   case X86::BI__builtin_ia32_rndscaleps_128_mask:
5244   case X86::BI__builtin_ia32_rndscalepd_128_mask:
5245   case X86::BI__builtin_ia32_rndscaleps_256_mask:
5246   case X86::BI__builtin_ia32_rndscalepd_256_mask:
5247   case X86::BI__builtin_ia32_rndscaleps_mask:
5248   case X86::BI__builtin_ia32_rndscalepd_mask:
5249   case X86::BI__builtin_ia32_rndscaleph_mask:
5250   case X86::BI__builtin_ia32_reducepd128_mask:
5251   case X86::BI__builtin_ia32_reducepd256_mask:
5252   case X86::BI__builtin_ia32_reducepd512_mask:
5253   case X86::BI__builtin_ia32_reduceps128_mask:
5254   case X86::BI__builtin_ia32_reduceps256_mask:
5255   case X86::BI__builtin_ia32_reduceps512_mask:
5256   case X86::BI__builtin_ia32_reduceph128_mask:
5257   case X86::BI__builtin_ia32_reduceph256_mask:
5258   case X86::BI__builtin_ia32_reduceph512_mask:
5259   case X86::BI__builtin_ia32_prold512:
5260   case X86::BI__builtin_ia32_prolq512:
5261   case X86::BI__builtin_ia32_prold128:
5262   case X86::BI__builtin_ia32_prold256:
5263   case X86::BI__builtin_ia32_prolq128:
5264   case X86::BI__builtin_ia32_prolq256:
5265   case X86::BI__builtin_ia32_prord512:
5266   case X86::BI__builtin_ia32_prorq512:
5267   case X86::BI__builtin_ia32_prord128:
5268   case X86::BI__builtin_ia32_prord256:
5269   case X86::BI__builtin_ia32_prorq128:
5270   case X86::BI__builtin_ia32_prorq256:
5271   case X86::BI__builtin_ia32_fpclasspd128_mask:
5272   case X86::BI__builtin_ia32_fpclasspd256_mask:
5273   case X86::BI__builtin_ia32_fpclassps128_mask:
5274   case X86::BI__builtin_ia32_fpclassps256_mask:
5275   case X86::BI__builtin_ia32_fpclassps512_mask:
5276   case X86::BI__builtin_ia32_fpclasspd512_mask:
5277   case X86::BI__builtin_ia32_fpclassph128_mask:
5278   case X86::BI__builtin_ia32_fpclassph256_mask:
5279   case X86::BI__builtin_ia32_fpclassph512_mask:
5280   case X86::BI__builtin_ia32_fpclasssd_mask:
5281   case X86::BI__builtin_ia32_fpclassss_mask:
5282   case X86::BI__builtin_ia32_fpclasssh_mask:
5283   case X86::BI__builtin_ia32_pslldqi128_byteshift:
5284   case X86::BI__builtin_ia32_pslldqi256_byteshift:
5285   case X86::BI__builtin_ia32_pslldqi512_byteshift:
5286   case X86::BI__builtin_ia32_psrldqi128_byteshift:
5287   case X86::BI__builtin_ia32_psrldqi256_byteshift:
5288   case X86::BI__builtin_ia32_psrldqi512_byteshift:
5289   case X86::BI__builtin_ia32_kshiftliqi:
5290   case X86::BI__builtin_ia32_kshiftlihi:
5291   case X86::BI__builtin_ia32_kshiftlisi:
5292   case X86::BI__builtin_ia32_kshiftlidi:
5293   case X86::BI__builtin_ia32_kshiftriqi:
5294   case X86::BI__builtin_ia32_kshiftrihi:
5295   case X86::BI__builtin_ia32_kshiftrisi:
5296   case X86::BI__builtin_ia32_kshiftridi:
5297     i = 1; l = 0; u = 255;
5298     break;
5299   case X86::BI__builtin_ia32_vperm2f128_pd256:
5300   case X86::BI__builtin_ia32_vperm2f128_ps256:
5301   case X86::BI__builtin_ia32_vperm2f128_si256:
5302   case X86::BI__builtin_ia32_permti256:
5303   case X86::BI__builtin_ia32_pblendw128:
5304   case X86::BI__builtin_ia32_pblendw256:
5305   case X86::BI__builtin_ia32_blendps256:
5306   case X86::BI__builtin_ia32_pblendd256:
5307   case X86::BI__builtin_ia32_palignr128:
5308   case X86::BI__builtin_ia32_palignr256:
5309   case X86::BI__builtin_ia32_palignr512:
5310   case X86::BI__builtin_ia32_alignq512:
5311   case X86::BI__builtin_ia32_alignd512:
5312   case X86::BI__builtin_ia32_alignd128:
5313   case X86::BI__builtin_ia32_alignd256:
5314   case X86::BI__builtin_ia32_alignq128:
5315   case X86::BI__builtin_ia32_alignq256:
5316   case X86::BI__builtin_ia32_vcomisd:
5317   case X86::BI__builtin_ia32_vcomiss:
5318   case X86::BI__builtin_ia32_shuf_f32x4:
5319   case X86::BI__builtin_ia32_shuf_f64x2:
5320   case X86::BI__builtin_ia32_shuf_i32x4:
5321   case X86::BI__builtin_ia32_shuf_i64x2:
5322   case X86::BI__builtin_ia32_shufpd512:
5323   case X86::BI__builtin_ia32_shufps:
5324   case X86::BI__builtin_ia32_shufps256:
5325   case X86::BI__builtin_ia32_shufps512:
5326   case X86::BI__builtin_ia32_dbpsadbw128:
5327   case X86::BI__builtin_ia32_dbpsadbw256:
5328   case X86::BI__builtin_ia32_dbpsadbw512:
5329   case X86::BI__builtin_ia32_vpshldd128:
5330   case X86::BI__builtin_ia32_vpshldd256:
5331   case X86::BI__builtin_ia32_vpshldd512:
5332   case X86::BI__builtin_ia32_vpshldq128:
5333   case X86::BI__builtin_ia32_vpshldq256:
5334   case X86::BI__builtin_ia32_vpshldq512:
5335   case X86::BI__builtin_ia32_vpshldw128:
5336   case X86::BI__builtin_ia32_vpshldw256:
5337   case X86::BI__builtin_ia32_vpshldw512:
5338   case X86::BI__builtin_ia32_vpshrdd128:
5339   case X86::BI__builtin_ia32_vpshrdd256:
5340   case X86::BI__builtin_ia32_vpshrdd512:
5341   case X86::BI__builtin_ia32_vpshrdq128:
5342   case X86::BI__builtin_ia32_vpshrdq256:
5343   case X86::BI__builtin_ia32_vpshrdq512:
5344   case X86::BI__builtin_ia32_vpshrdw128:
5345   case X86::BI__builtin_ia32_vpshrdw256:
5346   case X86::BI__builtin_ia32_vpshrdw512:
5347     i = 2; l = 0; u = 255;
5348     break;
5349   case X86::BI__builtin_ia32_fixupimmpd512_mask:
5350   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
5351   case X86::BI__builtin_ia32_fixupimmps512_mask:
5352   case X86::BI__builtin_ia32_fixupimmps512_maskz:
5353   case X86::BI__builtin_ia32_fixupimmsd_mask:
5354   case X86::BI__builtin_ia32_fixupimmsd_maskz:
5355   case X86::BI__builtin_ia32_fixupimmss_mask:
5356   case X86::BI__builtin_ia32_fixupimmss_maskz:
5357   case X86::BI__builtin_ia32_fixupimmpd128_mask:
5358   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
5359   case X86::BI__builtin_ia32_fixupimmpd256_mask:
5360   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
5361   case X86::BI__builtin_ia32_fixupimmps128_mask:
5362   case X86::BI__builtin_ia32_fixupimmps128_maskz:
5363   case X86::BI__builtin_ia32_fixupimmps256_mask:
5364   case X86::BI__builtin_ia32_fixupimmps256_maskz:
5365   case X86::BI__builtin_ia32_pternlogd512_mask:
5366   case X86::BI__builtin_ia32_pternlogd512_maskz:
5367   case X86::BI__builtin_ia32_pternlogq512_mask:
5368   case X86::BI__builtin_ia32_pternlogq512_maskz:
5369   case X86::BI__builtin_ia32_pternlogd128_mask:
5370   case X86::BI__builtin_ia32_pternlogd128_maskz:
5371   case X86::BI__builtin_ia32_pternlogd256_mask:
5372   case X86::BI__builtin_ia32_pternlogd256_maskz:
5373   case X86::BI__builtin_ia32_pternlogq128_mask:
5374   case X86::BI__builtin_ia32_pternlogq128_maskz:
5375   case X86::BI__builtin_ia32_pternlogq256_mask:
5376   case X86::BI__builtin_ia32_pternlogq256_maskz:
5377     i = 3; l = 0; u = 255;
5378     break;
5379   case X86::BI__builtin_ia32_gatherpfdpd:
5380   case X86::BI__builtin_ia32_gatherpfdps:
5381   case X86::BI__builtin_ia32_gatherpfqpd:
5382   case X86::BI__builtin_ia32_gatherpfqps:
5383   case X86::BI__builtin_ia32_scatterpfdpd:
5384   case X86::BI__builtin_ia32_scatterpfdps:
5385   case X86::BI__builtin_ia32_scatterpfqpd:
5386   case X86::BI__builtin_ia32_scatterpfqps:
5387     i = 4; l = 2; u = 3;
5388     break;
5389   case X86::BI__builtin_ia32_reducesd_mask:
5390   case X86::BI__builtin_ia32_reducess_mask:
5391   case X86::BI__builtin_ia32_rndscalesd_round_mask:
5392   case X86::BI__builtin_ia32_rndscaless_round_mask:
5393   case X86::BI__builtin_ia32_rndscalesh_round_mask:
5394   case X86::BI__builtin_ia32_reducesh_mask:
5395     i = 4; l = 0; u = 255;
5396     break;
5397   }
5398 
5399   // Note that we don't force a hard error on the range check here, allowing
5400   // template-generated or macro-generated dead code to potentially have out-of-
5401   // range values. These need to code generate, but don't need to necessarily
5402   // make any sense. We use a warning that defaults to an error.
5403   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
5404 }
5405 
5406 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
5407 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
5408 /// Returns true when the format fits the function and the FormatStringInfo has
5409 /// been populated.
5410 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
5411                                bool IsVariadic, FormatStringInfo *FSI) {
5412   if (Format->getFirstArg() == 0)
5413     FSI->ArgPassingKind = FAPK_VAList;
5414   else if (IsVariadic)
5415     FSI->ArgPassingKind = FAPK_Variadic;
5416   else
5417     FSI->ArgPassingKind = FAPK_Fixed;
5418   FSI->FormatIdx = Format->getFormatIdx() - 1;
5419   FSI->FirstDataArg =
5420       FSI->ArgPassingKind == FAPK_VAList ? 0 : Format->getFirstArg() - 1;
5421 
5422   // The way the format attribute works in GCC, the implicit this argument
5423   // of member functions is counted. However, it doesn't appear in our own
5424   // lists, so decrement format_idx in that case.
5425   if (IsCXXMember) {
5426     if(FSI->FormatIdx == 0)
5427       return false;
5428     --FSI->FormatIdx;
5429     if (FSI->FirstDataArg != 0)
5430       --FSI->FirstDataArg;
5431   }
5432   return true;
5433 }
5434 
5435 /// Checks if a the given expression evaluates to null.
5436 ///
5437 /// Returns true if the value evaluates to null.
5438 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
5439   // If the expression has non-null type, it doesn't evaluate to null.
5440   if (auto nullability
5441         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
5442     if (*nullability == NullabilityKind::NonNull)
5443       return false;
5444   }
5445 
5446   // As a special case, transparent unions initialized with zero are
5447   // considered null for the purposes of the nonnull attribute.
5448   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
5449     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
5450       if (const CompoundLiteralExpr *CLE =
5451           dyn_cast<CompoundLiteralExpr>(Expr))
5452         if (const InitListExpr *ILE =
5453             dyn_cast<InitListExpr>(CLE->getInitializer()))
5454           Expr = ILE->getInit(0);
5455   }
5456 
5457   bool Result;
5458   return (!Expr->isValueDependent() &&
5459           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
5460           !Result);
5461 }
5462 
5463 static void CheckNonNullArgument(Sema &S,
5464                                  const Expr *ArgExpr,
5465                                  SourceLocation CallSiteLoc) {
5466   if (CheckNonNullExpr(S, ArgExpr))
5467     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
5468                           S.PDiag(diag::warn_null_arg)
5469                               << ArgExpr->getSourceRange());
5470 }
5471 
5472 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
5473   FormatStringInfo FSI;
5474   if ((GetFormatStringType(Format) == FST_NSString) &&
5475       getFormatStringInfo(Format, false, true, &FSI)) {
5476     Idx = FSI.FormatIdx;
5477     return true;
5478   }
5479   return false;
5480 }
5481 
5482 /// Diagnose use of %s directive in an NSString which is being passed
5483 /// as formatting string to formatting method.
5484 static void
5485 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
5486                                         const NamedDecl *FDecl,
5487                                         Expr **Args,
5488                                         unsigned NumArgs) {
5489   unsigned Idx = 0;
5490   bool Format = false;
5491   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
5492   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
5493     Idx = 2;
5494     Format = true;
5495   }
5496   else
5497     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
5498       if (S.GetFormatNSStringIdx(I, Idx)) {
5499         Format = true;
5500         break;
5501       }
5502     }
5503   if (!Format || NumArgs <= Idx)
5504     return;
5505   const Expr *FormatExpr = Args[Idx];
5506   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
5507     FormatExpr = CSCE->getSubExpr();
5508   const StringLiteral *FormatString;
5509   if (const ObjCStringLiteral *OSL =
5510       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
5511     FormatString = OSL->getString();
5512   else
5513     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
5514   if (!FormatString)
5515     return;
5516   if (S.FormatStringHasSArg(FormatString)) {
5517     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
5518       << "%s" << 1 << 1;
5519     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
5520       << FDecl->getDeclName();
5521   }
5522 }
5523 
5524 /// Determine whether the given type has a non-null nullability annotation.
5525 static bool isNonNullType(ASTContext &ctx, QualType type) {
5526   if (auto nullability = type->getNullability(ctx))
5527     return *nullability == NullabilityKind::NonNull;
5528 
5529   return false;
5530 }
5531 
5532 static void CheckNonNullArguments(Sema &S,
5533                                   const NamedDecl *FDecl,
5534                                   const FunctionProtoType *Proto,
5535                                   ArrayRef<const Expr *> Args,
5536                                   SourceLocation CallSiteLoc) {
5537   assert((FDecl || Proto) && "Need a function declaration or prototype");
5538 
5539   // Already checked by by constant evaluator.
5540   if (S.isConstantEvaluated())
5541     return;
5542   // Check the attributes attached to the method/function itself.
5543   llvm::SmallBitVector NonNullArgs;
5544   if (FDecl) {
5545     // Handle the nonnull attribute on the function/method declaration itself.
5546     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
5547       if (!NonNull->args_size()) {
5548         // Easy case: all pointer arguments are nonnull.
5549         for (const auto *Arg : Args)
5550           if (S.isValidPointerAttrType(Arg->getType()))
5551             CheckNonNullArgument(S, Arg, CallSiteLoc);
5552         return;
5553       }
5554 
5555       for (const ParamIdx &Idx : NonNull->args()) {
5556         unsigned IdxAST = Idx.getASTIndex();
5557         if (IdxAST >= Args.size())
5558           continue;
5559         if (NonNullArgs.empty())
5560           NonNullArgs.resize(Args.size());
5561         NonNullArgs.set(IdxAST);
5562       }
5563     }
5564   }
5565 
5566   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
5567     // Handle the nonnull attribute on the parameters of the
5568     // function/method.
5569     ArrayRef<ParmVarDecl*> parms;
5570     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
5571       parms = FD->parameters();
5572     else
5573       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
5574 
5575     unsigned ParamIndex = 0;
5576     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
5577          I != E; ++I, ++ParamIndex) {
5578       const ParmVarDecl *PVD = *I;
5579       if (PVD->hasAttr<NonNullAttr>() ||
5580           isNonNullType(S.Context, PVD->getType())) {
5581         if (NonNullArgs.empty())
5582           NonNullArgs.resize(Args.size());
5583 
5584         NonNullArgs.set(ParamIndex);
5585       }
5586     }
5587   } else {
5588     // If we have a non-function, non-method declaration but no
5589     // function prototype, try to dig out the function prototype.
5590     if (!Proto) {
5591       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
5592         QualType type = VD->getType().getNonReferenceType();
5593         if (auto pointerType = type->getAs<PointerType>())
5594           type = pointerType->getPointeeType();
5595         else if (auto blockType = type->getAs<BlockPointerType>())
5596           type = blockType->getPointeeType();
5597         // FIXME: data member pointers?
5598 
5599         // Dig out the function prototype, if there is one.
5600         Proto = type->getAs<FunctionProtoType>();
5601       }
5602     }
5603 
5604     // Fill in non-null argument information from the nullability
5605     // information on the parameter types (if we have them).
5606     if (Proto) {
5607       unsigned Index = 0;
5608       for (auto paramType : Proto->getParamTypes()) {
5609         if (isNonNullType(S.Context, paramType)) {
5610           if (NonNullArgs.empty())
5611             NonNullArgs.resize(Args.size());
5612 
5613           NonNullArgs.set(Index);
5614         }
5615 
5616         ++Index;
5617       }
5618     }
5619   }
5620 
5621   // Check for non-null arguments.
5622   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
5623        ArgIndex != ArgIndexEnd; ++ArgIndex) {
5624     if (NonNullArgs[ArgIndex])
5625       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
5626   }
5627 }
5628 
5629 /// Warn if a pointer or reference argument passed to a function points to an
5630 /// object that is less aligned than the parameter. This can happen when
5631 /// creating a typedef with a lower alignment than the original type and then
5632 /// calling functions defined in terms of the original type.
5633 void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
5634                              StringRef ParamName, QualType ArgTy,
5635                              QualType ParamTy) {
5636 
5637   // If a function accepts a pointer or reference type
5638   if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
5639     return;
5640 
5641   // If the parameter is a pointer type, get the pointee type for the
5642   // argument too. If the parameter is a reference type, don't try to get
5643   // the pointee type for the argument.
5644   if (ParamTy->isPointerType())
5645     ArgTy = ArgTy->getPointeeType();
5646 
5647   // Remove reference or pointer
5648   ParamTy = ParamTy->getPointeeType();
5649 
5650   // Find expected alignment, and the actual alignment of the passed object.
5651   // getTypeAlignInChars requires complete types
5652   if (ArgTy.isNull() || ParamTy->isIncompleteType() ||
5653       ArgTy->isIncompleteType() || ParamTy->isUndeducedType() ||
5654       ArgTy->isUndeducedType())
5655     return;
5656 
5657   CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
5658   CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
5659 
5660   // If the argument is less aligned than the parameter, there is a
5661   // potential alignment issue.
5662   if (ArgAlign < ParamAlign)
5663     Diag(Loc, diag::warn_param_mismatched_alignment)
5664         << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
5665         << ParamName << (FDecl != nullptr) << FDecl;
5666 }
5667 
5668 /// Handles the checks for format strings, non-POD arguments to vararg
5669 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
5670 /// attributes.
5671 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
5672                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
5673                      bool IsMemberFunction, SourceLocation Loc,
5674                      SourceRange Range, VariadicCallType CallType) {
5675   // FIXME: We should check as much as we can in the template definition.
5676   if (CurContext->isDependentContext())
5677     return;
5678 
5679   // Printf and scanf checking.
5680   llvm::SmallBitVector CheckedVarArgs;
5681   if (FDecl) {
5682     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
5683       // Only create vector if there are format attributes.
5684       CheckedVarArgs.resize(Args.size());
5685 
5686       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
5687                            CheckedVarArgs);
5688     }
5689   }
5690 
5691   // Refuse POD arguments that weren't caught by the format string
5692   // checks above.
5693   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
5694   if (CallType != VariadicDoesNotApply &&
5695       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
5696     unsigned NumParams = Proto ? Proto->getNumParams()
5697                        : FDecl && isa<FunctionDecl>(FDecl)
5698                            ? cast<FunctionDecl>(FDecl)->getNumParams()
5699                        : FDecl && isa<ObjCMethodDecl>(FDecl)
5700                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
5701                        : 0;
5702 
5703     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
5704       // Args[ArgIdx] can be null in malformed code.
5705       if (const Expr *Arg = Args[ArgIdx]) {
5706         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
5707           checkVariadicArgument(Arg, CallType);
5708       }
5709     }
5710   }
5711 
5712   if (FDecl || Proto) {
5713     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
5714 
5715     // Type safety checking.
5716     if (FDecl) {
5717       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
5718         CheckArgumentWithTypeTag(I, Args, Loc);
5719     }
5720   }
5721 
5722   // Check that passed arguments match the alignment of original arguments.
5723   // Try to get the missing prototype from the declaration.
5724   if (!Proto && FDecl) {
5725     const auto *FT = FDecl->getFunctionType();
5726     if (isa_and_nonnull<FunctionProtoType>(FT))
5727       Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
5728   }
5729   if (Proto) {
5730     // For variadic functions, we may have more args than parameters.
5731     // For some K&R functions, we may have less args than parameters.
5732     const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
5733     for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
5734       // Args[ArgIdx] can be null in malformed code.
5735       if (const Expr *Arg = Args[ArgIdx]) {
5736         if (Arg->containsErrors())
5737           continue;
5738 
5739         QualType ParamTy = Proto->getParamType(ArgIdx);
5740         QualType ArgTy = Arg->getType();
5741         CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
5742                           ArgTy, ParamTy);
5743       }
5744     }
5745   }
5746 
5747   if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
5748     auto *AA = FDecl->getAttr<AllocAlignAttr>();
5749     const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
5750     if (!Arg->isValueDependent()) {
5751       Expr::EvalResult Align;
5752       if (Arg->EvaluateAsInt(Align, Context)) {
5753         const llvm::APSInt &I = Align.Val.getInt();
5754         if (!I.isPowerOf2())
5755           Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
5756               << Arg->getSourceRange();
5757 
5758         if (I > Sema::MaximumAlignment)
5759           Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
5760               << Arg->getSourceRange() << Sema::MaximumAlignment;
5761       }
5762     }
5763   }
5764 
5765   if (FD)
5766     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
5767 }
5768 
5769 /// CheckConstructorCall - Check a constructor call for correctness and safety
5770 /// properties not enforced by the C type system.
5771 void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
5772                                 ArrayRef<const Expr *> Args,
5773                                 const FunctionProtoType *Proto,
5774                                 SourceLocation Loc) {
5775   VariadicCallType CallType =
5776       Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
5777 
5778   auto *Ctor = cast<CXXConstructorDecl>(FDecl);
5779   CheckArgAlignment(Loc, FDecl, "'this'", Context.getPointerType(ThisType),
5780                     Context.getPointerType(Ctor->getThisObjectType()));
5781 
5782   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
5783             Loc, SourceRange(), CallType);
5784 }
5785 
5786 /// CheckFunctionCall - Check a direct function call for various correctness
5787 /// and safety properties not strictly enforced by the C type system.
5788 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
5789                              const FunctionProtoType *Proto) {
5790   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
5791                               isa<CXXMethodDecl>(FDecl);
5792   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
5793                           IsMemberOperatorCall;
5794   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
5795                                                   TheCall->getCallee());
5796   Expr** Args = TheCall->getArgs();
5797   unsigned NumArgs = TheCall->getNumArgs();
5798 
5799   Expr *ImplicitThis = nullptr;
5800   if (IsMemberOperatorCall) {
5801     // If this is a call to a member operator, hide the first argument
5802     // from checkCall.
5803     // FIXME: Our choice of AST representation here is less than ideal.
5804     ImplicitThis = Args[0];
5805     ++Args;
5806     --NumArgs;
5807   } else if (IsMemberFunction)
5808     ImplicitThis =
5809         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
5810 
5811   if (ImplicitThis) {
5812     // ImplicitThis may or may not be a pointer, depending on whether . or -> is
5813     // used.
5814     QualType ThisType = ImplicitThis->getType();
5815     if (!ThisType->isPointerType()) {
5816       assert(!ThisType->isReferenceType());
5817       ThisType = Context.getPointerType(ThisType);
5818     }
5819 
5820     QualType ThisTypeFromDecl =
5821         Context.getPointerType(cast<CXXMethodDecl>(FDecl)->getThisObjectType());
5822 
5823     CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
5824                       ThisTypeFromDecl);
5825   }
5826 
5827   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
5828             IsMemberFunction, TheCall->getRParenLoc(),
5829             TheCall->getCallee()->getSourceRange(), CallType);
5830 
5831   IdentifierInfo *FnInfo = FDecl->getIdentifier();
5832   // None of the checks below are needed for functions that don't have
5833   // simple names (e.g., C++ conversion functions).
5834   if (!FnInfo)
5835     return false;
5836 
5837   // Enforce TCB except for builtin calls, which are always allowed.
5838   if (FDecl->getBuiltinID() == 0)
5839     CheckTCBEnforcement(TheCall->getExprLoc(), FDecl);
5840 
5841   CheckAbsoluteValueFunction(TheCall, FDecl);
5842   CheckMaxUnsignedZero(TheCall, FDecl);
5843 
5844   if (getLangOpts().ObjC)
5845     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
5846 
5847   unsigned CMId = FDecl->getMemoryFunctionKind();
5848 
5849   // Handle memory setting and copying functions.
5850   switch (CMId) {
5851   case 0:
5852     return false;
5853   case Builtin::BIstrlcpy: // fallthrough
5854   case Builtin::BIstrlcat:
5855     CheckStrlcpycatArguments(TheCall, FnInfo);
5856     break;
5857   case Builtin::BIstrncat:
5858     CheckStrncatArguments(TheCall, FnInfo);
5859     break;
5860   case Builtin::BIfree:
5861     CheckFreeArguments(TheCall);
5862     break;
5863   default:
5864     CheckMemaccessArguments(TheCall, CMId, FnInfo);
5865   }
5866 
5867   return false;
5868 }
5869 
5870 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
5871                                ArrayRef<const Expr *> Args) {
5872   VariadicCallType CallType =
5873       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
5874 
5875   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
5876             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
5877             CallType);
5878 
5879   CheckTCBEnforcement(lbrac, Method);
5880 
5881   return false;
5882 }
5883 
5884 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
5885                             const FunctionProtoType *Proto) {
5886   QualType Ty;
5887   if (const auto *V = dyn_cast<VarDecl>(NDecl))
5888     Ty = V->getType().getNonReferenceType();
5889   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
5890     Ty = F->getType().getNonReferenceType();
5891   else
5892     return false;
5893 
5894   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
5895       !Ty->isFunctionProtoType())
5896     return false;
5897 
5898   VariadicCallType CallType;
5899   if (!Proto || !Proto->isVariadic()) {
5900     CallType = VariadicDoesNotApply;
5901   } else if (Ty->isBlockPointerType()) {
5902     CallType = VariadicBlock;
5903   } else { // Ty->isFunctionPointerType()
5904     CallType = VariadicFunction;
5905   }
5906 
5907   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
5908             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5909             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
5910             TheCall->getCallee()->getSourceRange(), CallType);
5911 
5912   return false;
5913 }
5914 
5915 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
5916 /// such as function pointers returned from functions.
5917 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
5918   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
5919                                                   TheCall->getCallee());
5920   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
5921             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5922             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
5923             TheCall->getCallee()->getSourceRange(), CallType);
5924 
5925   return false;
5926 }
5927 
5928 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
5929   if (!llvm::isValidAtomicOrderingCABI(Ordering))
5930     return false;
5931 
5932   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
5933   switch (Op) {
5934   case AtomicExpr::AO__c11_atomic_init:
5935   case AtomicExpr::AO__opencl_atomic_init:
5936     llvm_unreachable("There is no ordering argument for an init");
5937 
5938   case AtomicExpr::AO__c11_atomic_load:
5939   case AtomicExpr::AO__opencl_atomic_load:
5940   case AtomicExpr::AO__hip_atomic_load:
5941   case AtomicExpr::AO__atomic_load_n:
5942   case AtomicExpr::AO__atomic_load:
5943     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
5944            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5945 
5946   case AtomicExpr::AO__c11_atomic_store:
5947   case AtomicExpr::AO__opencl_atomic_store:
5948   case AtomicExpr::AO__hip_atomic_store:
5949   case AtomicExpr::AO__atomic_store:
5950   case AtomicExpr::AO__atomic_store_n:
5951     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
5952            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
5953            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5954 
5955   default:
5956     return true;
5957   }
5958 }
5959 
5960 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
5961                                          AtomicExpr::AtomicOp Op) {
5962   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
5963   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5964   MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
5965   return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
5966                          DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
5967                          Op);
5968 }
5969 
5970 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
5971                                  SourceLocation RParenLoc, MultiExprArg Args,
5972                                  AtomicExpr::AtomicOp Op,
5973                                  AtomicArgumentOrder ArgOrder) {
5974   // All the non-OpenCL operations take one of the following forms.
5975   // The OpenCL operations take the __c11 forms with one extra argument for
5976   // synchronization scope.
5977   enum {
5978     // C    __c11_atomic_init(A *, C)
5979     Init,
5980 
5981     // C    __c11_atomic_load(A *, int)
5982     Load,
5983 
5984     // void __atomic_load(A *, CP, int)
5985     LoadCopy,
5986 
5987     // void __atomic_store(A *, CP, int)
5988     Copy,
5989 
5990     // C    __c11_atomic_add(A *, M, int)
5991     Arithmetic,
5992 
5993     // C    __atomic_exchange_n(A *, CP, int)
5994     Xchg,
5995 
5996     // void __atomic_exchange(A *, C *, CP, int)
5997     GNUXchg,
5998 
5999     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
6000     C11CmpXchg,
6001 
6002     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
6003     GNUCmpXchg
6004   } Form = Init;
6005 
6006   const unsigned NumForm = GNUCmpXchg + 1;
6007   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
6008   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
6009   // where:
6010   //   C is an appropriate type,
6011   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
6012   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
6013   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
6014   //   the int parameters are for orderings.
6015 
6016   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
6017       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
6018       "need to update code for modified forms");
6019   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
6020                     AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
6021                         AtomicExpr::AO__atomic_load,
6022                 "need to update code for modified C11 atomics");
6023   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
6024                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
6025   bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_load &&
6026                Op <= AtomicExpr::AO__hip_atomic_fetch_max;
6027   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
6028                Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
6029                IsOpenCL;
6030   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
6031              Op == AtomicExpr::AO__atomic_store_n ||
6032              Op == AtomicExpr::AO__atomic_exchange_n ||
6033              Op == AtomicExpr::AO__atomic_compare_exchange_n;
6034   bool IsAddSub = false;
6035 
6036   switch (Op) {
6037   case AtomicExpr::AO__c11_atomic_init:
6038   case AtomicExpr::AO__opencl_atomic_init:
6039     Form = Init;
6040     break;
6041 
6042   case AtomicExpr::AO__c11_atomic_load:
6043   case AtomicExpr::AO__opencl_atomic_load:
6044   case AtomicExpr::AO__hip_atomic_load:
6045   case AtomicExpr::AO__atomic_load_n:
6046     Form = Load;
6047     break;
6048 
6049   case AtomicExpr::AO__atomic_load:
6050     Form = LoadCopy;
6051     break;
6052 
6053   case AtomicExpr::AO__c11_atomic_store:
6054   case AtomicExpr::AO__opencl_atomic_store:
6055   case AtomicExpr::AO__hip_atomic_store:
6056   case AtomicExpr::AO__atomic_store:
6057   case AtomicExpr::AO__atomic_store_n:
6058     Form = Copy;
6059     break;
6060   case AtomicExpr::AO__hip_atomic_fetch_add:
6061   case AtomicExpr::AO__hip_atomic_fetch_min:
6062   case AtomicExpr::AO__hip_atomic_fetch_max:
6063   case AtomicExpr::AO__c11_atomic_fetch_add:
6064   case AtomicExpr::AO__c11_atomic_fetch_sub:
6065   case AtomicExpr::AO__opencl_atomic_fetch_add:
6066   case AtomicExpr::AO__opencl_atomic_fetch_sub:
6067   case AtomicExpr::AO__atomic_fetch_add:
6068   case AtomicExpr::AO__atomic_fetch_sub:
6069   case AtomicExpr::AO__atomic_add_fetch:
6070   case AtomicExpr::AO__atomic_sub_fetch:
6071     IsAddSub = true;
6072     Form = Arithmetic;
6073     break;
6074   case AtomicExpr::AO__c11_atomic_fetch_and:
6075   case AtomicExpr::AO__c11_atomic_fetch_or:
6076   case AtomicExpr::AO__c11_atomic_fetch_xor:
6077   case AtomicExpr::AO__hip_atomic_fetch_and:
6078   case AtomicExpr::AO__hip_atomic_fetch_or:
6079   case AtomicExpr::AO__hip_atomic_fetch_xor:
6080   case AtomicExpr::AO__c11_atomic_fetch_nand:
6081   case AtomicExpr::AO__opencl_atomic_fetch_and:
6082   case AtomicExpr::AO__opencl_atomic_fetch_or:
6083   case AtomicExpr::AO__opencl_atomic_fetch_xor:
6084   case AtomicExpr::AO__atomic_fetch_and:
6085   case AtomicExpr::AO__atomic_fetch_or:
6086   case AtomicExpr::AO__atomic_fetch_xor:
6087   case AtomicExpr::AO__atomic_fetch_nand:
6088   case AtomicExpr::AO__atomic_and_fetch:
6089   case AtomicExpr::AO__atomic_or_fetch:
6090   case AtomicExpr::AO__atomic_xor_fetch:
6091   case AtomicExpr::AO__atomic_nand_fetch:
6092     Form = Arithmetic;
6093     break;
6094   case AtomicExpr::AO__c11_atomic_fetch_min:
6095   case AtomicExpr::AO__c11_atomic_fetch_max:
6096   case AtomicExpr::AO__opencl_atomic_fetch_min:
6097   case AtomicExpr::AO__opencl_atomic_fetch_max:
6098   case AtomicExpr::AO__atomic_min_fetch:
6099   case AtomicExpr::AO__atomic_max_fetch:
6100   case AtomicExpr::AO__atomic_fetch_min:
6101   case AtomicExpr::AO__atomic_fetch_max:
6102     Form = Arithmetic;
6103     break;
6104 
6105   case AtomicExpr::AO__c11_atomic_exchange:
6106   case AtomicExpr::AO__hip_atomic_exchange:
6107   case AtomicExpr::AO__opencl_atomic_exchange:
6108   case AtomicExpr::AO__atomic_exchange_n:
6109     Form = Xchg;
6110     break;
6111 
6112   case AtomicExpr::AO__atomic_exchange:
6113     Form = GNUXchg;
6114     break;
6115 
6116   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
6117   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
6118   case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
6119   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
6120   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
6121   case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
6122     Form = C11CmpXchg;
6123     break;
6124 
6125   case AtomicExpr::AO__atomic_compare_exchange:
6126   case AtomicExpr::AO__atomic_compare_exchange_n:
6127     Form = GNUCmpXchg;
6128     break;
6129   }
6130 
6131   unsigned AdjustedNumArgs = NumArgs[Form];
6132   if ((IsOpenCL || IsHIP) && Op != AtomicExpr::AO__opencl_atomic_init)
6133     ++AdjustedNumArgs;
6134   // Check we have the right number of arguments.
6135   if (Args.size() < AdjustedNumArgs) {
6136     Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
6137         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
6138         << ExprRange;
6139     return ExprError();
6140   } else if (Args.size() > AdjustedNumArgs) {
6141     Diag(Args[AdjustedNumArgs]->getBeginLoc(),
6142          diag::err_typecheck_call_too_many_args)
6143         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
6144         << ExprRange;
6145     return ExprError();
6146   }
6147 
6148   // Inspect the first argument of the atomic operation.
6149   Expr *Ptr = Args[0];
6150   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
6151   if (ConvertedPtr.isInvalid())
6152     return ExprError();
6153 
6154   Ptr = ConvertedPtr.get();
6155   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
6156   if (!pointerType) {
6157     Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
6158         << Ptr->getType() << Ptr->getSourceRange();
6159     return ExprError();
6160   }
6161 
6162   // For a __c11 builtin, this should be a pointer to an _Atomic type.
6163   QualType AtomTy = pointerType->getPointeeType(); // 'A'
6164   QualType ValType = AtomTy; // 'C'
6165   if (IsC11) {
6166     if (!AtomTy->isAtomicType()) {
6167       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
6168           << Ptr->getType() << Ptr->getSourceRange();
6169       return ExprError();
6170     }
6171     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
6172         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
6173       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
6174           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
6175           << Ptr->getSourceRange();
6176       return ExprError();
6177     }
6178     ValType = AtomTy->castAs<AtomicType>()->getValueType();
6179   } else if (Form != Load && Form != LoadCopy) {
6180     if (ValType.isConstQualified()) {
6181       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
6182           << Ptr->getType() << Ptr->getSourceRange();
6183       return ExprError();
6184     }
6185   }
6186 
6187   // For an arithmetic operation, the implied arithmetic must be well-formed.
6188   if (Form == Arithmetic) {
6189     // GCC does not enforce these rules for GNU atomics, but we do to help catch
6190     // trivial type errors.
6191     auto IsAllowedValueType = [&](QualType ValType) {
6192       if (ValType->isIntegerType())
6193         return true;
6194       if (ValType->isPointerType())
6195         return true;
6196       if (!ValType->isFloatingType())
6197         return false;
6198       // LLVM Parser does not allow atomicrmw with x86_fp80 type.
6199       if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
6200           &Context.getTargetInfo().getLongDoubleFormat() ==
6201               &llvm::APFloat::x87DoubleExtended())
6202         return false;
6203       return true;
6204     };
6205     if (IsAddSub && !IsAllowedValueType(ValType)) {
6206       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_ptr_or_fp)
6207           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
6208       return ExprError();
6209     }
6210     if (!IsAddSub && !ValType->isIntegerType()) {
6211       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
6212           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
6213       return ExprError();
6214     }
6215     if (IsC11 && ValType->isPointerType() &&
6216         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
6217                             diag::err_incomplete_type)) {
6218       return ExprError();
6219     }
6220   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
6221     // For __atomic_*_n operations, the value type must be a scalar integral or
6222     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
6223     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
6224         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
6225     return ExprError();
6226   }
6227 
6228   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
6229       !AtomTy->isScalarType()) {
6230     // For GNU atomics, require a trivially-copyable type. This is not part of
6231     // the GNU atomics specification but we enforce it for consistency with
6232     // other atomics which generally all require a trivially-copyable type. This
6233     // is because atomics just copy bits.
6234     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
6235         << Ptr->getType() << Ptr->getSourceRange();
6236     return ExprError();
6237   }
6238 
6239   switch (ValType.getObjCLifetime()) {
6240   case Qualifiers::OCL_None:
6241   case Qualifiers::OCL_ExplicitNone:
6242     // okay
6243     break;
6244 
6245   case Qualifiers::OCL_Weak:
6246   case Qualifiers::OCL_Strong:
6247   case Qualifiers::OCL_Autoreleasing:
6248     // FIXME: Can this happen? By this point, ValType should be known
6249     // to be trivially copyable.
6250     Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
6251         << ValType << Ptr->getSourceRange();
6252     return ExprError();
6253   }
6254 
6255   // All atomic operations have an overload which takes a pointer to a volatile
6256   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
6257   // into the result or the other operands. Similarly atomic_load takes a
6258   // pointer to a const 'A'.
6259   ValType.removeLocalVolatile();
6260   ValType.removeLocalConst();
6261   QualType ResultType = ValType;
6262   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
6263       Form == Init)
6264     ResultType = Context.VoidTy;
6265   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
6266     ResultType = Context.BoolTy;
6267 
6268   // The type of a parameter passed 'by value'. In the GNU atomics, such
6269   // arguments are actually passed as pointers.
6270   QualType ByValType = ValType; // 'CP'
6271   bool IsPassedByAddress = false;
6272   if (!IsC11 && !IsHIP && !IsN) {
6273     ByValType = Ptr->getType();
6274     IsPassedByAddress = true;
6275   }
6276 
6277   SmallVector<Expr *, 5> APIOrderedArgs;
6278   if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
6279     APIOrderedArgs.push_back(Args[0]);
6280     switch (Form) {
6281     case Init:
6282     case Load:
6283       APIOrderedArgs.push_back(Args[1]); // Val1/Order
6284       break;
6285     case LoadCopy:
6286     case Copy:
6287     case Arithmetic:
6288     case Xchg:
6289       APIOrderedArgs.push_back(Args[2]); // Val1
6290       APIOrderedArgs.push_back(Args[1]); // Order
6291       break;
6292     case GNUXchg:
6293       APIOrderedArgs.push_back(Args[2]); // Val1
6294       APIOrderedArgs.push_back(Args[3]); // Val2
6295       APIOrderedArgs.push_back(Args[1]); // Order
6296       break;
6297     case C11CmpXchg:
6298       APIOrderedArgs.push_back(Args[2]); // Val1
6299       APIOrderedArgs.push_back(Args[4]); // Val2
6300       APIOrderedArgs.push_back(Args[1]); // Order
6301       APIOrderedArgs.push_back(Args[3]); // OrderFail
6302       break;
6303     case GNUCmpXchg:
6304       APIOrderedArgs.push_back(Args[2]); // Val1
6305       APIOrderedArgs.push_back(Args[4]); // Val2
6306       APIOrderedArgs.push_back(Args[5]); // Weak
6307       APIOrderedArgs.push_back(Args[1]); // Order
6308       APIOrderedArgs.push_back(Args[3]); // OrderFail
6309       break;
6310     }
6311   } else
6312     APIOrderedArgs.append(Args.begin(), Args.end());
6313 
6314   // The first argument's non-CV pointer type is used to deduce the type of
6315   // subsequent arguments, except for:
6316   //  - weak flag (always converted to bool)
6317   //  - memory order (always converted to int)
6318   //  - scope  (always converted to int)
6319   for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
6320     QualType Ty;
6321     if (i < NumVals[Form] + 1) {
6322       switch (i) {
6323       case 0:
6324         // The first argument is always a pointer. It has a fixed type.
6325         // It is always dereferenced, a nullptr is undefined.
6326         CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
6327         // Nothing else to do: we already know all we want about this pointer.
6328         continue;
6329       case 1:
6330         // The second argument is the non-atomic operand. For arithmetic, this
6331         // is always passed by value, and for a compare_exchange it is always
6332         // passed by address. For the rest, GNU uses by-address and C11 uses
6333         // by-value.
6334         assert(Form != Load);
6335         if (Form == Arithmetic && ValType->isPointerType())
6336           Ty = Context.getPointerDiffType();
6337         else if (Form == Init || Form == Arithmetic)
6338           Ty = ValType;
6339         else if (Form == Copy || Form == Xchg) {
6340           if (IsPassedByAddress) {
6341             // The value pointer is always dereferenced, a nullptr is undefined.
6342             CheckNonNullArgument(*this, APIOrderedArgs[i],
6343                                  ExprRange.getBegin());
6344           }
6345           Ty = ByValType;
6346         } else {
6347           Expr *ValArg = APIOrderedArgs[i];
6348           // The value pointer is always dereferenced, a nullptr is undefined.
6349           CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
6350           LangAS AS = LangAS::Default;
6351           // Keep address space of non-atomic pointer type.
6352           if (const PointerType *PtrTy =
6353                   ValArg->getType()->getAs<PointerType>()) {
6354             AS = PtrTy->getPointeeType().getAddressSpace();
6355           }
6356           Ty = Context.getPointerType(
6357               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
6358         }
6359         break;
6360       case 2:
6361         // The third argument to compare_exchange / GNU exchange is the desired
6362         // value, either by-value (for the C11 and *_n variant) or as a pointer.
6363         if (IsPassedByAddress)
6364           CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
6365         Ty = ByValType;
6366         break;
6367       case 3:
6368         // The fourth argument to GNU compare_exchange is a 'weak' flag.
6369         Ty = Context.BoolTy;
6370         break;
6371       }
6372     } else {
6373       // The order(s) and scope are always converted to int.
6374       Ty = Context.IntTy;
6375     }
6376 
6377     InitializedEntity Entity =
6378         InitializedEntity::InitializeParameter(Context, Ty, false);
6379     ExprResult Arg = APIOrderedArgs[i];
6380     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6381     if (Arg.isInvalid())
6382       return true;
6383     APIOrderedArgs[i] = Arg.get();
6384   }
6385 
6386   // Permute the arguments into a 'consistent' order.
6387   SmallVector<Expr*, 5> SubExprs;
6388   SubExprs.push_back(Ptr);
6389   switch (Form) {
6390   case Init:
6391     // Note, AtomicExpr::getVal1() has a special case for this atomic.
6392     SubExprs.push_back(APIOrderedArgs[1]); // Val1
6393     break;
6394   case Load:
6395     SubExprs.push_back(APIOrderedArgs[1]); // Order
6396     break;
6397   case LoadCopy:
6398   case Copy:
6399   case Arithmetic:
6400   case Xchg:
6401     SubExprs.push_back(APIOrderedArgs[2]); // Order
6402     SubExprs.push_back(APIOrderedArgs[1]); // Val1
6403     break;
6404   case GNUXchg:
6405     // Note, AtomicExpr::getVal2() has a special case for this atomic.
6406     SubExprs.push_back(APIOrderedArgs[3]); // Order
6407     SubExprs.push_back(APIOrderedArgs[1]); // Val1
6408     SubExprs.push_back(APIOrderedArgs[2]); // Val2
6409     break;
6410   case C11CmpXchg:
6411     SubExprs.push_back(APIOrderedArgs[3]); // Order
6412     SubExprs.push_back(APIOrderedArgs[1]); // Val1
6413     SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
6414     SubExprs.push_back(APIOrderedArgs[2]); // Val2
6415     break;
6416   case GNUCmpXchg:
6417     SubExprs.push_back(APIOrderedArgs[4]); // Order
6418     SubExprs.push_back(APIOrderedArgs[1]); // Val1
6419     SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
6420     SubExprs.push_back(APIOrderedArgs[2]); // Val2
6421     SubExprs.push_back(APIOrderedArgs[3]); // Weak
6422     break;
6423   }
6424 
6425   if (SubExprs.size() >= 2 && Form != Init) {
6426     if (Optional<llvm::APSInt> Result =
6427             SubExprs[1]->getIntegerConstantExpr(Context))
6428       if (!isValidOrderingForOp(Result->getSExtValue(), Op))
6429         Diag(SubExprs[1]->getBeginLoc(),
6430              diag::warn_atomic_op_has_invalid_memory_order)
6431             << SubExprs[1]->getSourceRange();
6432   }
6433 
6434   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
6435     auto *Scope = Args[Args.size() - 1];
6436     if (Optional<llvm::APSInt> Result =
6437             Scope->getIntegerConstantExpr(Context)) {
6438       if (!ScopeModel->isValid(Result->getZExtValue()))
6439         Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
6440             << Scope->getSourceRange();
6441     }
6442     SubExprs.push_back(Scope);
6443   }
6444 
6445   AtomicExpr *AE = new (Context)
6446       AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
6447 
6448   if ((Op == AtomicExpr::AO__c11_atomic_load ||
6449        Op == AtomicExpr::AO__c11_atomic_store ||
6450        Op == AtomicExpr::AO__opencl_atomic_load ||
6451        Op == AtomicExpr::AO__hip_atomic_load ||
6452        Op == AtomicExpr::AO__opencl_atomic_store ||
6453        Op == AtomicExpr::AO__hip_atomic_store) &&
6454       Context.AtomicUsesUnsupportedLibcall(AE))
6455     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
6456         << ((Op == AtomicExpr::AO__c11_atomic_load ||
6457              Op == AtomicExpr::AO__opencl_atomic_load ||
6458              Op == AtomicExpr::AO__hip_atomic_load)
6459                 ? 0
6460                 : 1);
6461 
6462   if (ValType->isBitIntType()) {
6463     Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_bit_int_prohibit);
6464     return ExprError();
6465   }
6466 
6467   return AE;
6468 }
6469 
6470 /// checkBuiltinArgument - Given a call to a builtin function, perform
6471 /// normal type-checking on the given argument, updating the call in
6472 /// place.  This is useful when a builtin function requires custom
6473 /// type-checking for some of its arguments but not necessarily all of
6474 /// them.
6475 ///
6476 /// Returns true on error.
6477 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
6478   FunctionDecl *Fn = E->getDirectCallee();
6479   assert(Fn && "builtin call without direct callee!");
6480 
6481   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
6482   InitializedEntity Entity =
6483     InitializedEntity::InitializeParameter(S.Context, Param);
6484 
6485   ExprResult Arg = E->getArg(ArgIndex);
6486   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
6487   if (Arg.isInvalid())
6488     return true;
6489 
6490   E->setArg(ArgIndex, Arg.get());
6491   return false;
6492 }
6493 
6494 /// We have a call to a function like __sync_fetch_and_add, which is an
6495 /// overloaded function based on the pointer type of its first argument.
6496 /// The main BuildCallExpr routines have already promoted the types of
6497 /// arguments because all of these calls are prototyped as void(...).
6498 ///
6499 /// This function goes through and does final semantic checking for these
6500 /// builtins, as well as generating any warnings.
6501 ExprResult
6502 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
6503   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
6504   Expr *Callee = TheCall->getCallee();
6505   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
6506   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6507 
6508   // Ensure that we have at least one argument to do type inference from.
6509   if (TheCall->getNumArgs() < 1) {
6510     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
6511         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
6512     return ExprError();
6513   }
6514 
6515   // Inspect the first argument of the atomic builtin.  This should always be
6516   // a pointer type, whose element is an integral scalar or pointer type.
6517   // Because it is a pointer type, we don't have to worry about any implicit
6518   // casts here.
6519   // FIXME: We don't allow floating point scalars as input.
6520   Expr *FirstArg = TheCall->getArg(0);
6521   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
6522   if (FirstArgResult.isInvalid())
6523     return ExprError();
6524   FirstArg = FirstArgResult.get();
6525   TheCall->setArg(0, FirstArg);
6526 
6527   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
6528   if (!pointerType) {
6529     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
6530         << FirstArg->getType() << FirstArg->getSourceRange();
6531     return ExprError();
6532   }
6533 
6534   QualType ValType = pointerType->getPointeeType();
6535   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
6536       !ValType->isBlockPointerType()) {
6537     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
6538         << FirstArg->getType() << FirstArg->getSourceRange();
6539     return ExprError();
6540   }
6541 
6542   if (ValType.isConstQualified()) {
6543     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
6544         << FirstArg->getType() << FirstArg->getSourceRange();
6545     return ExprError();
6546   }
6547 
6548   switch (ValType.getObjCLifetime()) {
6549   case Qualifiers::OCL_None:
6550   case Qualifiers::OCL_ExplicitNone:
6551     // okay
6552     break;
6553 
6554   case Qualifiers::OCL_Weak:
6555   case Qualifiers::OCL_Strong:
6556   case Qualifiers::OCL_Autoreleasing:
6557     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
6558         << ValType << FirstArg->getSourceRange();
6559     return ExprError();
6560   }
6561 
6562   // Strip any qualifiers off ValType.
6563   ValType = ValType.getUnqualifiedType();
6564 
6565   // The majority of builtins return a value, but a few have special return
6566   // types, so allow them to override appropriately below.
6567   QualType ResultType = ValType;
6568 
6569   // We need to figure out which concrete builtin this maps onto.  For example,
6570   // __sync_fetch_and_add with a 2 byte object turns into
6571   // __sync_fetch_and_add_2.
6572 #define BUILTIN_ROW(x) \
6573   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
6574     Builtin::BI##x##_8, Builtin::BI##x##_16 }
6575 
6576   static const unsigned BuiltinIndices[][5] = {
6577     BUILTIN_ROW(__sync_fetch_and_add),
6578     BUILTIN_ROW(__sync_fetch_and_sub),
6579     BUILTIN_ROW(__sync_fetch_and_or),
6580     BUILTIN_ROW(__sync_fetch_and_and),
6581     BUILTIN_ROW(__sync_fetch_and_xor),
6582     BUILTIN_ROW(__sync_fetch_and_nand),
6583 
6584     BUILTIN_ROW(__sync_add_and_fetch),
6585     BUILTIN_ROW(__sync_sub_and_fetch),
6586     BUILTIN_ROW(__sync_and_and_fetch),
6587     BUILTIN_ROW(__sync_or_and_fetch),
6588     BUILTIN_ROW(__sync_xor_and_fetch),
6589     BUILTIN_ROW(__sync_nand_and_fetch),
6590 
6591     BUILTIN_ROW(__sync_val_compare_and_swap),
6592     BUILTIN_ROW(__sync_bool_compare_and_swap),
6593     BUILTIN_ROW(__sync_lock_test_and_set),
6594     BUILTIN_ROW(__sync_lock_release),
6595     BUILTIN_ROW(__sync_swap)
6596   };
6597 #undef BUILTIN_ROW
6598 
6599   // Determine the index of the size.
6600   unsigned SizeIndex;
6601   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
6602   case 1: SizeIndex = 0; break;
6603   case 2: SizeIndex = 1; break;
6604   case 4: SizeIndex = 2; break;
6605   case 8: SizeIndex = 3; break;
6606   case 16: SizeIndex = 4; break;
6607   default:
6608     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
6609         << FirstArg->getType() << FirstArg->getSourceRange();
6610     return ExprError();
6611   }
6612 
6613   // Each of these builtins has one pointer argument, followed by some number of
6614   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
6615   // that we ignore.  Find out which row of BuiltinIndices to read from as well
6616   // as the number of fixed args.
6617   unsigned BuiltinID = FDecl->getBuiltinID();
6618   unsigned BuiltinIndex, NumFixed = 1;
6619   bool WarnAboutSemanticsChange = false;
6620   switch (BuiltinID) {
6621   default: llvm_unreachable("Unknown overloaded atomic builtin!");
6622   case Builtin::BI__sync_fetch_and_add:
6623   case Builtin::BI__sync_fetch_and_add_1:
6624   case Builtin::BI__sync_fetch_and_add_2:
6625   case Builtin::BI__sync_fetch_and_add_4:
6626   case Builtin::BI__sync_fetch_and_add_8:
6627   case Builtin::BI__sync_fetch_and_add_16:
6628     BuiltinIndex = 0;
6629     break;
6630 
6631   case Builtin::BI__sync_fetch_and_sub:
6632   case Builtin::BI__sync_fetch_and_sub_1:
6633   case Builtin::BI__sync_fetch_and_sub_2:
6634   case Builtin::BI__sync_fetch_and_sub_4:
6635   case Builtin::BI__sync_fetch_and_sub_8:
6636   case Builtin::BI__sync_fetch_and_sub_16:
6637     BuiltinIndex = 1;
6638     break;
6639 
6640   case Builtin::BI__sync_fetch_and_or:
6641   case Builtin::BI__sync_fetch_and_or_1:
6642   case Builtin::BI__sync_fetch_and_or_2:
6643   case Builtin::BI__sync_fetch_and_or_4:
6644   case Builtin::BI__sync_fetch_and_or_8:
6645   case Builtin::BI__sync_fetch_and_or_16:
6646     BuiltinIndex = 2;
6647     break;
6648 
6649   case Builtin::BI__sync_fetch_and_and:
6650   case Builtin::BI__sync_fetch_and_and_1:
6651   case Builtin::BI__sync_fetch_and_and_2:
6652   case Builtin::BI__sync_fetch_and_and_4:
6653   case Builtin::BI__sync_fetch_and_and_8:
6654   case Builtin::BI__sync_fetch_and_and_16:
6655     BuiltinIndex = 3;
6656     break;
6657 
6658   case Builtin::BI__sync_fetch_and_xor:
6659   case Builtin::BI__sync_fetch_and_xor_1:
6660   case Builtin::BI__sync_fetch_and_xor_2:
6661   case Builtin::BI__sync_fetch_and_xor_4:
6662   case Builtin::BI__sync_fetch_and_xor_8:
6663   case Builtin::BI__sync_fetch_and_xor_16:
6664     BuiltinIndex = 4;
6665     break;
6666 
6667   case Builtin::BI__sync_fetch_and_nand:
6668   case Builtin::BI__sync_fetch_and_nand_1:
6669   case Builtin::BI__sync_fetch_and_nand_2:
6670   case Builtin::BI__sync_fetch_and_nand_4:
6671   case Builtin::BI__sync_fetch_and_nand_8:
6672   case Builtin::BI__sync_fetch_and_nand_16:
6673     BuiltinIndex = 5;
6674     WarnAboutSemanticsChange = true;
6675     break;
6676 
6677   case Builtin::BI__sync_add_and_fetch:
6678   case Builtin::BI__sync_add_and_fetch_1:
6679   case Builtin::BI__sync_add_and_fetch_2:
6680   case Builtin::BI__sync_add_and_fetch_4:
6681   case Builtin::BI__sync_add_and_fetch_8:
6682   case Builtin::BI__sync_add_and_fetch_16:
6683     BuiltinIndex = 6;
6684     break;
6685 
6686   case Builtin::BI__sync_sub_and_fetch:
6687   case Builtin::BI__sync_sub_and_fetch_1:
6688   case Builtin::BI__sync_sub_and_fetch_2:
6689   case Builtin::BI__sync_sub_and_fetch_4:
6690   case Builtin::BI__sync_sub_and_fetch_8:
6691   case Builtin::BI__sync_sub_and_fetch_16:
6692     BuiltinIndex = 7;
6693     break;
6694 
6695   case Builtin::BI__sync_and_and_fetch:
6696   case Builtin::BI__sync_and_and_fetch_1:
6697   case Builtin::BI__sync_and_and_fetch_2:
6698   case Builtin::BI__sync_and_and_fetch_4:
6699   case Builtin::BI__sync_and_and_fetch_8:
6700   case Builtin::BI__sync_and_and_fetch_16:
6701     BuiltinIndex = 8;
6702     break;
6703 
6704   case Builtin::BI__sync_or_and_fetch:
6705   case Builtin::BI__sync_or_and_fetch_1:
6706   case Builtin::BI__sync_or_and_fetch_2:
6707   case Builtin::BI__sync_or_and_fetch_4:
6708   case Builtin::BI__sync_or_and_fetch_8:
6709   case Builtin::BI__sync_or_and_fetch_16:
6710     BuiltinIndex = 9;
6711     break;
6712 
6713   case Builtin::BI__sync_xor_and_fetch:
6714   case Builtin::BI__sync_xor_and_fetch_1:
6715   case Builtin::BI__sync_xor_and_fetch_2:
6716   case Builtin::BI__sync_xor_and_fetch_4:
6717   case Builtin::BI__sync_xor_and_fetch_8:
6718   case Builtin::BI__sync_xor_and_fetch_16:
6719     BuiltinIndex = 10;
6720     break;
6721 
6722   case Builtin::BI__sync_nand_and_fetch:
6723   case Builtin::BI__sync_nand_and_fetch_1:
6724   case Builtin::BI__sync_nand_and_fetch_2:
6725   case Builtin::BI__sync_nand_and_fetch_4:
6726   case Builtin::BI__sync_nand_and_fetch_8:
6727   case Builtin::BI__sync_nand_and_fetch_16:
6728     BuiltinIndex = 11;
6729     WarnAboutSemanticsChange = true;
6730     break;
6731 
6732   case Builtin::BI__sync_val_compare_and_swap:
6733   case Builtin::BI__sync_val_compare_and_swap_1:
6734   case Builtin::BI__sync_val_compare_and_swap_2:
6735   case Builtin::BI__sync_val_compare_and_swap_4:
6736   case Builtin::BI__sync_val_compare_and_swap_8:
6737   case Builtin::BI__sync_val_compare_and_swap_16:
6738     BuiltinIndex = 12;
6739     NumFixed = 2;
6740     break;
6741 
6742   case Builtin::BI__sync_bool_compare_and_swap:
6743   case Builtin::BI__sync_bool_compare_and_swap_1:
6744   case Builtin::BI__sync_bool_compare_and_swap_2:
6745   case Builtin::BI__sync_bool_compare_and_swap_4:
6746   case Builtin::BI__sync_bool_compare_and_swap_8:
6747   case Builtin::BI__sync_bool_compare_and_swap_16:
6748     BuiltinIndex = 13;
6749     NumFixed = 2;
6750     ResultType = Context.BoolTy;
6751     break;
6752 
6753   case Builtin::BI__sync_lock_test_and_set:
6754   case Builtin::BI__sync_lock_test_and_set_1:
6755   case Builtin::BI__sync_lock_test_and_set_2:
6756   case Builtin::BI__sync_lock_test_and_set_4:
6757   case Builtin::BI__sync_lock_test_and_set_8:
6758   case Builtin::BI__sync_lock_test_and_set_16:
6759     BuiltinIndex = 14;
6760     break;
6761 
6762   case Builtin::BI__sync_lock_release:
6763   case Builtin::BI__sync_lock_release_1:
6764   case Builtin::BI__sync_lock_release_2:
6765   case Builtin::BI__sync_lock_release_4:
6766   case Builtin::BI__sync_lock_release_8:
6767   case Builtin::BI__sync_lock_release_16:
6768     BuiltinIndex = 15;
6769     NumFixed = 0;
6770     ResultType = Context.VoidTy;
6771     break;
6772 
6773   case Builtin::BI__sync_swap:
6774   case Builtin::BI__sync_swap_1:
6775   case Builtin::BI__sync_swap_2:
6776   case Builtin::BI__sync_swap_4:
6777   case Builtin::BI__sync_swap_8:
6778   case Builtin::BI__sync_swap_16:
6779     BuiltinIndex = 16;
6780     break;
6781   }
6782 
6783   // Now that we know how many fixed arguments we expect, first check that we
6784   // have at least that many.
6785   if (TheCall->getNumArgs() < 1+NumFixed) {
6786     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
6787         << 0 << 1 + NumFixed << TheCall->getNumArgs()
6788         << Callee->getSourceRange();
6789     return ExprError();
6790   }
6791 
6792   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
6793       << Callee->getSourceRange();
6794 
6795   if (WarnAboutSemanticsChange) {
6796     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
6797         << Callee->getSourceRange();
6798   }
6799 
6800   // Get the decl for the concrete builtin from this, we can tell what the
6801   // concrete integer type we should convert to is.
6802   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
6803   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
6804   FunctionDecl *NewBuiltinDecl;
6805   if (NewBuiltinID == BuiltinID)
6806     NewBuiltinDecl = FDecl;
6807   else {
6808     // Perform builtin lookup to avoid redeclaring it.
6809     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
6810     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
6811     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
6812     assert(Res.getFoundDecl());
6813     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
6814     if (!NewBuiltinDecl)
6815       return ExprError();
6816   }
6817 
6818   // The first argument --- the pointer --- has a fixed type; we
6819   // deduce the types of the rest of the arguments accordingly.  Walk
6820   // the remaining arguments, converting them to the deduced value type.
6821   for (unsigned i = 0; i != NumFixed; ++i) {
6822     ExprResult Arg = TheCall->getArg(i+1);
6823 
6824     // GCC does an implicit conversion to the pointer or integer ValType.  This
6825     // can fail in some cases (1i -> int**), check for this error case now.
6826     // Initialize the argument.
6827     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6828                                                    ValType, /*consume*/ false);
6829     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6830     if (Arg.isInvalid())
6831       return ExprError();
6832 
6833     // Okay, we have something that *can* be converted to the right type.  Check
6834     // to see if there is a potentially weird extension going on here.  This can
6835     // happen when you do an atomic operation on something like an char* and
6836     // pass in 42.  The 42 gets converted to char.  This is even more strange
6837     // for things like 45.123 -> char, etc.
6838     // FIXME: Do this check.
6839     TheCall->setArg(i+1, Arg.get());
6840   }
6841 
6842   // Create a new DeclRefExpr to refer to the new decl.
6843   DeclRefExpr *NewDRE = DeclRefExpr::Create(
6844       Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
6845       /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
6846       DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
6847 
6848   // Set the callee in the CallExpr.
6849   // FIXME: This loses syntactic information.
6850   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
6851   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
6852                                               CK_BuiltinFnToFnPtr);
6853   TheCall->setCallee(PromotedCall.get());
6854 
6855   // Change the result type of the call to match the original value type. This
6856   // is arbitrary, but the codegen for these builtins ins design to handle it
6857   // gracefully.
6858   TheCall->setType(ResultType);
6859 
6860   // Prohibit problematic uses of bit-precise integer types with atomic
6861   // builtins. The arguments would have already been converted to the first
6862   // argument's type, so only need to check the first argument.
6863   const auto *BitIntValType = ValType->getAs<BitIntType>();
6864   if (BitIntValType && !llvm::isPowerOf2_64(BitIntValType->getNumBits())) {
6865     Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
6866     return ExprError();
6867   }
6868 
6869   return TheCallResult;
6870 }
6871 
6872 /// SemaBuiltinNontemporalOverloaded - We have a call to
6873 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
6874 /// overloaded function based on the pointer type of its last argument.
6875 ///
6876 /// This function goes through and does final semantic checking for these
6877 /// builtins.
6878 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
6879   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
6880   DeclRefExpr *DRE =
6881       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6882   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6883   unsigned BuiltinID = FDecl->getBuiltinID();
6884   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
6885           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
6886          "Unexpected nontemporal load/store builtin!");
6887   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
6888   unsigned numArgs = isStore ? 2 : 1;
6889 
6890   // Ensure that we have the proper number of arguments.
6891   if (checkArgCount(*this, TheCall, numArgs))
6892     return ExprError();
6893 
6894   // Inspect the last argument of the nontemporal builtin.  This should always
6895   // be a pointer type, from which we imply the type of the memory access.
6896   // Because it is a pointer type, we don't have to worry about any implicit
6897   // casts here.
6898   Expr *PointerArg = TheCall->getArg(numArgs - 1);
6899   ExprResult PointerArgResult =
6900       DefaultFunctionArrayLvalueConversion(PointerArg);
6901 
6902   if (PointerArgResult.isInvalid())
6903     return ExprError();
6904   PointerArg = PointerArgResult.get();
6905   TheCall->setArg(numArgs - 1, PointerArg);
6906 
6907   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
6908   if (!pointerType) {
6909     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
6910         << PointerArg->getType() << PointerArg->getSourceRange();
6911     return ExprError();
6912   }
6913 
6914   QualType ValType = pointerType->getPointeeType();
6915 
6916   // Strip any qualifiers off ValType.
6917   ValType = ValType.getUnqualifiedType();
6918   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
6919       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
6920       !ValType->isVectorType()) {
6921     Diag(DRE->getBeginLoc(),
6922          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
6923         << PointerArg->getType() << PointerArg->getSourceRange();
6924     return ExprError();
6925   }
6926 
6927   if (!isStore) {
6928     TheCall->setType(ValType);
6929     return TheCallResult;
6930   }
6931 
6932   ExprResult ValArg = TheCall->getArg(0);
6933   InitializedEntity Entity = InitializedEntity::InitializeParameter(
6934       Context, ValType, /*consume*/ false);
6935   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
6936   if (ValArg.isInvalid())
6937     return ExprError();
6938 
6939   TheCall->setArg(0, ValArg.get());
6940   TheCall->setType(Context.VoidTy);
6941   return TheCallResult;
6942 }
6943 
6944 /// CheckObjCString - Checks that the argument to the builtin
6945 /// CFString constructor is correct
6946 /// Note: It might also make sense to do the UTF-16 conversion here (would
6947 /// simplify the backend).
6948 bool Sema::CheckObjCString(Expr *Arg) {
6949   Arg = Arg->IgnoreParenCasts();
6950   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
6951 
6952   if (!Literal || !Literal->isOrdinary()) {
6953     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
6954         << Arg->getSourceRange();
6955     return true;
6956   }
6957 
6958   if (Literal->containsNonAsciiOrNull()) {
6959     StringRef String = Literal->getString();
6960     unsigned NumBytes = String.size();
6961     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
6962     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
6963     llvm::UTF16 *ToPtr = &ToBuf[0];
6964 
6965     llvm::ConversionResult Result =
6966         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
6967                                  ToPtr + NumBytes, llvm::strictConversion);
6968     // Check for conversion failure.
6969     if (Result != llvm::conversionOK)
6970       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
6971           << Arg->getSourceRange();
6972   }
6973   return false;
6974 }
6975 
6976 /// CheckObjCString - Checks that the format string argument to the os_log()
6977 /// and os_trace() functions is correct, and converts it to const char *.
6978 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
6979   Arg = Arg->IgnoreParenCasts();
6980   auto *Literal = dyn_cast<StringLiteral>(Arg);
6981   if (!Literal) {
6982     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
6983       Literal = ObjcLiteral->getString();
6984     }
6985   }
6986 
6987   if (!Literal || (!Literal->isOrdinary() && !Literal->isUTF8())) {
6988     return ExprError(
6989         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
6990         << Arg->getSourceRange());
6991   }
6992 
6993   ExprResult Result(Literal);
6994   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
6995   InitializedEntity Entity =
6996       InitializedEntity::InitializeParameter(Context, ResultTy, false);
6997   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
6998   return Result;
6999 }
7000 
7001 /// Check that the user is calling the appropriate va_start builtin for the
7002 /// target and calling convention.
7003 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
7004   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
7005   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
7006   bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
7007                     TT.getArch() == llvm::Triple::aarch64_32);
7008   bool IsWindows = TT.isOSWindows();
7009   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
7010   if (IsX64 || IsAArch64) {
7011     CallingConv CC = CC_C;
7012     if (const FunctionDecl *FD = S.getCurFunctionDecl())
7013       CC = FD->getType()->castAs<FunctionType>()->getCallConv();
7014     if (IsMSVAStart) {
7015       // Don't allow this in System V ABI functions.
7016       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
7017         return S.Diag(Fn->getBeginLoc(),
7018                       diag::err_ms_va_start_used_in_sysv_function);
7019     } else {
7020       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
7021       // On x64 Windows, don't allow this in System V ABI functions.
7022       // (Yes, that means there's no corresponding way to support variadic
7023       // System V ABI functions on Windows.)
7024       if ((IsWindows && CC == CC_X86_64SysV) ||
7025           (!IsWindows && CC == CC_Win64))
7026         return S.Diag(Fn->getBeginLoc(),
7027                       diag::err_va_start_used_in_wrong_abi_function)
7028                << !IsWindows;
7029     }
7030     return false;
7031   }
7032 
7033   if (IsMSVAStart)
7034     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
7035   return false;
7036 }
7037 
7038 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
7039                                              ParmVarDecl **LastParam = nullptr) {
7040   // Determine whether the current function, block, or obj-c method is variadic
7041   // and get its parameter list.
7042   bool IsVariadic = false;
7043   ArrayRef<ParmVarDecl *> Params;
7044   DeclContext *Caller = S.CurContext;
7045   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
7046     IsVariadic = Block->isVariadic();
7047     Params = Block->parameters();
7048   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
7049     IsVariadic = FD->isVariadic();
7050     Params = FD->parameters();
7051   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
7052     IsVariadic = MD->isVariadic();
7053     // FIXME: This isn't correct for methods (results in bogus warning).
7054     Params = MD->parameters();
7055   } else if (isa<CapturedDecl>(Caller)) {
7056     // We don't support va_start in a CapturedDecl.
7057     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
7058     return true;
7059   } else {
7060     // This must be some other declcontext that parses exprs.
7061     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
7062     return true;
7063   }
7064 
7065   if (!IsVariadic) {
7066     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
7067     return true;
7068   }
7069 
7070   if (LastParam)
7071     *LastParam = Params.empty() ? nullptr : Params.back();
7072 
7073   return false;
7074 }
7075 
7076 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
7077 /// for validity.  Emit an error and return true on failure; return false
7078 /// on success.
7079 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
7080   Expr *Fn = TheCall->getCallee();
7081 
7082   if (checkVAStartABI(*this, BuiltinID, Fn))
7083     return true;
7084 
7085   if (checkArgCount(*this, TheCall, 2))
7086     return true;
7087 
7088   // Type-check the first argument normally.
7089   if (checkBuiltinArgument(*this, TheCall, 0))
7090     return true;
7091 
7092   // Check that the current function is variadic, and get its last parameter.
7093   ParmVarDecl *LastParam;
7094   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
7095     return true;
7096 
7097   // Verify that the second argument to the builtin is the last argument of the
7098   // current function or method.
7099   bool SecondArgIsLastNamedArgument = false;
7100   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
7101 
7102   // These are valid if SecondArgIsLastNamedArgument is false after the next
7103   // block.
7104   QualType Type;
7105   SourceLocation ParamLoc;
7106   bool IsCRegister = false;
7107 
7108   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
7109     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
7110       SecondArgIsLastNamedArgument = PV == LastParam;
7111 
7112       Type = PV->getType();
7113       ParamLoc = PV->getLocation();
7114       IsCRegister =
7115           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
7116     }
7117   }
7118 
7119   if (!SecondArgIsLastNamedArgument)
7120     Diag(TheCall->getArg(1)->getBeginLoc(),
7121          diag::warn_second_arg_of_va_start_not_last_named_param);
7122   else if (IsCRegister || Type->isReferenceType() ||
7123            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
7124              // Promotable integers are UB, but enumerations need a bit of
7125              // extra checking to see what their promotable type actually is.
7126              if (!Type->isPromotableIntegerType())
7127                return false;
7128              if (!Type->isEnumeralType())
7129                return true;
7130              const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
7131              return !(ED &&
7132                       Context.typesAreCompatible(ED->getPromotionType(), Type));
7133            }()) {
7134     unsigned Reason = 0;
7135     if (Type->isReferenceType())  Reason = 1;
7136     else if (IsCRegister)         Reason = 2;
7137     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
7138     Diag(ParamLoc, diag::note_parameter_type) << Type;
7139   }
7140 
7141   TheCall->setType(Context.VoidTy);
7142   return false;
7143 }
7144 
7145 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
7146   auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {
7147     const LangOptions &LO = getLangOpts();
7148 
7149     if (LO.CPlusPlus)
7150       return Arg->getType()
7151                  .getCanonicalType()
7152                  .getTypePtr()
7153                  ->getPointeeType()
7154                  .withoutLocalFastQualifiers() == Context.CharTy;
7155 
7156     // In C, allow aliasing through `char *`, this is required for AArch64 at
7157     // least.
7158     return true;
7159   };
7160 
7161   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
7162   //                 const char *named_addr);
7163 
7164   Expr *Func = Call->getCallee();
7165 
7166   if (Call->getNumArgs() < 3)
7167     return Diag(Call->getEndLoc(),
7168                 diag::err_typecheck_call_too_few_args_at_least)
7169            << 0 /*function call*/ << 3 << Call->getNumArgs();
7170 
7171   // Type-check the first argument normally.
7172   if (checkBuiltinArgument(*this, Call, 0))
7173     return true;
7174 
7175   // Check that the current function is variadic.
7176   if (checkVAStartIsInVariadicFunction(*this, Func))
7177     return true;
7178 
7179   // __va_start on Windows does not validate the parameter qualifiers
7180 
7181   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
7182   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
7183 
7184   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
7185   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
7186 
7187   const QualType &ConstCharPtrTy =
7188       Context.getPointerType(Context.CharTy.withConst());
7189   if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
7190     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
7191         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
7192         << 0                                      /* qualifier difference */
7193         << 3                                      /* parameter mismatch */
7194         << 2 << Arg1->getType() << ConstCharPtrTy;
7195 
7196   const QualType SizeTy = Context.getSizeType();
7197   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
7198     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
7199         << Arg2->getType() << SizeTy << 1 /* different class */
7200         << 0                              /* qualifier difference */
7201         << 3                              /* parameter mismatch */
7202         << 3 << Arg2->getType() << SizeTy;
7203 
7204   return false;
7205 }
7206 
7207 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
7208 /// friends.  This is declared to take (...), so we have to check everything.
7209 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
7210   if (checkArgCount(*this, TheCall, 2))
7211     return true;
7212 
7213   ExprResult OrigArg0 = TheCall->getArg(0);
7214   ExprResult OrigArg1 = TheCall->getArg(1);
7215 
7216   // Do standard promotions between the two arguments, returning their common
7217   // type.
7218   QualType Res = UsualArithmeticConversions(
7219       OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
7220   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
7221     return true;
7222 
7223   // Make sure any conversions are pushed back into the call; this is
7224   // type safe since unordered compare builtins are declared as "_Bool
7225   // foo(...)".
7226   TheCall->setArg(0, OrigArg0.get());
7227   TheCall->setArg(1, OrigArg1.get());
7228 
7229   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
7230     return false;
7231 
7232   // If the common type isn't a real floating type, then the arguments were
7233   // invalid for this operation.
7234   if (Res.isNull() || !Res->isRealFloatingType())
7235     return Diag(OrigArg0.get()->getBeginLoc(),
7236                 diag::err_typecheck_call_invalid_ordered_compare)
7237            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
7238            << SourceRange(OrigArg0.get()->getBeginLoc(),
7239                           OrigArg1.get()->getEndLoc());
7240 
7241   return false;
7242 }
7243 
7244 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
7245 /// __builtin_isnan and friends.  This is declared to take (...), so we have
7246 /// to check everything. We expect the last argument to be a floating point
7247 /// value.
7248 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
7249   if (checkArgCount(*this, TheCall, NumArgs))
7250     return true;
7251 
7252   // __builtin_fpclassify is the only case where NumArgs != 1, so we can count
7253   // on all preceding parameters just being int.  Try all of those.
7254   for (unsigned i = 0; i < NumArgs - 1; ++i) {
7255     Expr *Arg = TheCall->getArg(i);
7256 
7257     if (Arg->isTypeDependent())
7258       return false;
7259 
7260     ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);
7261 
7262     if (Res.isInvalid())
7263       return true;
7264     TheCall->setArg(i, Res.get());
7265   }
7266 
7267   Expr *OrigArg = TheCall->getArg(NumArgs-1);
7268 
7269   if (OrigArg->isTypeDependent())
7270     return false;
7271 
7272   // Usual Unary Conversions will convert half to float, which we want for
7273   // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
7274   // type how it is, but do normal L->Rvalue conversions.
7275   if (Context.getTargetInfo().useFP16ConversionIntrinsics())
7276     OrigArg = UsualUnaryConversions(OrigArg).get();
7277   else
7278     OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
7279   TheCall->setArg(NumArgs - 1, OrigArg);
7280 
7281   // This operation requires a non-_Complex floating-point number.
7282   if (!OrigArg->getType()->isRealFloatingType())
7283     return Diag(OrigArg->getBeginLoc(),
7284                 diag::err_typecheck_call_invalid_unary_fp)
7285            << OrigArg->getType() << OrigArg->getSourceRange();
7286 
7287   return false;
7288 }
7289 
7290 /// Perform semantic analysis for a call to __builtin_complex.
7291 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) {
7292   if (checkArgCount(*this, TheCall, 2))
7293     return true;
7294 
7295   bool Dependent = false;
7296   for (unsigned I = 0; I != 2; ++I) {
7297     Expr *Arg = TheCall->getArg(I);
7298     QualType T = Arg->getType();
7299     if (T->isDependentType()) {
7300       Dependent = true;
7301       continue;
7302     }
7303 
7304     // Despite supporting _Complex int, GCC requires a real floating point type
7305     // for the operands of __builtin_complex.
7306     if (!T->isRealFloatingType()) {
7307       return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
7308              << Arg->getType() << Arg->getSourceRange();
7309     }
7310 
7311     ExprResult Converted = DefaultLvalueConversion(Arg);
7312     if (Converted.isInvalid())
7313       return true;
7314     TheCall->setArg(I, Converted.get());
7315   }
7316 
7317   if (Dependent) {
7318     TheCall->setType(Context.DependentTy);
7319     return false;
7320   }
7321 
7322   Expr *Real = TheCall->getArg(0);
7323   Expr *Imag = TheCall->getArg(1);
7324   if (!Context.hasSameType(Real->getType(), Imag->getType())) {
7325     return Diag(Real->getBeginLoc(),
7326                 diag::err_typecheck_call_different_arg_types)
7327            << Real->getType() << Imag->getType()
7328            << Real->getSourceRange() << Imag->getSourceRange();
7329   }
7330 
7331   // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers;
7332   // don't allow this builtin to form those types either.
7333   // FIXME: Should we allow these types?
7334   if (Real->getType()->isFloat16Type())
7335     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
7336            << "_Float16";
7337   if (Real->getType()->isHalfType())
7338     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
7339            << "half";
7340 
7341   TheCall->setType(Context.getComplexType(Real->getType()));
7342   return false;
7343 }
7344 
7345 // Customized Sema Checking for VSX builtins that have the following signature:
7346 // vector [...] builtinName(vector [...], vector [...], const int);
7347 // Which takes the same type of vectors (any legal vector type) for the first
7348 // two arguments and takes compile time constant for the third argument.
7349 // Example builtins are :
7350 // vector double vec_xxpermdi(vector double, vector double, int);
7351 // vector short vec_xxsldwi(vector short, vector short, int);
7352 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
7353   unsigned ExpectedNumArgs = 3;
7354   if (checkArgCount(*this, TheCall, ExpectedNumArgs))
7355     return true;
7356 
7357   // Check the third argument is a compile time constant
7358   if (!TheCall->getArg(2)->isIntegerConstantExpr(Context))
7359     return Diag(TheCall->getBeginLoc(),
7360                 diag::err_vsx_builtin_nonconstant_argument)
7361            << 3 /* argument index */ << TheCall->getDirectCallee()
7362            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
7363                           TheCall->getArg(2)->getEndLoc());
7364 
7365   QualType Arg1Ty = TheCall->getArg(0)->getType();
7366   QualType Arg2Ty = TheCall->getArg(1)->getType();
7367 
7368   // Check the type of argument 1 and argument 2 are vectors.
7369   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
7370   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
7371       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
7372     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
7373            << TheCall->getDirectCallee()
7374            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
7375                           TheCall->getArg(1)->getEndLoc());
7376   }
7377 
7378   // Check the first two arguments are the same type.
7379   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
7380     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
7381            << TheCall->getDirectCallee()
7382            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
7383                           TheCall->getArg(1)->getEndLoc());
7384   }
7385 
7386   // When default clang type checking is turned off and the customized type
7387   // checking is used, the returning type of the function must be explicitly
7388   // set. Otherwise it is _Bool by default.
7389   TheCall->setType(Arg1Ty);
7390 
7391   return false;
7392 }
7393 
7394 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
7395 // This is declared to take (...), so we have to check everything.
7396 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
7397   if (TheCall->getNumArgs() < 2)
7398     return ExprError(Diag(TheCall->getEndLoc(),
7399                           diag::err_typecheck_call_too_few_args_at_least)
7400                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
7401                      << TheCall->getSourceRange());
7402 
7403   // Determine which of the following types of shufflevector we're checking:
7404   // 1) unary, vector mask: (lhs, mask)
7405   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
7406   QualType resType = TheCall->getArg(0)->getType();
7407   unsigned numElements = 0;
7408 
7409   if (!TheCall->getArg(0)->isTypeDependent() &&
7410       !TheCall->getArg(1)->isTypeDependent()) {
7411     QualType LHSType = TheCall->getArg(0)->getType();
7412     QualType RHSType = TheCall->getArg(1)->getType();
7413 
7414     if (!LHSType->isVectorType() || !RHSType->isVectorType())
7415       return ExprError(
7416           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
7417           << TheCall->getDirectCallee()
7418           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
7419                          TheCall->getArg(1)->getEndLoc()));
7420 
7421     numElements = LHSType->castAs<VectorType>()->getNumElements();
7422     unsigned numResElements = TheCall->getNumArgs() - 2;
7423 
7424     // Check to see if we have a call with 2 vector arguments, the unary shuffle
7425     // with mask.  If so, verify that RHS is an integer vector type with the
7426     // same number of elts as lhs.
7427     if (TheCall->getNumArgs() == 2) {
7428       if (!RHSType->hasIntegerRepresentation() ||
7429           RHSType->castAs<VectorType>()->getNumElements() != numElements)
7430         return ExprError(Diag(TheCall->getBeginLoc(),
7431                               diag::err_vec_builtin_incompatible_vector)
7432                          << TheCall->getDirectCallee()
7433                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
7434                                         TheCall->getArg(1)->getEndLoc()));
7435     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
7436       return ExprError(Diag(TheCall->getBeginLoc(),
7437                             diag::err_vec_builtin_incompatible_vector)
7438                        << TheCall->getDirectCallee()
7439                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
7440                                       TheCall->getArg(1)->getEndLoc()));
7441     } else if (numElements != numResElements) {
7442       QualType eltType = LHSType->castAs<VectorType>()->getElementType();
7443       resType = Context.getVectorType(eltType, numResElements,
7444                                       VectorType::GenericVector);
7445     }
7446   }
7447 
7448   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
7449     if (TheCall->getArg(i)->isTypeDependent() ||
7450         TheCall->getArg(i)->isValueDependent())
7451       continue;
7452 
7453     Optional<llvm::APSInt> Result;
7454     if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context)))
7455       return ExprError(Diag(TheCall->getBeginLoc(),
7456                             diag::err_shufflevector_nonconstant_argument)
7457                        << TheCall->getArg(i)->getSourceRange());
7458 
7459     // Allow -1 which will be translated to undef in the IR.
7460     if (Result->isSigned() && Result->isAllOnes())
7461       continue;
7462 
7463     if (Result->getActiveBits() > 64 ||
7464         Result->getZExtValue() >= numElements * 2)
7465       return ExprError(Diag(TheCall->getBeginLoc(),
7466                             diag::err_shufflevector_argument_too_large)
7467                        << TheCall->getArg(i)->getSourceRange());
7468   }
7469 
7470   SmallVector<Expr*, 32> exprs;
7471 
7472   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
7473     exprs.push_back(TheCall->getArg(i));
7474     TheCall->setArg(i, nullptr);
7475   }
7476 
7477   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
7478                                          TheCall->getCallee()->getBeginLoc(),
7479                                          TheCall->getRParenLoc());
7480 }
7481 
7482 /// SemaConvertVectorExpr - Handle __builtin_convertvector
7483 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
7484                                        SourceLocation BuiltinLoc,
7485                                        SourceLocation RParenLoc) {
7486   ExprValueKind VK = VK_PRValue;
7487   ExprObjectKind OK = OK_Ordinary;
7488   QualType DstTy = TInfo->getType();
7489   QualType SrcTy = E->getType();
7490 
7491   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
7492     return ExprError(Diag(BuiltinLoc,
7493                           diag::err_convertvector_non_vector)
7494                      << E->getSourceRange());
7495   if (!DstTy->isVectorType() && !DstTy->isDependentType())
7496     return ExprError(Diag(BuiltinLoc,
7497                           diag::err_convertvector_non_vector_type));
7498 
7499   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
7500     unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
7501     unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
7502     if (SrcElts != DstElts)
7503       return ExprError(Diag(BuiltinLoc,
7504                             diag::err_convertvector_incompatible_vector)
7505                        << E->getSourceRange());
7506   }
7507 
7508   return new (Context)
7509       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
7510 }
7511 
7512 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
7513 // This is declared to take (const void*, ...) and can take two
7514 // optional constant int args.
7515 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
7516   unsigned NumArgs = TheCall->getNumArgs();
7517 
7518   if (NumArgs > 3)
7519     return Diag(TheCall->getEndLoc(),
7520                 diag::err_typecheck_call_too_many_args_at_most)
7521            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
7522 
7523   // Argument 0 is checked for us and the remaining arguments must be
7524   // constant integers.
7525   for (unsigned i = 1; i != NumArgs; ++i)
7526     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
7527       return true;
7528 
7529   return false;
7530 }
7531 
7532 /// SemaBuiltinArithmeticFence - Handle __arithmetic_fence.
7533 bool Sema::SemaBuiltinArithmeticFence(CallExpr *TheCall) {
7534   if (!Context.getTargetInfo().checkArithmeticFenceSupported())
7535     return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
7536            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7537   if (checkArgCount(*this, TheCall, 1))
7538     return true;
7539   Expr *Arg = TheCall->getArg(0);
7540   if (Arg->isInstantiationDependent())
7541     return false;
7542 
7543   QualType ArgTy = Arg->getType();
7544   if (!ArgTy->hasFloatingRepresentation())
7545     return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector)
7546            << ArgTy;
7547   if (Arg->isLValue()) {
7548     ExprResult FirstArg = DefaultLvalueConversion(Arg);
7549     TheCall->setArg(0, FirstArg.get());
7550   }
7551   TheCall->setType(TheCall->getArg(0)->getType());
7552   return false;
7553 }
7554 
7555 /// SemaBuiltinAssume - Handle __assume (MS Extension).
7556 // __assume does not evaluate its arguments, and should warn if its argument
7557 // has side effects.
7558 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
7559   Expr *Arg = TheCall->getArg(0);
7560   if (Arg->isInstantiationDependent()) return false;
7561 
7562   if (Arg->HasSideEffects(Context))
7563     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
7564         << Arg->getSourceRange()
7565         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
7566 
7567   return false;
7568 }
7569 
7570 /// Handle __builtin_alloca_with_align. This is declared
7571 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
7572 /// than 8.
7573 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
7574   // The alignment must be a constant integer.
7575   Expr *Arg = TheCall->getArg(1);
7576 
7577   // We can't check the value of a dependent argument.
7578   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
7579     if (const auto *UE =
7580             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
7581       if (UE->getKind() == UETT_AlignOf ||
7582           UE->getKind() == UETT_PreferredAlignOf)
7583         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
7584             << Arg->getSourceRange();
7585 
7586     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
7587 
7588     if (!Result.isPowerOf2())
7589       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
7590              << Arg->getSourceRange();
7591 
7592     if (Result < Context.getCharWidth())
7593       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
7594              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
7595 
7596     if (Result > std::numeric_limits<int32_t>::max())
7597       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
7598              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
7599   }
7600 
7601   return false;
7602 }
7603 
7604 /// Handle __builtin_assume_aligned. This is declared
7605 /// as (const void*, size_t, ...) and can take one optional constant int arg.
7606 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
7607   unsigned NumArgs = TheCall->getNumArgs();
7608 
7609   if (NumArgs > 3)
7610     return Diag(TheCall->getEndLoc(),
7611                 diag::err_typecheck_call_too_many_args_at_most)
7612            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
7613 
7614   // The alignment must be a constant integer.
7615   Expr *Arg = TheCall->getArg(1);
7616 
7617   // We can't check the value of a dependent argument.
7618   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
7619     llvm::APSInt Result;
7620     if (SemaBuiltinConstantArg(TheCall, 1, Result))
7621       return true;
7622 
7623     if (!Result.isPowerOf2())
7624       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
7625              << Arg->getSourceRange();
7626 
7627     if (Result > Sema::MaximumAlignment)
7628       Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
7629           << Arg->getSourceRange() << Sema::MaximumAlignment;
7630   }
7631 
7632   if (NumArgs > 2) {
7633     ExprResult Arg(TheCall->getArg(2));
7634     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
7635       Context.getSizeType(), false);
7636     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
7637     if (Arg.isInvalid()) return true;
7638     TheCall->setArg(2, Arg.get());
7639   }
7640 
7641   return false;
7642 }
7643 
7644 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
7645   unsigned BuiltinID =
7646       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
7647   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
7648 
7649   unsigned NumArgs = TheCall->getNumArgs();
7650   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
7651   if (NumArgs < NumRequiredArgs) {
7652     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
7653            << 0 /* function call */ << NumRequiredArgs << NumArgs
7654            << TheCall->getSourceRange();
7655   }
7656   if (NumArgs >= NumRequiredArgs + 0x100) {
7657     return Diag(TheCall->getEndLoc(),
7658                 diag::err_typecheck_call_too_many_args_at_most)
7659            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
7660            << TheCall->getSourceRange();
7661   }
7662   unsigned i = 0;
7663 
7664   // For formatting call, check buffer arg.
7665   if (!IsSizeCall) {
7666     ExprResult Arg(TheCall->getArg(i));
7667     InitializedEntity Entity = InitializedEntity::InitializeParameter(
7668         Context, Context.VoidPtrTy, false);
7669     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
7670     if (Arg.isInvalid())
7671       return true;
7672     TheCall->setArg(i, Arg.get());
7673     i++;
7674   }
7675 
7676   // Check string literal arg.
7677   unsigned FormatIdx = i;
7678   {
7679     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
7680     if (Arg.isInvalid())
7681       return true;
7682     TheCall->setArg(i, Arg.get());
7683     i++;
7684   }
7685 
7686   // Make sure variadic args are scalar.
7687   unsigned FirstDataArg = i;
7688   while (i < NumArgs) {
7689     ExprResult Arg = DefaultVariadicArgumentPromotion(
7690         TheCall->getArg(i), VariadicFunction, nullptr);
7691     if (Arg.isInvalid())
7692       return true;
7693     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
7694     if (ArgSize.getQuantity() >= 0x100) {
7695       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
7696              << i << (int)ArgSize.getQuantity() << 0xff
7697              << TheCall->getSourceRange();
7698     }
7699     TheCall->setArg(i, Arg.get());
7700     i++;
7701   }
7702 
7703   // Check formatting specifiers. NOTE: We're only doing this for the non-size
7704   // call to avoid duplicate diagnostics.
7705   if (!IsSizeCall) {
7706     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
7707     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
7708     bool Success = CheckFormatArguments(
7709         Args, FAPK_Variadic, FormatIdx, FirstDataArg, FST_OSLog,
7710         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
7711         CheckedVarArgs);
7712     if (!Success)
7713       return true;
7714   }
7715 
7716   if (IsSizeCall) {
7717     TheCall->setType(Context.getSizeType());
7718   } else {
7719     TheCall->setType(Context.VoidPtrTy);
7720   }
7721   return false;
7722 }
7723 
7724 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
7725 /// TheCall is a constant expression.
7726 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
7727                                   llvm::APSInt &Result) {
7728   Expr *Arg = TheCall->getArg(ArgNum);
7729   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
7730   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
7731 
7732   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
7733 
7734   Optional<llvm::APSInt> R;
7735   if (!(R = Arg->getIntegerConstantExpr(Context)))
7736     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
7737            << FDecl->getDeclName() << Arg->getSourceRange();
7738   Result = *R;
7739   return false;
7740 }
7741 
7742 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
7743 /// TheCall is a constant expression in the range [Low, High].
7744 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
7745                                        int Low, int High, bool RangeIsError) {
7746   if (isConstantEvaluated())
7747     return false;
7748   llvm::APSInt Result;
7749 
7750   // We can't check the value of a dependent argument.
7751   Expr *Arg = TheCall->getArg(ArgNum);
7752   if (Arg->isTypeDependent() || Arg->isValueDependent())
7753     return false;
7754 
7755   // Check constant-ness first.
7756   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7757     return true;
7758 
7759   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
7760     if (RangeIsError)
7761       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
7762              << toString(Result, 10) << Low << High << Arg->getSourceRange();
7763     else
7764       // Defer the warning until we know if the code will be emitted so that
7765       // dead code can ignore this.
7766       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
7767                           PDiag(diag::warn_argument_invalid_range)
7768                               << toString(Result, 10) << Low << High
7769                               << Arg->getSourceRange());
7770   }
7771 
7772   return false;
7773 }
7774 
7775 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
7776 /// TheCall is a constant expression is a multiple of Num..
7777 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
7778                                           unsigned Num) {
7779   llvm::APSInt Result;
7780 
7781   // We can't check the value of a dependent argument.
7782   Expr *Arg = TheCall->getArg(ArgNum);
7783   if (Arg->isTypeDependent() || Arg->isValueDependent())
7784     return false;
7785 
7786   // Check constant-ness first.
7787   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7788     return true;
7789 
7790   if (Result.getSExtValue() % Num != 0)
7791     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
7792            << Num << Arg->getSourceRange();
7793 
7794   return false;
7795 }
7796 
7797 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
7798 /// constant expression representing a power of 2.
7799 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
7800   llvm::APSInt Result;
7801 
7802   // We can't check the value of a dependent argument.
7803   Expr *Arg = TheCall->getArg(ArgNum);
7804   if (Arg->isTypeDependent() || Arg->isValueDependent())
7805     return false;
7806 
7807   // Check constant-ness first.
7808   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7809     return true;
7810 
7811   // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
7812   // and only if x is a power of 2.
7813   if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
7814     return false;
7815 
7816   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
7817          << Arg->getSourceRange();
7818 }
7819 
7820 static bool IsShiftedByte(llvm::APSInt Value) {
7821   if (Value.isNegative())
7822     return false;
7823 
7824   // Check if it's a shifted byte, by shifting it down
7825   while (true) {
7826     // If the value fits in the bottom byte, the check passes.
7827     if (Value < 0x100)
7828       return true;
7829 
7830     // Otherwise, if the value has _any_ bits in the bottom byte, the check
7831     // fails.
7832     if ((Value & 0xFF) != 0)
7833       return false;
7834 
7835     // If the bottom 8 bits are all 0, but something above that is nonzero,
7836     // then shifting the value right by 8 bits won't affect whether it's a
7837     // shifted byte or not. So do that, and go round again.
7838     Value >>= 8;
7839   }
7840 }
7841 
7842 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
7843 /// a constant expression representing an arbitrary byte value shifted left by
7844 /// a multiple of 8 bits.
7845 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
7846                                              unsigned ArgBits) {
7847   llvm::APSInt Result;
7848 
7849   // We can't check the value of a dependent argument.
7850   Expr *Arg = TheCall->getArg(ArgNum);
7851   if (Arg->isTypeDependent() || Arg->isValueDependent())
7852     return false;
7853 
7854   // Check constant-ness first.
7855   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7856     return true;
7857 
7858   // Truncate to the given size.
7859   Result = Result.getLoBits(ArgBits);
7860   Result.setIsUnsigned(true);
7861 
7862   if (IsShiftedByte(Result))
7863     return false;
7864 
7865   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
7866          << Arg->getSourceRange();
7867 }
7868 
7869 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
7870 /// TheCall is a constant expression representing either a shifted byte value,
7871 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
7872 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
7873 /// Arm MVE intrinsics.
7874 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
7875                                                    int ArgNum,
7876                                                    unsigned ArgBits) {
7877   llvm::APSInt Result;
7878 
7879   // We can't check the value of a dependent argument.
7880   Expr *Arg = TheCall->getArg(ArgNum);
7881   if (Arg->isTypeDependent() || Arg->isValueDependent())
7882     return false;
7883 
7884   // Check constant-ness first.
7885   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7886     return true;
7887 
7888   // Truncate to the given size.
7889   Result = Result.getLoBits(ArgBits);
7890   Result.setIsUnsigned(true);
7891 
7892   // Check to see if it's in either of the required forms.
7893   if (IsShiftedByte(Result) ||
7894       (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
7895     return false;
7896 
7897   return Diag(TheCall->getBeginLoc(),
7898               diag::err_argument_not_shifted_byte_or_xxff)
7899          << Arg->getSourceRange();
7900 }
7901 
7902 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
7903 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
7904   if (BuiltinID == AArch64::BI__builtin_arm_irg) {
7905     if (checkArgCount(*this, TheCall, 2))
7906       return true;
7907     Expr *Arg0 = TheCall->getArg(0);
7908     Expr *Arg1 = TheCall->getArg(1);
7909 
7910     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7911     if (FirstArg.isInvalid())
7912       return true;
7913     QualType FirstArgType = FirstArg.get()->getType();
7914     if (!FirstArgType->isAnyPointerType())
7915       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7916                << "first" << FirstArgType << Arg0->getSourceRange();
7917     TheCall->setArg(0, FirstArg.get());
7918 
7919     ExprResult SecArg = DefaultLvalueConversion(Arg1);
7920     if (SecArg.isInvalid())
7921       return true;
7922     QualType SecArgType = SecArg.get()->getType();
7923     if (!SecArgType->isIntegerType())
7924       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
7925                << "second" << SecArgType << Arg1->getSourceRange();
7926 
7927     // Derive the return type from the pointer argument.
7928     TheCall->setType(FirstArgType);
7929     return false;
7930   }
7931 
7932   if (BuiltinID == AArch64::BI__builtin_arm_addg) {
7933     if (checkArgCount(*this, TheCall, 2))
7934       return true;
7935 
7936     Expr *Arg0 = TheCall->getArg(0);
7937     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7938     if (FirstArg.isInvalid())
7939       return true;
7940     QualType FirstArgType = FirstArg.get()->getType();
7941     if (!FirstArgType->isAnyPointerType())
7942       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7943                << "first" << FirstArgType << Arg0->getSourceRange();
7944     TheCall->setArg(0, FirstArg.get());
7945 
7946     // Derive the return type from the pointer argument.
7947     TheCall->setType(FirstArgType);
7948 
7949     // Second arg must be an constant in range [0,15]
7950     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
7951   }
7952 
7953   if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
7954     if (checkArgCount(*this, TheCall, 2))
7955       return true;
7956     Expr *Arg0 = TheCall->getArg(0);
7957     Expr *Arg1 = TheCall->getArg(1);
7958 
7959     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7960     if (FirstArg.isInvalid())
7961       return true;
7962     QualType FirstArgType = FirstArg.get()->getType();
7963     if (!FirstArgType->isAnyPointerType())
7964       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7965                << "first" << FirstArgType << Arg0->getSourceRange();
7966 
7967     QualType SecArgType = Arg1->getType();
7968     if (!SecArgType->isIntegerType())
7969       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
7970                << "second" << SecArgType << Arg1->getSourceRange();
7971     TheCall->setType(Context.IntTy);
7972     return false;
7973   }
7974 
7975   if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
7976       BuiltinID == AArch64::BI__builtin_arm_stg) {
7977     if (checkArgCount(*this, TheCall, 1))
7978       return true;
7979     Expr *Arg0 = TheCall->getArg(0);
7980     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7981     if (FirstArg.isInvalid())
7982       return true;
7983 
7984     QualType FirstArgType = FirstArg.get()->getType();
7985     if (!FirstArgType->isAnyPointerType())
7986       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7987                << "first" << FirstArgType << Arg0->getSourceRange();
7988     TheCall->setArg(0, FirstArg.get());
7989 
7990     // Derive the return type from the pointer argument.
7991     if (BuiltinID == AArch64::BI__builtin_arm_ldg)
7992       TheCall->setType(FirstArgType);
7993     return false;
7994   }
7995 
7996   if (BuiltinID == AArch64::BI__builtin_arm_subp) {
7997     Expr *ArgA = TheCall->getArg(0);
7998     Expr *ArgB = TheCall->getArg(1);
7999 
8000     ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
8001     ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
8002 
8003     if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
8004       return true;
8005 
8006     QualType ArgTypeA = ArgExprA.get()->getType();
8007     QualType ArgTypeB = ArgExprB.get()->getType();
8008 
8009     auto isNull = [&] (Expr *E) -> bool {
8010       return E->isNullPointerConstant(
8011                         Context, Expr::NPC_ValueDependentIsNotNull); };
8012 
8013     // argument should be either a pointer or null
8014     if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
8015       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
8016         << "first" << ArgTypeA << ArgA->getSourceRange();
8017 
8018     if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
8019       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
8020         << "second" << ArgTypeB << ArgB->getSourceRange();
8021 
8022     // Ensure Pointee types are compatible
8023     if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
8024         ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
8025       QualType pointeeA = ArgTypeA->getPointeeType();
8026       QualType pointeeB = ArgTypeB->getPointeeType();
8027       if (!Context.typesAreCompatible(
8028              Context.getCanonicalType(pointeeA).getUnqualifiedType(),
8029              Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
8030         return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
8031           << ArgTypeA <<  ArgTypeB << ArgA->getSourceRange()
8032           << ArgB->getSourceRange();
8033       }
8034     }
8035 
8036     // at least one argument should be pointer type
8037     if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
8038       return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
8039         <<  ArgTypeA << ArgTypeB << ArgA->getSourceRange();
8040 
8041     if (isNull(ArgA)) // adopt type of the other pointer
8042       ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
8043 
8044     if (isNull(ArgB))
8045       ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
8046 
8047     TheCall->setArg(0, ArgExprA.get());
8048     TheCall->setArg(1, ArgExprB.get());
8049     TheCall->setType(Context.LongLongTy);
8050     return false;
8051   }
8052   assert(false && "Unhandled ARM MTE intrinsic");
8053   return true;
8054 }
8055 
8056 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
8057 /// TheCall is an ARM/AArch64 special register string literal.
8058 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
8059                                     int ArgNum, unsigned ExpectedFieldNum,
8060                                     bool AllowName) {
8061   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
8062                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
8063                       BuiltinID == ARM::BI__builtin_arm_rsr ||
8064                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
8065                       BuiltinID == ARM::BI__builtin_arm_wsr ||
8066                       BuiltinID == ARM::BI__builtin_arm_wsrp;
8067   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
8068                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
8069                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
8070                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
8071                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
8072                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
8073   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
8074 
8075   // We can't check the value of a dependent argument.
8076   Expr *Arg = TheCall->getArg(ArgNum);
8077   if (Arg->isTypeDependent() || Arg->isValueDependent())
8078     return false;
8079 
8080   // Check if the argument is a string literal.
8081   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
8082     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
8083            << Arg->getSourceRange();
8084 
8085   // Check the type of special register given.
8086   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
8087   SmallVector<StringRef, 6> Fields;
8088   Reg.split(Fields, ":");
8089 
8090   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
8091     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
8092            << Arg->getSourceRange();
8093 
8094   // If the string is the name of a register then we cannot check that it is
8095   // valid here but if the string is of one the forms described in ACLE then we
8096   // can check that the supplied fields are integers and within the valid
8097   // ranges.
8098   if (Fields.size() > 1) {
8099     bool FiveFields = Fields.size() == 5;
8100 
8101     bool ValidString = true;
8102     if (IsARMBuiltin) {
8103       ValidString &= Fields[0].startswith_insensitive("cp") ||
8104                      Fields[0].startswith_insensitive("p");
8105       if (ValidString)
8106         Fields[0] = Fields[0].drop_front(
8107             Fields[0].startswith_insensitive("cp") ? 2 : 1);
8108 
8109       ValidString &= Fields[2].startswith_insensitive("c");
8110       if (ValidString)
8111         Fields[2] = Fields[2].drop_front(1);
8112 
8113       if (FiveFields) {
8114         ValidString &= Fields[3].startswith_insensitive("c");
8115         if (ValidString)
8116           Fields[3] = Fields[3].drop_front(1);
8117       }
8118     }
8119 
8120     SmallVector<int, 5> Ranges;
8121     if (FiveFields)
8122       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
8123     else
8124       Ranges.append({15, 7, 15});
8125 
8126     for (unsigned i=0; i<Fields.size(); ++i) {
8127       int IntField;
8128       ValidString &= !Fields[i].getAsInteger(10, IntField);
8129       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
8130     }
8131 
8132     if (!ValidString)
8133       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
8134              << Arg->getSourceRange();
8135   } else if (IsAArch64Builtin && Fields.size() == 1) {
8136     // If the register name is one of those that appear in the condition below
8137     // and the special register builtin being used is one of the write builtins,
8138     // then we require that the argument provided for writing to the register
8139     // is an integer constant expression. This is because it will be lowered to
8140     // an MSR (immediate) instruction, so we need to know the immediate at
8141     // compile time.
8142     if (TheCall->getNumArgs() != 2)
8143       return false;
8144 
8145     std::string RegLower = Reg.lower();
8146     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
8147         RegLower != "pan" && RegLower != "uao")
8148       return false;
8149 
8150     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
8151   }
8152 
8153   return false;
8154 }
8155 
8156 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity.
8157 /// Emit an error and return true on failure; return false on success.
8158 /// TypeStr is a string containing the type descriptor of the value returned by
8159 /// the builtin and the descriptors of the expected type of the arguments.
8160 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, unsigned BuiltinID,
8161                                  const char *TypeStr) {
8162 
8163   assert((TypeStr[0] != '\0') &&
8164          "Invalid types in PPC MMA builtin declaration");
8165 
8166   switch (BuiltinID) {
8167   default:
8168     // This function is called in CheckPPCBuiltinFunctionCall where the
8169     // BuiltinID is guaranteed to be an MMA or pair vector memop builtin, here
8170     // we are isolating the pair vector memop builtins that can be used with mma
8171     // off so the default case is every builtin that requires mma and paired
8172     // vector memops.
8173     if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops",
8174                          diag::err_ppc_builtin_only_on_arch, "10") ||
8175         SemaFeatureCheck(*this, TheCall, "mma",
8176                          diag::err_ppc_builtin_only_on_arch, "10"))
8177       return true;
8178     break;
8179   case PPC::BI__builtin_vsx_lxvp:
8180   case PPC::BI__builtin_vsx_stxvp:
8181   case PPC::BI__builtin_vsx_assemble_pair:
8182   case PPC::BI__builtin_vsx_disassemble_pair:
8183     if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops",
8184                          diag::err_ppc_builtin_only_on_arch, "10"))
8185       return true;
8186     break;
8187   }
8188 
8189   unsigned Mask = 0;
8190   unsigned ArgNum = 0;
8191 
8192   // The first type in TypeStr is the type of the value returned by the
8193   // builtin. So we first read that type and change the type of TheCall.
8194   QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
8195   TheCall->setType(type);
8196 
8197   while (*TypeStr != '\0') {
8198     Mask = 0;
8199     QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
8200     if (ArgNum >= TheCall->getNumArgs()) {
8201       ArgNum++;
8202       break;
8203     }
8204 
8205     Expr *Arg = TheCall->getArg(ArgNum);
8206     QualType PassedType = Arg->getType();
8207     QualType StrippedRVType = PassedType.getCanonicalType();
8208 
8209     // Strip Restrict/Volatile qualifiers.
8210     if (StrippedRVType.isRestrictQualified() ||
8211         StrippedRVType.isVolatileQualified())
8212       StrippedRVType = StrippedRVType.getCanonicalType().getUnqualifiedType();
8213 
8214     // The only case where the argument type and expected type are allowed to
8215     // mismatch is if the argument type is a non-void pointer (or array) and
8216     // expected type is a void pointer.
8217     if (StrippedRVType != ExpectedType)
8218       if (!(ExpectedType->isVoidPointerType() &&
8219             (StrippedRVType->isPointerType() || StrippedRVType->isArrayType())))
8220         return Diag(Arg->getBeginLoc(),
8221                     diag::err_typecheck_convert_incompatible)
8222                << PassedType << ExpectedType << 1 << 0 << 0;
8223 
8224     // If the value of the Mask is not 0, we have a constraint in the size of
8225     // the integer argument so here we ensure the argument is a constant that
8226     // is in the valid range.
8227     if (Mask != 0 &&
8228         SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true))
8229       return true;
8230 
8231     ArgNum++;
8232   }
8233 
8234   // In case we exited early from the previous loop, there are other types to
8235   // read from TypeStr. So we need to read them all to ensure we have the right
8236   // number of arguments in TheCall and if it is not the case, to display a
8237   // better error message.
8238   while (*TypeStr != '\0') {
8239     (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
8240     ArgNum++;
8241   }
8242   if (checkArgCount(*this, TheCall, ArgNum))
8243     return true;
8244 
8245   return false;
8246 }
8247 
8248 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
8249 /// This checks that the target supports __builtin_longjmp and
8250 /// that val is a constant 1.
8251 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
8252   if (!Context.getTargetInfo().hasSjLjLowering())
8253     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
8254            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
8255 
8256   Expr *Arg = TheCall->getArg(1);
8257   llvm::APSInt Result;
8258 
8259   // TODO: This is less than ideal. Overload this to take a value.
8260   if (SemaBuiltinConstantArg(TheCall, 1, Result))
8261     return true;
8262 
8263   if (Result != 1)
8264     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
8265            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
8266 
8267   return false;
8268 }
8269 
8270 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
8271 /// This checks that the target supports __builtin_setjmp.
8272 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
8273   if (!Context.getTargetInfo().hasSjLjLowering())
8274     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
8275            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
8276   return false;
8277 }
8278 
8279 namespace {
8280 
8281 class UncoveredArgHandler {
8282   enum { Unknown = -1, AllCovered = -2 };
8283 
8284   signed FirstUncoveredArg = Unknown;
8285   SmallVector<const Expr *, 4> DiagnosticExprs;
8286 
8287 public:
8288   UncoveredArgHandler() = default;
8289 
8290   bool hasUncoveredArg() const {
8291     return (FirstUncoveredArg >= 0);
8292   }
8293 
8294   unsigned getUncoveredArg() const {
8295     assert(hasUncoveredArg() && "no uncovered argument");
8296     return FirstUncoveredArg;
8297   }
8298 
8299   void setAllCovered() {
8300     // A string has been found with all arguments covered, so clear out
8301     // the diagnostics.
8302     DiagnosticExprs.clear();
8303     FirstUncoveredArg = AllCovered;
8304   }
8305 
8306   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
8307     assert(NewFirstUncoveredArg >= 0 && "Outside range");
8308 
8309     // Don't update if a previous string covers all arguments.
8310     if (FirstUncoveredArg == AllCovered)
8311       return;
8312 
8313     // UncoveredArgHandler tracks the highest uncovered argument index
8314     // and with it all the strings that match this index.
8315     if (NewFirstUncoveredArg == FirstUncoveredArg)
8316       DiagnosticExprs.push_back(StrExpr);
8317     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
8318       DiagnosticExprs.clear();
8319       DiagnosticExprs.push_back(StrExpr);
8320       FirstUncoveredArg = NewFirstUncoveredArg;
8321     }
8322   }
8323 
8324   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
8325 };
8326 
8327 enum StringLiteralCheckType {
8328   SLCT_NotALiteral,
8329   SLCT_UncheckedLiteral,
8330   SLCT_CheckedLiteral
8331 };
8332 
8333 } // namespace
8334 
8335 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
8336                                      BinaryOperatorKind BinOpKind,
8337                                      bool AddendIsRight) {
8338   unsigned BitWidth = Offset.getBitWidth();
8339   unsigned AddendBitWidth = Addend.getBitWidth();
8340   // There might be negative interim results.
8341   if (Addend.isUnsigned()) {
8342     Addend = Addend.zext(++AddendBitWidth);
8343     Addend.setIsSigned(true);
8344   }
8345   // Adjust the bit width of the APSInts.
8346   if (AddendBitWidth > BitWidth) {
8347     Offset = Offset.sext(AddendBitWidth);
8348     BitWidth = AddendBitWidth;
8349   } else if (BitWidth > AddendBitWidth) {
8350     Addend = Addend.sext(BitWidth);
8351   }
8352 
8353   bool Ov = false;
8354   llvm::APSInt ResOffset = Offset;
8355   if (BinOpKind == BO_Add)
8356     ResOffset = Offset.sadd_ov(Addend, Ov);
8357   else {
8358     assert(AddendIsRight && BinOpKind == BO_Sub &&
8359            "operator must be add or sub with addend on the right");
8360     ResOffset = Offset.ssub_ov(Addend, Ov);
8361   }
8362 
8363   // We add an offset to a pointer here so we should support an offset as big as
8364   // possible.
8365   if (Ov) {
8366     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
8367            "index (intermediate) result too big");
8368     Offset = Offset.sext(2 * BitWidth);
8369     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
8370     return;
8371   }
8372 
8373   Offset = ResOffset;
8374 }
8375 
8376 namespace {
8377 
8378 // This is a wrapper class around StringLiteral to support offsetted string
8379 // literals as format strings. It takes the offset into account when returning
8380 // the string and its length or the source locations to display notes correctly.
8381 class FormatStringLiteral {
8382   const StringLiteral *FExpr;
8383   int64_t Offset;
8384 
8385  public:
8386   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
8387       : FExpr(fexpr), Offset(Offset) {}
8388 
8389   StringRef getString() const {
8390     return FExpr->getString().drop_front(Offset);
8391   }
8392 
8393   unsigned getByteLength() const {
8394     return FExpr->getByteLength() - getCharByteWidth() * Offset;
8395   }
8396 
8397   unsigned getLength() const { return FExpr->getLength() - Offset; }
8398   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
8399 
8400   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
8401 
8402   QualType getType() const { return FExpr->getType(); }
8403 
8404   bool isAscii() const { return FExpr->isOrdinary(); }
8405   bool isWide() const { return FExpr->isWide(); }
8406   bool isUTF8() const { return FExpr->isUTF8(); }
8407   bool isUTF16() const { return FExpr->isUTF16(); }
8408   bool isUTF32() const { return FExpr->isUTF32(); }
8409   bool isPascal() const { return FExpr->isPascal(); }
8410 
8411   SourceLocation getLocationOfByte(
8412       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
8413       const TargetInfo &Target, unsigned *StartToken = nullptr,
8414       unsigned *StartTokenByteOffset = nullptr) const {
8415     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
8416                                     StartToken, StartTokenByteOffset);
8417   }
8418 
8419   SourceLocation getBeginLoc() const LLVM_READONLY {
8420     return FExpr->getBeginLoc().getLocWithOffset(Offset);
8421   }
8422 
8423   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
8424 };
8425 
8426 } // namespace
8427 
8428 static void CheckFormatString(
8429     Sema &S, const FormatStringLiteral *FExpr, const Expr *OrigFormatExpr,
8430     ArrayRef<const Expr *> Args, Sema::FormatArgumentPassingKind APK,
8431     unsigned format_idx, unsigned firstDataArg, Sema::FormatStringType Type,
8432     bool inFunctionCall, Sema::VariadicCallType CallType,
8433     llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
8434     bool IgnoreStringsWithoutSpecifiers);
8435 
8436 // Determine if an expression is a string literal or constant string.
8437 // If this function returns false on the arguments to a function expecting a
8438 // format string, we will usually need to emit a warning.
8439 // True string literals are then checked by CheckFormatString.
8440 static StringLiteralCheckType
8441 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
8442                       Sema::FormatArgumentPassingKind APK, unsigned format_idx,
8443                       unsigned firstDataArg, Sema::FormatStringType Type,
8444                       Sema::VariadicCallType CallType, bool InFunctionCall,
8445                       llvm::SmallBitVector &CheckedVarArgs,
8446                       UncoveredArgHandler &UncoveredArg, llvm::APSInt Offset,
8447                       bool IgnoreStringsWithoutSpecifiers = false) {
8448   if (S.isConstantEvaluated())
8449     return SLCT_NotALiteral;
8450 tryAgain:
8451   assert(Offset.isSigned() && "invalid offset");
8452 
8453   if (E->isTypeDependent() || E->isValueDependent())
8454     return SLCT_NotALiteral;
8455 
8456   E = E->IgnoreParenCasts();
8457 
8458   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
8459     // Technically -Wformat-nonliteral does not warn about this case.
8460     // The behavior of printf and friends in this case is implementation
8461     // dependent.  Ideally if the format string cannot be null then
8462     // it should have a 'nonnull' attribute in the function prototype.
8463     return SLCT_UncheckedLiteral;
8464 
8465   switch (E->getStmtClass()) {
8466   case Stmt::BinaryConditionalOperatorClass:
8467   case Stmt::ConditionalOperatorClass: {
8468     // The expression is a literal if both sub-expressions were, and it was
8469     // completely checked only if both sub-expressions were checked.
8470     const AbstractConditionalOperator *C =
8471         cast<AbstractConditionalOperator>(E);
8472 
8473     // Determine whether it is necessary to check both sub-expressions, for
8474     // example, because the condition expression is a constant that can be
8475     // evaluated at compile time.
8476     bool CheckLeft = true, CheckRight = true;
8477 
8478     bool Cond;
8479     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
8480                                                  S.isConstantEvaluated())) {
8481       if (Cond)
8482         CheckRight = false;
8483       else
8484         CheckLeft = false;
8485     }
8486 
8487     // We need to maintain the offsets for the right and the left hand side
8488     // separately to check if every possible indexed expression is a valid
8489     // string literal. They might have different offsets for different string
8490     // literals in the end.
8491     StringLiteralCheckType Left;
8492     if (!CheckLeft)
8493       Left = SLCT_UncheckedLiteral;
8494     else {
8495       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, APK, format_idx,
8496                                    firstDataArg, Type, CallType, InFunctionCall,
8497                                    CheckedVarArgs, UncoveredArg, Offset,
8498                                    IgnoreStringsWithoutSpecifiers);
8499       if (Left == SLCT_NotALiteral || !CheckRight) {
8500         return Left;
8501       }
8502     }
8503 
8504     StringLiteralCheckType Right = checkFormatStringExpr(
8505         S, C->getFalseExpr(), Args, APK, format_idx, firstDataArg, Type,
8506         CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
8507         IgnoreStringsWithoutSpecifiers);
8508 
8509     return (CheckLeft && Left < Right) ? Left : Right;
8510   }
8511 
8512   case Stmt::ImplicitCastExprClass:
8513     E = cast<ImplicitCastExpr>(E)->getSubExpr();
8514     goto tryAgain;
8515 
8516   case Stmt::OpaqueValueExprClass:
8517     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
8518       E = src;
8519       goto tryAgain;
8520     }
8521     return SLCT_NotALiteral;
8522 
8523   case Stmt::PredefinedExprClass:
8524     // While __func__, etc., are technically not string literals, they
8525     // cannot contain format specifiers and thus are not a security
8526     // liability.
8527     return SLCT_UncheckedLiteral;
8528 
8529   case Stmt::DeclRefExprClass: {
8530     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
8531 
8532     // As an exception, do not flag errors for variables binding to
8533     // const string literals.
8534     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
8535       bool isConstant = false;
8536       QualType T = DR->getType();
8537 
8538       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
8539         isConstant = AT->getElementType().isConstant(S.Context);
8540       } else if (const PointerType *PT = T->getAs<PointerType>()) {
8541         isConstant = T.isConstant(S.Context) &&
8542                      PT->getPointeeType().isConstant(S.Context);
8543       } else if (T->isObjCObjectPointerType()) {
8544         // In ObjC, there is usually no "const ObjectPointer" type,
8545         // so don't check if the pointee type is constant.
8546         isConstant = T.isConstant(S.Context);
8547       }
8548 
8549       if (isConstant) {
8550         if (const Expr *Init = VD->getAnyInitializer()) {
8551           // Look through initializers like const char c[] = { "foo" }
8552           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
8553             if (InitList->isStringLiteralInit())
8554               Init = InitList->getInit(0)->IgnoreParenImpCasts();
8555           }
8556           return checkFormatStringExpr(
8557               S, Init, Args, APK, format_idx, firstDataArg, Type, CallType,
8558               /*InFunctionCall*/ false, CheckedVarArgs, UncoveredArg, Offset);
8559         }
8560       }
8561 
8562       // When the format argument is an argument of this function, and this
8563       // function also has the format attribute, there are several interactions
8564       // for which there shouldn't be a warning. For instance, when calling
8565       // v*printf from a function that has the printf format attribute, we
8566       // should not emit a warning about using `fmt`, even though it's not
8567       // constant, because the arguments have already been checked for the
8568       // caller of `logmessage`:
8569       //
8570       //  __attribute__((format(printf, 1, 2)))
8571       //  void logmessage(char const *fmt, ...) {
8572       //    va_list ap;
8573       //    va_start(ap, fmt);
8574       //    vprintf(fmt, ap);  /* do not emit a warning about "fmt" */
8575       //    ...
8576       // }
8577       //
8578       // Another interaction that we need to support is calling a variadic
8579       // format function from a format function that has fixed arguments. For
8580       // instance:
8581       //
8582       //  __attribute__((format(printf, 1, 2)))
8583       //  void logstring(char const *fmt, char const *str) {
8584       //    printf(fmt, str);  /* do not emit a warning about "fmt" */
8585       //  }
8586       //
8587       // Same (and perhaps more relatably) for the variadic template case:
8588       //
8589       //  template<typename... Args>
8590       //  __attribute__((format(printf, 1, 2)))
8591       //  void log(const char *fmt, Args&&... args) {
8592       //    printf(fmt, forward<Args>(args)...);
8593       //           /* do not emit a warning about "fmt" */
8594       //  }
8595       //
8596       // Due to implementation difficulty, we only check the format, not the
8597       // format arguments, in all cases.
8598       //
8599       if (const auto *PV = dyn_cast<ParmVarDecl>(VD)) {
8600         if (const auto *D = dyn_cast<Decl>(PV->getDeclContext())) {
8601           for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) {
8602             bool IsCXXMember = false;
8603             if (const auto *MD = dyn_cast<CXXMethodDecl>(D))
8604               IsCXXMember = MD->isInstance();
8605 
8606             bool IsVariadic = false;
8607             if (const FunctionType *FnTy = D->getFunctionType())
8608               IsVariadic = cast<FunctionProtoType>(FnTy)->isVariadic();
8609             else if (const auto *BD = dyn_cast<BlockDecl>(D))
8610               IsVariadic = BD->isVariadic();
8611             else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D))
8612               IsVariadic = OMD->isVariadic();
8613 
8614             Sema::FormatStringInfo CallerFSI;
8615             if (Sema::getFormatStringInfo(PVFormat, IsCXXMember, IsVariadic,
8616                                           &CallerFSI)) {
8617               // We also check if the formats are compatible.
8618               // We can't pass a 'scanf' string to a 'printf' function.
8619               if (PV->getFunctionScopeIndex() == CallerFSI.FormatIdx &&
8620                   Type == S.GetFormatStringType(PVFormat)) {
8621                 // Lastly, check that argument passing kinds transition in a
8622                 // way that makes sense:
8623                 // from a caller with FAPK_VAList, allow FAPK_VAList
8624                 // from a caller with FAPK_Fixed, allow FAPK_Fixed
8625                 // from a caller with FAPK_Fixed, allow FAPK_Variadic
8626                 // from a caller with FAPK_Variadic, allow FAPK_VAList
8627                 switch (combineFAPK(CallerFSI.ArgPassingKind, APK)) {
8628                 case combineFAPK(Sema::FAPK_VAList, Sema::FAPK_VAList):
8629                 case combineFAPK(Sema::FAPK_Fixed, Sema::FAPK_Fixed):
8630                 case combineFAPK(Sema::FAPK_Fixed, Sema::FAPK_Variadic):
8631                 case combineFAPK(Sema::FAPK_Variadic, Sema::FAPK_VAList):
8632                   return SLCT_UncheckedLiteral;
8633                 }
8634               }
8635             }
8636           }
8637         }
8638       }
8639     }
8640 
8641     return SLCT_NotALiteral;
8642   }
8643 
8644   case Stmt::CallExprClass:
8645   case Stmt::CXXMemberCallExprClass: {
8646     const CallExpr *CE = cast<CallExpr>(E);
8647     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
8648       bool IsFirst = true;
8649       StringLiteralCheckType CommonResult;
8650       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
8651         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
8652         StringLiteralCheckType Result = checkFormatStringExpr(
8653             S, Arg, Args, APK, format_idx, firstDataArg, Type, CallType,
8654             InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
8655             IgnoreStringsWithoutSpecifiers);
8656         if (IsFirst) {
8657           CommonResult = Result;
8658           IsFirst = false;
8659         }
8660       }
8661       if (!IsFirst)
8662         return CommonResult;
8663 
8664       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
8665         unsigned BuiltinID = FD->getBuiltinID();
8666         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
8667             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
8668           const Expr *Arg = CE->getArg(0);
8669           return checkFormatStringExpr(
8670               S, Arg, Args, APK, format_idx, firstDataArg, Type, CallType,
8671               InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
8672               IgnoreStringsWithoutSpecifiers);
8673         }
8674       }
8675     }
8676 
8677     return SLCT_NotALiteral;
8678   }
8679   case Stmt::ObjCMessageExprClass: {
8680     const auto *ME = cast<ObjCMessageExpr>(E);
8681     if (const auto *MD = ME->getMethodDecl()) {
8682       if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
8683         // As a special case heuristic, if we're using the method -[NSBundle
8684         // localizedStringForKey:value:table:], ignore any key strings that lack
8685         // format specifiers. The idea is that if the key doesn't have any
8686         // format specifiers then its probably just a key to map to the
8687         // localized strings. If it does have format specifiers though, then its
8688         // likely that the text of the key is the format string in the
8689         // programmer's language, and should be checked.
8690         const ObjCInterfaceDecl *IFace;
8691         if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
8692             IFace->getIdentifier()->isStr("NSBundle") &&
8693             MD->getSelector().isKeywordSelector(
8694                 {"localizedStringForKey", "value", "table"})) {
8695           IgnoreStringsWithoutSpecifiers = true;
8696         }
8697 
8698         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
8699         return checkFormatStringExpr(
8700             S, Arg, Args, APK, format_idx, firstDataArg, Type, CallType,
8701             InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
8702             IgnoreStringsWithoutSpecifiers);
8703       }
8704     }
8705 
8706     return SLCT_NotALiteral;
8707   }
8708   case Stmt::ObjCStringLiteralClass:
8709   case Stmt::StringLiteralClass: {
8710     const StringLiteral *StrE = nullptr;
8711 
8712     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
8713       StrE = ObjCFExpr->getString();
8714     else
8715       StrE = cast<StringLiteral>(E);
8716 
8717     if (StrE) {
8718       if (Offset.isNegative() || Offset > StrE->getLength()) {
8719         // TODO: It would be better to have an explicit warning for out of
8720         // bounds literals.
8721         return SLCT_NotALiteral;
8722       }
8723       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
8724       CheckFormatString(S, &FStr, E, Args, APK, format_idx, firstDataArg, Type,
8725                         InFunctionCall, CallType, CheckedVarArgs, UncoveredArg,
8726                         IgnoreStringsWithoutSpecifiers);
8727       return SLCT_CheckedLiteral;
8728     }
8729 
8730     return SLCT_NotALiteral;
8731   }
8732   case Stmt::BinaryOperatorClass: {
8733     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
8734 
8735     // A string literal + an int offset is still a string literal.
8736     if (BinOp->isAdditiveOp()) {
8737       Expr::EvalResult LResult, RResult;
8738 
8739       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
8740           LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
8741       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
8742           RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
8743 
8744       if (LIsInt != RIsInt) {
8745         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
8746 
8747         if (LIsInt) {
8748           if (BinOpKind == BO_Add) {
8749             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
8750             E = BinOp->getRHS();
8751             goto tryAgain;
8752           }
8753         } else {
8754           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
8755           E = BinOp->getLHS();
8756           goto tryAgain;
8757         }
8758       }
8759     }
8760 
8761     return SLCT_NotALiteral;
8762   }
8763   case Stmt::UnaryOperatorClass: {
8764     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
8765     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
8766     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
8767       Expr::EvalResult IndexResult;
8768       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
8769                                        Expr::SE_NoSideEffects,
8770                                        S.isConstantEvaluated())) {
8771         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
8772                    /*RHS is int*/ true);
8773         E = ASE->getBase();
8774         goto tryAgain;
8775       }
8776     }
8777 
8778     return SLCT_NotALiteral;
8779   }
8780 
8781   default:
8782     return SLCT_NotALiteral;
8783   }
8784 }
8785 
8786 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
8787   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
8788       .Case("scanf", FST_Scanf)
8789       .Cases("printf", "printf0", FST_Printf)
8790       .Cases("NSString", "CFString", FST_NSString)
8791       .Case("strftime", FST_Strftime)
8792       .Case("strfmon", FST_Strfmon)
8793       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
8794       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
8795       .Case("os_trace", FST_OSLog)
8796       .Case("os_log", FST_OSLog)
8797       .Default(FST_Unknown);
8798 }
8799 
8800 /// CheckFormatArguments - Check calls to printf and scanf (and similar
8801 /// functions) for correct use of format strings.
8802 /// Returns true if a format string has been fully checked.
8803 bool Sema::CheckFormatArguments(const FormatAttr *Format,
8804                                 ArrayRef<const Expr *> Args, bool IsCXXMember,
8805                                 VariadicCallType CallType, SourceLocation Loc,
8806                                 SourceRange Range,
8807                                 llvm::SmallBitVector &CheckedVarArgs) {
8808   FormatStringInfo FSI;
8809   if (getFormatStringInfo(Format, IsCXXMember, CallType != VariadicDoesNotApply,
8810                           &FSI))
8811     return CheckFormatArguments(Args, FSI.ArgPassingKind, FSI.FormatIdx,
8812                                 FSI.FirstDataArg, GetFormatStringType(Format),
8813                                 CallType, Loc, Range, CheckedVarArgs);
8814   return false;
8815 }
8816 
8817 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
8818                                 Sema::FormatArgumentPassingKind APK,
8819                                 unsigned format_idx, unsigned firstDataArg,
8820                                 FormatStringType Type,
8821                                 VariadicCallType CallType, SourceLocation Loc,
8822                                 SourceRange Range,
8823                                 llvm::SmallBitVector &CheckedVarArgs) {
8824   // CHECK: printf/scanf-like function is called with no format string.
8825   if (format_idx >= Args.size()) {
8826     Diag(Loc, diag::warn_missing_format_string) << Range;
8827     return false;
8828   }
8829 
8830   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
8831 
8832   // CHECK: format string is not a string literal.
8833   //
8834   // Dynamically generated format strings are difficult to
8835   // automatically vet at compile time.  Requiring that format strings
8836   // are string literals: (1) permits the checking of format strings by
8837   // the compiler and thereby (2) can practically remove the source of
8838   // many format string exploits.
8839 
8840   // Format string can be either ObjC string (e.g. @"%d") or
8841   // C string (e.g. "%d")
8842   // ObjC string uses the same format specifiers as C string, so we can use
8843   // the same format string checking logic for both ObjC and C strings.
8844   UncoveredArgHandler UncoveredArg;
8845   StringLiteralCheckType CT = checkFormatStringExpr(
8846       *this, OrigFormatExpr, Args, APK, format_idx, firstDataArg, Type,
8847       CallType,
8848       /*IsFunctionCall*/ true, CheckedVarArgs, UncoveredArg,
8849       /*no string offset*/ llvm::APSInt(64, false) = 0);
8850 
8851   // Generate a diagnostic where an uncovered argument is detected.
8852   if (UncoveredArg.hasUncoveredArg()) {
8853     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
8854     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
8855     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
8856   }
8857 
8858   if (CT != SLCT_NotALiteral)
8859     // Literal format string found, check done!
8860     return CT == SLCT_CheckedLiteral;
8861 
8862   // Strftime is particular as it always uses a single 'time' argument,
8863   // so it is safe to pass a non-literal string.
8864   if (Type == FST_Strftime)
8865     return false;
8866 
8867   // Do not emit diag when the string param is a macro expansion and the
8868   // format is either NSString or CFString. This is a hack to prevent
8869   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
8870   // which are usually used in place of NS and CF string literals.
8871   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
8872   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
8873     return false;
8874 
8875   // If there are no arguments specified, warn with -Wformat-security, otherwise
8876   // warn only with -Wformat-nonliteral.
8877   if (Args.size() == firstDataArg) {
8878     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
8879       << OrigFormatExpr->getSourceRange();
8880     switch (Type) {
8881     default:
8882       break;
8883     case FST_Kprintf:
8884     case FST_FreeBSDKPrintf:
8885     case FST_Printf:
8886       Diag(FormatLoc, diag::note_format_security_fixit)
8887         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
8888       break;
8889     case FST_NSString:
8890       Diag(FormatLoc, diag::note_format_security_fixit)
8891         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
8892       break;
8893     }
8894   } else {
8895     Diag(FormatLoc, diag::warn_format_nonliteral)
8896       << OrigFormatExpr->getSourceRange();
8897   }
8898   return false;
8899 }
8900 
8901 namespace {
8902 
8903 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
8904 protected:
8905   Sema &S;
8906   const FormatStringLiteral *FExpr;
8907   const Expr *OrigFormatExpr;
8908   const Sema::FormatStringType FSType;
8909   const unsigned FirstDataArg;
8910   const unsigned NumDataArgs;
8911   const char *Beg; // Start of format string.
8912   const Sema::FormatArgumentPassingKind ArgPassingKind;
8913   ArrayRef<const Expr *> Args;
8914   unsigned FormatIdx;
8915   llvm::SmallBitVector CoveredArgs;
8916   bool usesPositionalArgs = false;
8917   bool atFirstArg = true;
8918   bool inFunctionCall;
8919   Sema::VariadicCallType CallType;
8920   llvm::SmallBitVector &CheckedVarArgs;
8921   UncoveredArgHandler &UncoveredArg;
8922 
8923 public:
8924   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
8925                      const Expr *origFormatExpr,
8926                      const Sema::FormatStringType type, unsigned firstDataArg,
8927                      unsigned numDataArgs, const char *beg,
8928                      Sema::FormatArgumentPassingKind APK,
8929                      ArrayRef<const Expr *> Args, unsigned formatIdx,
8930                      bool inFunctionCall, Sema::VariadicCallType callType,
8931                      llvm::SmallBitVector &CheckedVarArgs,
8932                      UncoveredArgHandler &UncoveredArg)
8933       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
8934         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
8935         ArgPassingKind(APK), Args(Args), FormatIdx(formatIdx),
8936         inFunctionCall(inFunctionCall), CallType(callType),
8937         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
8938     CoveredArgs.resize(numDataArgs);
8939     CoveredArgs.reset();
8940   }
8941 
8942   void DoneProcessing();
8943 
8944   void HandleIncompleteSpecifier(const char *startSpecifier,
8945                                  unsigned specifierLen) override;
8946 
8947   void HandleInvalidLengthModifier(
8948                            const analyze_format_string::FormatSpecifier &FS,
8949                            const analyze_format_string::ConversionSpecifier &CS,
8950                            const char *startSpecifier, unsigned specifierLen,
8951                            unsigned DiagID);
8952 
8953   void HandleNonStandardLengthModifier(
8954                     const analyze_format_string::FormatSpecifier &FS,
8955                     const char *startSpecifier, unsigned specifierLen);
8956 
8957   void HandleNonStandardConversionSpecifier(
8958                     const analyze_format_string::ConversionSpecifier &CS,
8959                     const char *startSpecifier, unsigned specifierLen);
8960 
8961   void HandlePosition(const char *startPos, unsigned posLen) override;
8962 
8963   void HandleInvalidPosition(const char *startSpecifier,
8964                              unsigned specifierLen,
8965                              analyze_format_string::PositionContext p) override;
8966 
8967   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
8968 
8969   void HandleNullChar(const char *nullCharacter) override;
8970 
8971   template <typename Range>
8972   static void
8973   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
8974                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
8975                        bool IsStringLocation, Range StringRange,
8976                        ArrayRef<FixItHint> Fixit = None);
8977 
8978 protected:
8979   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
8980                                         const char *startSpec,
8981                                         unsigned specifierLen,
8982                                         const char *csStart, unsigned csLen);
8983 
8984   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
8985                                          const char *startSpec,
8986                                          unsigned specifierLen);
8987 
8988   SourceRange getFormatStringRange();
8989   CharSourceRange getSpecifierRange(const char *startSpecifier,
8990                                     unsigned specifierLen);
8991   SourceLocation getLocationOfByte(const char *x);
8992 
8993   const Expr *getDataArg(unsigned i) const;
8994 
8995   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
8996                     const analyze_format_string::ConversionSpecifier &CS,
8997                     const char *startSpecifier, unsigned specifierLen,
8998                     unsigned argIndex);
8999 
9000   template <typename Range>
9001   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
9002                             bool IsStringLocation, Range StringRange,
9003                             ArrayRef<FixItHint> Fixit = None);
9004 };
9005 
9006 } // namespace
9007 
9008 SourceRange CheckFormatHandler::getFormatStringRange() {
9009   return OrigFormatExpr->getSourceRange();
9010 }
9011 
9012 CharSourceRange CheckFormatHandler::
9013 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
9014   SourceLocation Start = getLocationOfByte(startSpecifier);
9015   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
9016 
9017   // Advance the end SourceLocation by one due to half-open ranges.
9018   End = End.getLocWithOffset(1);
9019 
9020   return CharSourceRange::getCharRange(Start, End);
9021 }
9022 
9023 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
9024   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
9025                                   S.getLangOpts(), S.Context.getTargetInfo());
9026 }
9027 
9028 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
9029                                                    unsigned specifierLen){
9030   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
9031                        getLocationOfByte(startSpecifier),
9032                        /*IsStringLocation*/true,
9033                        getSpecifierRange(startSpecifier, specifierLen));
9034 }
9035 
9036 void CheckFormatHandler::HandleInvalidLengthModifier(
9037     const analyze_format_string::FormatSpecifier &FS,
9038     const analyze_format_string::ConversionSpecifier &CS,
9039     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
9040   using namespace analyze_format_string;
9041 
9042   const LengthModifier &LM = FS.getLengthModifier();
9043   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
9044 
9045   // See if we know how to fix this length modifier.
9046   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
9047   if (FixedLM) {
9048     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
9049                          getLocationOfByte(LM.getStart()),
9050                          /*IsStringLocation*/true,
9051                          getSpecifierRange(startSpecifier, specifierLen));
9052 
9053     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
9054       << FixedLM->toString()
9055       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
9056 
9057   } else {
9058     FixItHint Hint;
9059     if (DiagID == diag::warn_format_nonsensical_length)
9060       Hint = FixItHint::CreateRemoval(LMRange);
9061 
9062     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
9063                          getLocationOfByte(LM.getStart()),
9064                          /*IsStringLocation*/true,
9065                          getSpecifierRange(startSpecifier, specifierLen),
9066                          Hint);
9067   }
9068 }
9069 
9070 void CheckFormatHandler::HandleNonStandardLengthModifier(
9071     const analyze_format_string::FormatSpecifier &FS,
9072     const char *startSpecifier, unsigned specifierLen) {
9073   using namespace analyze_format_string;
9074 
9075   const LengthModifier &LM = FS.getLengthModifier();
9076   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
9077 
9078   // See if we know how to fix this length modifier.
9079   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
9080   if (FixedLM) {
9081     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
9082                            << LM.toString() << 0,
9083                          getLocationOfByte(LM.getStart()),
9084                          /*IsStringLocation*/true,
9085                          getSpecifierRange(startSpecifier, specifierLen));
9086 
9087     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
9088       << FixedLM->toString()
9089       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
9090 
9091   } else {
9092     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
9093                            << LM.toString() << 0,
9094                          getLocationOfByte(LM.getStart()),
9095                          /*IsStringLocation*/true,
9096                          getSpecifierRange(startSpecifier, specifierLen));
9097   }
9098 }
9099 
9100 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
9101     const analyze_format_string::ConversionSpecifier &CS,
9102     const char *startSpecifier, unsigned specifierLen) {
9103   using namespace analyze_format_string;
9104 
9105   // See if we know how to fix this conversion specifier.
9106   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
9107   if (FixedCS) {
9108     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
9109                           << CS.toString() << /*conversion specifier*/1,
9110                          getLocationOfByte(CS.getStart()),
9111                          /*IsStringLocation*/true,
9112                          getSpecifierRange(startSpecifier, specifierLen));
9113 
9114     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
9115     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
9116       << FixedCS->toString()
9117       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
9118   } else {
9119     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
9120                           << CS.toString() << /*conversion specifier*/1,
9121                          getLocationOfByte(CS.getStart()),
9122                          /*IsStringLocation*/true,
9123                          getSpecifierRange(startSpecifier, specifierLen));
9124   }
9125 }
9126 
9127 void CheckFormatHandler::HandlePosition(const char *startPos,
9128                                         unsigned posLen) {
9129   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
9130                                getLocationOfByte(startPos),
9131                                /*IsStringLocation*/true,
9132                                getSpecifierRange(startPos, posLen));
9133 }
9134 
9135 void
9136 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
9137                                      analyze_format_string::PositionContext p) {
9138   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
9139                          << (unsigned) p,
9140                        getLocationOfByte(startPos), /*IsStringLocation*/true,
9141                        getSpecifierRange(startPos, posLen));
9142 }
9143 
9144 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
9145                                             unsigned posLen) {
9146   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
9147                                getLocationOfByte(startPos),
9148                                /*IsStringLocation*/true,
9149                                getSpecifierRange(startPos, posLen));
9150 }
9151 
9152 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
9153   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
9154     // The presence of a null character is likely an error.
9155     EmitFormatDiagnostic(
9156       S.PDiag(diag::warn_printf_format_string_contains_null_char),
9157       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
9158       getFormatStringRange());
9159   }
9160 }
9161 
9162 // Note that this may return NULL if there was an error parsing or building
9163 // one of the argument expressions.
9164 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
9165   return Args[FirstDataArg + i];
9166 }
9167 
9168 void CheckFormatHandler::DoneProcessing() {
9169   // Does the number of data arguments exceed the number of
9170   // format conversions in the format string?
9171   if (ArgPassingKind != Sema::FAPK_VAList) {
9172     // Find any arguments that weren't covered.
9173     CoveredArgs.flip();
9174     signed notCoveredArg = CoveredArgs.find_first();
9175     if (notCoveredArg >= 0) {
9176       assert((unsigned)notCoveredArg < NumDataArgs);
9177       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
9178     } else {
9179       UncoveredArg.setAllCovered();
9180     }
9181   }
9182 }
9183 
9184 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
9185                                    const Expr *ArgExpr) {
9186   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
9187          "Invalid state");
9188 
9189   if (!ArgExpr)
9190     return;
9191 
9192   SourceLocation Loc = ArgExpr->getBeginLoc();
9193 
9194   if (S.getSourceManager().isInSystemMacro(Loc))
9195     return;
9196 
9197   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
9198   for (auto E : DiagnosticExprs)
9199     PDiag << E->getSourceRange();
9200 
9201   CheckFormatHandler::EmitFormatDiagnostic(
9202                                   S, IsFunctionCall, DiagnosticExprs[0],
9203                                   PDiag, Loc, /*IsStringLocation*/false,
9204                                   DiagnosticExprs[0]->getSourceRange());
9205 }
9206 
9207 bool
9208 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
9209                                                      SourceLocation Loc,
9210                                                      const char *startSpec,
9211                                                      unsigned specifierLen,
9212                                                      const char *csStart,
9213                                                      unsigned csLen) {
9214   bool keepGoing = true;
9215   if (argIndex < NumDataArgs) {
9216     // Consider the argument coverered, even though the specifier doesn't
9217     // make sense.
9218     CoveredArgs.set(argIndex);
9219   }
9220   else {
9221     // If argIndex exceeds the number of data arguments we
9222     // don't issue a warning because that is just a cascade of warnings (and
9223     // they may have intended '%%' anyway). We don't want to continue processing
9224     // the format string after this point, however, as we will like just get
9225     // gibberish when trying to match arguments.
9226     keepGoing = false;
9227   }
9228 
9229   StringRef Specifier(csStart, csLen);
9230 
9231   // If the specifier in non-printable, it could be the first byte of a UTF-8
9232   // sequence. In that case, print the UTF-8 code point. If not, print the byte
9233   // hex value.
9234   std::string CodePointStr;
9235   if (!llvm::sys::locale::isPrint(*csStart)) {
9236     llvm::UTF32 CodePoint;
9237     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
9238     const llvm::UTF8 *E =
9239         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
9240     llvm::ConversionResult Result =
9241         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
9242 
9243     if (Result != llvm::conversionOK) {
9244       unsigned char FirstChar = *csStart;
9245       CodePoint = (llvm::UTF32)FirstChar;
9246     }
9247 
9248     llvm::raw_string_ostream OS(CodePointStr);
9249     if (CodePoint < 256)
9250       OS << "\\x" << llvm::format("%02x", CodePoint);
9251     else if (CodePoint <= 0xFFFF)
9252       OS << "\\u" << llvm::format("%04x", CodePoint);
9253     else
9254       OS << "\\U" << llvm::format("%08x", CodePoint);
9255     OS.flush();
9256     Specifier = CodePointStr;
9257   }
9258 
9259   EmitFormatDiagnostic(
9260       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
9261       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
9262 
9263   return keepGoing;
9264 }
9265 
9266 void
9267 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
9268                                                       const char *startSpec,
9269                                                       unsigned specifierLen) {
9270   EmitFormatDiagnostic(
9271     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
9272     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
9273 }
9274 
9275 bool
9276 CheckFormatHandler::CheckNumArgs(
9277   const analyze_format_string::FormatSpecifier &FS,
9278   const analyze_format_string::ConversionSpecifier &CS,
9279   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
9280 
9281   if (argIndex >= NumDataArgs) {
9282     PartialDiagnostic PDiag = FS.usesPositionalArg()
9283       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
9284            << (argIndex+1) << NumDataArgs)
9285       : S.PDiag(diag::warn_printf_insufficient_data_args);
9286     EmitFormatDiagnostic(
9287       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
9288       getSpecifierRange(startSpecifier, specifierLen));
9289 
9290     // Since more arguments than conversion tokens are given, by extension
9291     // all arguments are covered, so mark this as so.
9292     UncoveredArg.setAllCovered();
9293     return false;
9294   }
9295   return true;
9296 }
9297 
9298 template<typename Range>
9299 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
9300                                               SourceLocation Loc,
9301                                               bool IsStringLocation,
9302                                               Range StringRange,
9303                                               ArrayRef<FixItHint> FixIt) {
9304   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
9305                        Loc, IsStringLocation, StringRange, FixIt);
9306 }
9307 
9308 /// If the format string is not within the function call, emit a note
9309 /// so that the function call and string are in diagnostic messages.
9310 ///
9311 /// \param InFunctionCall if true, the format string is within the function
9312 /// call and only one diagnostic message will be produced.  Otherwise, an
9313 /// extra note will be emitted pointing to location of the format string.
9314 ///
9315 /// \param ArgumentExpr the expression that is passed as the format string
9316 /// argument in the function call.  Used for getting locations when two
9317 /// diagnostics are emitted.
9318 ///
9319 /// \param PDiag the callee should already have provided any strings for the
9320 /// diagnostic message.  This function only adds locations and fixits
9321 /// to diagnostics.
9322 ///
9323 /// \param Loc primary location for diagnostic.  If two diagnostics are
9324 /// required, one will be at Loc and a new SourceLocation will be created for
9325 /// the other one.
9326 ///
9327 /// \param IsStringLocation if true, Loc points to the format string should be
9328 /// used for the note.  Otherwise, Loc points to the argument list and will
9329 /// be used with PDiag.
9330 ///
9331 /// \param StringRange some or all of the string to highlight.  This is
9332 /// templated so it can accept either a CharSourceRange or a SourceRange.
9333 ///
9334 /// \param FixIt optional fix it hint for the format string.
9335 template <typename Range>
9336 void CheckFormatHandler::EmitFormatDiagnostic(
9337     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
9338     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
9339     Range StringRange, ArrayRef<FixItHint> FixIt) {
9340   if (InFunctionCall) {
9341     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
9342     D << StringRange;
9343     D << FixIt;
9344   } else {
9345     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
9346       << ArgumentExpr->getSourceRange();
9347 
9348     const Sema::SemaDiagnosticBuilder &Note =
9349       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
9350              diag::note_format_string_defined);
9351 
9352     Note << StringRange;
9353     Note << FixIt;
9354   }
9355 }
9356 
9357 //===--- CHECK: Printf format string checking ------------------------------===//
9358 
9359 namespace {
9360 
9361 class CheckPrintfHandler : public CheckFormatHandler {
9362 public:
9363   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
9364                      const Expr *origFormatExpr,
9365                      const Sema::FormatStringType type, unsigned firstDataArg,
9366                      unsigned numDataArgs, bool isObjC, const char *beg,
9367                      Sema::FormatArgumentPassingKind APK,
9368                      ArrayRef<const Expr *> Args, unsigned formatIdx,
9369                      bool inFunctionCall, Sema::VariadicCallType CallType,
9370                      llvm::SmallBitVector &CheckedVarArgs,
9371                      UncoveredArgHandler &UncoveredArg)
9372       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
9373                            numDataArgs, beg, APK, Args, formatIdx,
9374                            inFunctionCall, CallType, CheckedVarArgs,
9375                            UncoveredArg) {}
9376 
9377   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
9378 
9379   /// Returns true if '%@' specifiers are allowed in the format string.
9380   bool allowsObjCArg() const {
9381     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
9382            FSType == Sema::FST_OSTrace;
9383   }
9384 
9385   bool HandleInvalidPrintfConversionSpecifier(
9386                                       const analyze_printf::PrintfSpecifier &FS,
9387                                       const char *startSpecifier,
9388                                       unsigned specifierLen) override;
9389 
9390   void handleInvalidMaskType(StringRef MaskType) override;
9391 
9392   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
9393                              const char *startSpecifier, unsigned specifierLen,
9394                              const TargetInfo &Target) override;
9395   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
9396                        const char *StartSpecifier,
9397                        unsigned SpecifierLen,
9398                        const Expr *E);
9399 
9400   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
9401                     const char *startSpecifier, unsigned specifierLen);
9402   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
9403                            const analyze_printf::OptionalAmount &Amt,
9404                            unsigned type,
9405                            const char *startSpecifier, unsigned specifierLen);
9406   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
9407                   const analyze_printf::OptionalFlag &flag,
9408                   const char *startSpecifier, unsigned specifierLen);
9409   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
9410                          const analyze_printf::OptionalFlag &ignoredFlag,
9411                          const analyze_printf::OptionalFlag &flag,
9412                          const char *startSpecifier, unsigned specifierLen);
9413   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
9414                            const Expr *E);
9415 
9416   void HandleEmptyObjCModifierFlag(const char *startFlag,
9417                                    unsigned flagLen) override;
9418 
9419   void HandleInvalidObjCModifierFlag(const char *startFlag,
9420                                             unsigned flagLen) override;
9421 
9422   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
9423                                            const char *flagsEnd,
9424                                            const char *conversionPosition)
9425                                              override;
9426 };
9427 
9428 } // namespace
9429 
9430 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
9431                                       const analyze_printf::PrintfSpecifier &FS,
9432                                       const char *startSpecifier,
9433                                       unsigned specifierLen) {
9434   const analyze_printf::PrintfConversionSpecifier &CS =
9435     FS.getConversionSpecifier();
9436 
9437   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
9438                                           getLocationOfByte(CS.getStart()),
9439                                           startSpecifier, specifierLen,
9440                                           CS.getStart(), CS.getLength());
9441 }
9442 
9443 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
9444   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
9445 }
9446 
9447 bool CheckPrintfHandler::HandleAmount(
9448     const analyze_format_string::OptionalAmount &Amt, unsigned k,
9449     const char *startSpecifier, unsigned specifierLen) {
9450   if (Amt.hasDataArgument()) {
9451     if (ArgPassingKind != Sema::FAPK_VAList) {
9452       unsigned argIndex = Amt.getArgIndex();
9453       if (argIndex >= NumDataArgs) {
9454         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
9455                                  << k,
9456                              getLocationOfByte(Amt.getStart()),
9457                              /*IsStringLocation*/ true,
9458                              getSpecifierRange(startSpecifier, specifierLen));
9459         // Don't do any more checking.  We will just emit
9460         // spurious errors.
9461         return false;
9462       }
9463 
9464       // Type check the data argument.  It should be an 'int'.
9465       // Although not in conformance with C99, we also allow the argument to be
9466       // an 'unsigned int' as that is a reasonably safe case.  GCC also
9467       // doesn't emit a warning for that case.
9468       CoveredArgs.set(argIndex);
9469       const Expr *Arg = getDataArg(argIndex);
9470       if (!Arg)
9471         return false;
9472 
9473       QualType T = Arg->getType();
9474 
9475       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
9476       assert(AT.isValid());
9477 
9478       if (!AT.matchesType(S.Context, T)) {
9479         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
9480                                << k << AT.getRepresentativeTypeName(S.Context)
9481                                << T << Arg->getSourceRange(),
9482                              getLocationOfByte(Amt.getStart()),
9483                              /*IsStringLocation*/true,
9484                              getSpecifierRange(startSpecifier, specifierLen));
9485         // Don't do any more checking.  We will just emit
9486         // spurious errors.
9487         return false;
9488       }
9489     }
9490   }
9491   return true;
9492 }
9493 
9494 void CheckPrintfHandler::HandleInvalidAmount(
9495                                       const analyze_printf::PrintfSpecifier &FS,
9496                                       const analyze_printf::OptionalAmount &Amt,
9497                                       unsigned type,
9498                                       const char *startSpecifier,
9499                                       unsigned specifierLen) {
9500   const analyze_printf::PrintfConversionSpecifier &CS =
9501     FS.getConversionSpecifier();
9502 
9503   FixItHint fixit =
9504     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
9505       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
9506                                  Amt.getConstantLength()))
9507       : FixItHint();
9508 
9509   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
9510                          << type << CS.toString(),
9511                        getLocationOfByte(Amt.getStart()),
9512                        /*IsStringLocation*/true,
9513                        getSpecifierRange(startSpecifier, specifierLen),
9514                        fixit);
9515 }
9516 
9517 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
9518                                     const analyze_printf::OptionalFlag &flag,
9519                                     const char *startSpecifier,
9520                                     unsigned specifierLen) {
9521   // Warn about pointless flag with a fixit removal.
9522   const analyze_printf::PrintfConversionSpecifier &CS =
9523     FS.getConversionSpecifier();
9524   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
9525                          << flag.toString() << CS.toString(),
9526                        getLocationOfByte(flag.getPosition()),
9527                        /*IsStringLocation*/true,
9528                        getSpecifierRange(startSpecifier, specifierLen),
9529                        FixItHint::CreateRemoval(
9530                          getSpecifierRange(flag.getPosition(), 1)));
9531 }
9532 
9533 void CheckPrintfHandler::HandleIgnoredFlag(
9534                                 const analyze_printf::PrintfSpecifier &FS,
9535                                 const analyze_printf::OptionalFlag &ignoredFlag,
9536                                 const analyze_printf::OptionalFlag &flag,
9537                                 const char *startSpecifier,
9538                                 unsigned specifierLen) {
9539   // Warn about ignored flag with a fixit removal.
9540   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
9541                          << ignoredFlag.toString() << flag.toString(),
9542                        getLocationOfByte(ignoredFlag.getPosition()),
9543                        /*IsStringLocation*/true,
9544                        getSpecifierRange(startSpecifier, specifierLen),
9545                        FixItHint::CreateRemoval(
9546                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
9547 }
9548 
9549 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
9550                                                      unsigned flagLen) {
9551   // Warn about an empty flag.
9552   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
9553                        getLocationOfByte(startFlag),
9554                        /*IsStringLocation*/true,
9555                        getSpecifierRange(startFlag, flagLen));
9556 }
9557 
9558 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
9559                                                        unsigned flagLen) {
9560   // Warn about an invalid flag.
9561   auto Range = getSpecifierRange(startFlag, flagLen);
9562   StringRef flag(startFlag, flagLen);
9563   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
9564                       getLocationOfByte(startFlag),
9565                       /*IsStringLocation*/true,
9566                       Range, FixItHint::CreateRemoval(Range));
9567 }
9568 
9569 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
9570     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
9571     // Warn about using '[...]' without a '@' conversion.
9572     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
9573     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
9574     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
9575                          getLocationOfByte(conversionPosition),
9576                          /*IsStringLocation*/true,
9577                          Range, FixItHint::CreateRemoval(Range));
9578 }
9579 
9580 // Determines if the specified is a C++ class or struct containing
9581 // a member with the specified name and kind (e.g. a CXXMethodDecl named
9582 // "c_str()").
9583 template<typename MemberKind>
9584 static llvm::SmallPtrSet<MemberKind*, 1>
9585 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
9586   const RecordType *RT = Ty->getAs<RecordType>();
9587   llvm::SmallPtrSet<MemberKind*, 1> Results;
9588 
9589   if (!RT)
9590     return Results;
9591   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
9592   if (!RD || !RD->getDefinition())
9593     return Results;
9594 
9595   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
9596                  Sema::LookupMemberName);
9597   R.suppressDiagnostics();
9598 
9599   // We just need to include all members of the right kind turned up by the
9600   // filter, at this point.
9601   if (S.LookupQualifiedName(R, RT->getDecl()))
9602     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
9603       NamedDecl *decl = (*I)->getUnderlyingDecl();
9604       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
9605         Results.insert(FK);
9606     }
9607   return Results;
9608 }
9609 
9610 /// Check if we could call '.c_str()' on an object.
9611 ///
9612 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
9613 /// allow the call, or if it would be ambiguous).
9614 bool Sema::hasCStrMethod(const Expr *E) {
9615   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
9616 
9617   MethodSet Results =
9618       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
9619   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
9620        MI != ME; ++MI)
9621     if ((*MI)->getMinRequiredArguments() == 0)
9622       return true;
9623   return false;
9624 }
9625 
9626 // Check if a (w)string was passed when a (w)char* was needed, and offer a
9627 // better diagnostic if so. AT is assumed to be valid.
9628 // Returns true when a c_str() conversion method is found.
9629 bool CheckPrintfHandler::checkForCStrMembers(
9630     const analyze_printf::ArgType &AT, const Expr *E) {
9631   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
9632 
9633   MethodSet Results =
9634       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
9635 
9636   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
9637        MI != ME; ++MI) {
9638     const CXXMethodDecl *Method = *MI;
9639     if (Method->getMinRequiredArguments() == 0 &&
9640         AT.matchesType(S.Context, Method->getReturnType())) {
9641       // FIXME: Suggest parens if the expression needs them.
9642       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
9643       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
9644           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
9645       return true;
9646     }
9647   }
9648 
9649   return false;
9650 }
9651 
9652 bool CheckPrintfHandler::HandlePrintfSpecifier(
9653     const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
9654     unsigned specifierLen, const TargetInfo &Target) {
9655   using namespace analyze_format_string;
9656   using namespace analyze_printf;
9657 
9658   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
9659 
9660   if (FS.consumesDataArgument()) {
9661     if (atFirstArg) {
9662         atFirstArg = false;
9663         usesPositionalArgs = FS.usesPositionalArg();
9664     }
9665     else if (usesPositionalArgs != FS.usesPositionalArg()) {
9666       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9667                                         startSpecifier, specifierLen);
9668       return false;
9669     }
9670   }
9671 
9672   // First check if the field width, precision, and conversion specifier
9673   // have matching data arguments.
9674   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
9675                     startSpecifier, specifierLen)) {
9676     return false;
9677   }
9678 
9679   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
9680                     startSpecifier, specifierLen)) {
9681     return false;
9682   }
9683 
9684   if (!CS.consumesDataArgument()) {
9685     // FIXME: Technically specifying a precision or field width here
9686     // makes no sense.  Worth issuing a warning at some point.
9687     return true;
9688   }
9689 
9690   // Consume the argument.
9691   unsigned argIndex = FS.getArgIndex();
9692   if (argIndex < NumDataArgs) {
9693     // The check to see if the argIndex is valid will come later.
9694     // We set the bit here because we may exit early from this
9695     // function if we encounter some other error.
9696     CoveredArgs.set(argIndex);
9697   }
9698 
9699   // FreeBSD kernel extensions.
9700   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
9701       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
9702     // We need at least two arguments.
9703     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
9704       return false;
9705 
9706     // Claim the second argument.
9707     CoveredArgs.set(argIndex + 1);
9708 
9709     // Type check the first argument (int for %b, pointer for %D)
9710     const Expr *Ex = getDataArg(argIndex);
9711     const analyze_printf::ArgType &AT =
9712       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
9713         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
9714     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
9715       EmitFormatDiagnostic(
9716           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9717               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
9718               << false << Ex->getSourceRange(),
9719           Ex->getBeginLoc(), /*IsStringLocation*/ false,
9720           getSpecifierRange(startSpecifier, specifierLen));
9721 
9722     // Type check the second argument (char * for both %b and %D)
9723     Ex = getDataArg(argIndex + 1);
9724     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
9725     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
9726       EmitFormatDiagnostic(
9727           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9728               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
9729               << false << Ex->getSourceRange(),
9730           Ex->getBeginLoc(), /*IsStringLocation*/ false,
9731           getSpecifierRange(startSpecifier, specifierLen));
9732 
9733      return true;
9734   }
9735 
9736   // Check for using an Objective-C specific conversion specifier
9737   // in a non-ObjC literal.
9738   if (!allowsObjCArg() && CS.isObjCArg()) {
9739     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9740                                                   specifierLen);
9741   }
9742 
9743   // %P can only be used with os_log.
9744   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
9745     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9746                                                   specifierLen);
9747   }
9748 
9749   // %n is not allowed with os_log.
9750   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
9751     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
9752                          getLocationOfByte(CS.getStart()),
9753                          /*IsStringLocation*/ false,
9754                          getSpecifierRange(startSpecifier, specifierLen));
9755 
9756     return true;
9757   }
9758 
9759   // Only scalars are allowed for os_trace.
9760   if (FSType == Sema::FST_OSTrace &&
9761       (CS.getKind() == ConversionSpecifier::PArg ||
9762        CS.getKind() == ConversionSpecifier::sArg ||
9763        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
9764     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9765                                                   specifierLen);
9766   }
9767 
9768   // Check for use of public/private annotation outside of os_log().
9769   if (FSType != Sema::FST_OSLog) {
9770     if (FS.isPublic().isSet()) {
9771       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
9772                                << "public",
9773                            getLocationOfByte(FS.isPublic().getPosition()),
9774                            /*IsStringLocation*/ false,
9775                            getSpecifierRange(startSpecifier, specifierLen));
9776     }
9777     if (FS.isPrivate().isSet()) {
9778       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
9779                                << "private",
9780                            getLocationOfByte(FS.isPrivate().getPosition()),
9781                            /*IsStringLocation*/ false,
9782                            getSpecifierRange(startSpecifier, specifierLen));
9783     }
9784   }
9785 
9786   const llvm::Triple &Triple = Target.getTriple();
9787   if (CS.getKind() == ConversionSpecifier::nArg &&
9788       (Triple.isAndroid() || Triple.isOSFuchsia())) {
9789     EmitFormatDiagnostic(S.PDiag(diag::warn_printf_narg_not_supported),
9790                          getLocationOfByte(CS.getStart()),
9791                          /*IsStringLocation*/ false,
9792                          getSpecifierRange(startSpecifier, specifierLen));
9793   }
9794 
9795   // Check for invalid use of field width
9796   if (!FS.hasValidFieldWidth()) {
9797     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
9798         startSpecifier, specifierLen);
9799   }
9800 
9801   // Check for invalid use of precision
9802   if (!FS.hasValidPrecision()) {
9803     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
9804         startSpecifier, specifierLen);
9805   }
9806 
9807   // Precision is mandatory for %P specifier.
9808   if (CS.getKind() == ConversionSpecifier::PArg &&
9809       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
9810     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
9811                          getLocationOfByte(startSpecifier),
9812                          /*IsStringLocation*/ false,
9813                          getSpecifierRange(startSpecifier, specifierLen));
9814   }
9815 
9816   // Check each flag does not conflict with any other component.
9817   if (!FS.hasValidThousandsGroupingPrefix())
9818     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
9819   if (!FS.hasValidLeadingZeros())
9820     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
9821   if (!FS.hasValidPlusPrefix())
9822     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
9823   if (!FS.hasValidSpacePrefix())
9824     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
9825   if (!FS.hasValidAlternativeForm())
9826     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
9827   if (!FS.hasValidLeftJustified())
9828     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
9829 
9830   // Check that flags are not ignored by another flag
9831   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
9832     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
9833         startSpecifier, specifierLen);
9834   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
9835     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
9836             startSpecifier, specifierLen);
9837 
9838   // Check the length modifier is valid with the given conversion specifier.
9839   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
9840                                  S.getLangOpts()))
9841     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9842                                 diag::warn_format_nonsensical_length);
9843   else if (!FS.hasStandardLengthModifier())
9844     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9845   else if (!FS.hasStandardLengthConversionCombination())
9846     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9847                                 diag::warn_format_non_standard_conversion_spec);
9848 
9849   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
9850     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9851 
9852   // The remaining checks depend on the data arguments.
9853   if (ArgPassingKind == Sema::FAPK_VAList)
9854     return true;
9855 
9856   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9857     return false;
9858 
9859   const Expr *Arg = getDataArg(argIndex);
9860   if (!Arg)
9861     return true;
9862 
9863   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
9864 }
9865 
9866 static bool requiresParensToAddCast(const Expr *E) {
9867   // FIXME: We should have a general way to reason about operator
9868   // precedence and whether parens are actually needed here.
9869   // Take care of a few common cases where they aren't.
9870   const Expr *Inside = E->IgnoreImpCasts();
9871   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
9872     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
9873 
9874   switch (Inside->getStmtClass()) {
9875   case Stmt::ArraySubscriptExprClass:
9876   case Stmt::CallExprClass:
9877   case Stmt::CharacterLiteralClass:
9878   case Stmt::CXXBoolLiteralExprClass:
9879   case Stmt::DeclRefExprClass:
9880   case Stmt::FloatingLiteralClass:
9881   case Stmt::IntegerLiteralClass:
9882   case Stmt::MemberExprClass:
9883   case Stmt::ObjCArrayLiteralClass:
9884   case Stmt::ObjCBoolLiteralExprClass:
9885   case Stmt::ObjCBoxedExprClass:
9886   case Stmt::ObjCDictionaryLiteralClass:
9887   case Stmt::ObjCEncodeExprClass:
9888   case Stmt::ObjCIvarRefExprClass:
9889   case Stmt::ObjCMessageExprClass:
9890   case Stmt::ObjCPropertyRefExprClass:
9891   case Stmt::ObjCStringLiteralClass:
9892   case Stmt::ObjCSubscriptRefExprClass:
9893   case Stmt::ParenExprClass:
9894   case Stmt::StringLiteralClass:
9895   case Stmt::UnaryOperatorClass:
9896     return false;
9897   default:
9898     return true;
9899   }
9900 }
9901 
9902 static std::pair<QualType, StringRef>
9903 shouldNotPrintDirectly(const ASTContext &Context,
9904                        QualType IntendedTy,
9905                        const Expr *E) {
9906   // Use a 'while' to peel off layers of typedefs.
9907   QualType TyTy = IntendedTy;
9908   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
9909     StringRef Name = UserTy->getDecl()->getName();
9910     QualType CastTy = llvm::StringSwitch<QualType>(Name)
9911       .Case("CFIndex", Context.getNSIntegerType())
9912       .Case("NSInteger", Context.getNSIntegerType())
9913       .Case("NSUInteger", Context.getNSUIntegerType())
9914       .Case("SInt32", Context.IntTy)
9915       .Case("UInt32", Context.UnsignedIntTy)
9916       .Default(QualType());
9917 
9918     if (!CastTy.isNull())
9919       return std::make_pair(CastTy, Name);
9920 
9921     TyTy = UserTy->desugar();
9922   }
9923 
9924   // Strip parens if necessary.
9925   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
9926     return shouldNotPrintDirectly(Context,
9927                                   PE->getSubExpr()->getType(),
9928                                   PE->getSubExpr());
9929 
9930   // If this is a conditional expression, then its result type is constructed
9931   // via usual arithmetic conversions and thus there might be no necessary
9932   // typedef sugar there.  Recurse to operands to check for NSInteger &
9933   // Co. usage condition.
9934   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9935     QualType TrueTy, FalseTy;
9936     StringRef TrueName, FalseName;
9937 
9938     std::tie(TrueTy, TrueName) =
9939       shouldNotPrintDirectly(Context,
9940                              CO->getTrueExpr()->getType(),
9941                              CO->getTrueExpr());
9942     std::tie(FalseTy, FalseName) =
9943       shouldNotPrintDirectly(Context,
9944                              CO->getFalseExpr()->getType(),
9945                              CO->getFalseExpr());
9946 
9947     if (TrueTy == FalseTy)
9948       return std::make_pair(TrueTy, TrueName);
9949     else if (TrueTy.isNull())
9950       return std::make_pair(FalseTy, FalseName);
9951     else if (FalseTy.isNull())
9952       return std::make_pair(TrueTy, TrueName);
9953   }
9954 
9955   return std::make_pair(QualType(), StringRef());
9956 }
9957 
9958 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
9959 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
9960 /// type do not count.
9961 static bool
9962 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
9963   QualType From = ICE->getSubExpr()->getType();
9964   QualType To = ICE->getType();
9965   // It's an integer promotion if the destination type is the promoted
9966   // source type.
9967   if (ICE->getCastKind() == CK_IntegralCast &&
9968       From->isPromotableIntegerType() &&
9969       S.Context.getPromotedIntegerType(From) == To)
9970     return true;
9971   // Look through vector types, since we do default argument promotion for
9972   // those in OpenCL.
9973   if (const auto *VecTy = From->getAs<ExtVectorType>())
9974     From = VecTy->getElementType();
9975   if (const auto *VecTy = To->getAs<ExtVectorType>())
9976     To = VecTy->getElementType();
9977   // It's a floating promotion if the source type is a lower rank.
9978   return ICE->getCastKind() == CK_FloatingCast &&
9979          S.Context.getFloatingTypeOrder(From, To) < 0;
9980 }
9981 
9982 bool
9983 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
9984                                     const char *StartSpecifier,
9985                                     unsigned SpecifierLen,
9986                                     const Expr *E) {
9987   using namespace analyze_format_string;
9988   using namespace analyze_printf;
9989 
9990   // Now type check the data expression that matches the
9991   // format specifier.
9992   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
9993   if (!AT.isValid())
9994     return true;
9995 
9996   QualType ExprTy = E->getType();
9997   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
9998     ExprTy = TET->getUnderlyingExpr()->getType();
9999   }
10000 
10001   // When using the format attribute in C++, you can receive a function or an
10002   // array that will necessarily decay to a pointer when passed to the final
10003   // format consumer. Apply decay before type comparison.
10004   if (ExprTy->canDecayToPointerType())
10005     ExprTy = S.Context.getDecayedType(ExprTy);
10006 
10007   // Diagnose attempts to print a boolean value as a character. Unlike other
10008   // -Wformat diagnostics, this is fine from a type perspective, but it still
10009   // doesn't make sense.
10010   if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
10011       E->isKnownToHaveBooleanValue()) {
10012     const CharSourceRange &CSR =
10013         getSpecifierRange(StartSpecifier, SpecifierLen);
10014     SmallString<4> FSString;
10015     llvm::raw_svector_ostream os(FSString);
10016     FS.toString(os);
10017     EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
10018                              << FSString,
10019                          E->getExprLoc(), false, CSR);
10020     return true;
10021   }
10022 
10023   analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
10024   if (Match == analyze_printf::ArgType::Match)
10025     return true;
10026 
10027   // Look through argument promotions for our error message's reported type.
10028   // This includes the integral and floating promotions, but excludes array
10029   // and function pointer decay (seeing that an argument intended to be a
10030   // string has type 'char [6]' is probably more confusing than 'char *') and
10031   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
10032   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
10033     if (isArithmeticArgumentPromotion(S, ICE)) {
10034       E = ICE->getSubExpr();
10035       ExprTy = E->getType();
10036 
10037       // Check if we didn't match because of an implicit cast from a 'char'
10038       // or 'short' to an 'int'.  This is done because printf is a varargs
10039       // function.
10040       if (ICE->getType() == S.Context.IntTy ||
10041           ICE->getType() == S.Context.UnsignedIntTy) {
10042         // All further checking is done on the subexpression
10043         const analyze_printf::ArgType::MatchKind ImplicitMatch =
10044             AT.matchesType(S.Context, ExprTy);
10045         if (ImplicitMatch == analyze_printf::ArgType::Match)
10046           return true;
10047         if (ImplicitMatch == ArgType::NoMatchPedantic ||
10048             ImplicitMatch == ArgType::NoMatchTypeConfusion)
10049           Match = ImplicitMatch;
10050       }
10051     }
10052   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
10053     // Special case for 'a', which has type 'int' in C.
10054     // Note, however, that we do /not/ want to treat multibyte constants like
10055     // 'MooV' as characters! This form is deprecated but still exists. In
10056     // addition, don't treat expressions as of type 'char' if one byte length
10057     // modifier is provided.
10058     if (ExprTy == S.Context.IntTy &&
10059         FS.getLengthModifier().getKind() != LengthModifier::AsChar)
10060       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
10061         ExprTy = S.Context.CharTy;
10062   }
10063 
10064   // Look through enums to their underlying type.
10065   bool IsEnum = false;
10066   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
10067     ExprTy = EnumTy->getDecl()->getIntegerType();
10068     IsEnum = true;
10069   }
10070 
10071   // %C in an Objective-C context prints a unichar, not a wchar_t.
10072   // If the argument is an integer of some kind, believe the %C and suggest
10073   // a cast instead of changing the conversion specifier.
10074   QualType IntendedTy = ExprTy;
10075   if (isObjCContext() &&
10076       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
10077     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
10078         !ExprTy->isCharType()) {
10079       // 'unichar' is defined as a typedef of unsigned short, but we should
10080       // prefer using the typedef if it is visible.
10081       IntendedTy = S.Context.UnsignedShortTy;
10082 
10083       // While we are here, check if the value is an IntegerLiteral that happens
10084       // to be within the valid range.
10085       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
10086         const llvm::APInt &V = IL->getValue();
10087         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
10088           return true;
10089       }
10090 
10091       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
10092                           Sema::LookupOrdinaryName);
10093       if (S.LookupName(Result, S.getCurScope())) {
10094         NamedDecl *ND = Result.getFoundDecl();
10095         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
10096           if (TD->getUnderlyingType() == IntendedTy)
10097             IntendedTy = S.Context.getTypedefType(TD);
10098       }
10099     }
10100   }
10101 
10102   // Special-case some of Darwin's platform-independence types by suggesting
10103   // casts to primitive types that are known to be large enough.
10104   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
10105   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
10106     QualType CastTy;
10107     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
10108     if (!CastTy.isNull()) {
10109       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
10110       // (long in ASTContext). Only complain to pedants.
10111       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
10112           (AT.isSizeT() || AT.isPtrdiffT()) &&
10113           AT.matchesType(S.Context, CastTy))
10114         Match = ArgType::NoMatchPedantic;
10115       IntendedTy = CastTy;
10116       ShouldNotPrintDirectly = true;
10117     }
10118   }
10119 
10120   // We may be able to offer a FixItHint if it is a supported type.
10121   PrintfSpecifier fixedFS = FS;
10122   bool Success =
10123       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
10124 
10125   if (Success) {
10126     // Get the fix string from the fixed format specifier
10127     SmallString<16> buf;
10128     llvm::raw_svector_ostream os(buf);
10129     fixedFS.toString(os);
10130 
10131     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
10132 
10133     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
10134       unsigned Diag;
10135       switch (Match) {
10136       case ArgType::Match: llvm_unreachable("expected non-matching");
10137       case ArgType::NoMatchPedantic:
10138         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
10139         break;
10140       case ArgType::NoMatchTypeConfusion:
10141         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
10142         break;
10143       case ArgType::NoMatch:
10144         Diag = diag::warn_format_conversion_argument_type_mismatch;
10145         break;
10146       }
10147 
10148       // In this case, the specifier is wrong and should be changed to match
10149       // the argument.
10150       EmitFormatDiagnostic(S.PDiag(Diag)
10151                                << AT.getRepresentativeTypeName(S.Context)
10152                                << IntendedTy << IsEnum << E->getSourceRange(),
10153                            E->getBeginLoc(),
10154                            /*IsStringLocation*/ false, SpecRange,
10155                            FixItHint::CreateReplacement(SpecRange, os.str()));
10156     } else {
10157       // The canonical type for formatting this value is different from the
10158       // actual type of the expression. (This occurs, for example, with Darwin's
10159       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
10160       // should be printed as 'long' for 64-bit compatibility.)
10161       // Rather than emitting a normal format/argument mismatch, we want to
10162       // add a cast to the recommended type (and correct the format string
10163       // if necessary).
10164       SmallString<16> CastBuf;
10165       llvm::raw_svector_ostream CastFix(CastBuf);
10166       CastFix << "(";
10167       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
10168       CastFix << ")";
10169 
10170       SmallVector<FixItHint,4> Hints;
10171       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
10172         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
10173 
10174       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
10175         // If there's already a cast present, just replace it.
10176         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
10177         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
10178 
10179       } else if (!requiresParensToAddCast(E)) {
10180         // If the expression has high enough precedence,
10181         // just write the C-style cast.
10182         Hints.push_back(
10183             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
10184       } else {
10185         // Otherwise, add parens around the expression as well as the cast.
10186         CastFix << "(";
10187         Hints.push_back(
10188             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
10189 
10190         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
10191         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
10192       }
10193 
10194       if (ShouldNotPrintDirectly) {
10195         // The expression has a type that should not be printed directly.
10196         // We extract the name from the typedef because we don't want to show
10197         // the underlying type in the diagnostic.
10198         StringRef Name;
10199         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
10200           Name = TypedefTy->getDecl()->getName();
10201         else
10202           Name = CastTyName;
10203         unsigned Diag = Match == ArgType::NoMatchPedantic
10204                             ? diag::warn_format_argument_needs_cast_pedantic
10205                             : diag::warn_format_argument_needs_cast;
10206         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
10207                                            << E->getSourceRange(),
10208                              E->getBeginLoc(), /*IsStringLocation=*/false,
10209                              SpecRange, Hints);
10210       } else {
10211         // In this case, the expression could be printed using a different
10212         // specifier, but we've decided that the specifier is probably correct
10213         // and we should cast instead. Just use the normal warning message.
10214         EmitFormatDiagnostic(
10215             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
10216                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
10217                 << E->getSourceRange(),
10218             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
10219       }
10220     }
10221   } else {
10222     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
10223                                                    SpecifierLen);
10224     // Since the warning for passing non-POD types to variadic functions
10225     // was deferred until now, we emit a warning for non-POD
10226     // arguments here.
10227     bool EmitTypeMismatch = false;
10228     switch (S.isValidVarArgType(ExprTy)) {
10229     case Sema::VAK_Valid:
10230     case Sema::VAK_ValidInCXX11: {
10231       unsigned Diag;
10232       switch (Match) {
10233       case ArgType::Match: llvm_unreachable("expected non-matching");
10234       case ArgType::NoMatchPedantic:
10235         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
10236         break;
10237       case ArgType::NoMatchTypeConfusion:
10238         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
10239         break;
10240       case ArgType::NoMatch:
10241         Diag = diag::warn_format_conversion_argument_type_mismatch;
10242         break;
10243       }
10244 
10245       EmitFormatDiagnostic(
10246           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
10247                         << IsEnum << CSR << E->getSourceRange(),
10248           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
10249       break;
10250     }
10251     case Sema::VAK_Undefined:
10252     case Sema::VAK_MSVCUndefined:
10253       if (CallType == Sema::VariadicDoesNotApply) {
10254         EmitTypeMismatch = true;
10255       } else {
10256         EmitFormatDiagnostic(
10257             S.PDiag(diag::warn_non_pod_vararg_with_format_string)
10258                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
10259                 << AT.getRepresentativeTypeName(S.Context) << CSR
10260                 << E->getSourceRange(),
10261             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
10262         checkForCStrMembers(AT, E);
10263       }
10264       break;
10265 
10266     case Sema::VAK_Invalid:
10267       if (CallType == Sema::VariadicDoesNotApply)
10268         EmitTypeMismatch = true;
10269       else if (ExprTy->isObjCObjectType())
10270         EmitFormatDiagnostic(
10271             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
10272                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
10273                 << AT.getRepresentativeTypeName(S.Context) << CSR
10274                 << E->getSourceRange(),
10275             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
10276       else
10277         // FIXME: If this is an initializer list, suggest removing the braces
10278         // or inserting a cast to the target type.
10279         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
10280             << isa<InitListExpr>(E) << ExprTy << CallType
10281             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
10282       break;
10283     }
10284 
10285     if (EmitTypeMismatch) {
10286       // The function is not variadic, so we do not generate warnings about
10287       // being allowed to pass that object as a variadic argument. Instead,
10288       // since there are inherently no printf specifiers for types which cannot
10289       // be passed as variadic arguments, emit a plain old specifier mismatch
10290       // argument.
10291       EmitFormatDiagnostic(
10292           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
10293               << AT.getRepresentativeTypeName(S.Context) << ExprTy << false
10294               << E->getSourceRange(),
10295           E->getBeginLoc(), false, CSR);
10296     }
10297 
10298     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
10299            "format string specifier index out of range");
10300     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
10301   }
10302 
10303   return true;
10304 }
10305 
10306 //===--- CHECK: Scanf format string checking ------------------------------===//
10307 
10308 namespace {
10309 
10310 class CheckScanfHandler : public CheckFormatHandler {
10311 public:
10312   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
10313                     const Expr *origFormatExpr, Sema::FormatStringType type,
10314                     unsigned firstDataArg, unsigned numDataArgs,
10315                     const char *beg, Sema::FormatArgumentPassingKind APK,
10316                     ArrayRef<const Expr *> Args, unsigned formatIdx,
10317                     bool inFunctionCall, Sema::VariadicCallType CallType,
10318                     llvm::SmallBitVector &CheckedVarArgs,
10319                     UncoveredArgHandler &UncoveredArg)
10320       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
10321                            numDataArgs, beg, APK, Args, formatIdx,
10322                            inFunctionCall, CallType, CheckedVarArgs,
10323                            UncoveredArg) {}
10324 
10325   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
10326                             const char *startSpecifier,
10327                             unsigned specifierLen) override;
10328 
10329   bool HandleInvalidScanfConversionSpecifier(
10330           const analyze_scanf::ScanfSpecifier &FS,
10331           const char *startSpecifier,
10332           unsigned specifierLen) override;
10333 
10334   void HandleIncompleteScanList(const char *start, const char *end) override;
10335 };
10336 
10337 } // namespace
10338 
10339 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
10340                                                  const char *end) {
10341   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
10342                        getLocationOfByte(end), /*IsStringLocation*/true,
10343                        getSpecifierRange(start, end - start));
10344 }
10345 
10346 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
10347                                         const analyze_scanf::ScanfSpecifier &FS,
10348                                         const char *startSpecifier,
10349                                         unsigned specifierLen) {
10350   const analyze_scanf::ScanfConversionSpecifier &CS =
10351     FS.getConversionSpecifier();
10352 
10353   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
10354                                           getLocationOfByte(CS.getStart()),
10355                                           startSpecifier, specifierLen,
10356                                           CS.getStart(), CS.getLength());
10357 }
10358 
10359 bool CheckScanfHandler::HandleScanfSpecifier(
10360                                        const analyze_scanf::ScanfSpecifier &FS,
10361                                        const char *startSpecifier,
10362                                        unsigned specifierLen) {
10363   using namespace analyze_scanf;
10364   using namespace analyze_format_string;
10365 
10366   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
10367 
10368   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
10369   // be used to decide if we are using positional arguments consistently.
10370   if (FS.consumesDataArgument()) {
10371     if (atFirstArg) {
10372       atFirstArg = false;
10373       usesPositionalArgs = FS.usesPositionalArg();
10374     }
10375     else if (usesPositionalArgs != FS.usesPositionalArg()) {
10376       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
10377                                         startSpecifier, specifierLen);
10378       return false;
10379     }
10380   }
10381 
10382   // Check if the field with is non-zero.
10383   const OptionalAmount &Amt = FS.getFieldWidth();
10384   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
10385     if (Amt.getConstantAmount() == 0) {
10386       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
10387                                                    Amt.getConstantLength());
10388       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
10389                            getLocationOfByte(Amt.getStart()),
10390                            /*IsStringLocation*/true, R,
10391                            FixItHint::CreateRemoval(R));
10392     }
10393   }
10394 
10395   if (!FS.consumesDataArgument()) {
10396     // FIXME: Technically specifying a precision or field width here
10397     // makes no sense.  Worth issuing a warning at some point.
10398     return true;
10399   }
10400 
10401   // Consume the argument.
10402   unsigned argIndex = FS.getArgIndex();
10403   if (argIndex < NumDataArgs) {
10404       // The check to see if the argIndex is valid will come later.
10405       // We set the bit here because we may exit early from this
10406       // function if we encounter some other error.
10407     CoveredArgs.set(argIndex);
10408   }
10409 
10410   // Check the length modifier is valid with the given conversion specifier.
10411   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
10412                                  S.getLangOpts()))
10413     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
10414                                 diag::warn_format_nonsensical_length);
10415   else if (!FS.hasStandardLengthModifier())
10416     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
10417   else if (!FS.hasStandardLengthConversionCombination())
10418     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
10419                                 diag::warn_format_non_standard_conversion_spec);
10420 
10421   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
10422     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
10423 
10424   // The remaining checks depend on the data arguments.
10425   if (ArgPassingKind == Sema::FAPK_VAList)
10426     return true;
10427 
10428   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
10429     return false;
10430 
10431   // Check that the argument type matches the format specifier.
10432   const Expr *Ex = getDataArg(argIndex);
10433   if (!Ex)
10434     return true;
10435 
10436   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
10437 
10438   if (!AT.isValid()) {
10439     return true;
10440   }
10441 
10442   analyze_format_string::ArgType::MatchKind Match =
10443       AT.matchesType(S.Context, Ex->getType());
10444   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
10445   if (Match == analyze_format_string::ArgType::Match)
10446     return true;
10447 
10448   ScanfSpecifier fixedFS = FS;
10449   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
10450                                  S.getLangOpts(), S.Context);
10451 
10452   unsigned Diag =
10453       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
10454                : diag::warn_format_conversion_argument_type_mismatch;
10455 
10456   if (Success) {
10457     // Get the fix string from the fixed format specifier.
10458     SmallString<128> buf;
10459     llvm::raw_svector_ostream os(buf);
10460     fixedFS.toString(os);
10461 
10462     EmitFormatDiagnostic(
10463         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
10464                       << Ex->getType() << false << Ex->getSourceRange(),
10465         Ex->getBeginLoc(),
10466         /*IsStringLocation*/ false,
10467         getSpecifierRange(startSpecifier, specifierLen),
10468         FixItHint::CreateReplacement(
10469             getSpecifierRange(startSpecifier, specifierLen), os.str()));
10470   } else {
10471     EmitFormatDiagnostic(S.PDiag(Diag)
10472                              << AT.getRepresentativeTypeName(S.Context)
10473                              << Ex->getType() << false << Ex->getSourceRange(),
10474                          Ex->getBeginLoc(),
10475                          /*IsStringLocation*/ false,
10476                          getSpecifierRange(startSpecifier, specifierLen));
10477   }
10478 
10479   return true;
10480 }
10481 
10482 static void CheckFormatString(
10483     Sema &S, const FormatStringLiteral *FExpr, const Expr *OrigFormatExpr,
10484     ArrayRef<const Expr *> Args, Sema::FormatArgumentPassingKind APK,
10485     unsigned format_idx, unsigned firstDataArg, Sema::FormatStringType Type,
10486     bool inFunctionCall, Sema::VariadicCallType CallType,
10487     llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
10488     bool IgnoreStringsWithoutSpecifiers) {
10489   // CHECK: is the format string a wide literal?
10490   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
10491     CheckFormatHandler::EmitFormatDiagnostic(
10492         S, inFunctionCall, Args[format_idx],
10493         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
10494         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
10495     return;
10496   }
10497 
10498   // Str - The format string.  NOTE: this is NOT null-terminated!
10499   StringRef StrRef = FExpr->getString();
10500   const char *Str = StrRef.data();
10501   // Account for cases where the string literal is truncated in a declaration.
10502   const ConstantArrayType *T =
10503     S.Context.getAsConstantArrayType(FExpr->getType());
10504   assert(T && "String literal not of constant array type!");
10505   size_t TypeSize = T->getSize().getZExtValue();
10506   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
10507   const unsigned numDataArgs = Args.size() - firstDataArg;
10508 
10509   if (IgnoreStringsWithoutSpecifiers &&
10510       !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
10511           Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
10512     return;
10513 
10514   // Emit a warning if the string literal is truncated and does not contain an
10515   // embedded null character.
10516   if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) {
10517     CheckFormatHandler::EmitFormatDiagnostic(
10518         S, inFunctionCall, Args[format_idx],
10519         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
10520         FExpr->getBeginLoc(),
10521         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
10522     return;
10523   }
10524 
10525   // CHECK: empty format string?
10526   if (StrLen == 0 && numDataArgs > 0) {
10527     CheckFormatHandler::EmitFormatDiagnostic(
10528         S, inFunctionCall, Args[format_idx],
10529         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
10530         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
10531     return;
10532   }
10533 
10534   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
10535       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
10536       Type == Sema::FST_OSTrace) {
10537     CheckPrintfHandler H(
10538         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
10539         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, APK,
10540         Args, format_idx, inFunctionCall, CallType, CheckedVarArgs,
10541         UncoveredArg);
10542 
10543     if (!analyze_format_string::ParsePrintfString(
10544             H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo(),
10545             Type == Sema::FST_FreeBSDKPrintf))
10546       H.DoneProcessing();
10547   } else if (Type == Sema::FST_Scanf) {
10548     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
10549                         numDataArgs, Str, APK, Args, format_idx, inFunctionCall,
10550                         CallType, CheckedVarArgs, UncoveredArg);
10551 
10552     if (!analyze_format_string::ParseScanfString(
10553             H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
10554       H.DoneProcessing();
10555   } // TODO: handle other formats
10556 }
10557 
10558 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
10559   // Str - The format string.  NOTE: this is NOT null-terminated!
10560   StringRef StrRef = FExpr->getString();
10561   const char *Str = StrRef.data();
10562   // Account for cases where the string literal is truncated in a declaration.
10563   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
10564   assert(T && "String literal not of constant array type!");
10565   size_t TypeSize = T->getSize().getZExtValue();
10566   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
10567   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
10568                                                          getLangOpts(),
10569                                                          Context.getTargetInfo());
10570 }
10571 
10572 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
10573 
10574 // Returns the related absolute value function that is larger, of 0 if one
10575 // does not exist.
10576 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
10577   switch (AbsFunction) {
10578   default:
10579     return 0;
10580 
10581   case Builtin::BI__builtin_abs:
10582     return Builtin::BI__builtin_labs;
10583   case Builtin::BI__builtin_labs:
10584     return Builtin::BI__builtin_llabs;
10585   case Builtin::BI__builtin_llabs:
10586     return 0;
10587 
10588   case Builtin::BI__builtin_fabsf:
10589     return Builtin::BI__builtin_fabs;
10590   case Builtin::BI__builtin_fabs:
10591     return Builtin::BI__builtin_fabsl;
10592   case Builtin::BI__builtin_fabsl:
10593     return 0;
10594 
10595   case Builtin::BI__builtin_cabsf:
10596     return Builtin::BI__builtin_cabs;
10597   case Builtin::BI__builtin_cabs:
10598     return Builtin::BI__builtin_cabsl;
10599   case Builtin::BI__builtin_cabsl:
10600     return 0;
10601 
10602   case Builtin::BIabs:
10603     return Builtin::BIlabs;
10604   case Builtin::BIlabs:
10605     return Builtin::BIllabs;
10606   case Builtin::BIllabs:
10607     return 0;
10608 
10609   case Builtin::BIfabsf:
10610     return Builtin::BIfabs;
10611   case Builtin::BIfabs:
10612     return Builtin::BIfabsl;
10613   case Builtin::BIfabsl:
10614     return 0;
10615 
10616   case Builtin::BIcabsf:
10617    return Builtin::BIcabs;
10618   case Builtin::BIcabs:
10619     return Builtin::BIcabsl;
10620   case Builtin::BIcabsl:
10621     return 0;
10622   }
10623 }
10624 
10625 // Returns the argument type of the absolute value function.
10626 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
10627                                              unsigned AbsType) {
10628   if (AbsType == 0)
10629     return QualType();
10630 
10631   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
10632   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
10633   if (Error != ASTContext::GE_None)
10634     return QualType();
10635 
10636   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
10637   if (!FT)
10638     return QualType();
10639 
10640   if (FT->getNumParams() != 1)
10641     return QualType();
10642 
10643   return FT->getParamType(0);
10644 }
10645 
10646 // Returns the best absolute value function, or zero, based on type and
10647 // current absolute value function.
10648 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
10649                                    unsigned AbsFunctionKind) {
10650   unsigned BestKind = 0;
10651   uint64_t ArgSize = Context.getTypeSize(ArgType);
10652   for (unsigned Kind = AbsFunctionKind; Kind != 0;
10653        Kind = getLargerAbsoluteValueFunction(Kind)) {
10654     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
10655     if (Context.getTypeSize(ParamType) >= ArgSize) {
10656       if (BestKind == 0)
10657         BestKind = Kind;
10658       else if (Context.hasSameType(ParamType, ArgType)) {
10659         BestKind = Kind;
10660         break;
10661       }
10662     }
10663   }
10664   return BestKind;
10665 }
10666 
10667 enum AbsoluteValueKind {
10668   AVK_Integer,
10669   AVK_Floating,
10670   AVK_Complex
10671 };
10672 
10673 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
10674   if (T->isIntegralOrEnumerationType())
10675     return AVK_Integer;
10676   if (T->isRealFloatingType())
10677     return AVK_Floating;
10678   if (T->isAnyComplexType())
10679     return AVK_Complex;
10680 
10681   llvm_unreachable("Type not integer, floating, or complex");
10682 }
10683 
10684 // Changes the absolute value function to a different type.  Preserves whether
10685 // the function is a builtin.
10686 static unsigned changeAbsFunction(unsigned AbsKind,
10687                                   AbsoluteValueKind ValueKind) {
10688   switch (ValueKind) {
10689   case AVK_Integer:
10690     switch (AbsKind) {
10691     default:
10692       return 0;
10693     case Builtin::BI__builtin_fabsf:
10694     case Builtin::BI__builtin_fabs:
10695     case Builtin::BI__builtin_fabsl:
10696     case Builtin::BI__builtin_cabsf:
10697     case Builtin::BI__builtin_cabs:
10698     case Builtin::BI__builtin_cabsl:
10699       return Builtin::BI__builtin_abs;
10700     case Builtin::BIfabsf:
10701     case Builtin::BIfabs:
10702     case Builtin::BIfabsl:
10703     case Builtin::BIcabsf:
10704     case Builtin::BIcabs:
10705     case Builtin::BIcabsl:
10706       return Builtin::BIabs;
10707     }
10708   case AVK_Floating:
10709     switch (AbsKind) {
10710     default:
10711       return 0;
10712     case Builtin::BI__builtin_abs:
10713     case Builtin::BI__builtin_labs:
10714     case Builtin::BI__builtin_llabs:
10715     case Builtin::BI__builtin_cabsf:
10716     case Builtin::BI__builtin_cabs:
10717     case Builtin::BI__builtin_cabsl:
10718       return Builtin::BI__builtin_fabsf;
10719     case Builtin::BIabs:
10720     case Builtin::BIlabs:
10721     case Builtin::BIllabs:
10722     case Builtin::BIcabsf:
10723     case Builtin::BIcabs:
10724     case Builtin::BIcabsl:
10725       return Builtin::BIfabsf;
10726     }
10727   case AVK_Complex:
10728     switch (AbsKind) {
10729     default:
10730       return 0;
10731     case Builtin::BI__builtin_abs:
10732     case Builtin::BI__builtin_labs:
10733     case Builtin::BI__builtin_llabs:
10734     case Builtin::BI__builtin_fabsf:
10735     case Builtin::BI__builtin_fabs:
10736     case Builtin::BI__builtin_fabsl:
10737       return Builtin::BI__builtin_cabsf;
10738     case Builtin::BIabs:
10739     case Builtin::BIlabs:
10740     case Builtin::BIllabs:
10741     case Builtin::BIfabsf:
10742     case Builtin::BIfabs:
10743     case Builtin::BIfabsl:
10744       return Builtin::BIcabsf;
10745     }
10746   }
10747   llvm_unreachable("Unable to convert function");
10748 }
10749 
10750 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
10751   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
10752   if (!FnInfo)
10753     return 0;
10754 
10755   switch (FDecl->getBuiltinID()) {
10756   default:
10757     return 0;
10758   case Builtin::BI__builtin_abs:
10759   case Builtin::BI__builtin_fabs:
10760   case Builtin::BI__builtin_fabsf:
10761   case Builtin::BI__builtin_fabsl:
10762   case Builtin::BI__builtin_labs:
10763   case Builtin::BI__builtin_llabs:
10764   case Builtin::BI__builtin_cabs:
10765   case Builtin::BI__builtin_cabsf:
10766   case Builtin::BI__builtin_cabsl:
10767   case Builtin::BIabs:
10768   case Builtin::BIlabs:
10769   case Builtin::BIllabs:
10770   case Builtin::BIfabs:
10771   case Builtin::BIfabsf:
10772   case Builtin::BIfabsl:
10773   case Builtin::BIcabs:
10774   case Builtin::BIcabsf:
10775   case Builtin::BIcabsl:
10776     return FDecl->getBuiltinID();
10777   }
10778   llvm_unreachable("Unknown Builtin type");
10779 }
10780 
10781 // If the replacement is valid, emit a note with replacement function.
10782 // Additionally, suggest including the proper header if not already included.
10783 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
10784                             unsigned AbsKind, QualType ArgType) {
10785   bool EmitHeaderHint = true;
10786   const char *HeaderName = nullptr;
10787   const char *FunctionName = nullptr;
10788   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
10789     FunctionName = "std::abs";
10790     if (ArgType->isIntegralOrEnumerationType()) {
10791       HeaderName = "cstdlib";
10792     } else if (ArgType->isRealFloatingType()) {
10793       HeaderName = "cmath";
10794     } else {
10795       llvm_unreachable("Invalid Type");
10796     }
10797 
10798     // Lookup all std::abs
10799     if (NamespaceDecl *Std = S.getStdNamespace()) {
10800       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
10801       R.suppressDiagnostics();
10802       S.LookupQualifiedName(R, Std);
10803 
10804       for (const auto *I : R) {
10805         const FunctionDecl *FDecl = nullptr;
10806         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
10807           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
10808         } else {
10809           FDecl = dyn_cast<FunctionDecl>(I);
10810         }
10811         if (!FDecl)
10812           continue;
10813 
10814         // Found std::abs(), check that they are the right ones.
10815         if (FDecl->getNumParams() != 1)
10816           continue;
10817 
10818         // Check that the parameter type can handle the argument.
10819         QualType ParamType = FDecl->getParamDecl(0)->getType();
10820         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
10821             S.Context.getTypeSize(ArgType) <=
10822                 S.Context.getTypeSize(ParamType)) {
10823           // Found a function, don't need the header hint.
10824           EmitHeaderHint = false;
10825           break;
10826         }
10827       }
10828     }
10829   } else {
10830     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
10831     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
10832 
10833     if (HeaderName) {
10834       DeclarationName DN(&S.Context.Idents.get(FunctionName));
10835       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
10836       R.suppressDiagnostics();
10837       S.LookupName(R, S.getCurScope());
10838 
10839       if (R.isSingleResult()) {
10840         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
10841         if (FD && FD->getBuiltinID() == AbsKind) {
10842           EmitHeaderHint = false;
10843         } else {
10844           return;
10845         }
10846       } else if (!R.empty()) {
10847         return;
10848       }
10849     }
10850   }
10851 
10852   S.Diag(Loc, diag::note_replace_abs_function)
10853       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
10854 
10855   if (!HeaderName)
10856     return;
10857 
10858   if (!EmitHeaderHint)
10859     return;
10860 
10861   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
10862                                                     << FunctionName;
10863 }
10864 
10865 template <std::size_t StrLen>
10866 static bool IsStdFunction(const FunctionDecl *FDecl,
10867                           const char (&Str)[StrLen]) {
10868   if (!FDecl)
10869     return false;
10870   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
10871     return false;
10872   if (!FDecl->isInStdNamespace())
10873     return false;
10874 
10875   return true;
10876 }
10877 
10878 // Warn when using the wrong abs() function.
10879 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
10880                                       const FunctionDecl *FDecl) {
10881   if (Call->getNumArgs() != 1)
10882     return;
10883 
10884   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
10885   bool IsStdAbs = IsStdFunction(FDecl, "abs");
10886   if (AbsKind == 0 && !IsStdAbs)
10887     return;
10888 
10889   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10890   QualType ParamType = Call->getArg(0)->getType();
10891 
10892   // Unsigned types cannot be negative.  Suggest removing the absolute value
10893   // function call.
10894   if (ArgType->isUnsignedIntegerType()) {
10895     const char *FunctionName =
10896         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
10897     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
10898     Diag(Call->getExprLoc(), diag::note_remove_abs)
10899         << FunctionName
10900         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
10901     return;
10902   }
10903 
10904   // Taking the absolute value of a pointer is very suspicious, they probably
10905   // wanted to index into an array, dereference a pointer, call a function, etc.
10906   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
10907     unsigned DiagType = 0;
10908     if (ArgType->isFunctionType())
10909       DiagType = 1;
10910     else if (ArgType->isArrayType())
10911       DiagType = 2;
10912 
10913     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
10914     return;
10915   }
10916 
10917   // std::abs has overloads which prevent most of the absolute value problems
10918   // from occurring.
10919   if (IsStdAbs)
10920     return;
10921 
10922   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
10923   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
10924 
10925   // The argument and parameter are the same kind.  Check if they are the right
10926   // size.
10927   if (ArgValueKind == ParamValueKind) {
10928     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
10929       return;
10930 
10931     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
10932     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
10933         << FDecl << ArgType << ParamType;
10934 
10935     if (NewAbsKind == 0)
10936       return;
10937 
10938     emitReplacement(*this, Call->getExprLoc(),
10939                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10940     return;
10941   }
10942 
10943   // ArgValueKind != ParamValueKind
10944   // The wrong type of absolute value function was used.  Attempt to find the
10945   // proper one.
10946   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
10947   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
10948   if (NewAbsKind == 0)
10949     return;
10950 
10951   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
10952       << FDecl << ParamValueKind << ArgValueKind;
10953 
10954   emitReplacement(*this, Call->getExprLoc(),
10955                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10956 }
10957 
10958 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
10959 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
10960                                 const FunctionDecl *FDecl) {
10961   if (!Call || !FDecl) return;
10962 
10963   // Ignore template specializations and macros.
10964   if (inTemplateInstantiation()) return;
10965   if (Call->getExprLoc().isMacroID()) return;
10966 
10967   // Only care about the one template argument, two function parameter std::max
10968   if (Call->getNumArgs() != 2) return;
10969   if (!IsStdFunction(FDecl, "max")) return;
10970   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
10971   if (!ArgList) return;
10972   if (ArgList->size() != 1) return;
10973 
10974   // Check that template type argument is unsigned integer.
10975   const auto& TA = ArgList->get(0);
10976   if (TA.getKind() != TemplateArgument::Type) return;
10977   QualType ArgType = TA.getAsType();
10978   if (!ArgType->isUnsignedIntegerType()) return;
10979 
10980   // See if either argument is a literal zero.
10981   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
10982     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
10983     if (!MTE) return false;
10984     const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
10985     if (!Num) return false;
10986     if (Num->getValue() != 0) return false;
10987     return true;
10988   };
10989 
10990   const Expr *FirstArg = Call->getArg(0);
10991   const Expr *SecondArg = Call->getArg(1);
10992   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
10993   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
10994 
10995   // Only warn when exactly one argument is zero.
10996   if (IsFirstArgZero == IsSecondArgZero) return;
10997 
10998   SourceRange FirstRange = FirstArg->getSourceRange();
10999   SourceRange SecondRange = SecondArg->getSourceRange();
11000 
11001   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
11002 
11003   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
11004       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
11005 
11006   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
11007   SourceRange RemovalRange;
11008   if (IsFirstArgZero) {
11009     RemovalRange = SourceRange(FirstRange.getBegin(),
11010                                SecondRange.getBegin().getLocWithOffset(-1));
11011   } else {
11012     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
11013                                SecondRange.getEnd());
11014   }
11015 
11016   Diag(Call->getExprLoc(), diag::note_remove_max_call)
11017         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
11018         << FixItHint::CreateRemoval(RemovalRange);
11019 }
11020 
11021 //===--- CHECK: Standard memory functions ---------------------------------===//
11022 
11023 /// Takes the expression passed to the size_t parameter of functions
11024 /// such as memcmp, strncat, etc and warns if it's a comparison.
11025 ///
11026 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
11027 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
11028                                            IdentifierInfo *FnName,
11029                                            SourceLocation FnLoc,
11030                                            SourceLocation RParenLoc) {
11031   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
11032   if (!Size)
11033     return false;
11034 
11035   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
11036   if (!Size->isComparisonOp() && !Size->isLogicalOp())
11037     return false;
11038 
11039   SourceRange SizeRange = Size->getSourceRange();
11040   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
11041       << SizeRange << FnName;
11042   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
11043       << FnName
11044       << FixItHint::CreateInsertion(
11045              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
11046       << FixItHint::CreateRemoval(RParenLoc);
11047   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
11048       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
11049       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
11050                                     ")");
11051 
11052   return true;
11053 }
11054 
11055 /// Determine whether the given type is or contains a dynamic class type
11056 /// (e.g., whether it has a vtable).
11057 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
11058                                                      bool &IsContained) {
11059   // Look through array types while ignoring qualifiers.
11060   const Type *Ty = T->getBaseElementTypeUnsafe();
11061   IsContained = false;
11062 
11063   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
11064   RD = RD ? RD->getDefinition() : nullptr;
11065   if (!RD || RD->isInvalidDecl())
11066     return nullptr;
11067 
11068   if (RD->isDynamicClass())
11069     return RD;
11070 
11071   // Check all the fields.  If any bases were dynamic, the class is dynamic.
11072   // It's impossible for a class to transitively contain itself by value, so
11073   // infinite recursion is impossible.
11074   for (auto *FD : RD->fields()) {
11075     bool SubContained;
11076     if (const CXXRecordDecl *ContainedRD =
11077             getContainedDynamicClass(FD->getType(), SubContained)) {
11078       IsContained = true;
11079       return ContainedRD;
11080     }
11081   }
11082 
11083   return nullptr;
11084 }
11085 
11086 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
11087   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
11088     if (Unary->getKind() == UETT_SizeOf)
11089       return Unary;
11090   return nullptr;
11091 }
11092 
11093 /// If E is a sizeof expression, returns its argument expression,
11094 /// otherwise returns NULL.
11095 static const Expr *getSizeOfExprArg(const Expr *E) {
11096   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
11097     if (!SizeOf->isArgumentType())
11098       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
11099   return nullptr;
11100 }
11101 
11102 /// If E is a sizeof expression, returns its argument type.
11103 static QualType getSizeOfArgType(const Expr *E) {
11104   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
11105     return SizeOf->getTypeOfArgument();
11106   return QualType();
11107 }
11108 
11109 namespace {
11110 
11111 struct SearchNonTrivialToInitializeField
11112     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
11113   using Super =
11114       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
11115 
11116   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
11117 
11118   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
11119                      SourceLocation SL) {
11120     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
11121       asDerived().visitArray(PDIK, AT, SL);
11122       return;
11123     }
11124 
11125     Super::visitWithKind(PDIK, FT, SL);
11126   }
11127 
11128   void visitARCStrong(QualType FT, SourceLocation SL) {
11129     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
11130   }
11131   void visitARCWeak(QualType FT, SourceLocation SL) {
11132     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
11133   }
11134   void visitStruct(QualType FT, SourceLocation SL) {
11135     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
11136       visit(FD->getType(), FD->getLocation());
11137   }
11138   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
11139                   const ArrayType *AT, SourceLocation SL) {
11140     visit(getContext().getBaseElementType(AT), SL);
11141   }
11142   void visitTrivial(QualType FT, SourceLocation SL) {}
11143 
11144   static void diag(QualType RT, const Expr *E, Sema &S) {
11145     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
11146   }
11147 
11148   ASTContext &getContext() { return S.getASTContext(); }
11149 
11150   const Expr *E;
11151   Sema &S;
11152 };
11153 
11154 struct SearchNonTrivialToCopyField
11155     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
11156   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
11157 
11158   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
11159 
11160   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
11161                      SourceLocation SL) {
11162     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
11163       asDerived().visitArray(PCK, AT, SL);
11164       return;
11165     }
11166 
11167     Super::visitWithKind(PCK, FT, SL);
11168   }
11169 
11170   void visitARCStrong(QualType FT, SourceLocation SL) {
11171     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
11172   }
11173   void visitARCWeak(QualType FT, SourceLocation SL) {
11174     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
11175   }
11176   void visitStruct(QualType FT, SourceLocation SL) {
11177     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
11178       visit(FD->getType(), FD->getLocation());
11179   }
11180   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
11181                   SourceLocation SL) {
11182     visit(getContext().getBaseElementType(AT), SL);
11183   }
11184   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
11185                 SourceLocation SL) {}
11186   void visitTrivial(QualType FT, SourceLocation SL) {}
11187   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
11188 
11189   static void diag(QualType RT, const Expr *E, Sema &S) {
11190     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
11191   }
11192 
11193   ASTContext &getContext() { return S.getASTContext(); }
11194 
11195   const Expr *E;
11196   Sema &S;
11197 };
11198 
11199 }
11200 
11201 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
11202 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
11203   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
11204 
11205   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
11206     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
11207       return false;
11208 
11209     return doesExprLikelyComputeSize(BO->getLHS()) ||
11210            doesExprLikelyComputeSize(BO->getRHS());
11211   }
11212 
11213   return getAsSizeOfExpr(SizeofExpr) != nullptr;
11214 }
11215 
11216 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
11217 ///
11218 /// \code
11219 ///   #define MACRO 0
11220 ///   foo(MACRO);
11221 ///   foo(0);
11222 /// \endcode
11223 ///
11224 /// This should return true for the first call to foo, but not for the second
11225 /// (regardless of whether foo is a macro or function).
11226 static bool isArgumentExpandedFromMacro(SourceManager &SM,
11227                                         SourceLocation CallLoc,
11228                                         SourceLocation ArgLoc) {
11229   if (!CallLoc.isMacroID())
11230     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
11231 
11232   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
11233          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
11234 }
11235 
11236 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
11237 /// last two arguments transposed.
11238 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
11239   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
11240     return;
11241 
11242   const Expr *SizeArg =
11243     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
11244 
11245   auto isLiteralZero = [](const Expr *E) {
11246     return (isa<IntegerLiteral>(E) &&
11247             cast<IntegerLiteral>(E)->getValue() == 0) ||
11248            (isa<CharacterLiteral>(E) &&
11249             cast<CharacterLiteral>(E)->getValue() == 0);
11250   };
11251 
11252   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
11253   SourceLocation CallLoc = Call->getRParenLoc();
11254   SourceManager &SM = S.getSourceManager();
11255   if (isLiteralZero(SizeArg) &&
11256       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
11257 
11258     SourceLocation DiagLoc = SizeArg->getExprLoc();
11259 
11260     // Some platforms #define bzero to __builtin_memset. See if this is the
11261     // case, and if so, emit a better diagnostic.
11262     if (BId == Builtin::BIbzero ||
11263         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
11264                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
11265       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
11266       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
11267     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
11268       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
11269       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
11270     }
11271     return;
11272   }
11273 
11274   // If the second argument to a memset is a sizeof expression and the third
11275   // isn't, this is also likely an error. This should catch
11276   // 'memset(buf, sizeof(buf), 0xff)'.
11277   if (BId == Builtin::BImemset &&
11278       doesExprLikelyComputeSize(Call->getArg(1)) &&
11279       !doesExprLikelyComputeSize(Call->getArg(2))) {
11280     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
11281     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
11282     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
11283     return;
11284   }
11285 }
11286 
11287 /// Check for dangerous or invalid arguments to memset().
11288 ///
11289 /// This issues warnings on known problematic, dangerous or unspecified
11290 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
11291 /// function calls.
11292 ///
11293 /// \param Call The call expression to diagnose.
11294 void Sema::CheckMemaccessArguments(const CallExpr *Call,
11295                                    unsigned BId,
11296                                    IdentifierInfo *FnName) {
11297   assert(BId != 0);
11298 
11299   // It is possible to have a non-standard definition of memset.  Validate
11300   // we have enough arguments, and if not, abort further checking.
11301   unsigned ExpectedNumArgs =
11302       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
11303   if (Call->getNumArgs() < ExpectedNumArgs)
11304     return;
11305 
11306   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
11307                       BId == Builtin::BIstrndup ? 1 : 2);
11308   unsigned LenArg =
11309       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
11310   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
11311 
11312   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
11313                                      Call->getBeginLoc(), Call->getRParenLoc()))
11314     return;
11315 
11316   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
11317   CheckMemaccessSize(*this, BId, Call);
11318 
11319   // We have special checking when the length is a sizeof expression.
11320   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
11321   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
11322   llvm::FoldingSetNodeID SizeOfArgID;
11323 
11324   // Although widely used, 'bzero' is not a standard function. Be more strict
11325   // with the argument types before allowing diagnostics and only allow the
11326   // form bzero(ptr, sizeof(...)).
11327   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
11328   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
11329     return;
11330 
11331   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
11332     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
11333     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
11334 
11335     QualType DestTy = Dest->getType();
11336     QualType PointeeTy;
11337     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
11338       PointeeTy = DestPtrTy->getPointeeType();
11339 
11340       // Never warn about void type pointers. This can be used to suppress
11341       // false positives.
11342       if (PointeeTy->isVoidType())
11343         continue;
11344 
11345       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
11346       // actually comparing the expressions for equality. Because computing the
11347       // expression IDs can be expensive, we only do this if the diagnostic is
11348       // enabled.
11349       if (SizeOfArg &&
11350           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
11351                            SizeOfArg->getExprLoc())) {
11352         // We only compute IDs for expressions if the warning is enabled, and
11353         // cache the sizeof arg's ID.
11354         if (SizeOfArgID == llvm::FoldingSetNodeID())
11355           SizeOfArg->Profile(SizeOfArgID, Context, true);
11356         llvm::FoldingSetNodeID DestID;
11357         Dest->Profile(DestID, Context, true);
11358         if (DestID == SizeOfArgID) {
11359           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
11360           //       over sizeof(src) as well.
11361           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
11362           StringRef ReadableName = FnName->getName();
11363 
11364           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
11365             if (UnaryOp->getOpcode() == UO_AddrOf)
11366               ActionIdx = 1; // If its an address-of operator, just remove it.
11367           if (!PointeeTy->isIncompleteType() &&
11368               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
11369             ActionIdx = 2; // If the pointee's size is sizeof(char),
11370                            // suggest an explicit length.
11371 
11372           // If the function is defined as a builtin macro, do not show macro
11373           // expansion.
11374           SourceLocation SL = SizeOfArg->getExprLoc();
11375           SourceRange DSR = Dest->getSourceRange();
11376           SourceRange SSR = SizeOfArg->getSourceRange();
11377           SourceManager &SM = getSourceManager();
11378 
11379           if (SM.isMacroArgExpansion(SL)) {
11380             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
11381             SL = SM.getSpellingLoc(SL);
11382             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
11383                              SM.getSpellingLoc(DSR.getEnd()));
11384             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
11385                              SM.getSpellingLoc(SSR.getEnd()));
11386           }
11387 
11388           DiagRuntimeBehavior(SL, SizeOfArg,
11389                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
11390                                 << ReadableName
11391                                 << PointeeTy
11392                                 << DestTy
11393                                 << DSR
11394                                 << SSR);
11395           DiagRuntimeBehavior(SL, SizeOfArg,
11396                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
11397                                 << ActionIdx
11398                                 << SSR);
11399 
11400           break;
11401         }
11402       }
11403 
11404       // Also check for cases where the sizeof argument is the exact same
11405       // type as the memory argument, and where it points to a user-defined
11406       // record type.
11407       if (SizeOfArgTy != QualType()) {
11408         if (PointeeTy->isRecordType() &&
11409             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
11410           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
11411                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
11412                                 << FnName << SizeOfArgTy << ArgIdx
11413                                 << PointeeTy << Dest->getSourceRange()
11414                                 << LenExpr->getSourceRange());
11415           break;
11416         }
11417       }
11418     } else if (DestTy->isArrayType()) {
11419       PointeeTy = DestTy;
11420     }
11421 
11422     if (PointeeTy == QualType())
11423       continue;
11424 
11425     // Always complain about dynamic classes.
11426     bool IsContained;
11427     if (const CXXRecordDecl *ContainedRD =
11428             getContainedDynamicClass(PointeeTy, IsContained)) {
11429 
11430       unsigned OperationType = 0;
11431       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
11432       // "overwritten" if we're warning about the destination for any call
11433       // but memcmp; otherwise a verb appropriate to the call.
11434       if (ArgIdx != 0 || IsCmp) {
11435         if (BId == Builtin::BImemcpy)
11436           OperationType = 1;
11437         else if(BId == Builtin::BImemmove)
11438           OperationType = 2;
11439         else if (IsCmp)
11440           OperationType = 3;
11441       }
11442 
11443       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11444                           PDiag(diag::warn_dyn_class_memaccess)
11445                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
11446                               << IsContained << ContainedRD << OperationType
11447                               << Call->getCallee()->getSourceRange());
11448     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
11449              BId != Builtin::BImemset)
11450       DiagRuntimeBehavior(
11451         Dest->getExprLoc(), Dest,
11452         PDiag(diag::warn_arc_object_memaccess)
11453           << ArgIdx << FnName << PointeeTy
11454           << Call->getCallee()->getSourceRange());
11455     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
11456       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
11457           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
11458         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11459                             PDiag(diag::warn_cstruct_memaccess)
11460                                 << ArgIdx << FnName << PointeeTy << 0);
11461         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
11462       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
11463                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
11464         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11465                             PDiag(diag::warn_cstruct_memaccess)
11466                                 << ArgIdx << FnName << PointeeTy << 1);
11467         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
11468       } else {
11469         continue;
11470       }
11471     } else
11472       continue;
11473 
11474     DiagRuntimeBehavior(
11475       Dest->getExprLoc(), Dest,
11476       PDiag(diag::note_bad_memaccess_silence)
11477         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
11478     break;
11479   }
11480 }
11481 
11482 // A little helper routine: ignore addition and subtraction of integer literals.
11483 // This intentionally does not ignore all integer constant expressions because
11484 // we don't want to remove sizeof().
11485 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
11486   Ex = Ex->IgnoreParenCasts();
11487 
11488   while (true) {
11489     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
11490     if (!BO || !BO->isAdditiveOp())
11491       break;
11492 
11493     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
11494     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
11495 
11496     if (isa<IntegerLiteral>(RHS))
11497       Ex = LHS;
11498     else if (isa<IntegerLiteral>(LHS))
11499       Ex = RHS;
11500     else
11501       break;
11502   }
11503 
11504   return Ex;
11505 }
11506 
11507 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
11508                                                       ASTContext &Context) {
11509   // Only handle constant-sized or VLAs, but not flexible members.
11510   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
11511     // Only issue the FIXIT for arrays of size > 1.
11512     if (CAT->getSize().getSExtValue() <= 1)
11513       return false;
11514   } else if (!Ty->isVariableArrayType()) {
11515     return false;
11516   }
11517   return true;
11518 }
11519 
11520 // Warn if the user has made the 'size' argument to strlcpy or strlcat
11521 // be the size of the source, instead of the destination.
11522 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
11523                                     IdentifierInfo *FnName) {
11524 
11525   // Don't crash if the user has the wrong number of arguments
11526   unsigned NumArgs = Call->getNumArgs();
11527   if ((NumArgs != 3) && (NumArgs != 4))
11528     return;
11529 
11530   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
11531   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
11532   const Expr *CompareWithSrc = nullptr;
11533 
11534   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
11535                                      Call->getBeginLoc(), Call->getRParenLoc()))
11536     return;
11537 
11538   // Look for 'strlcpy(dst, x, sizeof(x))'
11539   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
11540     CompareWithSrc = Ex;
11541   else {
11542     // Look for 'strlcpy(dst, x, strlen(x))'
11543     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
11544       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
11545           SizeCall->getNumArgs() == 1)
11546         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
11547     }
11548   }
11549 
11550   if (!CompareWithSrc)
11551     return;
11552 
11553   // Determine if the argument to sizeof/strlen is equal to the source
11554   // argument.  In principle there's all kinds of things you could do
11555   // here, for instance creating an == expression and evaluating it with
11556   // EvaluateAsBooleanCondition, but this uses a more direct technique:
11557   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
11558   if (!SrcArgDRE)
11559     return;
11560 
11561   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
11562   if (!CompareWithSrcDRE ||
11563       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
11564     return;
11565 
11566   const Expr *OriginalSizeArg = Call->getArg(2);
11567   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
11568       << OriginalSizeArg->getSourceRange() << FnName;
11569 
11570   // Output a FIXIT hint if the destination is an array (rather than a
11571   // pointer to an array).  This could be enhanced to handle some
11572   // pointers if we know the actual size, like if DstArg is 'array+2'
11573   // we could say 'sizeof(array)-2'.
11574   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
11575   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
11576     return;
11577 
11578   SmallString<128> sizeString;
11579   llvm::raw_svector_ostream OS(sizeString);
11580   OS << "sizeof(";
11581   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11582   OS << ")";
11583 
11584   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
11585       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
11586                                       OS.str());
11587 }
11588 
11589 /// Check if two expressions refer to the same declaration.
11590 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
11591   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
11592     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
11593       return D1->getDecl() == D2->getDecl();
11594   return false;
11595 }
11596 
11597 static const Expr *getStrlenExprArg(const Expr *E) {
11598   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
11599     const FunctionDecl *FD = CE->getDirectCallee();
11600     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
11601       return nullptr;
11602     return CE->getArg(0)->IgnoreParenCasts();
11603   }
11604   return nullptr;
11605 }
11606 
11607 // Warn on anti-patterns as the 'size' argument to strncat.
11608 // The correct size argument should look like following:
11609 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
11610 void Sema::CheckStrncatArguments(const CallExpr *CE,
11611                                  IdentifierInfo *FnName) {
11612   // Don't crash if the user has the wrong number of arguments.
11613   if (CE->getNumArgs() < 3)
11614     return;
11615   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
11616   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
11617   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
11618 
11619   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
11620                                      CE->getRParenLoc()))
11621     return;
11622 
11623   // Identify common expressions, which are wrongly used as the size argument
11624   // to strncat and may lead to buffer overflows.
11625   unsigned PatternType = 0;
11626   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
11627     // - sizeof(dst)
11628     if (referToTheSameDecl(SizeOfArg, DstArg))
11629       PatternType = 1;
11630     // - sizeof(src)
11631     else if (referToTheSameDecl(SizeOfArg, SrcArg))
11632       PatternType = 2;
11633   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
11634     if (BE->getOpcode() == BO_Sub) {
11635       const Expr *L = BE->getLHS()->IgnoreParenCasts();
11636       const Expr *R = BE->getRHS()->IgnoreParenCasts();
11637       // - sizeof(dst) - strlen(dst)
11638       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
11639           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
11640         PatternType = 1;
11641       // - sizeof(src) - (anything)
11642       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
11643         PatternType = 2;
11644     }
11645   }
11646 
11647   if (PatternType == 0)
11648     return;
11649 
11650   // Generate the diagnostic.
11651   SourceLocation SL = LenArg->getBeginLoc();
11652   SourceRange SR = LenArg->getSourceRange();
11653   SourceManager &SM = getSourceManager();
11654 
11655   // If the function is defined as a builtin macro, do not show macro expansion.
11656   if (SM.isMacroArgExpansion(SL)) {
11657     SL = SM.getSpellingLoc(SL);
11658     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
11659                      SM.getSpellingLoc(SR.getEnd()));
11660   }
11661 
11662   // Check if the destination is an array (rather than a pointer to an array).
11663   QualType DstTy = DstArg->getType();
11664   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
11665                                                                     Context);
11666   if (!isKnownSizeArray) {
11667     if (PatternType == 1)
11668       Diag(SL, diag::warn_strncat_wrong_size) << SR;
11669     else
11670       Diag(SL, diag::warn_strncat_src_size) << SR;
11671     return;
11672   }
11673 
11674   if (PatternType == 1)
11675     Diag(SL, diag::warn_strncat_large_size) << SR;
11676   else
11677     Diag(SL, diag::warn_strncat_src_size) << SR;
11678 
11679   SmallString<128> sizeString;
11680   llvm::raw_svector_ostream OS(sizeString);
11681   OS << "sizeof(";
11682   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11683   OS << ") - ";
11684   OS << "strlen(";
11685   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11686   OS << ") - 1";
11687 
11688   Diag(SL, diag::note_strncat_wrong_size)
11689     << FixItHint::CreateReplacement(SR, OS.str());
11690 }
11691 
11692 namespace {
11693 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
11694                                 const UnaryOperator *UnaryExpr, const Decl *D) {
11695   if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) {
11696     S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
11697         << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
11698     return;
11699   }
11700 }
11701 
11702 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
11703                                  const UnaryOperator *UnaryExpr) {
11704   if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
11705     const Decl *D = Lvalue->getDecl();
11706     if (isa<DeclaratorDecl>(D))
11707       if (!dyn_cast<DeclaratorDecl>(D)->getType()->isReferenceType())
11708         return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
11709   }
11710 
11711   if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
11712     return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
11713                                       Lvalue->getMemberDecl());
11714 }
11715 
11716 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
11717                             const UnaryOperator *UnaryExpr) {
11718   const auto *Lambda = dyn_cast<LambdaExpr>(
11719       UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens());
11720   if (!Lambda)
11721     return;
11722 
11723   S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
11724       << CalleeName << 2 /*object: lambda expression*/;
11725 }
11726 
11727 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
11728                                   const DeclRefExpr *Lvalue) {
11729   const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
11730   if (Var == nullptr)
11731     return;
11732 
11733   S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
11734       << CalleeName << 0 /*object: */ << Var;
11735 }
11736 
11737 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
11738                             const CastExpr *Cast) {
11739   SmallString<128> SizeString;
11740   llvm::raw_svector_ostream OS(SizeString);
11741 
11742   clang::CastKind Kind = Cast->getCastKind();
11743   if (Kind == clang::CK_BitCast &&
11744       !Cast->getSubExpr()->getType()->isFunctionPointerType())
11745     return;
11746   if (Kind == clang::CK_IntegralToPointer &&
11747       !isa<IntegerLiteral>(
11748           Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
11749     return;
11750 
11751   switch (Cast->getCastKind()) {
11752   case clang::CK_BitCast:
11753   case clang::CK_IntegralToPointer:
11754   case clang::CK_FunctionToPointerDecay:
11755     OS << '\'';
11756     Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
11757     OS << '\'';
11758     break;
11759   default:
11760     return;
11761   }
11762 
11763   S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
11764       << CalleeName << 0 /*object: */ << OS.str();
11765 }
11766 } // namespace
11767 
11768 /// Alerts the user that they are attempting to free a non-malloc'd object.
11769 void Sema::CheckFreeArguments(const CallExpr *E) {
11770   const std::string CalleeName =
11771       cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
11772 
11773   { // Prefer something that doesn't involve a cast to make things simpler.
11774     const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
11775     if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
11776       switch (UnaryExpr->getOpcode()) {
11777       case UnaryOperator::Opcode::UO_AddrOf:
11778         return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
11779       case UnaryOperator::Opcode::UO_Plus:
11780         return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
11781       default:
11782         break;
11783       }
11784 
11785     if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
11786       if (Lvalue->getType()->isArrayType())
11787         return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
11788 
11789     if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
11790       Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
11791           << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
11792       return;
11793     }
11794 
11795     if (isa<BlockExpr>(Arg)) {
11796       Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
11797           << CalleeName << 1 /*object: block*/;
11798       return;
11799     }
11800   }
11801   // Maybe the cast was important, check after the other cases.
11802   if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
11803     return CheckFreeArgumentsCast(*this, CalleeName, Cast);
11804 }
11805 
11806 void
11807 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
11808                          SourceLocation ReturnLoc,
11809                          bool isObjCMethod,
11810                          const AttrVec *Attrs,
11811                          const FunctionDecl *FD) {
11812   // Check if the return value is null but should not be.
11813   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
11814        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
11815       CheckNonNullExpr(*this, RetValExp))
11816     Diag(ReturnLoc, diag::warn_null_ret)
11817       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
11818 
11819   // C++11 [basic.stc.dynamic.allocation]p4:
11820   //   If an allocation function declared with a non-throwing
11821   //   exception-specification fails to allocate storage, it shall return
11822   //   a null pointer. Any other allocation function that fails to allocate
11823   //   storage shall indicate failure only by throwing an exception [...]
11824   if (FD) {
11825     OverloadedOperatorKind Op = FD->getOverloadedOperator();
11826     if (Op == OO_New || Op == OO_Array_New) {
11827       const FunctionProtoType *Proto
11828         = FD->getType()->castAs<FunctionProtoType>();
11829       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
11830           CheckNonNullExpr(*this, RetValExp))
11831         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
11832           << FD << getLangOpts().CPlusPlus11;
11833     }
11834   }
11835 
11836   // PPC MMA non-pointer types are not allowed as return type. Checking the type
11837   // here prevent the user from using a PPC MMA type as trailing return type.
11838   if (Context.getTargetInfo().getTriple().isPPC64())
11839     CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
11840 }
11841 
11842 /// Check for comparisons of floating-point values using == and !=. Issue a
11843 /// warning if the comparison is not likely to do what the programmer intended.
11844 void Sema::CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS,
11845                                 BinaryOperatorKind Opcode) {
11846   // Match and capture subexpressions such as "(float) X == 0.1".
11847   FloatingLiteral *FPLiteral;
11848   CastExpr *FPCast;
11849   auto getCastAndLiteral = [&FPLiteral, &FPCast](Expr *L, Expr *R) {
11850     FPLiteral = dyn_cast<FloatingLiteral>(L->IgnoreParens());
11851     FPCast = dyn_cast<CastExpr>(R->IgnoreParens());
11852     return FPLiteral && FPCast;
11853   };
11854 
11855   if (getCastAndLiteral(LHS, RHS) || getCastAndLiteral(RHS, LHS)) {
11856     auto *SourceTy = FPCast->getSubExpr()->getType()->getAs<BuiltinType>();
11857     auto *TargetTy = FPLiteral->getType()->getAs<BuiltinType>();
11858     if (SourceTy && TargetTy && SourceTy->isFloatingPoint() &&
11859         TargetTy->isFloatingPoint()) {
11860       bool Lossy;
11861       llvm::APFloat TargetC = FPLiteral->getValue();
11862       TargetC.convert(Context.getFloatTypeSemantics(QualType(SourceTy, 0)),
11863                       llvm::APFloat::rmNearestTiesToEven, &Lossy);
11864       if (Lossy) {
11865         // If the literal cannot be represented in the source type, then a
11866         // check for == is always false and check for != is always true.
11867         Diag(Loc, diag::warn_float_compare_literal)
11868             << (Opcode == BO_EQ) << QualType(SourceTy, 0)
11869             << LHS->getSourceRange() << RHS->getSourceRange();
11870         return;
11871       }
11872     }
11873   }
11874 
11875   // Match a more general floating-point equality comparison (-Wfloat-equal).
11876   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
11877   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
11878 
11879   // Special case: check for x == x (which is OK).
11880   // Do not emit warnings for such cases.
11881   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
11882     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
11883       if (DRL->getDecl() == DRR->getDecl())
11884         return;
11885 
11886   // Special case: check for comparisons against literals that can be exactly
11887   //  represented by APFloat.  In such cases, do not emit a warning.  This
11888   //  is a heuristic: often comparison against such literals are used to
11889   //  detect if a value in a variable has not changed.  This clearly can
11890   //  lead to false negatives.
11891   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
11892     if (FLL->isExact())
11893       return;
11894   } else
11895     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
11896       if (FLR->isExact())
11897         return;
11898 
11899   // Check for comparisons with builtin types.
11900   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
11901     if (CL->getBuiltinCallee())
11902       return;
11903 
11904   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
11905     if (CR->getBuiltinCallee())
11906       return;
11907 
11908   // Emit the diagnostic.
11909   Diag(Loc, diag::warn_floatingpoint_eq)
11910     << LHS->getSourceRange() << RHS->getSourceRange();
11911 }
11912 
11913 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
11914 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
11915 
11916 namespace {
11917 
11918 /// Structure recording the 'active' range of an integer-valued
11919 /// expression.
11920 struct IntRange {
11921   /// The number of bits active in the int. Note that this includes exactly one
11922   /// sign bit if !NonNegative.
11923   unsigned Width;
11924 
11925   /// True if the int is known not to have negative values. If so, all leading
11926   /// bits before Width are known zero, otherwise they are known to be the
11927   /// same as the MSB within Width.
11928   bool NonNegative;
11929 
11930   IntRange(unsigned Width, bool NonNegative)
11931       : Width(Width), NonNegative(NonNegative) {}
11932 
11933   /// Number of bits excluding the sign bit.
11934   unsigned valueBits() const {
11935     return NonNegative ? Width : Width - 1;
11936   }
11937 
11938   /// Returns the range of the bool type.
11939   static IntRange forBoolType() {
11940     return IntRange(1, true);
11941   }
11942 
11943   /// Returns the range of an opaque value of the given integral type.
11944   static IntRange forValueOfType(ASTContext &C, QualType T) {
11945     return forValueOfCanonicalType(C,
11946                           T->getCanonicalTypeInternal().getTypePtr());
11947   }
11948 
11949   /// Returns the range of an opaque value of a canonical integral type.
11950   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
11951     assert(T->isCanonicalUnqualified());
11952 
11953     if (const VectorType *VT = dyn_cast<VectorType>(T))
11954       T = VT->getElementType().getTypePtr();
11955     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11956       T = CT->getElementType().getTypePtr();
11957     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11958       T = AT->getValueType().getTypePtr();
11959 
11960     if (!C.getLangOpts().CPlusPlus) {
11961       // For enum types in C code, use the underlying datatype.
11962       if (const EnumType *ET = dyn_cast<EnumType>(T))
11963         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
11964     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
11965       // For enum types in C++, use the known bit width of the enumerators.
11966       EnumDecl *Enum = ET->getDecl();
11967       // In C++11, enums can have a fixed underlying type. Use this type to
11968       // compute the range.
11969       if (Enum->isFixed()) {
11970         return IntRange(C.getIntWidth(QualType(T, 0)),
11971                         !ET->isSignedIntegerOrEnumerationType());
11972       }
11973 
11974       unsigned NumPositive = Enum->getNumPositiveBits();
11975       unsigned NumNegative = Enum->getNumNegativeBits();
11976 
11977       if (NumNegative == 0)
11978         return IntRange(NumPositive, true/*NonNegative*/);
11979       else
11980         return IntRange(std::max(NumPositive + 1, NumNegative),
11981                         false/*NonNegative*/);
11982     }
11983 
11984     if (const auto *EIT = dyn_cast<BitIntType>(T))
11985       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11986 
11987     const BuiltinType *BT = cast<BuiltinType>(T);
11988     assert(BT->isInteger());
11989 
11990     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11991   }
11992 
11993   /// Returns the "target" range of a canonical integral type, i.e.
11994   /// the range of values expressible in the type.
11995   ///
11996   /// This matches forValueOfCanonicalType except that enums have the
11997   /// full range of their type, not the range of their enumerators.
11998   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
11999     assert(T->isCanonicalUnqualified());
12000 
12001     if (const VectorType *VT = dyn_cast<VectorType>(T))
12002       T = VT->getElementType().getTypePtr();
12003     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
12004       T = CT->getElementType().getTypePtr();
12005     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
12006       T = AT->getValueType().getTypePtr();
12007     if (const EnumType *ET = dyn_cast<EnumType>(T))
12008       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
12009 
12010     if (const auto *EIT = dyn_cast<BitIntType>(T))
12011       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
12012 
12013     const BuiltinType *BT = cast<BuiltinType>(T);
12014     assert(BT->isInteger());
12015 
12016     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
12017   }
12018 
12019   /// Returns the supremum of two ranges: i.e. their conservative merge.
12020   static IntRange join(IntRange L, IntRange R) {
12021     bool Unsigned = L.NonNegative && R.NonNegative;
12022     return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
12023                     L.NonNegative && R.NonNegative);
12024   }
12025 
12026   /// Return the range of a bitwise-AND of the two ranges.
12027   static IntRange bit_and(IntRange L, IntRange R) {
12028     unsigned Bits = std::max(L.Width, R.Width);
12029     bool NonNegative = false;
12030     if (L.NonNegative) {
12031       Bits = std::min(Bits, L.Width);
12032       NonNegative = true;
12033     }
12034     if (R.NonNegative) {
12035       Bits = std::min(Bits, R.Width);
12036       NonNegative = true;
12037     }
12038     return IntRange(Bits, NonNegative);
12039   }
12040 
12041   /// Return the range of a sum of the two ranges.
12042   static IntRange sum(IntRange L, IntRange R) {
12043     bool Unsigned = L.NonNegative && R.NonNegative;
12044     return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
12045                     Unsigned);
12046   }
12047 
12048   /// Return the range of a difference of the two ranges.
12049   static IntRange difference(IntRange L, IntRange R) {
12050     // We need a 1-bit-wider range if:
12051     //   1) LHS can be negative: least value can be reduced.
12052     //   2) RHS can be negative: greatest value can be increased.
12053     bool CanWiden = !L.NonNegative || !R.NonNegative;
12054     bool Unsigned = L.NonNegative && R.Width == 0;
12055     return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
12056                         !Unsigned,
12057                     Unsigned);
12058   }
12059 
12060   /// Return the range of a product of the two ranges.
12061   static IntRange product(IntRange L, IntRange R) {
12062     // If both LHS and RHS can be negative, we can form
12063     //   -2^L * -2^R = 2^(L + R)
12064     // which requires L + R + 1 value bits to represent.
12065     bool CanWiden = !L.NonNegative && !R.NonNegative;
12066     bool Unsigned = L.NonNegative && R.NonNegative;
12067     return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
12068                     Unsigned);
12069   }
12070 
12071   /// Return the range of a remainder operation between the two ranges.
12072   static IntRange rem(IntRange L, IntRange R) {
12073     // The result of a remainder can't be larger than the result of
12074     // either side. The sign of the result is the sign of the LHS.
12075     bool Unsigned = L.NonNegative;
12076     return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
12077                     Unsigned);
12078   }
12079 };
12080 
12081 } // namespace
12082 
12083 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
12084                               unsigned MaxWidth) {
12085   if (value.isSigned() && value.isNegative())
12086     return IntRange(value.getMinSignedBits(), false);
12087 
12088   if (value.getBitWidth() > MaxWidth)
12089     value = value.trunc(MaxWidth);
12090 
12091   // isNonNegative() just checks the sign bit without considering
12092   // signedness.
12093   return IntRange(value.getActiveBits(), true);
12094 }
12095 
12096 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
12097                               unsigned MaxWidth) {
12098   if (result.isInt())
12099     return GetValueRange(C, result.getInt(), MaxWidth);
12100 
12101   if (result.isVector()) {
12102     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
12103     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
12104       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
12105       R = IntRange::join(R, El);
12106     }
12107     return R;
12108   }
12109 
12110   if (result.isComplexInt()) {
12111     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
12112     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
12113     return IntRange::join(R, I);
12114   }
12115 
12116   // This can happen with lossless casts to intptr_t of "based" lvalues.
12117   // Assume it might use arbitrary bits.
12118   // FIXME: The only reason we need to pass the type in here is to get
12119   // the sign right on this one case.  It would be nice if APValue
12120   // preserved this.
12121   assert(result.isLValue() || result.isAddrLabelDiff());
12122   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
12123 }
12124 
12125 static QualType GetExprType(const Expr *E) {
12126   QualType Ty = E->getType();
12127   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
12128     Ty = AtomicRHS->getValueType();
12129   return Ty;
12130 }
12131 
12132 /// Pseudo-evaluate the given integer expression, estimating the
12133 /// range of values it might take.
12134 ///
12135 /// \param MaxWidth The width to which the value will be truncated.
12136 /// \param Approximate If \c true, return a likely range for the result: in
12137 ///        particular, assume that arithmetic on narrower types doesn't leave
12138 ///        those types. If \c false, return a range including all possible
12139 ///        result values.
12140 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
12141                              bool InConstantContext, bool Approximate) {
12142   E = E->IgnoreParens();
12143 
12144   // Try a full evaluation first.
12145   Expr::EvalResult result;
12146   if (E->EvaluateAsRValue(result, C, InConstantContext))
12147     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
12148 
12149   // I think we only want to look through implicit casts here; if the
12150   // user has an explicit widening cast, we should treat the value as
12151   // being of the new, wider type.
12152   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
12153     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
12154       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
12155                           Approximate);
12156 
12157     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
12158 
12159     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
12160                          CE->getCastKind() == CK_BooleanToSignedIntegral;
12161 
12162     // Assume that non-integer casts can span the full range of the type.
12163     if (!isIntegerCast)
12164       return OutputTypeRange;
12165 
12166     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
12167                                      std::min(MaxWidth, OutputTypeRange.Width),
12168                                      InConstantContext, Approximate);
12169 
12170     // Bail out if the subexpr's range is as wide as the cast type.
12171     if (SubRange.Width >= OutputTypeRange.Width)
12172       return OutputTypeRange;
12173 
12174     // Otherwise, we take the smaller width, and we're non-negative if
12175     // either the output type or the subexpr is.
12176     return IntRange(SubRange.Width,
12177                     SubRange.NonNegative || OutputTypeRange.NonNegative);
12178   }
12179 
12180   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
12181     // If we can fold the condition, just take that operand.
12182     bool CondResult;
12183     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
12184       return GetExprRange(C,
12185                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
12186                           MaxWidth, InConstantContext, Approximate);
12187 
12188     // Otherwise, conservatively merge.
12189     // GetExprRange requires an integer expression, but a throw expression
12190     // results in a void type.
12191     Expr *E = CO->getTrueExpr();
12192     IntRange L = E->getType()->isVoidType()
12193                      ? IntRange{0, true}
12194                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
12195     E = CO->getFalseExpr();
12196     IntRange R = E->getType()->isVoidType()
12197                      ? IntRange{0, true}
12198                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
12199     return IntRange::join(L, R);
12200   }
12201 
12202   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
12203     IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
12204 
12205     switch (BO->getOpcode()) {
12206     case BO_Cmp:
12207       llvm_unreachable("builtin <=> should have class type");
12208 
12209     // Boolean-valued operations are single-bit and positive.
12210     case BO_LAnd:
12211     case BO_LOr:
12212     case BO_LT:
12213     case BO_GT:
12214     case BO_LE:
12215     case BO_GE:
12216     case BO_EQ:
12217     case BO_NE:
12218       return IntRange::forBoolType();
12219 
12220     // The type of the assignments is the type of the LHS, so the RHS
12221     // is not necessarily the same type.
12222     case BO_MulAssign:
12223     case BO_DivAssign:
12224     case BO_RemAssign:
12225     case BO_AddAssign:
12226     case BO_SubAssign:
12227     case BO_XorAssign:
12228     case BO_OrAssign:
12229       // TODO: bitfields?
12230       return IntRange::forValueOfType(C, GetExprType(E));
12231 
12232     // Simple assignments just pass through the RHS, which will have
12233     // been coerced to the LHS type.
12234     case BO_Assign:
12235       // TODO: bitfields?
12236       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
12237                           Approximate);
12238 
12239     // Operations with opaque sources are black-listed.
12240     case BO_PtrMemD:
12241     case BO_PtrMemI:
12242       return IntRange::forValueOfType(C, GetExprType(E));
12243 
12244     // Bitwise-and uses the *infinum* of the two source ranges.
12245     case BO_And:
12246     case BO_AndAssign:
12247       Combine = IntRange::bit_and;
12248       break;
12249 
12250     // Left shift gets black-listed based on a judgement call.
12251     case BO_Shl:
12252       // ...except that we want to treat '1 << (blah)' as logically
12253       // positive.  It's an important idiom.
12254       if (IntegerLiteral *I
12255             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
12256         if (I->getValue() == 1) {
12257           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
12258           return IntRange(R.Width, /*NonNegative*/ true);
12259         }
12260       }
12261       LLVM_FALLTHROUGH;
12262 
12263     case BO_ShlAssign:
12264       return IntRange::forValueOfType(C, GetExprType(E));
12265 
12266     // Right shift by a constant can narrow its left argument.
12267     case BO_Shr:
12268     case BO_ShrAssign: {
12269       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext,
12270                                 Approximate);
12271 
12272       // If the shift amount is a positive constant, drop the width by
12273       // that much.
12274       if (Optional<llvm::APSInt> shift =
12275               BO->getRHS()->getIntegerConstantExpr(C)) {
12276         if (shift->isNonNegative()) {
12277           unsigned zext = shift->getZExtValue();
12278           if (zext >= L.Width)
12279             L.Width = (L.NonNegative ? 0 : 1);
12280           else
12281             L.Width -= zext;
12282         }
12283       }
12284 
12285       return L;
12286     }
12287 
12288     // Comma acts as its right operand.
12289     case BO_Comma:
12290       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
12291                           Approximate);
12292 
12293     case BO_Add:
12294       if (!Approximate)
12295         Combine = IntRange::sum;
12296       break;
12297 
12298     case BO_Sub:
12299       if (BO->getLHS()->getType()->isPointerType())
12300         return IntRange::forValueOfType(C, GetExprType(E));
12301       if (!Approximate)
12302         Combine = IntRange::difference;
12303       break;
12304 
12305     case BO_Mul:
12306       if (!Approximate)
12307         Combine = IntRange::product;
12308       break;
12309 
12310     // The width of a division result is mostly determined by the size
12311     // of the LHS.
12312     case BO_Div: {
12313       // Don't 'pre-truncate' the operands.
12314       unsigned opWidth = C.getIntWidth(GetExprType(E));
12315       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext,
12316                                 Approximate);
12317 
12318       // If the divisor is constant, use that.
12319       if (Optional<llvm::APSInt> divisor =
12320               BO->getRHS()->getIntegerConstantExpr(C)) {
12321         unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
12322         if (log2 >= L.Width)
12323           L.Width = (L.NonNegative ? 0 : 1);
12324         else
12325           L.Width = std::min(L.Width - log2, MaxWidth);
12326         return L;
12327       }
12328 
12329       // Otherwise, just use the LHS's width.
12330       // FIXME: This is wrong if the LHS could be its minimal value and the RHS
12331       // could be -1.
12332       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext,
12333                                 Approximate);
12334       return IntRange(L.Width, L.NonNegative && R.NonNegative);
12335     }
12336 
12337     case BO_Rem:
12338       Combine = IntRange::rem;
12339       break;
12340 
12341     // The default behavior is okay for these.
12342     case BO_Xor:
12343     case BO_Or:
12344       break;
12345     }
12346 
12347     // Combine the two ranges, but limit the result to the type in which we
12348     // performed the computation.
12349     QualType T = GetExprType(E);
12350     unsigned opWidth = C.getIntWidth(T);
12351     IntRange L =
12352         GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate);
12353     IntRange R =
12354         GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate);
12355     IntRange C = Combine(L, R);
12356     C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
12357     C.Width = std::min(C.Width, MaxWidth);
12358     return C;
12359   }
12360 
12361   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
12362     switch (UO->getOpcode()) {
12363     // Boolean-valued operations are white-listed.
12364     case UO_LNot:
12365       return IntRange::forBoolType();
12366 
12367     // Operations with opaque sources are black-listed.
12368     case UO_Deref:
12369     case UO_AddrOf: // should be impossible
12370       return IntRange::forValueOfType(C, GetExprType(E));
12371 
12372     default:
12373       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
12374                           Approximate);
12375     }
12376   }
12377 
12378   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
12379     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
12380                         Approximate);
12381 
12382   if (const auto *BitField = E->getSourceBitField())
12383     return IntRange(BitField->getBitWidthValue(C),
12384                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
12385 
12386   return IntRange::forValueOfType(C, GetExprType(E));
12387 }
12388 
12389 static IntRange GetExprRange(ASTContext &C, const Expr *E,
12390                              bool InConstantContext, bool Approximate) {
12391   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
12392                       Approximate);
12393 }
12394 
12395 /// Checks whether the given value, which currently has the given
12396 /// source semantics, has the same value when coerced through the
12397 /// target semantics.
12398 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
12399                                  const llvm::fltSemantics &Src,
12400                                  const llvm::fltSemantics &Tgt) {
12401   llvm::APFloat truncated = value;
12402 
12403   bool ignored;
12404   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
12405   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
12406 
12407   return truncated.bitwiseIsEqual(value);
12408 }
12409 
12410 /// Checks whether the given value, which currently has the given
12411 /// source semantics, has the same value when coerced through the
12412 /// target semantics.
12413 ///
12414 /// The value might be a vector of floats (or a complex number).
12415 static bool IsSameFloatAfterCast(const APValue &value,
12416                                  const llvm::fltSemantics &Src,
12417                                  const llvm::fltSemantics &Tgt) {
12418   if (value.isFloat())
12419     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
12420 
12421   if (value.isVector()) {
12422     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
12423       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
12424         return false;
12425     return true;
12426   }
12427 
12428   assert(value.isComplexFloat());
12429   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
12430           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
12431 }
12432 
12433 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
12434                                        bool IsListInit = false);
12435 
12436 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
12437   // Suppress cases where we are comparing against an enum constant.
12438   if (const DeclRefExpr *DR =
12439       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
12440     if (isa<EnumConstantDecl>(DR->getDecl()))
12441       return true;
12442 
12443   // Suppress cases where the value is expanded from a macro, unless that macro
12444   // is how a language represents a boolean literal. This is the case in both C
12445   // and Objective-C.
12446   SourceLocation BeginLoc = E->getBeginLoc();
12447   if (BeginLoc.isMacroID()) {
12448     StringRef MacroName = Lexer::getImmediateMacroName(
12449         BeginLoc, S.getSourceManager(), S.getLangOpts());
12450     return MacroName != "YES" && MacroName != "NO" &&
12451            MacroName != "true" && MacroName != "false";
12452   }
12453 
12454   return false;
12455 }
12456 
12457 static bool isKnownToHaveUnsignedValue(Expr *E) {
12458   return E->getType()->isIntegerType() &&
12459          (!E->getType()->isSignedIntegerType() ||
12460           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
12461 }
12462 
12463 namespace {
12464 /// The promoted range of values of a type. In general this has the
12465 /// following structure:
12466 ///
12467 ///     |-----------| . . . |-----------|
12468 ///     ^           ^       ^           ^
12469 ///    Min       HoleMin  HoleMax      Max
12470 ///
12471 /// ... where there is only a hole if a signed type is promoted to unsigned
12472 /// (in which case Min and Max are the smallest and largest representable
12473 /// values).
12474 struct PromotedRange {
12475   // Min, or HoleMax if there is a hole.
12476   llvm::APSInt PromotedMin;
12477   // Max, or HoleMin if there is a hole.
12478   llvm::APSInt PromotedMax;
12479 
12480   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
12481     if (R.Width == 0)
12482       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
12483     else if (R.Width >= BitWidth && !Unsigned) {
12484       // Promotion made the type *narrower*. This happens when promoting
12485       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
12486       // Treat all values of 'signed int' as being in range for now.
12487       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
12488       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
12489     } else {
12490       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
12491                         .extOrTrunc(BitWidth);
12492       PromotedMin.setIsUnsigned(Unsigned);
12493 
12494       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
12495                         .extOrTrunc(BitWidth);
12496       PromotedMax.setIsUnsigned(Unsigned);
12497     }
12498   }
12499 
12500   // Determine whether this range is contiguous (has no hole).
12501   bool isContiguous() const { return PromotedMin <= PromotedMax; }
12502 
12503   // Where a constant value is within the range.
12504   enum ComparisonResult {
12505     LT = 0x1,
12506     LE = 0x2,
12507     GT = 0x4,
12508     GE = 0x8,
12509     EQ = 0x10,
12510     NE = 0x20,
12511     InRangeFlag = 0x40,
12512 
12513     Less = LE | LT | NE,
12514     Min = LE | InRangeFlag,
12515     InRange = InRangeFlag,
12516     Max = GE | InRangeFlag,
12517     Greater = GE | GT | NE,
12518 
12519     OnlyValue = LE | GE | EQ | InRangeFlag,
12520     InHole = NE
12521   };
12522 
12523   ComparisonResult compare(const llvm::APSInt &Value) const {
12524     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
12525            Value.isUnsigned() == PromotedMin.isUnsigned());
12526     if (!isContiguous()) {
12527       assert(Value.isUnsigned() && "discontiguous range for signed compare");
12528       if (Value.isMinValue()) return Min;
12529       if (Value.isMaxValue()) return Max;
12530       if (Value >= PromotedMin) return InRange;
12531       if (Value <= PromotedMax) return InRange;
12532       return InHole;
12533     }
12534 
12535     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
12536     case -1: return Less;
12537     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
12538     case 1:
12539       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
12540       case -1: return InRange;
12541       case 0: return Max;
12542       case 1: return Greater;
12543       }
12544     }
12545 
12546     llvm_unreachable("impossible compare result");
12547   }
12548 
12549   static llvm::Optional<StringRef>
12550   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
12551     if (Op == BO_Cmp) {
12552       ComparisonResult LTFlag = LT, GTFlag = GT;
12553       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
12554 
12555       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
12556       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
12557       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
12558       return llvm::None;
12559     }
12560 
12561     ComparisonResult TrueFlag, FalseFlag;
12562     if (Op == BO_EQ) {
12563       TrueFlag = EQ;
12564       FalseFlag = NE;
12565     } else if (Op == BO_NE) {
12566       TrueFlag = NE;
12567       FalseFlag = EQ;
12568     } else {
12569       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
12570         TrueFlag = LT;
12571         FalseFlag = GE;
12572       } else {
12573         TrueFlag = GT;
12574         FalseFlag = LE;
12575       }
12576       if (Op == BO_GE || Op == BO_LE)
12577         std::swap(TrueFlag, FalseFlag);
12578     }
12579     if (R & TrueFlag)
12580       return StringRef("true");
12581     if (R & FalseFlag)
12582       return StringRef("false");
12583     return llvm::None;
12584   }
12585 };
12586 }
12587 
12588 static bool HasEnumType(Expr *E) {
12589   // Strip off implicit integral promotions.
12590   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
12591     if (ICE->getCastKind() != CK_IntegralCast &&
12592         ICE->getCastKind() != CK_NoOp)
12593       break;
12594     E = ICE->getSubExpr();
12595   }
12596 
12597   return E->getType()->isEnumeralType();
12598 }
12599 
12600 static int classifyConstantValue(Expr *Constant) {
12601   // The values of this enumeration are used in the diagnostics
12602   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
12603   enum ConstantValueKind {
12604     Miscellaneous = 0,
12605     LiteralTrue,
12606     LiteralFalse
12607   };
12608   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
12609     return BL->getValue() ? ConstantValueKind::LiteralTrue
12610                           : ConstantValueKind::LiteralFalse;
12611   return ConstantValueKind::Miscellaneous;
12612 }
12613 
12614 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
12615                                         Expr *Constant, Expr *Other,
12616                                         const llvm::APSInt &Value,
12617                                         bool RhsConstant) {
12618   if (S.inTemplateInstantiation())
12619     return false;
12620 
12621   Expr *OriginalOther = Other;
12622 
12623   Constant = Constant->IgnoreParenImpCasts();
12624   Other = Other->IgnoreParenImpCasts();
12625 
12626   // Suppress warnings on tautological comparisons between values of the same
12627   // enumeration type. There are only two ways we could warn on this:
12628   //  - If the constant is outside the range of representable values of
12629   //    the enumeration. In such a case, we should warn about the cast
12630   //    to enumeration type, not about the comparison.
12631   //  - If the constant is the maximum / minimum in-range value. For an
12632   //    enumeratin type, such comparisons can be meaningful and useful.
12633   if (Constant->getType()->isEnumeralType() &&
12634       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
12635     return false;
12636 
12637   IntRange OtherValueRange = GetExprRange(
12638       S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false);
12639 
12640   QualType OtherT = Other->getType();
12641   if (const auto *AT = OtherT->getAs<AtomicType>())
12642     OtherT = AT->getValueType();
12643   IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
12644 
12645   // Special case for ObjC BOOL on targets where its a typedef for a signed char
12646   // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
12647   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
12648                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
12649                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
12650 
12651   // Whether we're treating Other as being a bool because of the form of
12652   // expression despite it having another type (typically 'int' in C).
12653   bool OtherIsBooleanDespiteType =
12654       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
12655   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
12656     OtherTypeRange = OtherValueRange = IntRange::forBoolType();
12657 
12658   // Check if all values in the range of possible values of this expression
12659   // lead to the same comparison outcome.
12660   PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(),
12661                                         Value.isUnsigned());
12662   auto Cmp = OtherPromotedValueRange.compare(Value);
12663   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
12664   if (!Result)
12665     return false;
12666 
12667   // Also consider the range determined by the type alone. This allows us to
12668   // classify the warning under the proper diagnostic group.
12669   bool TautologicalTypeCompare = false;
12670   {
12671     PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
12672                                          Value.isUnsigned());
12673     auto TypeCmp = OtherPromotedTypeRange.compare(Value);
12674     if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
12675                                                        RhsConstant)) {
12676       TautologicalTypeCompare = true;
12677       Cmp = TypeCmp;
12678       Result = TypeResult;
12679     }
12680   }
12681 
12682   // Don't warn if the non-constant operand actually always evaluates to the
12683   // same value.
12684   if (!TautologicalTypeCompare && OtherValueRange.Width == 0)
12685     return false;
12686 
12687   // Suppress the diagnostic for an in-range comparison if the constant comes
12688   // from a macro or enumerator. We don't want to diagnose
12689   //
12690   //   some_long_value <= INT_MAX
12691   //
12692   // when sizeof(int) == sizeof(long).
12693   bool InRange = Cmp & PromotedRange::InRangeFlag;
12694   if (InRange && IsEnumConstOrFromMacro(S, Constant))
12695     return false;
12696 
12697   // A comparison of an unsigned bit-field against 0 is really a type problem,
12698   // even though at the type level the bit-field might promote to 'signed int'.
12699   if (Other->refersToBitField() && InRange && Value == 0 &&
12700       Other->getType()->isUnsignedIntegerOrEnumerationType())
12701     TautologicalTypeCompare = true;
12702 
12703   // If this is a comparison to an enum constant, include that
12704   // constant in the diagnostic.
12705   const EnumConstantDecl *ED = nullptr;
12706   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
12707     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
12708 
12709   // Should be enough for uint128 (39 decimal digits)
12710   SmallString<64> PrettySourceValue;
12711   llvm::raw_svector_ostream OS(PrettySourceValue);
12712   if (ED) {
12713     OS << '\'' << *ED << "' (" << Value << ")";
12714   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
12715                Constant->IgnoreParenImpCasts())) {
12716     OS << (BL->getValue() ? "YES" : "NO");
12717   } else {
12718     OS << Value;
12719   }
12720 
12721   if (!TautologicalTypeCompare) {
12722     S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
12723         << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative
12724         << E->getOpcodeStr() << OS.str() << *Result
12725         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12726     return true;
12727   }
12728 
12729   if (IsObjCSignedCharBool) {
12730     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
12731                           S.PDiag(diag::warn_tautological_compare_objc_bool)
12732                               << OS.str() << *Result);
12733     return true;
12734   }
12735 
12736   // FIXME: We use a somewhat different formatting for the in-range cases and
12737   // cases involving boolean values for historical reasons. We should pick a
12738   // consistent way of presenting these diagnostics.
12739   if (!InRange || Other->isKnownToHaveBooleanValue()) {
12740 
12741     S.DiagRuntimeBehavior(
12742         E->getOperatorLoc(), E,
12743         S.PDiag(!InRange ? diag::warn_out_of_range_compare
12744                          : diag::warn_tautological_bool_compare)
12745             << OS.str() << classifyConstantValue(Constant) << OtherT
12746             << OtherIsBooleanDespiteType << *Result
12747             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
12748   } else {
12749     bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
12750     unsigned Diag =
12751         (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
12752             ? (HasEnumType(OriginalOther)
12753                    ? diag::warn_unsigned_enum_always_true_comparison
12754                    : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
12755                               : diag::warn_unsigned_always_true_comparison)
12756             : diag::warn_tautological_constant_compare;
12757 
12758     S.Diag(E->getOperatorLoc(), Diag)
12759         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
12760         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12761   }
12762 
12763   return true;
12764 }
12765 
12766 /// Analyze the operands of the given comparison.  Implements the
12767 /// fallback case from AnalyzeComparison.
12768 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
12769   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12770   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12771 }
12772 
12773 /// Implements -Wsign-compare.
12774 ///
12775 /// \param E the binary operator to check for warnings
12776 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
12777   // The type the comparison is being performed in.
12778   QualType T = E->getLHS()->getType();
12779 
12780   // Only analyze comparison operators where both sides have been converted to
12781   // the same type.
12782   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
12783     return AnalyzeImpConvsInComparison(S, E);
12784 
12785   // Don't analyze value-dependent comparisons directly.
12786   if (E->isValueDependent())
12787     return AnalyzeImpConvsInComparison(S, E);
12788 
12789   Expr *LHS = E->getLHS();
12790   Expr *RHS = E->getRHS();
12791 
12792   if (T->isIntegralType(S.Context)) {
12793     Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context);
12794     Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context);
12795 
12796     // We don't care about expressions whose result is a constant.
12797     if (RHSValue && LHSValue)
12798       return AnalyzeImpConvsInComparison(S, E);
12799 
12800     // We only care about expressions where just one side is literal
12801     if ((bool)RHSValue ^ (bool)LHSValue) {
12802       // Is the constant on the RHS or LHS?
12803       const bool RhsConstant = (bool)RHSValue;
12804       Expr *Const = RhsConstant ? RHS : LHS;
12805       Expr *Other = RhsConstant ? LHS : RHS;
12806       const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
12807 
12808       // Check whether an integer constant comparison results in a value
12809       // of 'true' or 'false'.
12810       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
12811         return AnalyzeImpConvsInComparison(S, E);
12812     }
12813   }
12814 
12815   if (!T->hasUnsignedIntegerRepresentation()) {
12816     // We don't do anything special if this isn't an unsigned integral
12817     // comparison:  we're only interested in integral comparisons, and
12818     // signed comparisons only happen in cases we don't care to warn about.
12819     return AnalyzeImpConvsInComparison(S, E);
12820   }
12821 
12822   LHS = LHS->IgnoreParenImpCasts();
12823   RHS = RHS->IgnoreParenImpCasts();
12824 
12825   if (!S.getLangOpts().CPlusPlus) {
12826     // Avoid warning about comparison of integers with different signs when
12827     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
12828     // the type of `E`.
12829     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
12830       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12831     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
12832       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12833   }
12834 
12835   // Check to see if one of the (unmodified) operands is of different
12836   // signedness.
12837   Expr *signedOperand, *unsignedOperand;
12838   if (LHS->getType()->hasSignedIntegerRepresentation()) {
12839     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
12840            "unsigned comparison between two signed integer expressions?");
12841     signedOperand = LHS;
12842     unsignedOperand = RHS;
12843   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
12844     signedOperand = RHS;
12845     unsignedOperand = LHS;
12846   } else {
12847     return AnalyzeImpConvsInComparison(S, E);
12848   }
12849 
12850   // Otherwise, calculate the effective range of the signed operand.
12851   IntRange signedRange = GetExprRange(
12852       S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true);
12853 
12854   // Go ahead and analyze implicit conversions in the operands.  Note
12855   // that we skip the implicit conversions on both sides.
12856   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
12857   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
12858 
12859   // If the signed range is non-negative, -Wsign-compare won't fire.
12860   if (signedRange.NonNegative)
12861     return;
12862 
12863   // For (in)equality comparisons, if the unsigned operand is a
12864   // constant which cannot collide with a overflowed signed operand,
12865   // then reinterpreting the signed operand as unsigned will not
12866   // change the result of the comparison.
12867   if (E->isEqualityOp()) {
12868     unsigned comparisonWidth = S.Context.getIntWidth(T);
12869     IntRange unsignedRange =
12870         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(),
12871                      /*Approximate*/ true);
12872 
12873     // We should never be unable to prove that the unsigned operand is
12874     // non-negative.
12875     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
12876 
12877     if (unsignedRange.Width < comparisonWidth)
12878       return;
12879   }
12880 
12881   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
12882                         S.PDiag(diag::warn_mixed_sign_comparison)
12883                             << LHS->getType() << RHS->getType()
12884                             << LHS->getSourceRange() << RHS->getSourceRange());
12885 }
12886 
12887 /// Analyzes an attempt to assign the given value to a bitfield.
12888 ///
12889 /// Returns true if there was something fishy about the attempt.
12890 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
12891                                       SourceLocation InitLoc) {
12892   assert(Bitfield->isBitField());
12893   if (Bitfield->isInvalidDecl())
12894     return false;
12895 
12896   // White-list bool bitfields.
12897   QualType BitfieldType = Bitfield->getType();
12898   if (BitfieldType->isBooleanType())
12899      return false;
12900 
12901   if (BitfieldType->isEnumeralType()) {
12902     EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
12903     // If the underlying enum type was not explicitly specified as an unsigned
12904     // type and the enum contain only positive values, MSVC++ will cause an
12905     // inconsistency by storing this as a signed type.
12906     if (S.getLangOpts().CPlusPlus11 &&
12907         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
12908         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
12909         BitfieldEnumDecl->getNumNegativeBits() == 0) {
12910       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
12911           << BitfieldEnumDecl;
12912     }
12913   }
12914 
12915   if (Bitfield->getType()->isBooleanType())
12916     return false;
12917 
12918   // Ignore value- or type-dependent expressions.
12919   if (Bitfield->getBitWidth()->isValueDependent() ||
12920       Bitfield->getBitWidth()->isTypeDependent() ||
12921       Init->isValueDependent() ||
12922       Init->isTypeDependent())
12923     return false;
12924 
12925   Expr *OriginalInit = Init->IgnoreParenImpCasts();
12926   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
12927 
12928   Expr::EvalResult Result;
12929   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
12930                                    Expr::SE_AllowSideEffects)) {
12931     // The RHS is not constant.  If the RHS has an enum type, make sure the
12932     // bitfield is wide enough to hold all the values of the enum without
12933     // truncation.
12934     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
12935       EnumDecl *ED = EnumTy->getDecl();
12936       bool SignedBitfield = BitfieldType->isSignedIntegerType();
12937 
12938       // Enum types are implicitly signed on Windows, so check if there are any
12939       // negative enumerators to see if the enum was intended to be signed or
12940       // not.
12941       bool SignedEnum = ED->getNumNegativeBits() > 0;
12942 
12943       // Check for surprising sign changes when assigning enum values to a
12944       // bitfield of different signedness.  If the bitfield is signed and we
12945       // have exactly the right number of bits to store this unsigned enum,
12946       // suggest changing the enum to an unsigned type. This typically happens
12947       // on Windows where unfixed enums always use an underlying type of 'int'.
12948       unsigned DiagID = 0;
12949       if (SignedEnum && !SignedBitfield) {
12950         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
12951       } else if (SignedBitfield && !SignedEnum &&
12952                  ED->getNumPositiveBits() == FieldWidth) {
12953         DiagID = diag::warn_signed_bitfield_enum_conversion;
12954       }
12955 
12956       if (DiagID) {
12957         S.Diag(InitLoc, DiagID) << Bitfield << ED;
12958         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
12959         SourceRange TypeRange =
12960             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
12961         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
12962             << SignedEnum << TypeRange;
12963       }
12964 
12965       // Compute the required bitwidth. If the enum has negative values, we need
12966       // one more bit than the normal number of positive bits to represent the
12967       // sign bit.
12968       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
12969                                                   ED->getNumNegativeBits())
12970                                        : ED->getNumPositiveBits();
12971 
12972       // Check the bitwidth.
12973       if (BitsNeeded > FieldWidth) {
12974         Expr *WidthExpr = Bitfield->getBitWidth();
12975         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
12976             << Bitfield << ED;
12977         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
12978             << BitsNeeded << ED << WidthExpr->getSourceRange();
12979       }
12980     }
12981 
12982     return false;
12983   }
12984 
12985   llvm::APSInt Value = Result.Val.getInt();
12986 
12987   unsigned OriginalWidth = Value.getBitWidth();
12988 
12989   if (!Value.isSigned() || Value.isNegative())
12990     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
12991       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
12992         OriginalWidth = Value.getMinSignedBits();
12993 
12994   if (OriginalWidth <= FieldWidth)
12995     return false;
12996 
12997   // Compute the value which the bitfield will contain.
12998   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
12999   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
13000 
13001   // Check whether the stored value is equal to the original value.
13002   TruncatedValue = TruncatedValue.extend(OriginalWidth);
13003   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
13004     return false;
13005 
13006   // Special-case bitfields of width 1: booleans are naturally 0/1, and
13007   // therefore don't strictly fit into a signed bitfield of width 1.
13008   if (FieldWidth == 1 && Value == 1)
13009     return false;
13010 
13011   std::string PrettyValue = toString(Value, 10);
13012   std::string PrettyTrunc = toString(TruncatedValue, 10);
13013 
13014   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
13015     << PrettyValue << PrettyTrunc << OriginalInit->getType()
13016     << Init->getSourceRange();
13017 
13018   return true;
13019 }
13020 
13021 /// Analyze the given simple or compound assignment for warning-worthy
13022 /// operations.
13023 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
13024   // Just recurse on the LHS.
13025   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
13026 
13027   // We want to recurse on the RHS as normal unless we're assigning to
13028   // a bitfield.
13029   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
13030     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
13031                                   E->getOperatorLoc())) {
13032       // Recurse, ignoring any implicit conversions on the RHS.
13033       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
13034                                         E->getOperatorLoc());
13035     }
13036   }
13037 
13038   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
13039 
13040   // Diagnose implicitly sequentially-consistent atomic assignment.
13041   if (E->getLHS()->getType()->isAtomicType())
13042     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
13043 }
13044 
13045 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
13046 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
13047                             SourceLocation CContext, unsigned diag,
13048                             bool pruneControlFlow = false) {
13049   if (pruneControlFlow) {
13050     S.DiagRuntimeBehavior(E->getExprLoc(), E,
13051                           S.PDiag(diag)
13052                               << SourceType << T << E->getSourceRange()
13053                               << SourceRange(CContext));
13054     return;
13055   }
13056   S.Diag(E->getExprLoc(), diag)
13057     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
13058 }
13059 
13060 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
13061 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
13062                             SourceLocation CContext,
13063                             unsigned diag, bool pruneControlFlow = false) {
13064   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
13065 }
13066 
13067 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
13068   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
13069       S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
13070 }
13071 
13072 static void adornObjCBoolConversionDiagWithTernaryFixit(
13073     Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
13074   Expr *Ignored = SourceExpr->IgnoreImplicit();
13075   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
13076     Ignored = OVE->getSourceExpr();
13077   bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
13078                      isa<BinaryOperator>(Ignored) ||
13079                      isa<CXXOperatorCallExpr>(Ignored);
13080   SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
13081   if (NeedsParens)
13082     Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
13083             << FixItHint::CreateInsertion(EndLoc, ")");
13084   Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
13085 }
13086 
13087 /// Diagnose an implicit cast from a floating point value to an integer value.
13088 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
13089                                     SourceLocation CContext) {
13090   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
13091   const bool PruneWarnings = S.inTemplateInstantiation();
13092 
13093   Expr *InnerE = E->IgnoreParenImpCasts();
13094   // We also want to warn on, e.g., "int i = -1.234"
13095   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
13096     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
13097       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
13098 
13099   const bool IsLiteral =
13100       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
13101 
13102   llvm::APFloat Value(0.0);
13103   bool IsConstant =
13104     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
13105   if (!IsConstant) {
13106     if (isObjCSignedCharBool(S, T)) {
13107       return adornObjCBoolConversionDiagWithTernaryFixit(
13108           S, E,
13109           S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
13110               << E->getType());
13111     }
13112 
13113     return DiagnoseImpCast(S, E, T, CContext,
13114                            diag::warn_impcast_float_integer, PruneWarnings);
13115   }
13116 
13117   bool isExact = false;
13118 
13119   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
13120                             T->hasUnsignedIntegerRepresentation());
13121   llvm::APFloat::opStatus Result = Value.convertToInteger(
13122       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
13123 
13124   // FIXME: Force the precision of the source value down so we don't print
13125   // digits which are usually useless (we don't really care here if we
13126   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
13127   // would automatically print the shortest representation, but it's a bit
13128   // tricky to implement.
13129   SmallString<16> PrettySourceValue;
13130   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
13131   precision = (precision * 59 + 195) / 196;
13132   Value.toString(PrettySourceValue, precision);
13133 
13134   if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
13135     return adornObjCBoolConversionDiagWithTernaryFixit(
13136         S, E,
13137         S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
13138             << PrettySourceValue);
13139   }
13140 
13141   if (Result == llvm::APFloat::opOK && isExact) {
13142     if (IsLiteral) return;
13143     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
13144                            PruneWarnings);
13145   }
13146 
13147   // Conversion of a floating-point value to a non-bool integer where the
13148   // integral part cannot be represented by the integer type is undefined.
13149   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
13150     return DiagnoseImpCast(
13151         S, E, T, CContext,
13152         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
13153                   : diag::warn_impcast_float_to_integer_out_of_range,
13154         PruneWarnings);
13155 
13156   unsigned DiagID = 0;
13157   if (IsLiteral) {
13158     // Warn on floating point literal to integer.
13159     DiagID = diag::warn_impcast_literal_float_to_integer;
13160   } else if (IntegerValue == 0) {
13161     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
13162       return DiagnoseImpCast(S, E, T, CContext,
13163                              diag::warn_impcast_float_integer, PruneWarnings);
13164     }
13165     // Warn on non-zero to zero conversion.
13166     DiagID = diag::warn_impcast_float_to_integer_zero;
13167   } else {
13168     if (IntegerValue.isUnsigned()) {
13169       if (!IntegerValue.isMaxValue()) {
13170         return DiagnoseImpCast(S, E, T, CContext,
13171                                diag::warn_impcast_float_integer, PruneWarnings);
13172       }
13173     } else {  // IntegerValue.isSigned()
13174       if (!IntegerValue.isMaxSignedValue() &&
13175           !IntegerValue.isMinSignedValue()) {
13176         return DiagnoseImpCast(S, E, T, CContext,
13177                                diag::warn_impcast_float_integer, PruneWarnings);
13178       }
13179     }
13180     // Warn on evaluatable floating point expression to integer conversion.
13181     DiagID = diag::warn_impcast_float_to_integer;
13182   }
13183 
13184   SmallString<16> PrettyTargetValue;
13185   if (IsBool)
13186     PrettyTargetValue = Value.isZero() ? "false" : "true";
13187   else
13188     IntegerValue.toString(PrettyTargetValue);
13189 
13190   if (PruneWarnings) {
13191     S.DiagRuntimeBehavior(E->getExprLoc(), E,
13192                           S.PDiag(DiagID)
13193                               << E->getType() << T.getUnqualifiedType()
13194                               << PrettySourceValue << PrettyTargetValue
13195                               << E->getSourceRange() << SourceRange(CContext));
13196   } else {
13197     S.Diag(E->getExprLoc(), DiagID)
13198         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
13199         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
13200   }
13201 }
13202 
13203 /// Analyze the given compound assignment for the possible losing of
13204 /// floating-point precision.
13205 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
13206   assert(isa<CompoundAssignOperator>(E) &&
13207          "Must be compound assignment operation");
13208   // Recurse on the LHS and RHS in here
13209   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
13210   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
13211 
13212   if (E->getLHS()->getType()->isAtomicType())
13213     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
13214 
13215   // Now check the outermost expression
13216   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
13217   const auto *RBT = cast<CompoundAssignOperator>(E)
13218                         ->getComputationResultType()
13219                         ->getAs<BuiltinType>();
13220 
13221   // The below checks assume source is floating point.
13222   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
13223 
13224   // If source is floating point but target is an integer.
13225   if (ResultBT->isInteger())
13226     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
13227                            E->getExprLoc(), diag::warn_impcast_float_integer);
13228 
13229   if (!ResultBT->isFloatingPoint())
13230     return;
13231 
13232   // If both source and target are floating points, warn about losing precision.
13233   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
13234       QualType(ResultBT, 0), QualType(RBT, 0));
13235   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
13236     // warn about dropping FP rank.
13237     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
13238                     diag::warn_impcast_float_result_precision);
13239 }
13240 
13241 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
13242                                       IntRange Range) {
13243   if (!Range.Width) return "0";
13244 
13245   llvm::APSInt ValueInRange = Value;
13246   ValueInRange.setIsSigned(!Range.NonNegative);
13247   ValueInRange = ValueInRange.trunc(Range.Width);
13248   return toString(ValueInRange, 10);
13249 }
13250 
13251 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
13252   if (!isa<ImplicitCastExpr>(Ex))
13253     return false;
13254 
13255   Expr *InnerE = Ex->IgnoreParenImpCasts();
13256   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
13257   const Type *Source =
13258     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
13259   if (Target->isDependentType())
13260     return false;
13261 
13262   const BuiltinType *FloatCandidateBT =
13263     dyn_cast<BuiltinType>(ToBool ? Source : Target);
13264   const Type *BoolCandidateType = ToBool ? Target : Source;
13265 
13266   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
13267           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
13268 }
13269 
13270 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
13271                                              SourceLocation CC) {
13272   unsigned NumArgs = TheCall->getNumArgs();
13273   for (unsigned i = 0; i < NumArgs; ++i) {
13274     Expr *CurrA = TheCall->getArg(i);
13275     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
13276       continue;
13277 
13278     bool IsSwapped = ((i > 0) &&
13279         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
13280     IsSwapped |= ((i < (NumArgs - 1)) &&
13281         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
13282     if (IsSwapped) {
13283       // Warn on this floating-point to bool conversion.
13284       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
13285                       CurrA->getType(), CC,
13286                       diag::warn_impcast_floating_point_to_bool);
13287     }
13288   }
13289 }
13290 
13291 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
13292                                    SourceLocation CC) {
13293   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
13294                         E->getExprLoc()))
13295     return;
13296 
13297   // Don't warn on functions which have return type nullptr_t.
13298   if (isa<CallExpr>(E))
13299     return;
13300 
13301   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
13302   const Expr::NullPointerConstantKind NullKind =
13303       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
13304   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
13305     return;
13306 
13307   // Return if target type is a safe conversion.
13308   if (T->isAnyPointerType() || T->isBlockPointerType() ||
13309       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
13310     return;
13311 
13312   SourceLocation Loc = E->getSourceRange().getBegin();
13313 
13314   // Venture through the macro stacks to get to the source of macro arguments.
13315   // The new location is a better location than the complete location that was
13316   // passed in.
13317   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
13318   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
13319 
13320   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
13321   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
13322     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
13323         Loc, S.SourceMgr, S.getLangOpts());
13324     if (MacroName == "NULL")
13325       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
13326   }
13327 
13328   // Only warn if the null and context location are in the same macro expansion.
13329   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
13330     return;
13331 
13332   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
13333       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
13334       << FixItHint::CreateReplacement(Loc,
13335                                       S.getFixItZeroLiteralForType(T, Loc));
13336 }
13337 
13338 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
13339                                   ObjCArrayLiteral *ArrayLiteral);
13340 
13341 static void
13342 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
13343                            ObjCDictionaryLiteral *DictionaryLiteral);
13344 
13345 /// Check a single element within a collection literal against the
13346 /// target element type.
13347 static void checkObjCCollectionLiteralElement(Sema &S,
13348                                               QualType TargetElementType,
13349                                               Expr *Element,
13350                                               unsigned ElementKind) {
13351   // Skip a bitcast to 'id' or qualified 'id'.
13352   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
13353     if (ICE->getCastKind() == CK_BitCast &&
13354         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
13355       Element = ICE->getSubExpr();
13356   }
13357 
13358   QualType ElementType = Element->getType();
13359   ExprResult ElementResult(Element);
13360   if (ElementType->getAs<ObjCObjectPointerType>() &&
13361       S.CheckSingleAssignmentConstraints(TargetElementType,
13362                                          ElementResult,
13363                                          false, false)
13364         != Sema::Compatible) {
13365     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
13366         << ElementType << ElementKind << TargetElementType
13367         << Element->getSourceRange();
13368   }
13369 
13370   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
13371     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
13372   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
13373     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
13374 }
13375 
13376 /// Check an Objective-C array literal being converted to the given
13377 /// target type.
13378 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
13379                                   ObjCArrayLiteral *ArrayLiteral) {
13380   if (!S.NSArrayDecl)
13381     return;
13382 
13383   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
13384   if (!TargetObjCPtr)
13385     return;
13386 
13387   if (TargetObjCPtr->isUnspecialized() ||
13388       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
13389         != S.NSArrayDecl->getCanonicalDecl())
13390     return;
13391 
13392   auto TypeArgs = TargetObjCPtr->getTypeArgs();
13393   if (TypeArgs.size() != 1)
13394     return;
13395 
13396   QualType TargetElementType = TypeArgs[0];
13397   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
13398     checkObjCCollectionLiteralElement(S, TargetElementType,
13399                                       ArrayLiteral->getElement(I),
13400                                       0);
13401   }
13402 }
13403 
13404 /// Check an Objective-C dictionary literal being converted to the given
13405 /// target type.
13406 static void
13407 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
13408                            ObjCDictionaryLiteral *DictionaryLiteral) {
13409   if (!S.NSDictionaryDecl)
13410     return;
13411 
13412   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
13413   if (!TargetObjCPtr)
13414     return;
13415 
13416   if (TargetObjCPtr->isUnspecialized() ||
13417       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
13418         != S.NSDictionaryDecl->getCanonicalDecl())
13419     return;
13420 
13421   auto TypeArgs = TargetObjCPtr->getTypeArgs();
13422   if (TypeArgs.size() != 2)
13423     return;
13424 
13425   QualType TargetKeyType = TypeArgs[0];
13426   QualType TargetObjectType = TypeArgs[1];
13427   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
13428     auto Element = DictionaryLiteral->getKeyValueElement(I);
13429     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
13430     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
13431   }
13432 }
13433 
13434 // Helper function to filter out cases for constant width constant conversion.
13435 // Don't warn on char array initialization or for non-decimal values.
13436 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
13437                                           SourceLocation CC) {
13438   // If initializing from a constant, and the constant starts with '0',
13439   // then it is a binary, octal, or hexadecimal.  Allow these constants
13440   // to fill all the bits, even if there is a sign change.
13441   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
13442     const char FirstLiteralCharacter =
13443         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
13444     if (FirstLiteralCharacter == '0')
13445       return false;
13446   }
13447 
13448   // If the CC location points to a '{', and the type is char, then assume
13449   // assume it is an array initialization.
13450   if (CC.isValid() && T->isCharType()) {
13451     const char FirstContextCharacter =
13452         S.getSourceManager().getCharacterData(CC)[0];
13453     if (FirstContextCharacter == '{')
13454       return false;
13455   }
13456 
13457   return true;
13458 }
13459 
13460 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
13461   const auto *IL = dyn_cast<IntegerLiteral>(E);
13462   if (!IL) {
13463     if (auto *UO = dyn_cast<UnaryOperator>(E)) {
13464       if (UO->getOpcode() == UO_Minus)
13465         return dyn_cast<IntegerLiteral>(UO->getSubExpr());
13466     }
13467   }
13468 
13469   return IL;
13470 }
13471 
13472 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
13473   E = E->IgnoreParenImpCasts();
13474   SourceLocation ExprLoc = E->getExprLoc();
13475 
13476   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
13477     BinaryOperator::Opcode Opc = BO->getOpcode();
13478     Expr::EvalResult Result;
13479     // Do not diagnose unsigned shifts.
13480     if (Opc == BO_Shl) {
13481       const auto *LHS = getIntegerLiteral(BO->getLHS());
13482       const auto *RHS = getIntegerLiteral(BO->getRHS());
13483       if (LHS && LHS->getValue() == 0)
13484         S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
13485       else if (!E->isValueDependent() && LHS && RHS &&
13486                RHS->getValue().isNonNegative() &&
13487                E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
13488         S.Diag(ExprLoc, diag::warn_left_shift_always)
13489             << (Result.Val.getInt() != 0);
13490       else if (E->getType()->isSignedIntegerType())
13491         S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
13492     }
13493   }
13494 
13495   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
13496     const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
13497     const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
13498     if (!LHS || !RHS)
13499       return;
13500     if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
13501         (RHS->getValue() == 0 || RHS->getValue() == 1))
13502       // Do not diagnose common idioms.
13503       return;
13504     if (LHS->getValue() != 0 && RHS->getValue() != 0)
13505       S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
13506   }
13507 }
13508 
13509 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
13510                                     SourceLocation CC,
13511                                     bool *ICContext = nullptr,
13512                                     bool IsListInit = false) {
13513   if (E->isTypeDependent() || E->isValueDependent()) return;
13514 
13515   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
13516   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
13517   if (Source == Target) return;
13518   if (Target->isDependentType()) return;
13519 
13520   // If the conversion context location is invalid don't complain. We also
13521   // don't want to emit a warning if the issue occurs from the expansion of
13522   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
13523   // delay this check as long as possible. Once we detect we are in that
13524   // scenario, we just return.
13525   if (CC.isInvalid())
13526     return;
13527 
13528   if (Source->isAtomicType())
13529     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
13530 
13531   // Diagnose implicit casts to bool.
13532   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
13533     if (isa<StringLiteral>(E))
13534       // Warn on string literal to bool.  Checks for string literals in logical
13535       // and expressions, for instance, assert(0 && "error here"), are
13536       // prevented by a check in AnalyzeImplicitConversions().
13537       return DiagnoseImpCast(S, E, T, CC,
13538                              diag::warn_impcast_string_literal_to_bool);
13539     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
13540         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
13541       // This covers the literal expressions that evaluate to Objective-C
13542       // objects.
13543       return DiagnoseImpCast(S, E, T, CC,
13544                              diag::warn_impcast_objective_c_literal_to_bool);
13545     }
13546     if (Source->isPointerType() || Source->canDecayToPointerType()) {
13547       // Warn on pointer to bool conversion that is always true.
13548       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
13549                                      SourceRange(CC));
13550     }
13551   }
13552 
13553   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
13554   // is a typedef for signed char (macOS), then that constant value has to be 1
13555   // or 0.
13556   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
13557     Expr::EvalResult Result;
13558     if (E->EvaluateAsInt(Result, S.getASTContext(),
13559                          Expr::SE_AllowSideEffects)) {
13560       if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
13561         adornObjCBoolConversionDiagWithTernaryFixit(
13562             S, E,
13563             S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
13564                 << toString(Result.Val.getInt(), 10));
13565       }
13566       return;
13567     }
13568   }
13569 
13570   // Check implicit casts from Objective-C collection literals to specialized
13571   // collection types, e.g., NSArray<NSString *> *.
13572   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
13573     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
13574   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
13575     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
13576 
13577   // Strip vector types.
13578   if (isa<VectorType>(Source)) {
13579     if (Target->isVLSTBuiltinType() &&
13580         (S.Context.areCompatibleSveTypes(QualType(Target, 0),
13581                                          QualType(Source, 0)) ||
13582          S.Context.areLaxCompatibleSveTypes(QualType(Target, 0),
13583                                             QualType(Source, 0))))
13584       return;
13585 
13586     if (!isa<VectorType>(Target)) {
13587       if (S.SourceMgr.isInSystemMacro(CC))
13588         return;
13589       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
13590     }
13591 
13592     // If the vector cast is cast between two vectors of the same size, it is
13593     // a bitcast, not a conversion.
13594     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
13595       return;
13596 
13597     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
13598     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
13599   }
13600   if (auto VecTy = dyn_cast<VectorType>(Target))
13601     Target = VecTy->getElementType().getTypePtr();
13602 
13603   // Strip complex types.
13604   if (isa<ComplexType>(Source)) {
13605     if (!isa<ComplexType>(Target)) {
13606       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
13607         return;
13608 
13609       return DiagnoseImpCast(S, E, T, CC,
13610                              S.getLangOpts().CPlusPlus
13611                                  ? diag::err_impcast_complex_scalar
13612                                  : diag::warn_impcast_complex_scalar);
13613     }
13614 
13615     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
13616     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
13617   }
13618 
13619   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
13620   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
13621 
13622   // Strip SVE vector types
13623   if (SourceBT && SourceBT->isVLSTBuiltinType()) {
13624     // Need the original target type for vector type checks
13625     const Type *OriginalTarget = S.Context.getCanonicalType(T).getTypePtr();
13626     // Handle conversion from scalable to fixed when msve-vector-bits is
13627     // specified
13628     if (S.Context.areCompatibleSveTypes(QualType(OriginalTarget, 0),
13629                                         QualType(Source, 0)) ||
13630         S.Context.areLaxCompatibleSveTypes(QualType(OriginalTarget, 0),
13631                                            QualType(Source, 0)))
13632       return;
13633 
13634     // If the vector cast is cast between two vectors of the same size, it is
13635     // a bitcast, not a conversion.
13636     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
13637       return;
13638 
13639     Source = SourceBT->getSveEltType(S.Context).getTypePtr();
13640   }
13641 
13642   if (TargetBT && TargetBT->isVLSTBuiltinType())
13643     Target = TargetBT->getSveEltType(S.Context).getTypePtr();
13644 
13645   // If the source is floating point...
13646   if (SourceBT && SourceBT->isFloatingPoint()) {
13647     // ...and the target is floating point...
13648     if (TargetBT && TargetBT->isFloatingPoint()) {
13649       // ...then warn if we're dropping FP rank.
13650 
13651       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
13652           QualType(SourceBT, 0), QualType(TargetBT, 0));
13653       if (Order > 0) {
13654         // Don't warn about float constants that are precisely
13655         // representable in the target type.
13656         Expr::EvalResult result;
13657         if (E->EvaluateAsRValue(result, S.Context)) {
13658           // Value might be a float, a float vector, or a float complex.
13659           if (IsSameFloatAfterCast(result.Val,
13660                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
13661                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
13662             return;
13663         }
13664 
13665         if (S.SourceMgr.isInSystemMacro(CC))
13666           return;
13667 
13668         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
13669       }
13670       // ... or possibly if we're increasing rank, too
13671       else if (Order < 0) {
13672         if (S.SourceMgr.isInSystemMacro(CC))
13673           return;
13674 
13675         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
13676       }
13677       return;
13678     }
13679 
13680     // If the target is integral, always warn.
13681     if (TargetBT && TargetBT->isInteger()) {
13682       if (S.SourceMgr.isInSystemMacro(CC))
13683         return;
13684 
13685       DiagnoseFloatingImpCast(S, E, T, CC);
13686     }
13687 
13688     // Detect the case where a call result is converted from floating-point to
13689     // to bool, and the final argument to the call is converted from bool, to
13690     // discover this typo:
13691     //
13692     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
13693     //
13694     // FIXME: This is an incredibly special case; is there some more general
13695     // way to detect this class of misplaced-parentheses bug?
13696     if (Target->isBooleanType() && isa<CallExpr>(E)) {
13697       // Check last argument of function call to see if it is an
13698       // implicit cast from a type matching the type the result
13699       // is being cast to.
13700       CallExpr *CEx = cast<CallExpr>(E);
13701       if (unsigned NumArgs = CEx->getNumArgs()) {
13702         Expr *LastA = CEx->getArg(NumArgs - 1);
13703         Expr *InnerE = LastA->IgnoreParenImpCasts();
13704         if (isa<ImplicitCastExpr>(LastA) &&
13705             InnerE->getType()->isBooleanType()) {
13706           // Warn on this floating-point to bool conversion
13707           DiagnoseImpCast(S, E, T, CC,
13708                           diag::warn_impcast_floating_point_to_bool);
13709         }
13710       }
13711     }
13712     return;
13713   }
13714 
13715   // Valid casts involving fixed point types should be accounted for here.
13716   if (Source->isFixedPointType()) {
13717     if (Target->isUnsaturatedFixedPointType()) {
13718       Expr::EvalResult Result;
13719       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
13720                                   S.isConstantEvaluated())) {
13721         llvm::APFixedPoint Value = Result.Val.getFixedPoint();
13722         llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
13723         llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T);
13724         if (Value > MaxVal || Value < MinVal) {
13725           S.DiagRuntimeBehavior(E->getExprLoc(), E,
13726                                 S.PDiag(diag::warn_impcast_fixed_point_range)
13727                                     << Value.toString() << T
13728                                     << E->getSourceRange()
13729                                     << clang::SourceRange(CC));
13730           return;
13731         }
13732       }
13733     } else if (Target->isIntegerType()) {
13734       Expr::EvalResult Result;
13735       if (!S.isConstantEvaluated() &&
13736           E->EvaluateAsFixedPoint(Result, S.Context,
13737                                   Expr::SE_AllowSideEffects)) {
13738         llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
13739 
13740         bool Overflowed;
13741         llvm::APSInt IntResult = FXResult.convertToInt(
13742             S.Context.getIntWidth(T),
13743             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
13744 
13745         if (Overflowed) {
13746           S.DiagRuntimeBehavior(E->getExprLoc(), E,
13747                                 S.PDiag(diag::warn_impcast_fixed_point_range)
13748                                     << FXResult.toString() << T
13749                                     << E->getSourceRange()
13750                                     << clang::SourceRange(CC));
13751           return;
13752         }
13753       }
13754     }
13755   } else if (Target->isUnsaturatedFixedPointType()) {
13756     if (Source->isIntegerType()) {
13757       Expr::EvalResult Result;
13758       if (!S.isConstantEvaluated() &&
13759           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
13760         llvm::APSInt Value = Result.Val.getInt();
13761 
13762         bool Overflowed;
13763         llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
13764             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
13765 
13766         if (Overflowed) {
13767           S.DiagRuntimeBehavior(E->getExprLoc(), E,
13768                                 S.PDiag(diag::warn_impcast_fixed_point_range)
13769                                     << toString(Value, /*Radix=*/10) << T
13770                                     << E->getSourceRange()
13771                                     << clang::SourceRange(CC));
13772           return;
13773         }
13774       }
13775     }
13776   }
13777 
13778   // If we are casting an integer type to a floating point type without
13779   // initialization-list syntax, we might lose accuracy if the floating
13780   // point type has a narrower significand than the integer type.
13781   if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
13782       TargetBT->isFloatingType() && !IsListInit) {
13783     // Determine the number of precision bits in the source integer type.
13784     IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(),
13785                                         /*Approximate*/ true);
13786     unsigned int SourcePrecision = SourceRange.Width;
13787 
13788     // Determine the number of precision bits in the
13789     // target floating point type.
13790     unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
13791         S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
13792 
13793     if (SourcePrecision > 0 && TargetPrecision > 0 &&
13794         SourcePrecision > TargetPrecision) {
13795 
13796       if (Optional<llvm::APSInt> SourceInt =
13797               E->getIntegerConstantExpr(S.Context)) {
13798         // If the source integer is a constant, convert it to the target
13799         // floating point type. Issue a warning if the value changes
13800         // during the whole conversion.
13801         llvm::APFloat TargetFloatValue(
13802             S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
13803         llvm::APFloat::opStatus ConversionStatus =
13804             TargetFloatValue.convertFromAPInt(
13805                 *SourceInt, SourceBT->isSignedInteger(),
13806                 llvm::APFloat::rmNearestTiesToEven);
13807 
13808         if (ConversionStatus != llvm::APFloat::opOK) {
13809           SmallString<32> PrettySourceValue;
13810           SourceInt->toString(PrettySourceValue, 10);
13811           SmallString<32> PrettyTargetValue;
13812           TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
13813 
13814           S.DiagRuntimeBehavior(
13815               E->getExprLoc(), E,
13816               S.PDiag(diag::warn_impcast_integer_float_precision_constant)
13817                   << PrettySourceValue << PrettyTargetValue << E->getType() << T
13818                   << E->getSourceRange() << clang::SourceRange(CC));
13819         }
13820       } else {
13821         // Otherwise, the implicit conversion may lose precision.
13822         DiagnoseImpCast(S, E, T, CC,
13823                         diag::warn_impcast_integer_float_precision);
13824       }
13825     }
13826   }
13827 
13828   DiagnoseNullConversion(S, E, T, CC);
13829 
13830   S.DiscardMisalignedMemberAddress(Target, E);
13831 
13832   if (Target->isBooleanType())
13833     DiagnoseIntInBoolContext(S, E);
13834 
13835   if (!Source->isIntegerType() || !Target->isIntegerType())
13836     return;
13837 
13838   // TODO: remove this early return once the false positives for constant->bool
13839   // in templates, macros, etc, are reduced or removed.
13840   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
13841     return;
13842 
13843   if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
13844       !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
13845     return adornObjCBoolConversionDiagWithTernaryFixit(
13846         S, E,
13847         S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
13848             << E->getType());
13849   }
13850 
13851   IntRange SourceTypeRange =
13852       IntRange::forTargetOfCanonicalType(S.Context, Source);
13853   IntRange LikelySourceRange =
13854       GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true);
13855   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
13856 
13857   if (LikelySourceRange.Width > TargetRange.Width) {
13858     // If the source is a constant, use a default-on diagnostic.
13859     // TODO: this should happen for bitfield stores, too.
13860     Expr::EvalResult Result;
13861     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
13862                          S.isConstantEvaluated())) {
13863       llvm::APSInt Value(32);
13864       Value = Result.Val.getInt();
13865 
13866       if (S.SourceMgr.isInSystemMacro(CC))
13867         return;
13868 
13869       std::string PrettySourceValue = toString(Value, 10);
13870       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13871 
13872       S.DiagRuntimeBehavior(
13873           E->getExprLoc(), E,
13874           S.PDiag(diag::warn_impcast_integer_precision_constant)
13875               << PrettySourceValue << PrettyTargetValue << E->getType() << T
13876               << E->getSourceRange() << SourceRange(CC));
13877       return;
13878     }
13879 
13880     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
13881     if (S.SourceMgr.isInSystemMacro(CC))
13882       return;
13883 
13884     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
13885       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
13886                              /* pruneControlFlow */ true);
13887     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
13888   }
13889 
13890   if (TargetRange.Width > SourceTypeRange.Width) {
13891     if (auto *UO = dyn_cast<UnaryOperator>(E))
13892       if (UO->getOpcode() == UO_Minus)
13893         if (Source->isUnsignedIntegerType()) {
13894           if (Target->isUnsignedIntegerType())
13895             return DiagnoseImpCast(S, E, T, CC,
13896                                    diag::warn_impcast_high_order_zero_bits);
13897           if (Target->isSignedIntegerType())
13898             return DiagnoseImpCast(S, E, T, CC,
13899                                    diag::warn_impcast_nonnegative_result);
13900         }
13901   }
13902 
13903   if (TargetRange.Width == LikelySourceRange.Width &&
13904       !TargetRange.NonNegative && LikelySourceRange.NonNegative &&
13905       Source->isSignedIntegerType()) {
13906     // Warn when doing a signed to signed conversion, warn if the positive
13907     // source value is exactly the width of the target type, which will
13908     // cause a negative value to be stored.
13909 
13910     Expr::EvalResult Result;
13911     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
13912         !S.SourceMgr.isInSystemMacro(CC)) {
13913       llvm::APSInt Value = Result.Val.getInt();
13914       if (isSameWidthConstantConversion(S, E, T, CC)) {
13915         std::string PrettySourceValue = toString(Value, 10);
13916         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13917 
13918         S.DiagRuntimeBehavior(
13919             E->getExprLoc(), E,
13920             S.PDiag(diag::warn_impcast_integer_precision_constant)
13921                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13922                 << E->getSourceRange() << SourceRange(CC));
13923         return;
13924       }
13925     }
13926 
13927     // Fall through for non-constants to give a sign conversion warning.
13928   }
13929 
13930   if ((!isa<EnumType>(Target) || !isa<EnumType>(Source)) &&
13931       ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) ||
13932        (!TargetRange.NonNegative && LikelySourceRange.NonNegative &&
13933         LikelySourceRange.Width == TargetRange.Width))) {
13934     if (S.SourceMgr.isInSystemMacro(CC))
13935       return;
13936 
13937     unsigned DiagID = diag::warn_impcast_integer_sign;
13938 
13939     // Traditionally, gcc has warned about this under -Wsign-compare.
13940     // We also want to warn about it in -Wconversion.
13941     // So if -Wconversion is off, use a completely identical diagnostic
13942     // in the sign-compare group.
13943     // The conditional-checking code will
13944     if (ICContext) {
13945       DiagID = diag::warn_impcast_integer_sign_conditional;
13946       *ICContext = true;
13947     }
13948 
13949     return DiagnoseImpCast(S, E, T, CC, DiagID);
13950   }
13951 
13952   // Diagnose conversions between different enumeration types.
13953   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
13954   // type, to give us better diagnostics.
13955   QualType SourceType = E->getType();
13956   if (!S.getLangOpts().CPlusPlus) {
13957     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13958       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
13959         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
13960         SourceType = S.Context.getTypeDeclType(Enum);
13961         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
13962       }
13963   }
13964 
13965   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
13966     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
13967       if (SourceEnum->getDecl()->hasNameForLinkage() &&
13968           TargetEnum->getDecl()->hasNameForLinkage() &&
13969           SourceEnum != TargetEnum) {
13970         if (S.SourceMgr.isInSystemMacro(CC))
13971           return;
13972 
13973         return DiagnoseImpCast(S, E, SourceType, T, CC,
13974                                diag::warn_impcast_different_enum_types);
13975       }
13976 }
13977 
13978 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13979                                      SourceLocation CC, QualType T);
13980 
13981 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
13982                                     SourceLocation CC, bool &ICContext) {
13983   E = E->IgnoreParenImpCasts();
13984 
13985   if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
13986     return CheckConditionalOperator(S, CO, CC, T);
13987 
13988   AnalyzeImplicitConversions(S, E, CC);
13989   if (E->getType() != T)
13990     return CheckImplicitConversion(S, E, T, CC, &ICContext);
13991 }
13992 
13993 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13994                                      SourceLocation CC, QualType T) {
13995   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
13996 
13997   Expr *TrueExpr = E->getTrueExpr();
13998   if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
13999     TrueExpr = BCO->getCommon();
14000 
14001   bool Suspicious = false;
14002   CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
14003   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
14004 
14005   if (T->isBooleanType())
14006     DiagnoseIntInBoolContext(S, E);
14007 
14008   // If -Wconversion would have warned about either of the candidates
14009   // for a signedness conversion to the context type...
14010   if (!Suspicious) return;
14011 
14012   // ...but it's currently ignored...
14013   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
14014     return;
14015 
14016   // ...then check whether it would have warned about either of the
14017   // candidates for a signedness conversion to the condition type.
14018   if (E->getType() == T) return;
14019 
14020   Suspicious = false;
14021   CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(),
14022                           E->getType(), CC, &Suspicious);
14023   if (!Suspicious)
14024     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
14025                             E->getType(), CC, &Suspicious);
14026 }
14027 
14028 /// Check conversion of given expression to boolean.
14029 /// Input argument E is a logical expression.
14030 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
14031   if (S.getLangOpts().Bool)
14032     return;
14033   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
14034     return;
14035   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
14036 }
14037 
14038 namespace {
14039 struct AnalyzeImplicitConversionsWorkItem {
14040   Expr *E;
14041   SourceLocation CC;
14042   bool IsListInit;
14043 };
14044 }
14045 
14046 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
14047 /// that should be visited are added to WorkList.
14048 static void AnalyzeImplicitConversions(
14049     Sema &S, AnalyzeImplicitConversionsWorkItem Item,
14050     llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
14051   Expr *OrigE = Item.E;
14052   SourceLocation CC = Item.CC;
14053 
14054   QualType T = OrigE->getType();
14055   Expr *E = OrigE->IgnoreParenImpCasts();
14056 
14057   // Propagate whether we are in a C++ list initialization expression.
14058   // If so, we do not issue warnings for implicit int-float conversion
14059   // precision loss, because C++11 narrowing already handles it.
14060   bool IsListInit = Item.IsListInit ||
14061                     (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
14062 
14063   if (E->isTypeDependent() || E->isValueDependent())
14064     return;
14065 
14066   Expr *SourceExpr = E;
14067   // Examine, but don't traverse into the source expression of an
14068   // OpaqueValueExpr, since it may have multiple parents and we don't want to
14069   // emit duplicate diagnostics. Its fine to examine the form or attempt to
14070   // evaluate it in the context of checking the specific conversion to T though.
14071   if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
14072     if (auto *Src = OVE->getSourceExpr())
14073       SourceExpr = Src;
14074 
14075   if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
14076     if (UO->getOpcode() == UO_Not &&
14077         UO->getSubExpr()->isKnownToHaveBooleanValue())
14078       S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
14079           << OrigE->getSourceRange() << T->isBooleanType()
14080           << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
14081 
14082   if (const auto *BO = dyn_cast<BinaryOperator>(SourceExpr))
14083     if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&
14084         BO->getLHS()->isKnownToHaveBooleanValue() &&
14085         BO->getRHS()->isKnownToHaveBooleanValue() &&
14086         BO->getLHS()->HasSideEffects(S.Context) &&
14087         BO->getRHS()->HasSideEffects(S.Context)) {
14088       S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical)
14089           << (BO->getOpcode() == BO_And ? "&" : "|") << OrigE->getSourceRange()
14090           << FixItHint::CreateReplacement(
14091                  BO->getOperatorLoc(),
14092                  (BO->getOpcode() == BO_And ? "&&" : "||"));
14093       S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int);
14094     }
14095 
14096   // For conditional operators, we analyze the arguments as if they
14097   // were being fed directly into the output.
14098   if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
14099     CheckConditionalOperator(S, CO, CC, T);
14100     return;
14101   }
14102 
14103   // Check implicit argument conversions for function calls.
14104   if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
14105     CheckImplicitArgumentConversions(S, Call, CC);
14106 
14107   // Go ahead and check any implicit conversions we might have skipped.
14108   // The non-canonical typecheck is just an optimization;
14109   // CheckImplicitConversion will filter out dead implicit conversions.
14110   if (SourceExpr->getType() != T)
14111     CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit);
14112 
14113   // Now continue drilling into this expression.
14114 
14115   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
14116     // The bound subexpressions in a PseudoObjectExpr are not reachable
14117     // as transitive children.
14118     // FIXME: Use a more uniform representation for this.
14119     for (auto *SE : POE->semantics())
14120       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
14121         WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
14122   }
14123 
14124   // Skip past explicit casts.
14125   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
14126     E = CE->getSubExpr()->IgnoreParenImpCasts();
14127     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
14128       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
14129     WorkList.push_back({E, CC, IsListInit});
14130     return;
14131   }
14132 
14133   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
14134     // Do a somewhat different check with comparison operators.
14135     if (BO->isComparisonOp())
14136       return AnalyzeComparison(S, BO);
14137 
14138     // And with simple assignments.
14139     if (BO->getOpcode() == BO_Assign)
14140       return AnalyzeAssignment(S, BO);
14141     // And with compound assignments.
14142     if (BO->isAssignmentOp())
14143       return AnalyzeCompoundAssignment(S, BO);
14144   }
14145 
14146   // These break the otherwise-useful invariant below.  Fortunately,
14147   // we don't really need to recurse into them, because any internal
14148   // expressions should have been analyzed already when they were
14149   // built into statements.
14150   if (isa<StmtExpr>(E)) return;
14151 
14152   // Don't descend into unevaluated contexts.
14153   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
14154 
14155   // Now just recurse over the expression's children.
14156   CC = E->getExprLoc();
14157   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
14158   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
14159   for (Stmt *SubStmt : E->children()) {
14160     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
14161     if (!ChildExpr)
14162       continue;
14163 
14164     if (auto *CSE = dyn_cast<CoroutineSuspendExpr>(E))
14165       if (ChildExpr == CSE->getOperand())
14166         // Do not recurse over a CoroutineSuspendExpr's operand.
14167         // The operand is also a subexpression of getCommonExpr(), and
14168         // recursing into it directly would produce duplicate diagnostics.
14169         continue;
14170 
14171     if (IsLogicalAndOperator &&
14172         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
14173       // Ignore checking string literals that are in logical and operators.
14174       // This is a common pattern for asserts.
14175       continue;
14176     WorkList.push_back({ChildExpr, CC, IsListInit});
14177   }
14178 
14179   if (BO && BO->isLogicalOp()) {
14180     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
14181     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
14182       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
14183 
14184     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
14185     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
14186       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
14187   }
14188 
14189   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
14190     if (U->getOpcode() == UO_LNot) {
14191       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
14192     } else if (U->getOpcode() != UO_AddrOf) {
14193       if (U->getSubExpr()->getType()->isAtomicType())
14194         S.Diag(U->getSubExpr()->getBeginLoc(),
14195                diag::warn_atomic_implicit_seq_cst);
14196     }
14197   }
14198 }
14199 
14200 /// AnalyzeImplicitConversions - Find and report any interesting
14201 /// implicit conversions in the given expression.  There are a couple
14202 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
14203 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
14204                                        bool IsListInit/*= false*/) {
14205   llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
14206   WorkList.push_back({OrigE, CC, IsListInit});
14207   while (!WorkList.empty())
14208     AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
14209 }
14210 
14211 /// Diagnose integer type and any valid implicit conversion to it.
14212 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
14213   // Taking into account implicit conversions,
14214   // allow any integer.
14215   if (!E->getType()->isIntegerType()) {
14216     S.Diag(E->getBeginLoc(),
14217            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
14218     return true;
14219   }
14220   // Potentially emit standard warnings for implicit conversions if enabled
14221   // using -Wconversion.
14222   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
14223   return false;
14224 }
14225 
14226 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
14227 // Returns true when emitting a warning about taking the address of a reference.
14228 static bool CheckForReference(Sema &SemaRef, const Expr *E,
14229                               const PartialDiagnostic &PD) {
14230   E = E->IgnoreParenImpCasts();
14231 
14232   const FunctionDecl *FD = nullptr;
14233 
14234   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14235     if (!DRE->getDecl()->getType()->isReferenceType())
14236       return false;
14237   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
14238     if (!M->getMemberDecl()->getType()->isReferenceType())
14239       return false;
14240   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
14241     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
14242       return false;
14243     FD = Call->getDirectCallee();
14244   } else {
14245     return false;
14246   }
14247 
14248   SemaRef.Diag(E->getExprLoc(), PD);
14249 
14250   // If possible, point to location of function.
14251   if (FD) {
14252     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
14253   }
14254 
14255   return true;
14256 }
14257 
14258 // Returns true if the SourceLocation is expanded from any macro body.
14259 // Returns false if the SourceLocation is invalid, is from not in a macro
14260 // expansion, or is from expanded from a top-level macro argument.
14261 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
14262   if (Loc.isInvalid())
14263     return false;
14264 
14265   while (Loc.isMacroID()) {
14266     if (SM.isMacroBodyExpansion(Loc))
14267       return true;
14268     Loc = SM.getImmediateMacroCallerLoc(Loc);
14269   }
14270 
14271   return false;
14272 }
14273 
14274 /// Diagnose pointers that are always non-null.
14275 /// \param E the expression containing the pointer
14276 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
14277 /// compared to a null pointer
14278 /// \param IsEqual True when the comparison is equal to a null pointer
14279 /// \param Range Extra SourceRange to highlight in the diagnostic
14280 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
14281                                         Expr::NullPointerConstantKind NullKind,
14282                                         bool IsEqual, SourceRange Range) {
14283   if (!E)
14284     return;
14285 
14286   // Don't warn inside macros.
14287   if (E->getExprLoc().isMacroID()) {
14288     const SourceManager &SM = getSourceManager();
14289     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
14290         IsInAnyMacroBody(SM, Range.getBegin()))
14291       return;
14292   }
14293   E = E->IgnoreImpCasts();
14294 
14295   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
14296 
14297   if (isa<CXXThisExpr>(E)) {
14298     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
14299                                 : diag::warn_this_bool_conversion;
14300     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
14301     return;
14302   }
14303 
14304   bool IsAddressOf = false;
14305 
14306   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
14307     if (UO->getOpcode() != UO_AddrOf)
14308       return;
14309     IsAddressOf = true;
14310     E = UO->getSubExpr();
14311   }
14312 
14313   if (IsAddressOf) {
14314     unsigned DiagID = IsCompare
14315                           ? diag::warn_address_of_reference_null_compare
14316                           : diag::warn_address_of_reference_bool_conversion;
14317     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
14318                                          << IsEqual;
14319     if (CheckForReference(*this, E, PD)) {
14320       return;
14321     }
14322   }
14323 
14324   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
14325     bool IsParam = isa<NonNullAttr>(NonnullAttr);
14326     std::string Str;
14327     llvm::raw_string_ostream S(Str);
14328     E->printPretty(S, nullptr, getPrintingPolicy());
14329     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
14330                                 : diag::warn_cast_nonnull_to_bool;
14331     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
14332       << E->getSourceRange() << Range << IsEqual;
14333     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
14334   };
14335 
14336   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
14337   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
14338     if (auto *Callee = Call->getDirectCallee()) {
14339       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
14340         ComplainAboutNonnullParamOrCall(A);
14341         return;
14342       }
14343     }
14344   }
14345 
14346   // Expect to find a single Decl.  Skip anything more complicated.
14347   ValueDecl *D = nullptr;
14348   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
14349     D = R->getDecl();
14350   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
14351     D = M->getMemberDecl();
14352   }
14353 
14354   // Weak Decls can be null.
14355   if (!D || D->isWeak())
14356     return;
14357 
14358   // Check for parameter decl with nonnull attribute
14359   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
14360     if (getCurFunction() &&
14361         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
14362       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
14363         ComplainAboutNonnullParamOrCall(A);
14364         return;
14365       }
14366 
14367       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
14368         // Skip function template not specialized yet.
14369         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
14370           return;
14371         auto ParamIter = llvm::find(FD->parameters(), PV);
14372         assert(ParamIter != FD->param_end());
14373         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
14374 
14375         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
14376           if (!NonNull->args_size()) {
14377               ComplainAboutNonnullParamOrCall(NonNull);
14378               return;
14379           }
14380 
14381           for (const ParamIdx &ArgNo : NonNull->args()) {
14382             if (ArgNo.getASTIndex() == ParamNo) {
14383               ComplainAboutNonnullParamOrCall(NonNull);
14384               return;
14385             }
14386           }
14387         }
14388       }
14389     }
14390   }
14391 
14392   QualType T = D->getType();
14393   const bool IsArray = T->isArrayType();
14394   const bool IsFunction = T->isFunctionType();
14395 
14396   // Address of function is used to silence the function warning.
14397   if (IsAddressOf && IsFunction) {
14398     return;
14399   }
14400 
14401   // Found nothing.
14402   if (!IsAddressOf && !IsFunction && !IsArray)
14403     return;
14404 
14405   // Pretty print the expression for the diagnostic.
14406   std::string Str;
14407   llvm::raw_string_ostream S(Str);
14408   E->printPretty(S, nullptr, getPrintingPolicy());
14409 
14410   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
14411                               : diag::warn_impcast_pointer_to_bool;
14412   enum {
14413     AddressOf,
14414     FunctionPointer,
14415     ArrayPointer
14416   } DiagType;
14417   if (IsAddressOf)
14418     DiagType = AddressOf;
14419   else if (IsFunction)
14420     DiagType = FunctionPointer;
14421   else if (IsArray)
14422     DiagType = ArrayPointer;
14423   else
14424     llvm_unreachable("Could not determine diagnostic.");
14425   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
14426                                 << Range << IsEqual;
14427 
14428   if (!IsFunction)
14429     return;
14430 
14431   // Suggest '&' to silence the function warning.
14432   Diag(E->getExprLoc(), diag::note_function_warning_silence)
14433       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
14434 
14435   // Check to see if '()' fixit should be emitted.
14436   QualType ReturnType;
14437   UnresolvedSet<4> NonTemplateOverloads;
14438   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
14439   if (ReturnType.isNull())
14440     return;
14441 
14442   if (IsCompare) {
14443     // There are two cases here.  If there is null constant, the only suggest
14444     // for a pointer return type.  If the null is 0, then suggest if the return
14445     // type is a pointer or an integer type.
14446     if (!ReturnType->isPointerType()) {
14447       if (NullKind == Expr::NPCK_ZeroExpression ||
14448           NullKind == Expr::NPCK_ZeroLiteral) {
14449         if (!ReturnType->isIntegerType())
14450           return;
14451       } else {
14452         return;
14453       }
14454     }
14455   } else { // !IsCompare
14456     // For function to bool, only suggest if the function pointer has bool
14457     // return type.
14458     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
14459       return;
14460   }
14461   Diag(E->getExprLoc(), diag::note_function_to_function_call)
14462       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
14463 }
14464 
14465 /// Diagnoses "dangerous" implicit conversions within the given
14466 /// expression (which is a full expression).  Implements -Wconversion
14467 /// and -Wsign-compare.
14468 ///
14469 /// \param CC the "context" location of the implicit conversion, i.e.
14470 ///   the most location of the syntactic entity requiring the implicit
14471 ///   conversion
14472 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
14473   // Don't diagnose in unevaluated contexts.
14474   if (isUnevaluatedContext())
14475     return;
14476 
14477   // Don't diagnose for value- or type-dependent expressions.
14478   if (E->isTypeDependent() || E->isValueDependent())
14479     return;
14480 
14481   // Check for array bounds violations in cases where the check isn't triggered
14482   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
14483   // ArraySubscriptExpr is on the RHS of a variable initialization.
14484   CheckArrayAccess(E);
14485 
14486   // This is not the right CC for (e.g.) a variable initialization.
14487   AnalyzeImplicitConversions(*this, E, CC);
14488 }
14489 
14490 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
14491 /// Input argument E is a logical expression.
14492 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
14493   ::CheckBoolLikeConversion(*this, E, CC);
14494 }
14495 
14496 /// Diagnose when expression is an integer constant expression and its evaluation
14497 /// results in integer overflow
14498 void Sema::CheckForIntOverflow (Expr *E) {
14499   // Use a work list to deal with nested struct initializers.
14500   SmallVector<Expr *, 2> Exprs(1, E);
14501 
14502   do {
14503     Expr *OriginalE = Exprs.pop_back_val();
14504     Expr *E = OriginalE->IgnoreParenCasts();
14505 
14506     if (isa<BinaryOperator>(E)) {
14507       E->EvaluateForOverflow(Context);
14508       continue;
14509     }
14510 
14511     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
14512       Exprs.append(InitList->inits().begin(), InitList->inits().end());
14513     else if (isa<ObjCBoxedExpr>(OriginalE))
14514       E->EvaluateForOverflow(Context);
14515     else if (auto Call = dyn_cast<CallExpr>(E))
14516       Exprs.append(Call->arg_begin(), Call->arg_end());
14517     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
14518       Exprs.append(Message->arg_begin(), Message->arg_end());
14519   } while (!Exprs.empty());
14520 }
14521 
14522 namespace {
14523 
14524 /// Visitor for expressions which looks for unsequenced operations on the
14525 /// same object.
14526 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
14527   using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
14528 
14529   /// A tree of sequenced regions within an expression. Two regions are
14530   /// unsequenced if one is an ancestor or a descendent of the other. When we
14531   /// finish processing an expression with sequencing, such as a comma
14532   /// expression, we fold its tree nodes into its parent, since they are
14533   /// unsequenced with respect to nodes we will visit later.
14534   class SequenceTree {
14535     struct Value {
14536       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
14537       unsigned Parent : 31;
14538       unsigned Merged : 1;
14539     };
14540     SmallVector<Value, 8> Values;
14541 
14542   public:
14543     /// A region within an expression which may be sequenced with respect
14544     /// to some other region.
14545     class Seq {
14546       friend class SequenceTree;
14547 
14548       unsigned Index;
14549 
14550       explicit Seq(unsigned N) : Index(N) {}
14551 
14552     public:
14553       Seq() : Index(0) {}
14554     };
14555 
14556     SequenceTree() { Values.push_back(Value(0)); }
14557     Seq root() const { return Seq(0); }
14558 
14559     /// Create a new sequence of operations, which is an unsequenced
14560     /// subset of \p Parent. This sequence of operations is sequenced with
14561     /// respect to other children of \p Parent.
14562     Seq allocate(Seq Parent) {
14563       Values.push_back(Value(Parent.Index));
14564       return Seq(Values.size() - 1);
14565     }
14566 
14567     /// Merge a sequence of operations into its parent.
14568     void merge(Seq S) {
14569       Values[S.Index].Merged = true;
14570     }
14571 
14572     /// Determine whether two operations are unsequenced. This operation
14573     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
14574     /// should have been merged into its parent as appropriate.
14575     bool isUnsequenced(Seq Cur, Seq Old) {
14576       unsigned C = representative(Cur.Index);
14577       unsigned Target = representative(Old.Index);
14578       while (C >= Target) {
14579         if (C == Target)
14580           return true;
14581         C = Values[C].Parent;
14582       }
14583       return false;
14584     }
14585 
14586   private:
14587     /// Pick a representative for a sequence.
14588     unsigned representative(unsigned K) {
14589       if (Values[K].Merged)
14590         // Perform path compression as we go.
14591         return Values[K].Parent = representative(Values[K].Parent);
14592       return K;
14593     }
14594   };
14595 
14596   /// An object for which we can track unsequenced uses.
14597   using Object = const NamedDecl *;
14598 
14599   /// Different flavors of object usage which we track. We only track the
14600   /// least-sequenced usage of each kind.
14601   enum UsageKind {
14602     /// A read of an object. Multiple unsequenced reads are OK.
14603     UK_Use,
14604 
14605     /// A modification of an object which is sequenced before the value
14606     /// computation of the expression, such as ++n in C++.
14607     UK_ModAsValue,
14608 
14609     /// A modification of an object which is not sequenced before the value
14610     /// computation of the expression, such as n++.
14611     UK_ModAsSideEffect,
14612 
14613     UK_Count = UK_ModAsSideEffect + 1
14614   };
14615 
14616   /// Bundle together a sequencing region and the expression corresponding
14617   /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
14618   struct Usage {
14619     const Expr *UsageExpr;
14620     SequenceTree::Seq Seq;
14621 
14622     Usage() : UsageExpr(nullptr) {}
14623   };
14624 
14625   struct UsageInfo {
14626     Usage Uses[UK_Count];
14627 
14628     /// Have we issued a diagnostic for this object already?
14629     bool Diagnosed;
14630 
14631     UsageInfo() : Diagnosed(false) {}
14632   };
14633   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
14634 
14635   Sema &SemaRef;
14636 
14637   /// Sequenced regions within the expression.
14638   SequenceTree Tree;
14639 
14640   /// Declaration modifications and references which we have seen.
14641   UsageInfoMap UsageMap;
14642 
14643   /// The region we are currently within.
14644   SequenceTree::Seq Region;
14645 
14646   /// Filled in with declarations which were modified as a side-effect
14647   /// (that is, post-increment operations).
14648   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
14649 
14650   /// Expressions to check later. We defer checking these to reduce
14651   /// stack usage.
14652   SmallVectorImpl<const Expr *> &WorkList;
14653 
14654   /// RAII object wrapping the visitation of a sequenced subexpression of an
14655   /// expression. At the end of this process, the side-effects of the evaluation
14656   /// become sequenced with respect to the value computation of the result, so
14657   /// we downgrade any UK_ModAsSideEffect within the evaluation to
14658   /// UK_ModAsValue.
14659   struct SequencedSubexpression {
14660     SequencedSubexpression(SequenceChecker &Self)
14661       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
14662       Self.ModAsSideEffect = &ModAsSideEffect;
14663     }
14664 
14665     ~SequencedSubexpression() {
14666       for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
14667         // Add a new usage with usage kind UK_ModAsValue, and then restore
14668         // the previous usage with UK_ModAsSideEffect (thus clearing it if
14669         // the previous one was empty).
14670         UsageInfo &UI = Self.UsageMap[M.first];
14671         auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
14672         Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
14673         SideEffectUsage = M.second;
14674       }
14675       Self.ModAsSideEffect = OldModAsSideEffect;
14676     }
14677 
14678     SequenceChecker &Self;
14679     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
14680     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
14681   };
14682 
14683   /// RAII object wrapping the visitation of a subexpression which we might
14684   /// choose to evaluate as a constant. If any subexpression is evaluated and
14685   /// found to be non-constant, this allows us to suppress the evaluation of
14686   /// the outer expression.
14687   class EvaluationTracker {
14688   public:
14689     EvaluationTracker(SequenceChecker &Self)
14690         : Self(Self), Prev(Self.EvalTracker) {
14691       Self.EvalTracker = this;
14692     }
14693 
14694     ~EvaluationTracker() {
14695       Self.EvalTracker = Prev;
14696       if (Prev)
14697         Prev->EvalOK &= EvalOK;
14698     }
14699 
14700     bool evaluate(const Expr *E, bool &Result) {
14701       if (!EvalOK || E->isValueDependent())
14702         return false;
14703       EvalOK = E->EvaluateAsBooleanCondition(
14704           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
14705       return EvalOK;
14706     }
14707 
14708   private:
14709     SequenceChecker &Self;
14710     EvaluationTracker *Prev;
14711     bool EvalOK = true;
14712   } *EvalTracker = nullptr;
14713 
14714   /// Find the object which is produced by the specified expression,
14715   /// if any.
14716   Object getObject(const Expr *E, bool Mod) const {
14717     E = E->IgnoreParenCasts();
14718     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
14719       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
14720         return getObject(UO->getSubExpr(), Mod);
14721     } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
14722       if (BO->getOpcode() == BO_Comma)
14723         return getObject(BO->getRHS(), Mod);
14724       if (Mod && BO->isAssignmentOp())
14725         return getObject(BO->getLHS(), Mod);
14726     } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14727       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
14728       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
14729         return ME->getMemberDecl();
14730     } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
14731       // FIXME: If this is a reference, map through to its value.
14732       return DRE->getDecl();
14733     return nullptr;
14734   }
14735 
14736   /// Note that an object \p O was modified or used by an expression
14737   /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
14738   /// the object \p O as obtained via the \p UsageMap.
14739   void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
14740     // Get the old usage for the given object and usage kind.
14741     Usage &U = UI.Uses[UK];
14742     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
14743       // If we have a modification as side effect and are in a sequenced
14744       // subexpression, save the old Usage so that we can restore it later
14745       // in SequencedSubexpression::~SequencedSubexpression.
14746       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
14747         ModAsSideEffect->push_back(std::make_pair(O, U));
14748       // Then record the new usage with the current sequencing region.
14749       U.UsageExpr = UsageExpr;
14750       U.Seq = Region;
14751     }
14752   }
14753 
14754   /// Check whether a modification or use of an object \p O in an expression
14755   /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
14756   /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
14757   /// \p IsModMod is true when we are checking for a mod-mod unsequenced
14758   /// usage and false we are checking for a mod-use unsequenced usage.
14759   void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
14760                   UsageKind OtherKind, bool IsModMod) {
14761     if (UI.Diagnosed)
14762       return;
14763 
14764     const Usage &U = UI.Uses[OtherKind];
14765     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
14766       return;
14767 
14768     const Expr *Mod = U.UsageExpr;
14769     const Expr *ModOrUse = UsageExpr;
14770     if (OtherKind == UK_Use)
14771       std::swap(Mod, ModOrUse);
14772 
14773     SemaRef.DiagRuntimeBehavior(
14774         Mod->getExprLoc(), {Mod, ModOrUse},
14775         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
14776                                : diag::warn_unsequenced_mod_use)
14777             << O << SourceRange(ModOrUse->getExprLoc()));
14778     UI.Diagnosed = true;
14779   }
14780 
14781   // A note on note{Pre, Post}{Use, Mod}:
14782   //
14783   // (It helps to follow the algorithm with an expression such as
14784   //  "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
14785   //  operations before C++17 and both are well-defined in C++17).
14786   //
14787   // When visiting a node which uses/modify an object we first call notePreUse
14788   // or notePreMod before visiting its sub-expression(s). At this point the
14789   // children of the current node have not yet been visited and so the eventual
14790   // uses/modifications resulting from the children of the current node have not
14791   // been recorded yet.
14792   //
14793   // We then visit the children of the current node. After that notePostUse or
14794   // notePostMod is called. These will 1) detect an unsequenced modification
14795   // as side effect (as in "k++ + k") and 2) add a new usage with the
14796   // appropriate usage kind.
14797   //
14798   // We also have to be careful that some operation sequences modification as
14799   // side effect as well (for example: || or ,). To account for this we wrap
14800   // the visitation of such a sub-expression (for example: the LHS of || or ,)
14801   // with SequencedSubexpression. SequencedSubexpression is an RAII object
14802   // which record usages which are modifications as side effect, and then
14803   // downgrade them (or more accurately restore the previous usage which was a
14804   // modification as side effect) when exiting the scope of the sequenced
14805   // subexpression.
14806 
14807   void notePreUse(Object O, const Expr *UseExpr) {
14808     UsageInfo &UI = UsageMap[O];
14809     // Uses conflict with other modifications.
14810     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
14811   }
14812 
14813   void notePostUse(Object O, const Expr *UseExpr) {
14814     UsageInfo &UI = UsageMap[O];
14815     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
14816                /*IsModMod=*/false);
14817     addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
14818   }
14819 
14820   void notePreMod(Object O, const Expr *ModExpr) {
14821     UsageInfo &UI = UsageMap[O];
14822     // Modifications conflict with other modifications and with uses.
14823     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
14824     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
14825   }
14826 
14827   void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
14828     UsageInfo &UI = UsageMap[O];
14829     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
14830                /*IsModMod=*/true);
14831     addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
14832   }
14833 
14834 public:
14835   SequenceChecker(Sema &S, const Expr *E,
14836                   SmallVectorImpl<const Expr *> &WorkList)
14837       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
14838     Visit(E);
14839     // Silence a -Wunused-private-field since WorkList is now unused.
14840     // TODO: Evaluate if it can be used, and if not remove it.
14841     (void)this->WorkList;
14842   }
14843 
14844   void VisitStmt(const Stmt *S) {
14845     // Skip all statements which aren't expressions for now.
14846   }
14847 
14848   void VisitExpr(const Expr *E) {
14849     // By default, just recurse to evaluated subexpressions.
14850     Base::VisitStmt(E);
14851   }
14852 
14853   void VisitCastExpr(const CastExpr *E) {
14854     Object O = Object();
14855     if (E->getCastKind() == CK_LValueToRValue)
14856       O = getObject(E->getSubExpr(), false);
14857 
14858     if (O)
14859       notePreUse(O, E);
14860     VisitExpr(E);
14861     if (O)
14862       notePostUse(O, E);
14863   }
14864 
14865   void VisitSequencedExpressions(const Expr *SequencedBefore,
14866                                  const Expr *SequencedAfter) {
14867     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
14868     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
14869     SequenceTree::Seq OldRegion = Region;
14870 
14871     {
14872       SequencedSubexpression SeqBefore(*this);
14873       Region = BeforeRegion;
14874       Visit(SequencedBefore);
14875     }
14876 
14877     Region = AfterRegion;
14878     Visit(SequencedAfter);
14879 
14880     Region = OldRegion;
14881 
14882     Tree.merge(BeforeRegion);
14883     Tree.merge(AfterRegion);
14884   }
14885 
14886   void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
14887     // C++17 [expr.sub]p1:
14888     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
14889     //   expression E1 is sequenced before the expression E2.
14890     if (SemaRef.getLangOpts().CPlusPlus17)
14891       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
14892     else {
14893       Visit(ASE->getLHS());
14894       Visit(ASE->getRHS());
14895     }
14896   }
14897 
14898   void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14899   void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14900   void VisitBinPtrMem(const BinaryOperator *BO) {
14901     // C++17 [expr.mptr.oper]p4:
14902     //  Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
14903     //  the expression E1 is sequenced before the expression E2.
14904     if (SemaRef.getLangOpts().CPlusPlus17)
14905       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14906     else {
14907       Visit(BO->getLHS());
14908       Visit(BO->getRHS());
14909     }
14910   }
14911 
14912   void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14913   void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14914   void VisitBinShlShr(const BinaryOperator *BO) {
14915     // C++17 [expr.shift]p4:
14916     //  The expression E1 is sequenced before the expression E2.
14917     if (SemaRef.getLangOpts().CPlusPlus17)
14918       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14919     else {
14920       Visit(BO->getLHS());
14921       Visit(BO->getRHS());
14922     }
14923   }
14924 
14925   void VisitBinComma(const BinaryOperator *BO) {
14926     // C++11 [expr.comma]p1:
14927     //   Every value computation and side effect associated with the left
14928     //   expression is sequenced before every value computation and side
14929     //   effect associated with the right expression.
14930     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14931   }
14932 
14933   void VisitBinAssign(const BinaryOperator *BO) {
14934     SequenceTree::Seq RHSRegion;
14935     SequenceTree::Seq LHSRegion;
14936     if (SemaRef.getLangOpts().CPlusPlus17) {
14937       RHSRegion = Tree.allocate(Region);
14938       LHSRegion = Tree.allocate(Region);
14939     } else {
14940       RHSRegion = Region;
14941       LHSRegion = Region;
14942     }
14943     SequenceTree::Seq OldRegion = Region;
14944 
14945     // C++11 [expr.ass]p1:
14946     //  [...] the assignment is sequenced after the value computation
14947     //  of the right and left operands, [...]
14948     //
14949     // so check it before inspecting the operands and update the
14950     // map afterwards.
14951     Object O = getObject(BO->getLHS(), /*Mod=*/true);
14952     if (O)
14953       notePreMod(O, BO);
14954 
14955     if (SemaRef.getLangOpts().CPlusPlus17) {
14956       // C++17 [expr.ass]p1:
14957       //  [...] The right operand is sequenced before the left operand. [...]
14958       {
14959         SequencedSubexpression SeqBefore(*this);
14960         Region = RHSRegion;
14961         Visit(BO->getRHS());
14962       }
14963 
14964       Region = LHSRegion;
14965       Visit(BO->getLHS());
14966 
14967       if (O && isa<CompoundAssignOperator>(BO))
14968         notePostUse(O, BO);
14969 
14970     } else {
14971       // C++11 does not specify any sequencing between the LHS and RHS.
14972       Region = LHSRegion;
14973       Visit(BO->getLHS());
14974 
14975       if (O && isa<CompoundAssignOperator>(BO))
14976         notePostUse(O, BO);
14977 
14978       Region = RHSRegion;
14979       Visit(BO->getRHS());
14980     }
14981 
14982     // C++11 [expr.ass]p1:
14983     //  the assignment is sequenced [...] before the value computation of the
14984     //  assignment expression.
14985     // C11 6.5.16/3 has no such rule.
14986     Region = OldRegion;
14987     if (O)
14988       notePostMod(O, BO,
14989                   SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14990                                                   : UK_ModAsSideEffect);
14991     if (SemaRef.getLangOpts().CPlusPlus17) {
14992       Tree.merge(RHSRegion);
14993       Tree.merge(LHSRegion);
14994     }
14995   }
14996 
14997   void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
14998     VisitBinAssign(CAO);
14999   }
15000 
15001   void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
15002   void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
15003   void VisitUnaryPreIncDec(const UnaryOperator *UO) {
15004     Object O = getObject(UO->getSubExpr(), true);
15005     if (!O)
15006       return VisitExpr(UO);
15007 
15008     notePreMod(O, UO);
15009     Visit(UO->getSubExpr());
15010     // C++11 [expr.pre.incr]p1:
15011     //   the expression ++x is equivalent to x+=1
15012     notePostMod(O, UO,
15013                 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
15014                                                 : UK_ModAsSideEffect);
15015   }
15016 
15017   void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
15018   void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
15019   void VisitUnaryPostIncDec(const UnaryOperator *UO) {
15020     Object O = getObject(UO->getSubExpr(), true);
15021     if (!O)
15022       return VisitExpr(UO);
15023 
15024     notePreMod(O, UO);
15025     Visit(UO->getSubExpr());
15026     notePostMod(O, UO, UK_ModAsSideEffect);
15027   }
15028 
15029   void VisitBinLOr(const BinaryOperator *BO) {
15030     // C++11 [expr.log.or]p2:
15031     //  If the second expression is evaluated, every value computation and
15032     //  side effect associated with the first expression is sequenced before
15033     //  every value computation and side effect associated with the
15034     //  second expression.
15035     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
15036     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
15037     SequenceTree::Seq OldRegion = Region;
15038 
15039     EvaluationTracker Eval(*this);
15040     {
15041       SequencedSubexpression Sequenced(*this);
15042       Region = LHSRegion;
15043       Visit(BO->getLHS());
15044     }
15045 
15046     // C++11 [expr.log.or]p1:
15047     //  [...] the second operand is not evaluated if the first operand
15048     //  evaluates to true.
15049     bool EvalResult = false;
15050     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
15051     bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
15052     if (ShouldVisitRHS) {
15053       Region = RHSRegion;
15054       Visit(BO->getRHS());
15055     }
15056 
15057     Region = OldRegion;
15058     Tree.merge(LHSRegion);
15059     Tree.merge(RHSRegion);
15060   }
15061 
15062   void VisitBinLAnd(const BinaryOperator *BO) {
15063     // C++11 [expr.log.and]p2:
15064     //  If the second expression is evaluated, every value computation and
15065     //  side effect associated with the first expression is sequenced before
15066     //  every value computation and side effect associated with the
15067     //  second expression.
15068     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
15069     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
15070     SequenceTree::Seq OldRegion = Region;
15071 
15072     EvaluationTracker Eval(*this);
15073     {
15074       SequencedSubexpression Sequenced(*this);
15075       Region = LHSRegion;
15076       Visit(BO->getLHS());
15077     }
15078 
15079     // C++11 [expr.log.and]p1:
15080     //  [...] the second operand is not evaluated if the first operand is false.
15081     bool EvalResult = false;
15082     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
15083     bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
15084     if (ShouldVisitRHS) {
15085       Region = RHSRegion;
15086       Visit(BO->getRHS());
15087     }
15088 
15089     Region = OldRegion;
15090     Tree.merge(LHSRegion);
15091     Tree.merge(RHSRegion);
15092   }
15093 
15094   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
15095     // C++11 [expr.cond]p1:
15096     //  [...] Every value computation and side effect associated with the first
15097     //  expression is sequenced before every value computation and side effect
15098     //  associated with the second or third expression.
15099     SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
15100 
15101     // No sequencing is specified between the true and false expression.
15102     // However since exactly one of both is going to be evaluated we can
15103     // consider them to be sequenced. This is needed to avoid warning on
15104     // something like "x ? y+= 1 : y += 2;" in the case where we will visit
15105     // both the true and false expressions because we can't evaluate x.
15106     // This will still allow us to detect an expression like (pre C++17)
15107     // "(x ? y += 1 : y += 2) = y".
15108     //
15109     // We don't wrap the visitation of the true and false expression with
15110     // SequencedSubexpression because we don't want to downgrade modifications
15111     // as side effect in the true and false expressions after the visition
15112     // is done. (for example in the expression "(x ? y++ : y++) + y" we should
15113     // not warn between the two "y++", but we should warn between the "y++"
15114     // and the "y".
15115     SequenceTree::Seq TrueRegion = Tree.allocate(Region);
15116     SequenceTree::Seq FalseRegion = Tree.allocate(Region);
15117     SequenceTree::Seq OldRegion = Region;
15118 
15119     EvaluationTracker Eval(*this);
15120     {
15121       SequencedSubexpression Sequenced(*this);
15122       Region = ConditionRegion;
15123       Visit(CO->getCond());
15124     }
15125 
15126     // C++11 [expr.cond]p1:
15127     // [...] The first expression is contextually converted to bool (Clause 4).
15128     // It is evaluated and if it is true, the result of the conditional
15129     // expression is the value of the second expression, otherwise that of the
15130     // third expression. Only one of the second and third expressions is
15131     // evaluated. [...]
15132     bool EvalResult = false;
15133     bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
15134     bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
15135     bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
15136     if (ShouldVisitTrueExpr) {
15137       Region = TrueRegion;
15138       Visit(CO->getTrueExpr());
15139     }
15140     if (ShouldVisitFalseExpr) {
15141       Region = FalseRegion;
15142       Visit(CO->getFalseExpr());
15143     }
15144 
15145     Region = OldRegion;
15146     Tree.merge(ConditionRegion);
15147     Tree.merge(TrueRegion);
15148     Tree.merge(FalseRegion);
15149   }
15150 
15151   void VisitCallExpr(const CallExpr *CE) {
15152     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
15153 
15154     if (CE->isUnevaluatedBuiltinCall(Context))
15155       return;
15156 
15157     // C++11 [intro.execution]p15:
15158     //   When calling a function [...], every value computation and side effect
15159     //   associated with any argument expression, or with the postfix expression
15160     //   designating the called function, is sequenced before execution of every
15161     //   expression or statement in the body of the function [and thus before
15162     //   the value computation of its result].
15163     SequencedSubexpression Sequenced(*this);
15164     SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
15165       // C++17 [expr.call]p5
15166       //   The postfix-expression is sequenced before each expression in the
15167       //   expression-list and any default argument. [...]
15168       SequenceTree::Seq CalleeRegion;
15169       SequenceTree::Seq OtherRegion;
15170       if (SemaRef.getLangOpts().CPlusPlus17) {
15171         CalleeRegion = Tree.allocate(Region);
15172         OtherRegion = Tree.allocate(Region);
15173       } else {
15174         CalleeRegion = Region;
15175         OtherRegion = Region;
15176       }
15177       SequenceTree::Seq OldRegion = Region;
15178 
15179       // Visit the callee expression first.
15180       Region = CalleeRegion;
15181       if (SemaRef.getLangOpts().CPlusPlus17) {
15182         SequencedSubexpression Sequenced(*this);
15183         Visit(CE->getCallee());
15184       } else {
15185         Visit(CE->getCallee());
15186       }
15187 
15188       // Then visit the argument expressions.
15189       Region = OtherRegion;
15190       for (const Expr *Argument : CE->arguments())
15191         Visit(Argument);
15192 
15193       Region = OldRegion;
15194       if (SemaRef.getLangOpts().CPlusPlus17) {
15195         Tree.merge(CalleeRegion);
15196         Tree.merge(OtherRegion);
15197       }
15198     });
15199   }
15200 
15201   void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
15202     // C++17 [over.match.oper]p2:
15203     //   [...] the operator notation is first transformed to the equivalent
15204     //   function-call notation as summarized in Table 12 (where @ denotes one
15205     //   of the operators covered in the specified subclause). However, the
15206     //   operands are sequenced in the order prescribed for the built-in
15207     //   operator (Clause 8).
15208     //
15209     // From the above only overloaded binary operators and overloaded call
15210     // operators have sequencing rules in C++17 that we need to handle
15211     // separately.
15212     if (!SemaRef.getLangOpts().CPlusPlus17 ||
15213         (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
15214       return VisitCallExpr(CXXOCE);
15215 
15216     enum {
15217       NoSequencing,
15218       LHSBeforeRHS,
15219       RHSBeforeLHS,
15220       LHSBeforeRest
15221     } SequencingKind;
15222     switch (CXXOCE->getOperator()) {
15223     case OO_Equal:
15224     case OO_PlusEqual:
15225     case OO_MinusEqual:
15226     case OO_StarEqual:
15227     case OO_SlashEqual:
15228     case OO_PercentEqual:
15229     case OO_CaretEqual:
15230     case OO_AmpEqual:
15231     case OO_PipeEqual:
15232     case OO_LessLessEqual:
15233     case OO_GreaterGreaterEqual:
15234       SequencingKind = RHSBeforeLHS;
15235       break;
15236 
15237     case OO_LessLess:
15238     case OO_GreaterGreater:
15239     case OO_AmpAmp:
15240     case OO_PipePipe:
15241     case OO_Comma:
15242     case OO_ArrowStar:
15243     case OO_Subscript:
15244       SequencingKind = LHSBeforeRHS;
15245       break;
15246 
15247     case OO_Call:
15248       SequencingKind = LHSBeforeRest;
15249       break;
15250 
15251     default:
15252       SequencingKind = NoSequencing;
15253       break;
15254     }
15255 
15256     if (SequencingKind == NoSequencing)
15257       return VisitCallExpr(CXXOCE);
15258 
15259     // This is a call, so all subexpressions are sequenced before the result.
15260     SequencedSubexpression Sequenced(*this);
15261 
15262     SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
15263       assert(SemaRef.getLangOpts().CPlusPlus17 &&
15264              "Should only get there with C++17 and above!");
15265       assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
15266              "Should only get there with an overloaded binary operator"
15267              " or an overloaded call operator!");
15268 
15269       if (SequencingKind == LHSBeforeRest) {
15270         assert(CXXOCE->getOperator() == OO_Call &&
15271                "We should only have an overloaded call operator here!");
15272 
15273         // This is very similar to VisitCallExpr, except that we only have the
15274         // C++17 case. The postfix-expression is the first argument of the
15275         // CXXOperatorCallExpr. The expressions in the expression-list, if any,
15276         // are in the following arguments.
15277         //
15278         // Note that we intentionally do not visit the callee expression since
15279         // it is just a decayed reference to a function.
15280         SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
15281         SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
15282         SequenceTree::Seq OldRegion = Region;
15283 
15284         assert(CXXOCE->getNumArgs() >= 1 &&
15285                "An overloaded call operator must have at least one argument"
15286                " for the postfix-expression!");
15287         const Expr *PostfixExpr = CXXOCE->getArgs()[0];
15288         llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
15289                                           CXXOCE->getNumArgs() - 1);
15290 
15291         // Visit the postfix-expression first.
15292         {
15293           Region = PostfixExprRegion;
15294           SequencedSubexpression Sequenced(*this);
15295           Visit(PostfixExpr);
15296         }
15297 
15298         // Then visit the argument expressions.
15299         Region = ArgsRegion;
15300         for (const Expr *Arg : Args)
15301           Visit(Arg);
15302 
15303         Region = OldRegion;
15304         Tree.merge(PostfixExprRegion);
15305         Tree.merge(ArgsRegion);
15306       } else {
15307         assert(CXXOCE->getNumArgs() == 2 &&
15308                "Should only have two arguments here!");
15309         assert((SequencingKind == LHSBeforeRHS ||
15310                 SequencingKind == RHSBeforeLHS) &&
15311                "Unexpected sequencing kind!");
15312 
15313         // We do not visit the callee expression since it is just a decayed
15314         // reference to a function.
15315         const Expr *E1 = CXXOCE->getArg(0);
15316         const Expr *E2 = CXXOCE->getArg(1);
15317         if (SequencingKind == RHSBeforeLHS)
15318           std::swap(E1, E2);
15319 
15320         return VisitSequencedExpressions(E1, E2);
15321       }
15322     });
15323   }
15324 
15325   void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
15326     // This is a call, so all subexpressions are sequenced before the result.
15327     SequencedSubexpression Sequenced(*this);
15328 
15329     if (!CCE->isListInitialization())
15330       return VisitExpr(CCE);
15331 
15332     // In C++11, list initializations are sequenced.
15333     SmallVector<SequenceTree::Seq, 32> Elts;
15334     SequenceTree::Seq Parent = Region;
15335     for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
15336                                               E = CCE->arg_end();
15337          I != E; ++I) {
15338       Region = Tree.allocate(Parent);
15339       Elts.push_back(Region);
15340       Visit(*I);
15341     }
15342 
15343     // Forget that the initializers are sequenced.
15344     Region = Parent;
15345     for (unsigned I = 0; I < Elts.size(); ++I)
15346       Tree.merge(Elts[I]);
15347   }
15348 
15349   void VisitInitListExpr(const InitListExpr *ILE) {
15350     if (!SemaRef.getLangOpts().CPlusPlus11)
15351       return VisitExpr(ILE);
15352 
15353     // In C++11, list initializations are sequenced.
15354     SmallVector<SequenceTree::Seq, 32> Elts;
15355     SequenceTree::Seq Parent = Region;
15356     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
15357       const Expr *E = ILE->getInit(I);
15358       if (!E)
15359         continue;
15360       Region = Tree.allocate(Parent);
15361       Elts.push_back(Region);
15362       Visit(E);
15363     }
15364 
15365     // Forget that the initializers are sequenced.
15366     Region = Parent;
15367     for (unsigned I = 0; I < Elts.size(); ++I)
15368       Tree.merge(Elts[I]);
15369   }
15370 };
15371 
15372 } // namespace
15373 
15374 void Sema::CheckUnsequencedOperations(const Expr *E) {
15375   SmallVector<const Expr *, 8> WorkList;
15376   WorkList.push_back(E);
15377   while (!WorkList.empty()) {
15378     const Expr *Item = WorkList.pop_back_val();
15379     SequenceChecker(*this, Item, WorkList);
15380   }
15381 }
15382 
15383 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
15384                               bool IsConstexpr) {
15385   llvm::SaveAndRestore<bool> ConstantContext(
15386       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
15387   CheckImplicitConversions(E, CheckLoc);
15388   if (!E->isInstantiationDependent())
15389     CheckUnsequencedOperations(E);
15390   if (!IsConstexpr && !E->isValueDependent())
15391     CheckForIntOverflow(E);
15392   DiagnoseMisalignedMembers();
15393 }
15394 
15395 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
15396                                        FieldDecl *BitField,
15397                                        Expr *Init) {
15398   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
15399 }
15400 
15401 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
15402                                          SourceLocation Loc) {
15403   if (!PType->isVariablyModifiedType())
15404     return;
15405   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
15406     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
15407     return;
15408   }
15409   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
15410     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
15411     return;
15412   }
15413   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
15414     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
15415     return;
15416   }
15417 
15418   const ArrayType *AT = S.Context.getAsArrayType(PType);
15419   if (!AT)
15420     return;
15421 
15422   if (AT->getSizeModifier() != ArrayType::Star) {
15423     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
15424     return;
15425   }
15426 
15427   S.Diag(Loc, diag::err_array_star_in_function_definition);
15428 }
15429 
15430 /// CheckParmsForFunctionDef - Check that the parameters of the given
15431 /// function are appropriate for the definition of a function. This
15432 /// takes care of any checks that cannot be performed on the
15433 /// declaration itself, e.g., that the types of each of the function
15434 /// parameters are complete.
15435 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
15436                                     bool CheckParameterNames) {
15437   bool HasInvalidParm = false;
15438   for (ParmVarDecl *Param : Parameters) {
15439     // C99 6.7.5.3p4: the parameters in a parameter type list in a
15440     // function declarator that is part of a function definition of
15441     // that function shall not have incomplete type.
15442     //
15443     // This is also C++ [dcl.fct]p6.
15444     if (!Param->isInvalidDecl() &&
15445         RequireCompleteType(Param->getLocation(), Param->getType(),
15446                             diag::err_typecheck_decl_incomplete_type)) {
15447       Param->setInvalidDecl();
15448       HasInvalidParm = true;
15449     }
15450 
15451     // C99 6.9.1p5: If the declarator includes a parameter type list, the
15452     // declaration of each parameter shall include an identifier.
15453     if (CheckParameterNames && Param->getIdentifier() == nullptr &&
15454         !Param->isImplicit() && !getLangOpts().CPlusPlus) {
15455       // Diagnose this as an extension in C17 and earlier.
15456       if (!getLangOpts().C2x)
15457         Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
15458     }
15459 
15460     // C99 6.7.5.3p12:
15461     //   If the function declarator is not part of a definition of that
15462     //   function, parameters may have incomplete type and may use the [*]
15463     //   notation in their sequences of declarator specifiers to specify
15464     //   variable length array types.
15465     QualType PType = Param->getOriginalType();
15466     // FIXME: This diagnostic should point the '[*]' if source-location
15467     // information is added for it.
15468     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
15469 
15470     // If the parameter is a c++ class type and it has to be destructed in the
15471     // callee function, declare the destructor so that it can be called by the
15472     // callee function. Do not perform any direct access check on the dtor here.
15473     if (!Param->isInvalidDecl()) {
15474       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
15475         if (!ClassDecl->isInvalidDecl() &&
15476             !ClassDecl->hasIrrelevantDestructor() &&
15477             !ClassDecl->isDependentContext() &&
15478             ClassDecl->isParamDestroyedInCallee()) {
15479           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
15480           MarkFunctionReferenced(Param->getLocation(), Destructor);
15481           DiagnoseUseOfDecl(Destructor, Param->getLocation());
15482         }
15483       }
15484     }
15485 
15486     // Parameters with the pass_object_size attribute only need to be marked
15487     // constant at function definitions. Because we lack information about
15488     // whether we're on a declaration or definition when we're instantiating the
15489     // attribute, we need to check for constness here.
15490     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
15491       if (!Param->getType().isConstQualified())
15492         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
15493             << Attr->getSpelling() << 1;
15494 
15495     // Check for parameter names shadowing fields from the class.
15496     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
15497       // The owning context for the parameter should be the function, but we
15498       // want to see if this function's declaration context is a record.
15499       DeclContext *DC = Param->getDeclContext();
15500       if (DC && DC->isFunctionOrMethod()) {
15501         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
15502           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
15503                                      RD, /*DeclIsField*/ false);
15504       }
15505     }
15506   }
15507 
15508   return HasInvalidParm;
15509 }
15510 
15511 Optional<std::pair<CharUnits, CharUnits>>
15512 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx);
15513 
15514 /// Compute the alignment and offset of the base class object given the
15515 /// derived-to-base cast expression and the alignment and offset of the derived
15516 /// class object.
15517 static std::pair<CharUnits, CharUnits>
15518 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
15519                                    CharUnits BaseAlignment, CharUnits Offset,
15520                                    ASTContext &Ctx) {
15521   for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
15522        ++PathI) {
15523     const CXXBaseSpecifier *Base = *PathI;
15524     const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
15525     if (Base->isVirtual()) {
15526       // The complete object may have a lower alignment than the non-virtual
15527       // alignment of the base, in which case the base may be misaligned. Choose
15528       // the smaller of the non-virtual alignment and BaseAlignment, which is a
15529       // conservative lower bound of the complete object alignment.
15530       CharUnits NonVirtualAlignment =
15531           Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment();
15532       BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
15533       Offset = CharUnits::Zero();
15534     } else {
15535       const ASTRecordLayout &RL =
15536           Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
15537       Offset += RL.getBaseClassOffset(BaseDecl);
15538     }
15539     DerivedType = Base->getType();
15540   }
15541 
15542   return std::make_pair(BaseAlignment, Offset);
15543 }
15544 
15545 /// Compute the alignment and offset of a binary additive operator.
15546 static Optional<std::pair<CharUnits, CharUnits>>
15547 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
15548                                      bool IsSub, ASTContext &Ctx) {
15549   QualType PointeeType = PtrE->getType()->getPointeeType();
15550 
15551   if (!PointeeType->isConstantSizeType())
15552     return llvm::None;
15553 
15554   auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
15555 
15556   if (!P)
15557     return llvm::None;
15558 
15559   CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
15560   if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
15561     CharUnits Offset = EltSize * IdxRes->getExtValue();
15562     if (IsSub)
15563       Offset = -Offset;
15564     return std::make_pair(P->first, P->second + Offset);
15565   }
15566 
15567   // If the integer expression isn't a constant expression, compute the lower
15568   // bound of the alignment using the alignment and offset of the pointer
15569   // expression and the element size.
15570   return std::make_pair(
15571       P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
15572       CharUnits::Zero());
15573 }
15574 
15575 /// This helper function takes an lvalue expression and returns the alignment of
15576 /// a VarDecl and a constant offset from the VarDecl.
15577 Optional<std::pair<CharUnits, CharUnits>>
15578 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) {
15579   E = E->IgnoreParens();
15580   switch (E->getStmtClass()) {
15581   default:
15582     break;
15583   case Stmt::CStyleCastExprClass:
15584   case Stmt::CXXStaticCastExprClass:
15585   case Stmt::ImplicitCastExprClass: {
15586     auto *CE = cast<CastExpr>(E);
15587     const Expr *From = CE->getSubExpr();
15588     switch (CE->getCastKind()) {
15589     default:
15590       break;
15591     case CK_NoOp:
15592       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15593     case CK_UncheckedDerivedToBase:
15594     case CK_DerivedToBase: {
15595       auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15596       if (!P)
15597         break;
15598       return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
15599                                                 P->second, Ctx);
15600     }
15601     }
15602     break;
15603   }
15604   case Stmt::ArraySubscriptExprClass: {
15605     auto *ASE = cast<ArraySubscriptExpr>(E);
15606     return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(),
15607                                                 false, Ctx);
15608   }
15609   case Stmt::DeclRefExprClass: {
15610     if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
15611       // FIXME: If VD is captured by copy or is an escaping __block variable,
15612       // use the alignment of VD's type.
15613       if (!VD->getType()->isReferenceType())
15614         return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
15615       if (VD->hasInit())
15616         return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
15617     }
15618     break;
15619   }
15620   case Stmt::MemberExprClass: {
15621     auto *ME = cast<MemberExpr>(E);
15622     auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
15623     if (!FD || FD->getType()->isReferenceType() ||
15624         FD->getParent()->isInvalidDecl())
15625       break;
15626     Optional<std::pair<CharUnits, CharUnits>> P;
15627     if (ME->isArrow())
15628       P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
15629     else
15630       P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
15631     if (!P)
15632       break;
15633     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
15634     uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
15635     return std::make_pair(P->first,
15636                           P->second + CharUnits::fromQuantity(Offset));
15637   }
15638   case Stmt::UnaryOperatorClass: {
15639     auto *UO = cast<UnaryOperator>(E);
15640     switch (UO->getOpcode()) {
15641     default:
15642       break;
15643     case UO_Deref:
15644       return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx);
15645     }
15646     break;
15647   }
15648   case Stmt::BinaryOperatorClass: {
15649     auto *BO = cast<BinaryOperator>(E);
15650     auto Opcode = BO->getOpcode();
15651     switch (Opcode) {
15652     default:
15653       break;
15654     case BO_Comma:
15655       return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx);
15656     }
15657     break;
15658   }
15659   }
15660   return llvm::None;
15661 }
15662 
15663 /// This helper function takes a pointer expression and returns the alignment of
15664 /// a VarDecl and a constant offset from the VarDecl.
15665 Optional<std::pair<CharUnits, CharUnits>>
15666 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) {
15667   E = E->IgnoreParens();
15668   switch (E->getStmtClass()) {
15669   default:
15670     break;
15671   case Stmt::CStyleCastExprClass:
15672   case Stmt::CXXStaticCastExprClass:
15673   case Stmt::ImplicitCastExprClass: {
15674     auto *CE = cast<CastExpr>(E);
15675     const Expr *From = CE->getSubExpr();
15676     switch (CE->getCastKind()) {
15677     default:
15678       break;
15679     case CK_NoOp:
15680       return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
15681     case CK_ArrayToPointerDecay:
15682       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15683     case CK_UncheckedDerivedToBase:
15684     case CK_DerivedToBase: {
15685       auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
15686       if (!P)
15687         break;
15688       return getDerivedToBaseAlignmentAndOffset(
15689           CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
15690     }
15691     }
15692     break;
15693   }
15694   case Stmt::CXXThisExprClass: {
15695     auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
15696     CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment();
15697     return std::make_pair(Alignment, CharUnits::Zero());
15698   }
15699   case Stmt::UnaryOperatorClass: {
15700     auto *UO = cast<UnaryOperator>(E);
15701     if (UO->getOpcode() == UO_AddrOf)
15702       return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx);
15703     break;
15704   }
15705   case Stmt::BinaryOperatorClass: {
15706     auto *BO = cast<BinaryOperator>(E);
15707     auto Opcode = BO->getOpcode();
15708     switch (Opcode) {
15709     default:
15710       break;
15711     case BO_Add:
15712     case BO_Sub: {
15713       const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
15714       if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
15715         std::swap(LHS, RHS);
15716       return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
15717                                                   Ctx);
15718     }
15719     case BO_Comma:
15720       return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
15721     }
15722     break;
15723   }
15724   }
15725   return llvm::None;
15726 }
15727 
15728 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
15729   // See if we can compute the alignment of a VarDecl and an offset from it.
15730   Optional<std::pair<CharUnits, CharUnits>> P =
15731       getBaseAlignmentAndOffsetFromPtr(E, S.Context);
15732 
15733   if (P)
15734     return P->first.alignmentAtOffset(P->second);
15735 
15736   // If that failed, return the type's alignment.
15737   return S.Context.getTypeAlignInChars(E->getType()->getPointeeType());
15738 }
15739 
15740 /// CheckCastAlign - Implements -Wcast-align, which warns when a
15741 /// pointer cast increases the alignment requirements.
15742 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
15743   // This is actually a lot of work to potentially be doing on every
15744   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
15745   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
15746     return;
15747 
15748   // Ignore dependent types.
15749   if (T->isDependentType() || Op->getType()->isDependentType())
15750     return;
15751 
15752   // Require that the destination be a pointer type.
15753   const PointerType *DestPtr = T->getAs<PointerType>();
15754   if (!DestPtr) return;
15755 
15756   // If the destination has alignment 1, we're done.
15757   QualType DestPointee = DestPtr->getPointeeType();
15758   if (DestPointee->isIncompleteType()) return;
15759   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
15760   if (DestAlign.isOne()) return;
15761 
15762   // Require that the source be a pointer type.
15763   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
15764   if (!SrcPtr) return;
15765   QualType SrcPointee = SrcPtr->getPointeeType();
15766 
15767   // Explicitly allow casts from cv void*.  We already implicitly
15768   // allowed casts to cv void*, since they have alignment 1.
15769   // Also allow casts involving incomplete types, which implicitly
15770   // includes 'void'.
15771   if (SrcPointee->isIncompleteType()) return;
15772 
15773   CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
15774 
15775   if (SrcAlign >= DestAlign) return;
15776 
15777   Diag(TRange.getBegin(), diag::warn_cast_align)
15778     << Op->getType() << T
15779     << static_cast<unsigned>(SrcAlign.getQuantity())
15780     << static_cast<unsigned>(DestAlign.getQuantity())
15781     << TRange << Op->getSourceRange();
15782 }
15783 
15784 /// Check whether this array fits the idiom of a size-one tail padded
15785 /// array member of a struct.
15786 ///
15787 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
15788 /// commonly used to emulate flexible arrays in C89 code.
15789 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
15790                                     const NamedDecl *ND) {
15791   if (Size != 1 || !ND) return false;
15792 
15793   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
15794   if (!FD) return false;
15795 
15796   // Don't consider sizes resulting from macro expansions or template argument
15797   // substitution to form C89 tail-padded arrays.
15798 
15799   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
15800   while (TInfo) {
15801     TypeLoc TL = TInfo->getTypeLoc();
15802     // Look through typedefs.
15803     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
15804       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
15805       TInfo = TDL->getTypeSourceInfo();
15806       continue;
15807     }
15808     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
15809       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
15810       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
15811         return false;
15812     }
15813     break;
15814   }
15815 
15816   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
15817   if (!RD) return false;
15818   if (RD->isUnion()) return false;
15819   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
15820     if (!CRD->isStandardLayout()) return false;
15821   }
15822 
15823   // See if this is the last field decl in the record.
15824   const Decl *D = FD;
15825   while ((D = D->getNextDeclInContext()))
15826     if (isa<FieldDecl>(D))
15827       return false;
15828   return true;
15829 }
15830 
15831 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
15832                             const ArraySubscriptExpr *ASE,
15833                             bool AllowOnePastEnd, bool IndexNegated) {
15834   // Already diagnosed by the constant evaluator.
15835   if (isConstantEvaluated())
15836     return;
15837 
15838   IndexExpr = IndexExpr->IgnoreParenImpCasts();
15839   if (IndexExpr->isValueDependent())
15840     return;
15841 
15842   const Type *EffectiveType =
15843       BaseExpr->getType()->getPointeeOrArrayElementType();
15844   BaseExpr = BaseExpr->IgnoreParenCasts();
15845   const ConstantArrayType *ArrayTy =
15846       Context.getAsConstantArrayType(BaseExpr->getType());
15847 
15848   const Type *BaseType =
15849       ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
15850   bool IsUnboundedArray = (BaseType == nullptr);
15851   if (EffectiveType->isDependentType() ||
15852       (!IsUnboundedArray && BaseType->isDependentType()))
15853     return;
15854 
15855   Expr::EvalResult Result;
15856   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
15857     return;
15858 
15859   llvm::APSInt index = Result.Val.getInt();
15860   if (IndexNegated) {
15861     index.setIsUnsigned(false);
15862     index = -index;
15863   }
15864 
15865   const NamedDecl *ND = nullptr;
15866   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15867     ND = DRE->getDecl();
15868   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
15869     ND = ME->getMemberDecl();
15870 
15871   if (IsUnboundedArray) {
15872     if (EffectiveType->isFunctionType())
15873       return;
15874     if (index.isUnsigned() || !index.isNegative()) {
15875       const auto &ASTC = getASTContext();
15876       unsigned AddrBits =
15877           ASTC.getTargetInfo().getPointerWidth(ASTC.getTargetAddressSpace(
15878               EffectiveType->getCanonicalTypeInternal()));
15879       if (index.getBitWidth() < AddrBits)
15880         index = index.zext(AddrBits);
15881       Optional<CharUnits> ElemCharUnits =
15882           ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
15883       // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
15884       // pointer) bounds-checking isn't meaningful.
15885       if (!ElemCharUnits)
15886         return;
15887       llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
15888       // If index has more active bits than address space, we already know
15889       // we have a bounds violation to warn about.  Otherwise, compute
15890       // address of (index + 1)th element, and warn about bounds violation
15891       // only if that address exceeds address space.
15892       if (index.getActiveBits() <= AddrBits) {
15893         bool Overflow;
15894         llvm::APInt Product(index);
15895         Product += 1;
15896         Product = Product.umul_ov(ElemBytes, Overflow);
15897         if (!Overflow && Product.getActiveBits() <= AddrBits)
15898           return;
15899       }
15900 
15901       // Need to compute max possible elements in address space, since that
15902       // is included in diag message.
15903       llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
15904       MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
15905       MaxElems += 1;
15906       ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
15907       MaxElems = MaxElems.udiv(ElemBytes);
15908 
15909       unsigned DiagID =
15910           ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
15911               : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
15912 
15913       // Diag message shows element size in bits and in "bytes" (platform-
15914       // dependent CharUnits)
15915       DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15916                           PDiag(DiagID)
15917                               << toString(index, 10, true) << AddrBits
15918                               << (unsigned)ASTC.toBits(*ElemCharUnits)
15919                               << toString(ElemBytes, 10, false)
15920                               << toString(MaxElems, 10, false)
15921                               << (unsigned)MaxElems.getLimitedValue(~0U)
15922                               << IndexExpr->getSourceRange());
15923 
15924       if (!ND) {
15925         // Try harder to find a NamedDecl to point at in the note.
15926         while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15927           BaseExpr = ASE->getBase()->IgnoreParenCasts();
15928         if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15929           ND = DRE->getDecl();
15930         if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15931           ND = ME->getMemberDecl();
15932       }
15933 
15934       if (ND)
15935         DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15936                             PDiag(diag::note_array_declared_here) << ND);
15937     }
15938     return;
15939   }
15940 
15941   if (index.isUnsigned() || !index.isNegative()) {
15942     // It is possible that the type of the base expression after
15943     // IgnoreParenCasts is incomplete, even though the type of the base
15944     // expression before IgnoreParenCasts is complete (see PR39746 for an
15945     // example). In this case we have no information about whether the array
15946     // access exceeds the array bounds. However we can still diagnose an array
15947     // access which precedes the array bounds.
15948     if (BaseType->isIncompleteType())
15949       return;
15950 
15951     llvm::APInt size = ArrayTy->getSize();
15952     if (!size.isStrictlyPositive())
15953       return;
15954 
15955     if (BaseType != EffectiveType) {
15956       // Make sure we're comparing apples to apples when comparing index to size
15957       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
15958       uint64_t array_typesize = Context.getTypeSize(BaseType);
15959       // Handle ptrarith_typesize being zero, such as when casting to void*
15960       if (!ptrarith_typesize) ptrarith_typesize = 1;
15961       if (ptrarith_typesize != array_typesize) {
15962         // There's a cast to a different size type involved
15963         uint64_t ratio = array_typesize / ptrarith_typesize;
15964         // TODO: Be smarter about handling cases where array_typesize is not a
15965         // multiple of ptrarith_typesize
15966         if (ptrarith_typesize * ratio == array_typesize)
15967           size *= llvm::APInt(size.getBitWidth(), ratio);
15968       }
15969     }
15970 
15971     if (size.getBitWidth() > index.getBitWidth())
15972       index = index.zext(size.getBitWidth());
15973     else if (size.getBitWidth() < index.getBitWidth())
15974       size = size.zext(index.getBitWidth());
15975 
15976     // For array subscripting the index must be less than size, but for pointer
15977     // arithmetic also allow the index (offset) to be equal to size since
15978     // computing the next address after the end of the array is legal and
15979     // commonly done e.g. in C++ iterators and range-based for loops.
15980     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
15981       return;
15982 
15983     // Also don't warn for arrays of size 1 which are members of some
15984     // structure. These are often used to approximate flexible arrays in C89
15985     // code.
15986     if (IsTailPaddedMemberArray(*this, size, ND))
15987       return;
15988 
15989     // Suppress the warning if the subscript expression (as identified by the
15990     // ']' location) and the index expression are both from macro expansions
15991     // within a system header.
15992     if (ASE) {
15993       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
15994           ASE->getRBracketLoc());
15995       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
15996         SourceLocation IndexLoc =
15997             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
15998         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
15999           return;
16000       }
16001     }
16002 
16003     unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
16004                           : diag::warn_ptr_arith_exceeds_bounds;
16005 
16006     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
16007                         PDiag(DiagID) << toString(index, 10, true)
16008                                       << toString(size, 10, true)
16009                                       << (unsigned)size.getLimitedValue(~0U)
16010                                       << IndexExpr->getSourceRange());
16011   } else {
16012     unsigned DiagID = diag::warn_array_index_precedes_bounds;
16013     if (!ASE) {
16014       DiagID = diag::warn_ptr_arith_precedes_bounds;
16015       if (index.isNegative()) index = -index;
16016     }
16017 
16018     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
16019                         PDiag(DiagID) << toString(index, 10, true)
16020                                       << IndexExpr->getSourceRange());
16021   }
16022 
16023   if (!ND) {
16024     // Try harder to find a NamedDecl to point at in the note.
16025     while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
16026       BaseExpr = ASE->getBase()->IgnoreParenCasts();
16027     if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
16028       ND = DRE->getDecl();
16029     if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
16030       ND = ME->getMemberDecl();
16031   }
16032 
16033   if (ND)
16034     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
16035                         PDiag(diag::note_array_declared_here) << ND);
16036 }
16037 
16038 void Sema::CheckArrayAccess(const Expr *expr) {
16039   int AllowOnePastEnd = 0;
16040   while (expr) {
16041     expr = expr->IgnoreParenImpCasts();
16042     switch (expr->getStmtClass()) {
16043       case Stmt::ArraySubscriptExprClass: {
16044         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
16045         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
16046                          AllowOnePastEnd > 0);
16047         expr = ASE->getBase();
16048         break;
16049       }
16050       case Stmt::MemberExprClass: {
16051         expr = cast<MemberExpr>(expr)->getBase();
16052         break;
16053       }
16054       case Stmt::OMPArraySectionExprClass: {
16055         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
16056         if (ASE->getLowerBound())
16057           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
16058                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
16059         return;
16060       }
16061       case Stmt::UnaryOperatorClass: {
16062         // Only unwrap the * and & unary operators
16063         const UnaryOperator *UO = cast<UnaryOperator>(expr);
16064         expr = UO->getSubExpr();
16065         switch (UO->getOpcode()) {
16066           case UO_AddrOf:
16067             AllowOnePastEnd++;
16068             break;
16069           case UO_Deref:
16070             AllowOnePastEnd--;
16071             break;
16072           default:
16073             return;
16074         }
16075         break;
16076       }
16077       case Stmt::ConditionalOperatorClass: {
16078         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
16079         if (const Expr *lhs = cond->getLHS())
16080           CheckArrayAccess(lhs);
16081         if (const Expr *rhs = cond->getRHS())
16082           CheckArrayAccess(rhs);
16083         return;
16084       }
16085       case Stmt::CXXOperatorCallExprClass: {
16086         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
16087         for (const auto *Arg : OCE->arguments())
16088           CheckArrayAccess(Arg);
16089         return;
16090       }
16091       default:
16092         return;
16093     }
16094   }
16095 }
16096 
16097 //===--- CHECK: Objective-C retain cycles ----------------------------------//
16098 
16099 namespace {
16100 
16101 struct RetainCycleOwner {
16102   VarDecl *Variable = nullptr;
16103   SourceRange Range;
16104   SourceLocation Loc;
16105   bool Indirect = false;
16106 
16107   RetainCycleOwner() = default;
16108 
16109   void setLocsFrom(Expr *e) {
16110     Loc = e->getExprLoc();
16111     Range = e->getSourceRange();
16112   }
16113 };
16114 
16115 } // namespace
16116 
16117 /// Consider whether capturing the given variable can possibly lead to
16118 /// a retain cycle.
16119 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
16120   // In ARC, it's captured strongly iff the variable has __strong
16121   // lifetime.  In MRR, it's captured strongly if the variable is
16122   // __block and has an appropriate type.
16123   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
16124     return false;
16125 
16126   owner.Variable = var;
16127   if (ref)
16128     owner.setLocsFrom(ref);
16129   return true;
16130 }
16131 
16132 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
16133   while (true) {
16134     e = e->IgnoreParens();
16135     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
16136       switch (cast->getCastKind()) {
16137       case CK_BitCast:
16138       case CK_LValueBitCast:
16139       case CK_LValueToRValue:
16140       case CK_ARCReclaimReturnedObject:
16141         e = cast->getSubExpr();
16142         continue;
16143 
16144       default:
16145         return false;
16146       }
16147     }
16148 
16149     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
16150       ObjCIvarDecl *ivar = ref->getDecl();
16151       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
16152         return false;
16153 
16154       // Try to find a retain cycle in the base.
16155       if (!findRetainCycleOwner(S, ref->getBase(), owner))
16156         return false;
16157 
16158       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
16159       owner.Indirect = true;
16160       return true;
16161     }
16162 
16163     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
16164       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
16165       if (!var) return false;
16166       return considerVariable(var, ref, owner);
16167     }
16168 
16169     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
16170       if (member->isArrow()) return false;
16171 
16172       // Don't count this as an indirect ownership.
16173       e = member->getBase();
16174       continue;
16175     }
16176 
16177     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
16178       // Only pay attention to pseudo-objects on property references.
16179       ObjCPropertyRefExpr *pre
16180         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
16181                                               ->IgnoreParens());
16182       if (!pre) return false;
16183       if (pre->isImplicitProperty()) return false;
16184       ObjCPropertyDecl *property = pre->getExplicitProperty();
16185       if (!property->isRetaining() &&
16186           !(property->getPropertyIvarDecl() &&
16187             property->getPropertyIvarDecl()->getType()
16188               .getObjCLifetime() == Qualifiers::OCL_Strong))
16189           return false;
16190 
16191       owner.Indirect = true;
16192       if (pre->isSuperReceiver()) {
16193         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
16194         if (!owner.Variable)
16195           return false;
16196         owner.Loc = pre->getLocation();
16197         owner.Range = pre->getSourceRange();
16198         return true;
16199       }
16200       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
16201                               ->getSourceExpr());
16202       continue;
16203     }
16204 
16205     // Array ivars?
16206 
16207     return false;
16208   }
16209 }
16210 
16211 namespace {
16212 
16213   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
16214     ASTContext &Context;
16215     VarDecl *Variable;
16216     Expr *Capturer = nullptr;
16217     bool VarWillBeReased = false;
16218 
16219     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
16220         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
16221           Context(Context), Variable(variable) {}
16222 
16223     void VisitDeclRefExpr(DeclRefExpr *ref) {
16224       if (ref->getDecl() == Variable && !Capturer)
16225         Capturer = ref;
16226     }
16227 
16228     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
16229       if (Capturer) return;
16230       Visit(ref->getBase());
16231       if (Capturer && ref->isFreeIvar())
16232         Capturer = ref;
16233     }
16234 
16235     void VisitBlockExpr(BlockExpr *block) {
16236       // Look inside nested blocks
16237       if (block->getBlockDecl()->capturesVariable(Variable))
16238         Visit(block->getBlockDecl()->getBody());
16239     }
16240 
16241     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
16242       if (Capturer) return;
16243       if (OVE->getSourceExpr())
16244         Visit(OVE->getSourceExpr());
16245     }
16246 
16247     void VisitBinaryOperator(BinaryOperator *BinOp) {
16248       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
16249         return;
16250       Expr *LHS = BinOp->getLHS();
16251       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
16252         if (DRE->getDecl() != Variable)
16253           return;
16254         if (Expr *RHS = BinOp->getRHS()) {
16255           RHS = RHS->IgnoreParenCasts();
16256           Optional<llvm::APSInt> Value;
16257           VarWillBeReased =
16258               (RHS && (Value = RHS->getIntegerConstantExpr(Context)) &&
16259                *Value == 0);
16260         }
16261       }
16262     }
16263   };
16264 
16265 } // namespace
16266 
16267 /// Check whether the given argument is a block which captures a
16268 /// variable.
16269 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
16270   assert(owner.Variable && owner.Loc.isValid());
16271 
16272   e = e->IgnoreParenCasts();
16273 
16274   // Look through [^{...} copy] and Block_copy(^{...}).
16275   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
16276     Selector Cmd = ME->getSelector();
16277     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
16278       e = ME->getInstanceReceiver();
16279       if (!e)
16280         return nullptr;
16281       e = e->IgnoreParenCasts();
16282     }
16283   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
16284     if (CE->getNumArgs() == 1) {
16285       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
16286       if (Fn) {
16287         const IdentifierInfo *FnI = Fn->getIdentifier();
16288         if (FnI && FnI->isStr("_Block_copy")) {
16289           e = CE->getArg(0)->IgnoreParenCasts();
16290         }
16291       }
16292     }
16293   }
16294 
16295   BlockExpr *block = dyn_cast<BlockExpr>(e);
16296   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
16297     return nullptr;
16298 
16299   FindCaptureVisitor visitor(S.Context, owner.Variable);
16300   visitor.Visit(block->getBlockDecl()->getBody());
16301   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
16302 }
16303 
16304 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
16305                                 RetainCycleOwner &owner) {
16306   assert(capturer);
16307   assert(owner.Variable && owner.Loc.isValid());
16308 
16309   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
16310     << owner.Variable << capturer->getSourceRange();
16311   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
16312     << owner.Indirect << owner.Range;
16313 }
16314 
16315 /// Check for a keyword selector that starts with the word 'add' or
16316 /// 'set'.
16317 static bool isSetterLikeSelector(Selector sel) {
16318   if (sel.isUnarySelector()) return false;
16319 
16320   StringRef str = sel.getNameForSlot(0);
16321   while (!str.empty() && str.front() == '_') str = str.substr(1);
16322   if (str.startswith("set"))
16323     str = str.substr(3);
16324   else if (str.startswith("add")) {
16325     // Specially allow 'addOperationWithBlock:'.
16326     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
16327       return false;
16328     str = str.substr(3);
16329   }
16330   else
16331     return false;
16332 
16333   if (str.empty()) return true;
16334   return !isLowercase(str.front());
16335 }
16336 
16337 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
16338                                                     ObjCMessageExpr *Message) {
16339   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
16340                                                 Message->getReceiverInterface(),
16341                                                 NSAPI::ClassId_NSMutableArray);
16342   if (!IsMutableArray) {
16343     return None;
16344   }
16345 
16346   Selector Sel = Message->getSelector();
16347 
16348   Optional<NSAPI::NSArrayMethodKind> MKOpt =
16349     S.NSAPIObj->getNSArrayMethodKind(Sel);
16350   if (!MKOpt) {
16351     return None;
16352   }
16353 
16354   NSAPI::NSArrayMethodKind MK = *MKOpt;
16355 
16356   switch (MK) {
16357     case NSAPI::NSMutableArr_addObject:
16358     case NSAPI::NSMutableArr_insertObjectAtIndex:
16359     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
16360       return 0;
16361     case NSAPI::NSMutableArr_replaceObjectAtIndex:
16362       return 1;
16363 
16364     default:
16365       return None;
16366   }
16367 
16368   return None;
16369 }
16370 
16371 static
16372 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
16373                                                   ObjCMessageExpr *Message) {
16374   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
16375                                             Message->getReceiverInterface(),
16376                                             NSAPI::ClassId_NSMutableDictionary);
16377   if (!IsMutableDictionary) {
16378     return None;
16379   }
16380 
16381   Selector Sel = Message->getSelector();
16382 
16383   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
16384     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
16385   if (!MKOpt) {
16386     return None;
16387   }
16388 
16389   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
16390 
16391   switch (MK) {
16392     case NSAPI::NSMutableDict_setObjectForKey:
16393     case NSAPI::NSMutableDict_setValueForKey:
16394     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
16395       return 0;
16396 
16397     default:
16398       return None;
16399   }
16400 
16401   return None;
16402 }
16403 
16404 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
16405   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
16406                                                 Message->getReceiverInterface(),
16407                                                 NSAPI::ClassId_NSMutableSet);
16408 
16409   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
16410                                             Message->getReceiverInterface(),
16411                                             NSAPI::ClassId_NSMutableOrderedSet);
16412   if (!IsMutableSet && !IsMutableOrderedSet) {
16413     return None;
16414   }
16415 
16416   Selector Sel = Message->getSelector();
16417 
16418   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
16419   if (!MKOpt) {
16420     return None;
16421   }
16422 
16423   NSAPI::NSSetMethodKind MK = *MKOpt;
16424 
16425   switch (MK) {
16426     case NSAPI::NSMutableSet_addObject:
16427     case NSAPI::NSOrderedSet_setObjectAtIndex:
16428     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
16429     case NSAPI::NSOrderedSet_insertObjectAtIndex:
16430       return 0;
16431     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
16432       return 1;
16433   }
16434 
16435   return None;
16436 }
16437 
16438 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
16439   if (!Message->isInstanceMessage()) {
16440     return;
16441   }
16442 
16443   Optional<int> ArgOpt;
16444 
16445   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
16446       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
16447       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
16448     return;
16449   }
16450 
16451   int ArgIndex = *ArgOpt;
16452 
16453   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
16454   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
16455     Arg = OE->getSourceExpr()->IgnoreImpCasts();
16456   }
16457 
16458   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
16459     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
16460       if (ArgRE->isObjCSelfExpr()) {
16461         Diag(Message->getSourceRange().getBegin(),
16462              diag::warn_objc_circular_container)
16463           << ArgRE->getDecl() << StringRef("'super'");
16464       }
16465     }
16466   } else {
16467     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
16468 
16469     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
16470       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
16471     }
16472 
16473     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
16474       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
16475         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
16476           ValueDecl *Decl = ReceiverRE->getDecl();
16477           Diag(Message->getSourceRange().getBegin(),
16478                diag::warn_objc_circular_container)
16479             << Decl << Decl;
16480           if (!ArgRE->isObjCSelfExpr()) {
16481             Diag(Decl->getLocation(),
16482                  diag::note_objc_circular_container_declared_here)
16483               << Decl;
16484           }
16485         }
16486       }
16487     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
16488       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
16489         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
16490           ObjCIvarDecl *Decl = IvarRE->getDecl();
16491           Diag(Message->getSourceRange().getBegin(),
16492                diag::warn_objc_circular_container)
16493             << Decl << Decl;
16494           Diag(Decl->getLocation(),
16495                diag::note_objc_circular_container_declared_here)
16496             << Decl;
16497         }
16498       }
16499     }
16500   }
16501 }
16502 
16503 /// Check a message send to see if it's likely to cause a retain cycle.
16504 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
16505   // Only check instance methods whose selector looks like a setter.
16506   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
16507     return;
16508 
16509   // Try to find a variable that the receiver is strongly owned by.
16510   RetainCycleOwner owner;
16511   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
16512     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
16513       return;
16514   } else {
16515     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
16516     owner.Variable = getCurMethodDecl()->getSelfDecl();
16517     owner.Loc = msg->getSuperLoc();
16518     owner.Range = msg->getSuperLoc();
16519   }
16520 
16521   // Check whether the receiver is captured by any of the arguments.
16522   const ObjCMethodDecl *MD = msg->getMethodDecl();
16523   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
16524     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
16525       // noescape blocks should not be retained by the method.
16526       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
16527         continue;
16528       return diagnoseRetainCycle(*this, capturer, owner);
16529     }
16530   }
16531 }
16532 
16533 /// Check a property assign to see if it's likely to cause a retain cycle.
16534 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
16535   RetainCycleOwner owner;
16536   if (!findRetainCycleOwner(*this, receiver, owner))
16537     return;
16538 
16539   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
16540     diagnoseRetainCycle(*this, capturer, owner);
16541 }
16542 
16543 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
16544   RetainCycleOwner Owner;
16545   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
16546     return;
16547 
16548   // Because we don't have an expression for the variable, we have to set the
16549   // location explicitly here.
16550   Owner.Loc = Var->getLocation();
16551   Owner.Range = Var->getSourceRange();
16552 
16553   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
16554     diagnoseRetainCycle(*this, Capturer, Owner);
16555 }
16556 
16557 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
16558                                      Expr *RHS, bool isProperty) {
16559   // Check if RHS is an Objective-C object literal, which also can get
16560   // immediately zapped in a weak reference.  Note that we explicitly
16561   // allow ObjCStringLiterals, since those are designed to never really die.
16562   RHS = RHS->IgnoreParenImpCasts();
16563 
16564   // This enum needs to match with the 'select' in
16565   // warn_objc_arc_literal_assign (off-by-1).
16566   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
16567   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
16568     return false;
16569 
16570   S.Diag(Loc, diag::warn_arc_literal_assign)
16571     << (unsigned) Kind
16572     << (isProperty ? 0 : 1)
16573     << RHS->getSourceRange();
16574 
16575   return true;
16576 }
16577 
16578 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
16579                                     Qualifiers::ObjCLifetime LT,
16580                                     Expr *RHS, bool isProperty) {
16581   // Strip off any implicit cast added to get to the one ARC-specific.
16582   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
16583     if (cast->getCastKind() == CK_ARCConsumeObject) {
16584       S.Diag(Loc, diag::warn_arc_retained_assign)
16585         << (LT == Qualifiers::OCL_ExplicitNone)
16586         << (isProperty ? 0 : 1)
16587         << RHS->getSourceRange();
16588       return true;
16589     }
16590     RHS = cast->getSubExpr();
16591   }
16592 
16593   if (LT == Qualifiers::OCL_Weak &&
16594       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
16595     return true;
16596 
16597   return false;
16598 }
16599 
16600 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
16601                               QualType LHS, Expr *RHS) {
16602   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
16603 
16604   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
16605     return false;
16606 
16607   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
16608     return true;
16609 
16610   return false;
16611 }
16612 
16613 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
16614                               Expr *LHS, Expr *RHS) {
16615   QualType LHSType;
16616   // PropertyRef on LHS type need be directly obtained from
16617   // its declaration as it has a PseudoType.
16618   ObjCPropertyRefExpr *PRE
16619     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
16620   if (PRE && !PRE->isImplicitProperty()) {
16621     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
16622     if (PD)
16623       LHSType = PD->getType();
16624   }
16625 
16626   if (LHSType.isNull())
16627     LHSType = LHS->getType();
16628 
16629   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
16630 
16631   if (LT == Qualifiers::OCL_Weak) {
16632     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
16633       getCurFunction()->markSafeWeakUse(LHS);
16634   }
16635 
16636   if (checkUnsafeAssigns(Loc, LHSType, RHS))
16637     return;
16638 
16639   // FIXME. Check for other life times.
16640   if (LT != Qualifiers::OCL_None)
16641     return;
16642 
16643   if (PRE) {
16644     if (PRE->isImplicitProperty())
16645       return;
16646     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
16647     if (!PD)
16648       return;
16649 
16650     unsigned Attributes = PD->getPropertyAttributes();
16651     if (Attributes & ObjCPropertyAttribute::kind_assign) {
16652       // when 'assign' attribute was not explicitly specified
16653       // by user, ignore it and rely on property type itself
16654       // for lifetime info.
16655       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
16656       if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
16657           LHSType->isObjCRetainableType())
16658         return;
16659 
16660       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
16661         if (cast->getCastKind() == CK_ARCConsumeObject) {
16662           Diag(Loc, diag::warn_arc_retained_property_assign)
16663           << RHS->getSourceRange();
16664           return;
16665         }
16666         RHS = cast->getSubExpr();
16667       }
16668     } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
16669       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
16670         return;
16671     }
16672   }
16673 }
16674 
16675 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
16676 
16677 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
16678                                         SourceLocation StmtLoc,
16679                                         const NullStmt *Body) {
16680   // Do not warn if the body is a macro that expands to nothing, e.g:
16681   //
16682   // #define CALL(x)
16683   // if (condition)
16684   //   CALL(0);
16685   if (Body->hasLeadingEmptyMacro())
16686     return false;
16687 
16688   // Get line numbers of statement and body.
16689   bool StmtLineInvalid;
16690   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
16691                                                       &StmtLineInvalid);
16692   if (StmtLineInvalid)
16693     return false;
16694 
16695   bool BodyLineInvalid;
16696   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
16697                                                       &BodyLineInvalid);
16698   if (BodyLineInvalid)
16699     return false;
16700 
16701   // Warn if null statement and body are on the same line.
16702   if (StmtLine != BodyLine)
16703     return false;
16704 
16705   return true;
16706 }
16707 
16708 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
16709                                  const Stmt *Body,
16710                                  unsigned DiagID) {
16711   // Since this is a syntactic check, don't emit diagnostic for template
16712   // instantiations, this just adds noise.
16713   if (CurrentInstantiationScope)
16714     return;
16715 
16716   // The body should be a null statement.
16717   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
16718   if (!NBody)
16719     return;
16720 
16721   // Do the usual checks.
16722   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
16723     return;
16724 
16725   Diag(NBody->getSemiLoc(), DiagID);
16726   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
16727 }
16728 
16729 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
16730                                  const Stmt *PossibleBody) {
16731   assert(!CurrentInstantiationScope); // Ensured by caller
16732 
16733   SourceLocation StmtLoc;
16734   const Stmt *Body;
16735   unsigned DiagID;
16736   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
16737     StmtLoc = FS->getRParenLoc();
16738     Body = FS->getBody();
16739     DiagID = diag::warn_empty_for_body;
16740   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
16741     StmtLoc = WS->getRParenLoc();
16742     Body = WS->getBody();
16743     DiagID = diag::warn_empty_while_body;
16744   } else
16745     return; // Neither `for' nor `while'.
16746 
16747   // The body should be a null statement.
16748   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
16749   if (!NBody)
16750     return;
16751 
16752   // Skip expensive checks if diagnostic is disabled.
16753   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
16754     return;
16755 
16756   // Do the usual checks.
16757   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
16758     return;
16759 
16760   // `for(...);' and `while(...);' are popular idioms, so in order to keep
16761   // noise level low, emit diagnostics only if for/while is followed by a
16762   // CompoundStmt, e.g.:
16763   //    for (int i = 0; i < n; i++);
16764   //    {
16765   //      a(i);
16766   //    }
16767   // or if for/while is followed by a statement with more indentation
16768   // than for/while itself:
16769   //    for (int i = 0; i < n; i++);
16770   //      a(i);
16771   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
16772   if (!ProbableTypo) {
16773     bool BodyColInvalid;
16774     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
16775         PossibleBody->getBeginLoc(), &BodyColInvalid);
16776     if (BodyColInvalid)
16777       return;
16778 
16779     bool StmtColInvalid;
16780     unsigned StmtCol =
16781         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
16782     if (StmtColInvalid)
16783       return;
16784 
16785     if (BodyCol > StmtCol)
16786       ProbableTypo = true;
16787   }
16788 
16789   if (ProbableTypo) {
16790     Diag(NBody->getSemiLoc(), DiagID);
16791     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
16792   }
16793 }
16794 
16795 //===--- CHECK: Warn on self move with std::move. -------------------------===//
16796 
16797 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
16798 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
16799                              SourceLocation OpLoc) {
16800   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
16801     return;
16802 
16803   if (inTemplateInstantiation())
16804     return;
16805 
16806   // Strip parens and casts away.
16807   LHSExpr = LHSExpr->IgnoreParenImpCasts();
16808   RHSExpr = RHSExpr->IgnoreParenImpCasts();
16809 
16810   // Check for a call expression
16811   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
16812   if (!CE || CE->getNumArgs() != 1)
16813     return;
16814 
16815   // Check for a call to std::move
16816   if (!CE->isCallToStdMove())
16817     return;
16818 
16819   // Get argument from std::move
16820   RHSExpr = CE->getArg(0);
16821 
16822   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
16823   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
16824 
16825   // Two DeclRefExpr's, check that the decls are the same.
16826   if (LHSDeclRef && RHSDeclRef) {
16827     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16828       return;
16829     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16830         RHSDeclRef->getDecl()->getCanonicalDecl())
16831       return;
16832 
16833     auto D = Diag(OpLoc, diag::warn_self_move)
16834              << LHSExpr->getType() << LHSExpr->getSourceRange()
16835              << RHSExpr->getSourceRange();
16836     if (const FieldDecl *F =
16837             getSelfAssignmentClassMemberCandidate(RHSDeclRef->getDecl()))
16838       D << 1 << F
16839         << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
16840     else
16841       D << 0;
16842     return;
16843   }
16844 
16845   // Member variables require a different approach to check for self moves.
16846   // MemberExpr's are the same if every nested MemberExpr refers to the same
16847   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
16848   // the base Expr's are CXXThisExpr's.
16849   const Expr *LHSBase = LHSExpr;
16850   const Expr *RHSBase = RHSExpr;
16851   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
16852   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
16853   if (!LHSME || !RHSME)
16854     return;
16855 
16856   while (LHSME && RHSME) {
16857     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
16858         RHSME->getMemberDecl()->getCanonicalDecl())
16859       return;
16860 
16861     LHSBase = LHSME->getBase();
16862     RHSBase = RHSME->getBase();
16863     LHSME = dyn_cast<MemberExpr>(LHSBase);
16864     RHSME = dyn_cast<MemberExpr>(RHSBase);
16865   }
16866 
16867   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
16868   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
16869   if (LHSDeclRef && RHSDeclRef) {
16870     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16871       return;
16872     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16873         RHSDeclRef->getDecl()->getCanonicalDecl())
16874       return;
16875 
16876     Diag(OpLoc, diag::warn_self_move)
16877         << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
16878         << RHSExpr->getSourceRange();
16879     return;
16880   }
16881 
16882   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
16883     Diag(OpLoc, diag::warn_self_move)
16884         << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
16885         << RHSExpr->getSourceRange();
16886 }
16887 
16888 //===--- Layout compatibility ----------------------------------------------//
16889 
16890 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
16891 
16892 /// Check if two enumeration types are layout-compatible.
16893 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
16894   // C++11 [dcl.enum] p8:
16895   // Two enumeration types are layout-compatible if they have the same
16896   // underlying type.
16897   return ED1->isComplete() && ED2->isComplete() &&
16898          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
16899 }
16900 
16901 /// Check if two fields are layout-compatible.
16902 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
16903                                FieldDecl *Field2) {
16904   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
16905     return false;
16906 
16907   if (Field1->isBitField() != Field2->isBitField())
16908     return false;
16909 
16910   if (Field1->isBitField()) {
16911     // Make sure that the bit-fields are the same length.
16912     unsigned Bits1 = Field1->getBitWidthValue(C);
16913     unsigned Bits2 = Field2->getBitWidthValue(C);
16914 
16915     if (Bits1 != Bits2)
16916       return false;
16917   }
16918 
16919   return true;
16920 }
16921 
16922 /// Check if two standard-layout structs are layout-compatible.
16923 /// (C++11 [class.mem] p17)
16924 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
16925                                      RecordDecl *RD2) {
16926   // If both records are C++ classes, check that base classes match.
16927   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
16928     // If one of records is a CXXRecordDecl we are in C++ mode,
16929     // thus the other one is a CXXRecordDecl, too.
16930     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
16931     // Check number of base classes.
16932     if (D1CXX->getNumBases() != D2CXX->getNumBases())
16933       return false;
16934 
16935     // Check the base classes.
16936     for (CXXRecordDecl::base_class_const_iterator
16937                Base1 = D1CXX->bases_begin(),
16938            BaseEnd1 = D1CXX->bases_end(),
16939               Base2 = D2CXX->bases_begin();
16940          Base1 != BaseEnd1;
16941          ++Base1, ++Base2) {
16942       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
16943         return false;
16944     }
16945   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
16946     // If only RD2 is a C++ class, it should have zero base classes.
16947     if (D2CXX->getNumBases() > 0)
16948       return false;
16949   }
16950 
16951   // Check the fields.
16952   RecordDecl::field_iterator Field2 = RD2->field_begin(),
16953                              Field2End = RD2->field_end(),
16954                              Field1 = RD1->field_begin(),
16955                              Field1End = RD1->field_end();
16956   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
16957     if (!isLayoutCompatible(C, *Field1, *Field2))
16958       return false;
16959   }
16960   if (Field1 != Field1End || Field2 != Field2End)
16961     return false;
16962 
16963   return true;
16964 }
16965 
16966 /// Check if two standard-layout unions are layout-compatible.
16967 /// (C++11 [class.mem] p18)
16968 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
16969                                     RecordDecl *RD2) {
16970   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
16971   for (auto *Field2 : RD2->fields())
16972     UnmatchedFields.insert(Field2);
16973 
16974   for (auto *Field1 : RD1->fields()) {
16975     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
16976         I = UnmatchedFields.begin(),
16977         E = UnmatchedFields.end();
16978 
16979     for ( ; I != E; ++I) {
16980       if (isLayoutCompatible(C, Field1, *I)) {
16981         bool Result = UnmatchedFields.erase(*I);
16982         (void) Result;
16983         assert(Result);
16984         break;
16985       }
16986     }
16987     if (I == E)
16988       return false;
16989   }
16990 
16991   return UnmatchedFields.empty();
16992 }
16993 
16994 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
16995                                RecordDecl *RD2) {
16996   if (RD1->isUnion() != RD2->isUnion())
16997     return false;
16998 
16999   if (RD1->isUnion())
17000     return isLayoutCompatibleUnion(C, RD1, RD2);
17001   else
17002     return isLayoutCompatibleStruct(C, RD1, RD2);
17003 }
17004 
17005 /// Check if two types are layout-compatible in C++11 sense.
17006 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
17007   if (T1.isNull() || T2.isNull())
17008     return false;
17009 
17010   // C++11 [basic.types] p11:
17011   // If two types T1 and T2 are the same type, then T1 and T2 are
17012   // layout-compatible types.
17013   if (C.hasSameType(T1, T2))
17014     return true;
17015 
17016   T1 = T1.getCanonicalType().getUnqualifiedType();
17017   T2 = T2.getCanonicalType().getUnqualifiedType();
17018 
17019   const Type::TypeClass TC1 = T1->getTypeClass();
17020   const Type::TypeClass TC2 = T2->getTypeClass();
17021 
17022   if (TC1 != TC2)
17023     return false;
17024 
17025   if (TC1 == Type::Enum) {
17026     return isLayoutCompatible(C,
17027                               cast<EnumType>(T1)->getDecl(),
17028                               cast<EnumType>(T2)->getDecl());
17029   } else if (TC1 == Type::Record) {
17030     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
17031       return false;
17032 
17033     return isLayoutCompatible(C,
17034                               cast<RecordType>(T1)->getDecl(),
17035                               cast<RecordType>(T2)->getDecl());
17036   }
17037 
17038   return false;
17039 }
17040 
17041 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
17042 
17043 /// Given a type tag expression find the type tag itself.
17044 ///
17045 /// \param TypeExpr Type tag expression, as it appears in user's code.
17046 ///
17047 /// \param VD Declaration of an identifier that appears in a type tag.
17048 ///
17049 /// \param MagicValue Type tag magic value.
17050 ///
17051 /// \param isConstantEvaluated whether the evalaution should be performed in
17052 
17053 /// constant context.
17054 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
17055                             const ValueDecl **VD, uint64_t *MagicValue,
17056                             bool isConstantEvaluated) {
17057   while(true) {
17058     if (!TypeExpr)
17059       return false;
17060 
17061     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
17062 
17063     switch (TypeExpr->getStmtClass()) {
17064     case Stmt::UnaryOperatorClass: {
17065       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
17066       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
17067         TypeExpr = UO->getSubExpr();
17068         continue;
17069       }
17070       return false;
17071     }
17072 
17073     case Stmt::DeclRefExprClass: {
17074       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
17075       *VD = DRE->getDecl();
17076       return true;
17077     }
17078 
17079     case Stmt::IntegerLiteralClass: {
17080       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
17081       llvm::APInt MagicValueAPInt = IL->getValue();
17082       if (MagicValueAPInt.getActiveBits() <= 64) {
17083         *MagicValue = MagicValueAPInt.getZExtValue();
17084         return true;
17085       } else
17086         return false;
17087     }
17088 
17089     case Stmt::BinaryConditionalOperatorClass:
17090     case Stmt::ConditionalOperatorClass: {
17091       const AbstractConditionalOperator *ACO =
17092           cast<AbstractConditionalOperator>(TypeExpr);
17093       bool Result;
17094       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
17095                                                      isConstantEvaluated)) {
17096         if (Result)
17097           TypeExpr = ACO->getTrueExpr();
17098         else
17099           TypeExpr = ACO->getFalseExpr();
17100         continue;
17101       }
17102       return false;
17103     }
17104 
17105     case Stmt::BinaryOperatorClass: {
17106       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
17107       if (BO->getOpcode() == BO_Comma) {
17108         TypeExpr = BO->getRHS();
17109         continue;
17110       }
17111       return false;
17112     }
17113 
17114     default:
17115       return false;
17116     }
17117   }
17118 }
17119 
17120 /// Retrieve the C type corresponding to type tag TypeExpr.
17121 ///
17122 /// \param TypeExpr Expression that specifies a type tag.
17123 ///
17124 /// \param MagicValues Registered magic values.
17125 ///
17126 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
17127 ///        kind.
17128 ///
17129 /// \param TypeInfo Information about the corresponding C type.
17130 ///
17131 /// \param isConstantEvaluated whether the evalaution should be performed in
17132 /// constant context.
17133 ///
17134 /// \returns true if the corresponding C type was found.
17135 static bool GetMatchingCType(
17136     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
17137     const ASTContext &Ctx,
17138     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
17139         *MagicValues,
17140     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
17141     bool isConstantEvaluated) {
17142   FoundWrongKind = false;
17143 
17144   // Variable declaration that has type_tag_for_datatype attribute.
17145   const ValueDecl *VD = nullptr;
17146 
17147   uint64_t MagicValue;
17148 
17149   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
17150     return false;
17151 
17152   if (VD) {
17153     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
17154       if (I->getArgumentKind() != ArgumentKind) {
17155         FoundWrongKind = true;
17156         return false;
17157       }
17158       TypeInfo.Type = I->getMatchingCType();
17159       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
17160       TypeInfo.MustBeNull = I->getMustBeNull();
17161       return true;
17162     }
17163     return false;
17164   }
17165 
17166   if (!MagicValues)
17167     return false;
17168 
17169   llvm::DenseMap<Sema::TypeTagMagicValue,
17170                  Sema::TypeTagData>::const_iterator I =
17171       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
17172   if (I == MagicValues->end())
17173     return false;
17174 
17175   TypeInfo = I->second;
17176   return true;
17177 }
17178 
17179 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
17180                                       uint64_t MagicValue, QualType Type,
17181                                       bool LayoutCompatible,
17182                                       bool MustBeNull) {
17183   if (!TypeTagForDatatypeMagicValues)
17184     TypeTagForDatatypeMagicValues.reset(
17185         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
17186 
17187   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
17188   (*TypeTagForDatatypeMagicValues)[Magic] =
17189       TypeTagData(Type, LayoutCompatible, MustBeNull);
17190 }
17191 
17192 static bool IsSameCharType(QualType T1, QualType T2) {
17193   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
17194   if (!BT1)
17195     return false;
17196 
17197   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
17198   if (!BT2)
17199     return false;
17200 
17201   BuiltinType::Kind T1Kind = BT1->getKind();
17202   BuiltinType::Kind T2Kind = BT2->getKind();
17203 
17204   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
17205          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
17206          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
17207          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
17208 }
17209 
17210 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
17211                                     const ArrayRef<const Expr *> ExprArgs,
17212                                     SourceLocation CallSiteLoc) {
17213   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
17214   bool IsPointerAttr = Attr->getIsPointer();
17215 
17216   // Retrieve the argument representing the 'type_tag'.
17217   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
17218   if (TypeTagIdxAST >= ExprArgs.size()) {
17219     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
17220         << 0 << Attr->getTypeTagIdx().getSourceIndex();
17221     return;
17222   }
17223   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
17224   bool FoundWrongKind;
17225   TypeTagData TypeInfo;
17226   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
17227                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
17228                         TypeInfo, isConstantEvaluated())) {
17229     if (FoundWrongKind)
17230       Diag(TypeTagExpr->getExprLoc(),
17231            diag::warn_type_tag_for_datatype_wrong_kind)
17232         << TypeTagExpr->getSourceRange();
17233     return;
17234   }
17235 
17236   // Retrieve the argument representing the 'arg_idx'.
17237   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
17238   if (ArgumentIdxAST >= ExprArgs.size()) {
17239     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
17240         << 1 << Attr->getArgumentIdx().getSourceIndex();
17241     return;
17242   }
17243   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
17244   if (IsPointerAttr) {
17245     // Skip implicit cast of pointer to `void *' (as a function argument).
17246     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
17247       if (ICE->getType()->isVoidPointerType() &&
17248           ICE->getCastKind() == CK_BitCast)
17249         ArgumentExpr = ICE->getSubExpr();
17250   }
17251   QualType ArgumentType = ArgumentExpr->getType();
17252 
17253   // Passing a `void*' pointer shouldn't trigger a warning.
17254   if (IsPointerAttr && ArgumentType->isVoidPointerType())
17255     return;
17256 
17257   if (TypeInfo.MustBeNull) {
17258     // Type tag with matching void type requires a null pointer.
17259     if (!ArgumentExpr->isNullPointerConstant(Context,
17260                                              Expr::NPC_ValueDependentIsNotNull)) {
17261       Diag(ArgumentExpr->getExprLoc(),
17262            diag::warn_type_safety_null_pointer_required)
17263           << ArgumentKind->getName()
17264           << ArgumentExpr->getSourceRange()
17265           << TypeTagExpr->getSourceRange();
17266     }
17267     return;
17268   }
17269 
17270   QualType RequiredType = TypeInfo.Type;
17271   if (IsPointerAttr)
17272     RequiredType = Context.getPointerType(RequiredType);
17273 
17274   bool mismatch = false;
17275   if (!TypeInfo.LayoutCompatible) {
17276     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
17277 
17278     // C++11 [basic.fundamental] p1:
17279     // Plain char, signed char, and unsigned char are three distinct types.
17280     //
17281     // But we treat plain `char' as equivalent to `signed char' or `unsigned
17282     // char' depending on the current char signedness mode.
17283     if (mismatch)
17284       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
17285                                            RequiredType->getPointeeType())) ||
17286           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
17287         mismatch = false;
17288   } else
17289     if (IsPointerAttr)
17290       mismatch = !isLayoutCompatible(Context,
17291                                      ArgumentType->getPointeeType(),
17292                                      RequiredType->getPointeeType());
17293     else
17294       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
17295 
17296   if (mismatch)
17297     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
17298         << ArgumentType << ArgumentKind
17299         << TypeInfo.LayoutCompatible << RequiredType
17300         << ArgumentExpr->getSourceRange()
17301         << TypeTagExpr->getSourceRange();
17302 }
17303 
17304 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
17305                                          CharUnits Alignment) {
17306   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
17307 }
17308 
17309 void Sema::DiagnoseMisalignedMembers() {
17310   for (MisalignedMember &m : MisalignedMembers) {
17311     const NamedDecl *ND = m.RD;
17312     if (ND->getName().empty()) {
17313       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
17314         ND = TD;
17315     }
17316     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
17317         << m.MD << ND << m.E->getSourceRange();
17318   }
17319   MisalignedMembers.clear();
17320 }
17321 
17322 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
17323   E = E->IgnoreParens();
17324   if (!T->isPointerType() && !T->isIntegerType())
17325     return;
17326   if (isa<UnaryOperator>(E) &&
17327       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
17328     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
17329     if (isa<MemberExpr>(Op)) {
17330       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
17331       if (MA != MisalignedMembers.end() &&
17332           (T->isIntegerType() ||
17333            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
17334                                    Context.getTypeAlignInChars(
17335                                        T->getPointeeType()) <= MA->Alignment))))
17336         MisalignedMembers.erase(MA);
17337     }
17338   }
17339 }
17340 
17341 void Sema::RefersToMemberWithReducedAlignment(
17342     Expr *E,
17343     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
17344         Action) {
17345   const auto *ME = dyn_cast<MemberExpr>(E);
17346   if (!ME)
17347     return;
17348 
17349   // No need to check expressions with an __unaligned-qualified type.
17350   if (E->getType().getQualifiers().hasUnaligned())
17351     return;
17352 
17353   // For a chain of MemberExpr like "a.b.c.d" this list
17354   // will keep FieldDecl's like [d, c, b].
17355   SmallVector<FieldDecl *, 4> ReverseMemberChain;
17356   const MemberExpr *TopME = nullptr;
17357   bool AnyIsPacked = false;
17358   do {
17359     QualType BaseType = ME->getBase()->getType();
17360     if (BaseType->isDependentType())
17361       return;
17362     if (ME->isArrow())
17363       BaseType = BaseType->getPointeeType();
17364     RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
17365     if (RD->isInvalidDecl())
17366       return;
17367 
17368     ValueDecl *MD = ME->getMemberDecl();
17369     auto *FD = dyn_cast<FieldDecl>(MD);
17370     // We do not care about non-data members.
17371     if (!FD || FD->isInvalidDecl())
17372       return;
17373 
17374     AnyIsPacked =
17375         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
17376     ReverseMemberChain.push_back(FD);
17377 
17378     TopME = ME;
17379     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
17380   } while (ME);
17381   assert(TopME && "We did not compute a topmost MemberExpr!");
17382 
17383   // Not the scope of this diagnostic.
17384   if (!AnyIsPacked)
17385     return;
17386 
17387   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
17388   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
17389   // TODO: The innermost base of the member expression may be too complicated.
17390   // For now, just disregard these cases. This is left for future
17391   // improvement.
17392   if (!DRE && !isa<CXXThisExpr>(TopBase))
17393       return;
17394 
17395   // Alignment expected by the whole expression.
17396   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
17397 
17398   // No need to do anything else with this case.
17399   if (ExpectedAlignment.isOne())
17400     return;
17401 
17402   // Synthesize offset of the whole access.
17403   CharUnits Offset;
17404   for (const FieldDecl *FD : llvm::reverse(ReverseMemberChain))
17405     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(FD));
17406 
17407   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
17408   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
17409       ReverseMemberChain.back()->getParent()->getTypeForDecl());
17410 
17411   // The base expression of the innermost MemberExpr may give
17412   // stronger guarantees than the class containing the member.
17413   if (DRE && !TopME->isArrow()) {
17414     const ValueDecl *VD = DRE->getDecl();
17415     if (!VD->getType()->isReferenceType())
17416       CompleteObjectAlignment =
17417           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
17418   }
17419 
17420   // Check if the synthesized offset fulfills the alignment.
17421   if (Offset % ExpectedAlignment != 0 ||
17422       // It may fulfill the offset it but the effective alignment may still be
17423       // lower than the expected expression alignment.
17424       CompleteObjectAlignment < ExpectedAlignment) {
17425     // If this happens, we want to determine a sensible culprit of this.
17426     // Intuitively, watching the chain of member expressions from right to
17427     // left, we start with the required alignment (as required by the field
17428     // type) but some packed attribute in that chain has reduced the alignment.
17429     // It may happen that another packed structure increases it again. But if
17430     // we are here such increase has not been enough. So pointing the first
17431     // FieldDecl that either is packed or else its RecordDecl is,
17432     // seems reasonable.
17433     FieldDecl *FD = nullptr;
17434     CharUnits Alignment;
17435     for (FieldDecl *FDI : ReverseMemberChain) {
17436       if (FDI->hasAttr<PackedAttr>() ||
17437           FDI->getParent()->hasAttr<PackedAttr>()) {
17438         FD = FDI;
17439         Alignment = std::min(
17440             Context.getTypeAlignInChars(FD->getType()),
17441             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
17442         break;
17443       }
17444     }
17445     assert(FD && "We did not find a packed FieldDecl!");
17446     Action(E, FD->getParent(), FD, Alignment);
17447   }
17448 }
17449 
17450 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
17451   using namespace std::placeholders;
17452 
17453   RefersToMemberWithReducedAlignment(
17454       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
17455                      _2, _3, _4));
17456 }
17457 
17458 // Check if \p Ty is a valid type for the elementwise math builtins. If it is
17459 // not a valid type, emit an error message and return true. Otherwise return
17460 // false.
17461 static bool checkMathBuiltinElementType(Sema &S, SourceLocation Loc,
17462                                         QualType Ty) {
17463   if (!Ty->getAs<VectorType>() && !ConstantMatrixType::isValidElementType(Ty)) {
17464     S.Diag(Loc, diag::err_builtin_invalid_arg_type)
17465         << 1 << /* vector, integer or float ty*/ 0 << Ty;
17466     return true;
17467   }
17468   return false;
17469 }
17470 
17471 bool Sema::PrepareBuiltinElementwiseMathOneArgCall(CallExpr *TheCall) {
17472   if (checkArgCount(*this, TheCall, 1))
17473     return true;
17474 
17475   ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
17476   if (A.isInvalid())
17477     return true;
17478 
17479   TheCall->setArg(0, A.get());
17480   QualType TyA = A.get()->getType();
17481 
17482   if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA))
17483     return true;
17484 
17485   TheCall->setType(TyA);
17486   return false;
17487 }
17488 
17489 bool Sema::SemaBuiltinElementwiseMath(CallExpr *TheCall) {
17490   if (checkArgCount(*this, TheCall, 2))
17491     return true;
17492 
17493   ExprResult A = TheCall->getArg(0);
17494   ExprResult B = TheCall->getArg(1);
17495   // Do standard promotions between the two arguments, returning their common
17496   // type.
17497   QualType Res =
17498       UsualArithmeticConversions(A, B, TheCall->getExprLoc(), ACK_Comparison);
17499   if (A.isInvalid() || B.isInvalid())
17500     return true;
17501 
17502   QualType TyA = A.get()->getType();
17503   QualType TyB = B.get()->getType();
17504 
17505   if (Res.isNull() || TyA.getCanonicalType() != TyB.getCanonicalType())
17506     return Diag(A.get()->getBeginLoc(),
17507                 diag::err_typecheck_call_different_arg_types)
17508            << TyA << TyB;
17509 
17510   if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA))
17511     return true;
17512 
17513   TheCall->setArg(0, A.get());
17514   TheCall->setArg(1, B.get());
17515   TheCall->setType(Res);
17516   return false;
17517 }
17518 
17519 bool Sema::PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall) {
17520   if (checkArgCount(*this, TheCall, 1))
17521     return true;
17522 
17523   ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
17524   if (A.isInvalid())
17525     return true;
17526 
17527   TheCall->setArg(0, A.get());
17528   return false;
17529 }
17530 
17531 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall,
17532                                             ExprResult CallResult) {
17533   if (checkArgCount(*this, TheCall, 1))
17534     return ExprError();
17535 
17536   ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
17537   if (MatrixArg.isInvalid())
17538     return MatrixArg;
17539   Expr *Matrix = MatrixArg.get();
17540 
17541   auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
17542   if (!MType) {
17543     Diag(Matrix->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17544         << 1 << /* matrix ty*/ 1 << Matrix->getType();
17545     return ExprError();
17546   }
17547 
17548   // Create returned matrix type by swapping rows and columns of the argument
17549   // matrix type.
17550   QualType ResultType = Context.getConstantMatrixType(
17551       MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
17552 
17553   // Change the return type to the type of the returned matrix.
17554   TheCall->setType(ResultType);
17555 
17556   // Update call argument to use the possibly converted matrix argument.
17557   TheCall->setArg(0, Matrix);
17558   return CallResult;
17559 }
17560 
17561 // Get and verify the matrix dimensions.
17562 static llvm::Optional<unsigned>
17563 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {
17564   SourceLocation ErrorPos;
17565   Optional<llvm::APSInt> Value =
17566       Expr->getIntegerConstantExpr(S.Context, &ErrorPos);
17567   if (!Value) {
17568     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
17569         << Name;
17570     return {};
17571   }
17572   uint64_t Dim = Value->getZExtValue();
17573   if (!ConstantMatrixType::isDimensionValid(Dim)) {
17574     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
17575         << Name << ConstantMatrixType::getMaxElementsPerDimension();
17576     return {};
17577   }
17578   return Dim;
17579 }
17580 
17581 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
17582                                                   ExprResult CallResult) {
17583   if (!getLangOpts().MatrixTypes) {
17584     Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
17585     return ExprError();
17586   }
17587 
17588   if (checkArgCount(*this, TheCall, 4))
17589     return ExprError();
17590 
17591   unsigned PtrArgIdx = 0;
17592   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
17593   Expr *RowsExpr = TheCall->getArg(1);
17594   Expr *ColumnsExpr = TheCall->getArg(2);
17595   Expr *StrideExpr = TheCall->getArg(3);
17596 
17597   bool ArgError = false;
17598 
17599   // Check pointer argument.
17600   {
17601     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
17602     if (PtrConv.isInvalid())
17603       return PtrConv;
17604     PtrExpr = PtrConv.get();
17605     TheCall->setArg(0, PtrExpr);
17606     if (PtrExpr->isTypeDependent()) {
17607       TheCall->setType(Context.DependentTy);
17608       return TheCall;
17609     }
17610   }
17611 
17612   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17613   QualType ElementTy;
17614   if (!PtrTy) {
17615     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17616         << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType();
17617     ArgError = true;
17618   } else {
17619     ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
17620 
17621     if (!ConstantMatrixType::isValidElementType(ElementTy)) {
17622       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17623           << PtrArgIdx + 1 << /* pointer to element ty*/ 2
17624           << PtrExpr->getType();
17625       ArgError = true;
17626     }
17627   }
17628 
17629   // Apply default Lvalue conversions and convert the expression to size_t.
17630   auto ApplyArgumentConversions = [this](Expr *E) {
17631     ExprResult Conv = DefaultLvalueConversion(E);
17632     if (Conv.isInvalid())
17633       return Conv;
17634 
17635     return tryConvertExprToType(Conv.get(), Context.getSizeType());
17636   };
17637 
17638   // Apply conversion to row and column expressions.
17639   ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
17640   if (!RowsConv.isInvalid()) {
17641     RowsExpr = RowsConv.get();
17642     TheCall->setArg(1, RowsExpr);
17643   } else
17644     RowsExpr = nullptr;
17645 
17646   ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
17647   if (!ColumnsConv.isInvalid()) {
17648     ColumnsExpr = ColumnsConv.get();
17649     TheCall->setArg(2, ColumnsExpr);
17650   } else
17651     ColumnsExpr = nullptr;
17652 
17653   // If any any part of the result matrix type is still pending, just use
17654   // Context.DependentTy, until all parts are resolved.
17655   if ((RowsExpr && RowsExpr->isTypeDependent()) ||
17656       (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
17657     TheCall->setType(Context.DependentTy);
17658     return CallResult;
17659   }
17660 
17661   // Check row and column dimensions.
17662   llvm::Optional<unsigned> MaybeRows;
17663   if (RowsExpr)
17664     MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
17665 
17666   llvm::Optional<unsigned> MaybeColumns;
17667   if (ColumnsExpr)
17668     MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
17669 
17670   // Check stride argument.
17671   ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
17672   if (StrideConv.isInvalid())
17673     return ExprError();
17674   StrideExpr = StrideConv.get();
17675   TheCall->setArg(3, StrideExpr);
17676 
17677   if (MaybeRows) {
17678     if (Optional<llvm::APSInt> Value =
17679             StrideExpr->getIntegerConstantExpr(Context)) {
17680       uint64_t Stride = Value->getZExtValue();
17681       if (Stride < *MaybeRows) {
17682         Diag(StrideExpr->getBeginLoc(),
17683              diag::err_builtin_matrix_stride_too_small);
17684         ArgError = true;
17685       }
17686     }
17687   }
17688 
17689   if (ArgError || !MaybeRows || !MaybeColumns)
17690     return ExprError();
17691 
17692   TheCall->setType(
17693       Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
17694   return CallResult;
17695 }
17696 
17697 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
17698                                                    ExprResult CallResult) {
17699   if (checkArgCount(*this, TheCall, 3))
17700     return ExprError();
17701 
17702   unsigned PtrArgIdx = 1;
17703   Expr *MatrixExpr = TheCall->getArg(0);
17704   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
17705   Expr *StrideExpr = TheCall->getArg(2);
17706 
17707   bool ArgError = false;
17708 
17709   {
17710     ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
17711     if (MatrixConv.isInvalid())
17712       return MatrixConv;
17713     MatrixExpr = MatrixConv.get();
17714     TheCall->setArg(0, MatrixExpr);
17715   }
17716   if (MatrixExpr->isTypeDependent()) {
17717     TheCall->setType(Context.DependentTy);
17718     return TheCall;
17719   }
17720 
17721   auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
17722   if (!MatrixTy) {
17723     Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17724         << 1 << /*matrix ty */ 1 << MatrixExpr->getType();
17725     ArgError = true;
17726   }
17727 
17728   {
17729     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
17730     if (PtrConv.isInvalid())
17731       return PtrConv;
17732     PtrExpr = PtrConv.get();
17733     TheCall->setArg(1, PtrExpr);
17734     if (PtrExpr->isTypeDependent()) {
17735       TheCall->setType(Context.DependentTy);
17736       return TheCall;
17737     }
17738   }
17739 
17740   // Check pointer argument.
17741   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17742   if (!PtrTy) {
17743     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17744         << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType();
17745     ArgError = true;
17746   } else {
17747     QualType ElementTy = PtrTy->getPointeeType();
17748     if (ElementTy.isConstQualified()) {
17749       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
17750       ArgError = true;
17751     }
17752     ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
17753     if (MatrixTy &&
17754         !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
17755       Diag(PtrExpr->getBeginLoc(),
17756            diag::err_builtin_matrix_pointer_arg_mismatch)
17757           << ElementTy << MatrixTy->getElementType();
17758       ArgError = true;
17759     }
17760   }
17761 
17762   // Apply default Lvalue conversions and convert the stride expression to
17763   // size_t.
17764   {
17765     ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
17766     if (StrideConv.isInvalid())
17767       return StrideConv;
17768 
17769     StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
17770     if (StrideConv.isInvalid())
17771       return StrideConv;
17772     StrideExpr = StrideConv.get();
17773     TheCall->setArg(2, StrideExpr);
17774   }
17775 
17776   // Check stride argument.
17777   if (MatrixTy) {
17778     if (Optional<llvm::APSInt> Value =
17779             StrideExpr->getIntegerConstantExpr(Context)) {
17780       uint64_t Stride = Value->getZExtValue();
17781       if (Stride < MatrixTy->getNumRows()) {
17782         Diag(StrideExpr->getBeginLoc(),
17783              diag::err_builtin_matrix_stride_too_small);
17784         ArgError = true;
17785       }
17786     }
17787   }
17788 
17789   if (ArgError)
17790     return ExprError();
17791 
17792   return CallResult;
17793 }
17794 
17795 /// \brief Enforce the bounds of a TCB
17796 /// CheckTCBEnforcement - Enforces that every function in a named TCB only
17797 /// directly calls other functions in the same TCB as marked by the enforce_tcb
17798 /// and enforce_tcb_leaf attributes.
17799 void Sema::CheckTCBEnforcement(const SourceLocation CallExprLoc,
17800                                const NamedDecl *Callee) {
17801   const NamedDecl *Caller = getCurFunctionOrMethodDecl();
17802 
17803   if (!Caller || !Caller->hasAttr<EnforceTCBAttr>())
17804     return;
17805 
17806   // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
17807   // all TCBs the callee is a part of.
17808   llvm::StringSet<> CalleeTCBs;
17809   for (const auto *A : Callee->specific_attrs<EnforceTCBAttr>())
17810     CalleeTCBs.insert(A->getTCBName());
17811   for (const auto *A : Callee->specific_attrs<EnforceTCBLeafAttr>())
17812     CalleeTCBs.insert(A->getTCBName());
17813 
17814   // Go through the TCBs the caller is a part of and emit warnings if Caller
17815   // is in a TCB that the Callee is not.
17816   for (const auto *A : Caller->specific_attrs<EnforceTCBAttr>()) {
17817     StringRef CallerTCB = A->getTCBName();
17818     if (CalleeTCBs.count(CallerTCB) == 0) {
17819       this->Diag(CallExprLoc, diag::warn_tcb_enforcement_violation)
17820           << Callee << CallerTCB;
17821     }
17822   }
17823 }
17824