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 /// Checks that a call expression's argument count is the desired number.
113 /// This is useful when doing custom type-checking.  Returns true on error.
114 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
115   unsigned argCount = call->getNumArgs();
116   if (argCount == desiredArgCount) return false;
117 
118   if (argCount < desiredArgCount)
119     return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args)
120            << 0 /*function call*/ << desiredArgCount << argCount
121            << call->getSourceRange();
122 
123   // Highlight all the excess arguments.
124   SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(),
125                     call->getArg(argCount - 1)->getEndLoc());
126 
127   return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
128     << 0 /*function call*/ << desiredArgCount << argCount
129     << call->getArg(1)->getSourceRange();
130 }
131 
132 /// Check that the first argument to __builtin_annotation is an integer
133 /// and the second argument is a non-wide string literal.
134 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
135   if (checkArgCount(S, TheCall, 2))
136     return true;
137 
138   // First argument should be an integer.
139   Expr *ValArg = TheCall->getArg(0);
140   QualType Ty = ValArg->getType();
141   if (!Ty->isIntegerType()) {
142     S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
143         << ValArg->getSourceRange();
144     return true;
145   }
146 
147   // Second argument should be a constant string.
148   Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
149   StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
150   if (!Literal || !Literal->isAscii()) {
151     S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
152         << StrArg->getSourceRange();
153     return true;
154   }
155 
156   TheCall->setType(Ty);
157   return false;
158 }
159 
160 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
161   // We need at least one argument.
162   if (TheCall->getNumArgs() < 1) {
163     S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
164         << 0 << 1 << TheCall->getNumArgs()
165         << TheCall->getCallee()->getSourceRange();
166     return true;
167   }
168 
169   // All arguments should be wide string literals.
170   for (Expr *Arg : TheCall->arguments()) {
171     auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
172     if (!Literal || !Literal->isWide()) {
173       S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
174           << Arg->getSourceRange();
175       return true;
176     }
177   }
178 
179   return false;
180 }
181 
182 /// Check that the argument to __builtin_addressof is a glvalue, and set the
183 /// result type to the corresponding pointer type.
184 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
185   if (checkArgCount(S, TheCall, 1))
186     return true;
187 
188   ExprResult Arg(TheCall->getArg(0));
189   QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
190   if (ResultType.isNull())
191     return true;
192 
193   TheCall->setArg(0, Arg.get());
194   TheCall->setType(ResultType);
195   return false;
196 }
197 
198 /// Check the number of arguments and set the result type to
199 /// the argument type.
200 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
201   if (checkArgCount(S, TheCall, 1))
202     return true;
203 
204   TheCall->setType(TheCall->getArg(0)->getType());
205   return false;
206 }
207 
208 /// Check that the value argument for __builtin_is_aligned(value, alignment) and
209 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
210 /// type (but not a function pointer) and that the alignment is a power-of-two.
211 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
212   if (checkArgCount(S, TheCall, 2))
213     return true;
214 
215   clang::Expr *Source = TheCall->getArg(0);
216   bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
217 
218   auto IsValidIntegerType = [](QualType Ty) {
219     return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
220   };
221   QualType SrcTy = Source->getType();
222   // We should also be able to use it with arrays (but not functions!).
223   if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
224     SrcTy = S.Context.getDecayedType(SrcTy);
225   }
226   if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
227       SrcTy->isFunctionPointerType()) {
228     // FIXME: this is not quite the right error message since we don't allow
229     // floating point types, or member pointers.
230     S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand)
231         << SrcTy;
232     return true;
233   }
234 
235   clang::Expr *AlignOp = TheCall->getArg(1);
236   if (!IsValidIntegerType(AlignOp->getType())) {
237     S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int)
238         << AlignOp->getType();
239     return true;
240   }
241   Expr::EvalResult AlignResult;
242   unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1;
243   // We can't check validity of alignment if it is value dependent.
244   if (!AlignOp->isValueDependent() &&
245       AlignOp->EvaluateAsInt(AlignResult, S.Context,
246                              Expr::SE_AllowSideEffects)) {
247     llvm::APSInt AlignValue = AlignResult.Val.getInt();
248     llvm::APSInt MaxValue(
249         llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits));
250     if (AlignValue < 1) {
251       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1;
252       return true;
253     }
254     if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) {
255       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big)
256           << MaxValue.toString(10);
257       return true;
258     }
259     if (!AlignValue.isPowerOf2()) {
260       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two);
261       return true;
262     }
263     if (AlignValue == 1) {
264       S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless)
265           << IsBooleanAlignBuiltin;
266     }
267   }
268 
269   ExprResult SrcArg = S.PerformCopyInitialization(
270       InitializedEntity::InitializeParameter(S.Context, SrcTy, false),
271       SourceLocation(), Source);
272   if (SrcArg.isInvalid())
273     return true;
274   TheCall->setArg(0, SrcArg.get());
275   ExprResult AlignArg =
276       S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
277                                       S.Context, AlignOp->getType(), false),
278                                   SourceLocation(), AlignOp);
279   if (AlignArg.isInvalid())
280     return true;
281   TheCall->setArg(1, AlignArg.get());
282   // For align_up/align_down, the return type is the same as the (potentially
283   // decayed) argument type including qualifiers. For is_aligned(), the result
284   // is always bool.
285   TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
286   return false;
287 }
288 
289 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall,
290                                 unsigned BuiltinID) {
291   if (checkArgCount(S, TheCall, 3))
292     return true;
293 
294   // First two arguments should be integers.
295   for (unsigned I = 0; I < 2; ++I) {
296     ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I));
297     if (Arg.isInvalid()) return true;
298     TheCall->setArg(I, Arg.get());
299 
300     QualType Ty = Arg.get()->getType();
301     if (!Ty->isIntegerType()) {
302       S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
303           << Ty << Arg.get()->getSourceRange();
304       return true;
305     }
306   }
307 
308   // Third argument should be a pointer to a non-const integer.
309   // IRGen correctly handles volatile, restrict, and address spaces, and
310   // the other qualifiers aren't possible.
311   {
312     ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(2));
313     if (Arg.isInvalid()) return true;
314     TheCall->setArg(2, Arg.get());
315 
316     QualType Ty = Arg.get()->getType();
317     const auto *PtrTy = Ty->getAs<PointerType>();
318     if (!PtrTy ||
319         !PtrTy->getPointeeType()->isIntegerType() ||
320         PtrTy->getPointeeType().isConstQualified()) {
321       S.Diag(Arg.get()->getBeginLoc(),
322              diag::err_overflow_builtin_must_be_ptr_int)
323         << Ty << Arg.get()->getSourceRange();
324       return true;
325     }
326   }
327 
328   // Disallow signed ExtIntType args larger than 128 bits to mul function until
329   // we improve backend support.
330   if (BuiltinID == Builtin::BI__builtin_mul_overflow) {
331     for (unsigned I = 0; I < 3; ++I) {
332       const auto Arg = TheCall->getArg(I);
333       // Third argument will be a pointer.
334       auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType();
335       if (Ty->isExtIntType() && Ty->isSignedIntegerType() &&
336           S.getASTContext().getIntWidth(Ty) > 128)
337         return S.Diag(Arg->getBeginLoc(),
338                       diag::err_overflow_builtin_ext_int_max_size)
339                << 128;
340     }
341   }
342 
343   return false;
344 }
345 
346 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
347   if (checkArgCount(S, BuiltinCall, 2))
348     return true;
349 
350   SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
351   Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
352   Expr *Call = BuiltinCall->getArg(0);
353   Expr *Chain = BuiltinCall->getArg(1);
354 
355   if (Call->getStmtClass() != Stmt::CallExprClass) {
356     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
357         << Call->getSourceRange();
358     return true;
359   }
360 
361   auto CE = cast<CallExpr>(Call);
362   if (CE->getCallee()->getType()->isBlockPointerType()) {
363     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
364         << Call->getSourceRange();
365     return true;
366   }
367 
368   const Decl *TargetDecl = CE->getCalleeDecl();
369   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
370     if (FD->getBuiltinID()) {
371       S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
372           << Call->getSourceRange();
373       return true;
374     }
375 
376   if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
377     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
378         << Call->getSourceRange();
379     return true;
380   }
381 
382   ExprResult ChainResult = S.UsualUnaryConversions(Chain);
383   if (ChainResult.isInvalid())
384     return true;
385   if (!ChainResult.get()->getType()->isPointerType()) {
386     S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
387         << Chain->getSourceRange();
388     return true;
389   }
390 
391   QualType ReturnTy = CE->getCallReturnType(S.Context);
392   QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
393   QualType BuiltinTy = S.Context.getFunctionType(
394       ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
395   QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
396 
397   Builtin =
398       S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
399 
400   BuiltinCall->setType(CE->getType());
401   BuiltinCall->setValueKind(CE->getValueKind());
402   BuiltinCall->setObjectKind(CE->getObjectKind());
403   BuiltinCall->setCallee(Builtin);
404   BuiltinCall->setArg(1, ChainResult.get());
405 
406   return false;
407 }
408 
409 namespace {
410 
411 class EstimateSizeFormatHandler
412     : public analyze_format_string::FormatStringHandler {
413   size_t Size;
414 
415 public:
416   EstimateSizeFormatHandler(StringRef Format)
417       : Size(std::min(Format.find(0), Format.size()) +
418              1 /* null byte always written by sprintf */) {}
419 
420   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
421                              const char *, unsigned SpecifierLen) override {
422 
423     const size_t FieldWidth = computeFieldWidth(FS);
424     const size_t Precision = computePrecision(FS);
425 
426     // The actual format.
427     switch (FS.getConversionSpecifier().getKind()) {
428     // Just a char.
429     case analyze_format_string::ConversionSpecifier::cArg:
430     case analyze_format_string::ConversionSpecifier::CArg:
431       Size += std::max(FieldWidth, (size_t)1);
432       break;
433     // Just an integer.
434     case analyze_format_string::ConversionSpecifier::dArg:
435     case analyze_format_string::ConversionSpecifier::DArg:
436     case analyze_format_string::ConversionSpecifier::iArg:
437     case analyze_format_string::ConversionSpecifier::oArg:
438     case analyze_format_string::ConversionSpecifier::OArg:
439     case analyze_format_string::ConversionSpecifier::uArg:
440     case analyze_format_string::ConversionSpecifier::UArg:
441     case analyze_format_string::ConversionSpecifier::xArg:
442     case analyze_format_string::ConversionSpecifier::XArg:
443       Size += std::max(FieldWidth, Precision);
444       break;
445 
446     // %g style conversion switches between %f or %e style dynamically.
447     // %f always takes less space, so default to it.
448     case analyze_format_string::ConversionSpecifier::gArg:
449     case analyze_format_string::ConversionSpecifier::GArg:
450 
451     // Floating point number in the form '[+]ddd.ddd'.
452     case analyze_format_string::ConversionSpecifier::fArg:
453     case analyze_format_string::ConversionSpecifier::FArg:
454       Size += std::max(FieldWidth, 1 /* integer part */ +
455                                        (Precision ? 1 + Precision
456                                                   : 0) /* period + decimal */);
457       break;
458 
459     // Floating point number in the form '[-]d.ddde[+-]dd'.
460     case analyze_format_string::ConversionSpecifier::eArg:
461     case analyze_format_string::ConversionSpecifier::EArg:
462       Size +=
463           std::max(FieldWidth,
464                    1 /* integer part */ +
465                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
466                        1 /* e or E letter */ + 2 /* exponent */);
467       break;
468 
469     // Floating point number in the form '[-]0xh.hhhhp±dd'.
470     case analyze_format_string::ConversionSpecifier::aArg:
471     case analyze_format_string::ConversionSpecifier::AArg:
472       Size +=
473           std::max(FieldWidth,
474                    2 /* 0x */ + 1 /* integer part */ +
475                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
476                        1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
477       break;
478 
479     // Just a string.
480     case analyze_format_string::ConversionSpecifier::sArg:
481     case analyze_format_string::ConversionSpecifier::SArg:
482       Size += FieldWidth;
483       break;
484 
485     // Just a pointer in the form '0xddd'.
486     case analyze_format_string::ConversionSpecifier::pArg:
487       Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
488       break;
489 
490     // A plain percent.
491     case analyze_format_string::ConversionSpecifier::PercentArg:
492       Size += 1;
493       break;
494 
495     default:
496       break;
497     }
498 
499     Size += FS.hasPlusPrefix() || FS.hasSpacePrefix();
500 
501     if (FS.hasAlternativeForm()) {
502       switch (FS.getConversionSpecifier().getKind()) {
503       default:
504         break;
505       // Force a leading '0'.
506       case analyze_format_string::ConversionSpecifier::oArg:
507         Size += 1;
508         break;
509       // Force a leading '0x'.
510       case analyze_format_string::ConversionSpecifier::xArg:
511       case analyze_format_string::ConversionSpecifier::XArg:
512         Size += 2;
513         break;
514       // Force a period '.' before decimal, even if precision is 0.
515       case analyze_format_string::ConversionSpecifier::aArg:
516       case analyze_format_string::ConversionSpecifier::AArg:
517       case analyze_format_string::ConversionSpecifier::eArg:
518       case analyze_format_string::ConversionSpecifier::EArg:
519       case analyze_format_string::ConversionSpecifier::fArg:
520       case analyze_format_string::ConversionSpecifier::FArg:
521       case analyze_format_string::ConversionSpecifier::gArg:
522       case analyze_format_string::ConversionSpecifier::GArg:
523         Size += (Precision ? 0 : 1);
524         break;
525       }
526     }
527     assert(SpecifierLen <= Size && "no underflow");
528     Size -= SpecifierLen;
529     return true;
530   }
531 
532   size_t getSizeLowerBound() const { return Size; }
533 
534 private:
535   static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
536     const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
537     size_t FieldWidth = 0;
538     if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant)
539       FieldWidth = FW.getConstantAmount();
540     return FieldWidth;
541   }
542 
543   static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
544     const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
545     size_t Precision = 0;
546 
547     // See man 3 printf for default precision value based on the specifier.
548     switch (FW.getHowSpecified()) {
549     case analyze_format_string::OptionalAmount::NotSpecified:
550       switch (FS.getConversionSpecifier().getKind()) {
551       default:
552         break;
553       case analyze_format_string::ConversionSpecifier::dArg: // %d
554       case analyze_format_string::ConversionSpecifier::DArg: // %D
555       case analyze_format_string::ConversionSpecifier::iArg: // %i
556         Precision = 1;
557         break;
558       case analyze_format_string::ConversionSpecifier::oArg: // %d
559       case analyze_format_string::ConversionSpecifier::OArg: // %D
560       case analyze_format_string::ConversionSpecifier::uArg: // %d
561       case analyze_format_string::ConversionSpecifier::UArg: // %D
562       case analyze_format_string::ConversionSpecifier::xArg: // %d
563       case analyze_format_string::ConversionSpecifier::XArg: // %D
564         Precision = 1;
565         break;
566       case analyze_format_string::ConversionSpecifier::fArg: // %f
567       case analyze_format_string::ConversionSpecifier::FArg: // %F
568       case analyze_format_string::ConversionSpecifier::eArg: // %e
569       case analyze_format_string::ConversionSpecifier::EArg: // %E
570       case analyze_format_string::ConversionSpecifier::gArg: // %g
571       case analyze_format_string::ConversionSpecifier::GArg: // %G
572         Precision = 6;
573         break;
574       case analyze_format_string::ConversionSpecifier::pArg: // %d
575         Precision = 1;
576         break;
577       }
578       break;
579     case analyze_format_string::OptionalAmount::Constant:
580       Precision = FW.getConstantAmount();
581       break;
582     default:
583       break;
584     }
585     return Precision;
586   }
587 };
588 
589 } // namespace
590 
591 /// Check a call to BuiltinID for buffer overflows. If BuiltinID is a
592 /// __builtin_*_chk function, then use the object size argument specified in the
593 /// source. Otherwise, infer the object size using __builtin_object_size.
594 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
595                                                CallExpr *TheCall) {
596   // FIXME: There are some more useful checks we could be doing here:
597   //  - Evaluate strlen of strcpy arguments, use as object size.
598 
599   if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
600       isConstantEvaluated())
601     return;
602 
603   unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true);
604   if (!BuiltinID)
605     return;
606 
607   const TargetInfo &TI = getASTContext().getTargetInfo();
608   unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
609 
610   unsigned DiagID = 0;
611   bool IsChkVariant = false;
612   Optional<llvm::APSInt> UsedSize;
613   unsigned SizeIndex, ObjectIndex;
614   switch (BuiltinID) {
615   default:
616     return;
617   case Builtin::BIsprintf:
618   case Builtin::BI__builtin___sprintf_chk: {
619     size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
620     auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
621 
622     if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) {
623 
624       if (!Format->isAscii() && !Format->isUTF8())
625         return;
626 
627       StringRef FormatStrRef = Format->getString();
628       EstimateSizeFormatHandler H(FormatStrRef);
629       const char *FormatBytes = FormatStrRef.data();
630       const ConstantArrayType *T =
631           Context.getAsConstantArrayType(Format->getType());
632       assert(T && "String literal not of constant array type!");
633       size_t TypeSize = T->getSize().getZExtValue();
634 
635       // In case there's a null byte somewhere.
636       size_t StrLen =
637           std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
638       if (!analyze_format_string::ParsePrintfString(
639               H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
640               Context.getTargetInfo(), false)) {
641         DiagID = diag::warn_fortify_source_format_overflow;
642         UsedSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
643                        .extOrTrunc(SizeTypeWidth);
644         if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
645           IsChkVariant = true;
646           ObjectIndex = 2;
647         } else {
648           IsChkVariant = false;
649           ObjectIndex = 0;
650         }
651         break;
652       }
653     }
654     return;
655   }
656   case Builtin::BI__builtin___memcpy_chk:
657   case Builtin::BI__builtin___memmove_chk:
658   case Builtin::BI__builtin___memset_chk:
659   case Builtin::BI__builtin___strlcat_chk:
660   case Builtin::BI__builtin___strlcpy_chk:
661   case Builtin::BI__builtin___strncat_chk:
662   case Builtin::BI__builtin___strncpy_chk:
663   case Builtin::BI__builtin___stpncpy_chk:
664   case Builtin::BI__builtin___memccpy_chk:
665   case Builtin::BI__builtin___mempcpy_chk: {
666     DiagID = diag::warn_builtin_chk_overflow;
667     IsChkVariant = true;
668     SizeIndex = TheCall->getNumArgs() - 2;
669     ObjectIndex = TheCall->getNumArgs() - 1;
670     break;
671   }
672 
673   case Builtin::BI__builtin___snprintf_chk:
674   case Builtin::BI__builtin___vsnprintf_chk: {
675     DiagID = diag::warn_builtin_chk_overflow;
676     IsChkVariant = true;
677     SizeIndex = 1;
678     ObjectIndex = 3;
679     break;
680   }
681 
682   case Builtin::BIstrncat:
683   case Builtin::BI__builtin_strncat:
684   case Builtin::BIstrncpy:
685   case Builtin::BI__builtin_strncpy:
686   case Builtin::BIstpncpy:
687   case Builtin::BI__builtin_stpncpy: {
688     // Whether these functions overflow depends on the runtime strlen of the
689     // string, not just the buffer size, so emitting the "always overflow"
690     // diagnostic isn't quite right. We should still diagnose passing a buffer
691     // size larger than the destination buffer though; this is a runtime abort
692     // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
693     DiagID = diag::warn_fortify_source_size_mismatch;
694     SizeIndex = TheCall->getNumArgs() - 1;
695     ObjectIndex = 0;
696     break;
697   }
698 
699   case Builtin::BImemcpy:
700   case Builtin::BI__builtin_memcpy:
701   case Builtin::BImemmove:
702   case Builtin::BI__builtin_memmove:
703   case Builtin::BImemset:
704   case Builtin::BI__builtin_memset:
705   case Builtin::BImempcpy:
706   case Builtin::BI__builtin_mempcpy: {
707     DiagID = diag::warn_fortify_source_overflow;
708     SizeIndex = TheCall->getNumArgs() - 1;
709     ObjectIndex = 0;
710     break;
711   }
712   case Builtin::BIsnprintf:
713   case Builtin::BI__builtin_snprintf:
714   case Builtin::BIvsnprintf:
715   case Builtin::BI__builtin_vsnprintf: {
716     DiagID = diag::warn_fortify_source_size_mismatch;
717     SizeIndex = 1;
718     ObjectIndex = 0;
719     break;
720   }
721   }
722 
723   llvm::APSInt ObjectSize;
724   // For __builtin___*_chk, the object size is explicitly provided by the caller
725   // (usually using __builtin_object_size). Use that value to check this call.
726   if (IsChkVariant) {
727     Expr::EvalResult Result;
728     Expr *SizeArg = TheCall->getArg(ObjectIndex);
729     if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
730       return;
731     ObjectSize = Result.Val.getInt();
732 
733   // Otherwise, try to evaluate an imaginary call to __builtin_object_size.
734   } else {
735     // If the parameter has a pass_object_size attribute, then we should use its
736     // (potentially) more strict checking mode. Otherwise, conservatively assume
737     // type 0.
738     int BOSType = 0;
739     if (const auto *POS =
740             FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>())
741       BOSType = POS->getType();
742 
743     Expr *ObjArg = TheCall->getArg(ObjectIndex);
744     uint64_t Result;
745     if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
746       return;
747     // Get the object size in the target's size_t width.
748     ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
749   }
750 
751   // Evaluate the number of bytes of the object that this call will use.
752   if (!UsedSize) {
753     Expr::EvalResult Result;
754     Expr *UsedSizeArg = TheCall->getArg(SizeIndex);
755     if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext()))
756       return;
757     UsedSize = Result.Val.getInt().extOrTrunc(SizeTypeWidth);
758   }
759 
760   if (UsedSize.getValue().ule(ObjectSize))
761     return;
762 
763   StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
764   // Skim off the details of whichever builtin was called to produce a better
765   // diagnostic, as it's unlikley that the user wrote the __builtin explicitly.
766   if (IsChkVariant) {
767     FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
768     FunctionName = FunctionName.drop_back(std::strlen("_chk"));
769   } else if (FunctionName.startswith("__builtin_")) {
770     FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
771   }
772 
773   DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
774                       PDiag(DiagID)
775                           << FunctionName << ObjectSize.toString(/*Radix=*/10)
776                           << UsedSize.getValue().toString(/*Radix=*/10));
777 }
778 
779 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
780                                      Scope::ScopeFlags NeededScopeFlags,
781                                      unsigned DiagID) {
782   // Scopes aren't available during instantiation. Fortunately, builtin
783   // functions cannot be template args so they cannot be formed through template
784   // instantiation. Therefore checking once during the parse is sufficient.
785   if (SemaRef.inTemplateInstantiation())
786     return false;
787 
788   Scope *S = SemaRef.getCurScope();
789   while (S && !S->isSEHExceptScope())
790     S = S->getParent();
791   if (!S || !(S->getFlags() & NeededScopeFlags)) {
792     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
793     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
794         << DRE->getDecl()->getIdentifier();
795     return true;
796   }
797 
798   return false;
799 }
800 
801 static inline bool isBlockPointer(Expr *Arg) {
802   return Arg->getType()->isBlockPointerType();
803 }
804 
805 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
806 /// void*, which is a requirement of device side enqueue.
807 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
808   const BlockPointerType *BPT =
809       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
810   ArrayRef<QualType> Params =
811       BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes();
812   unsigned ArgCounter = 0;
813   bool IllegalParams = false;
814   // Iterate through the block parameters until either one is found that is not
815   // a local void*, or the block is valid.
816   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
817        I != E; ++I, ++ArgCounter) {
818     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
819         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
820             LangAS::opencl_local) {
821       // Get the location of the error. If a block literal has been passed
822       // (BlockExpr) then we can point straight to the offending argument,
823       // else we just point to the variable reference.
824       SourceLocation ErrorLoc;
825       if (isa<BlockExpr>(BlockArg)) {
826         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
827         ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
828       } else if (isa<DeclRefExpr>(BlockArg)) {
829         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
830       }
831       S.Diag(ErrorLoc,
832              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
833       IllegalParams = true;
834     }
835   }
836 
837   return IllegalParams;
838 }
839 
840 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
841   if (!S.getOpenCLOptions().isSupported("cl_khr_subgroups", S.getLangOpts())) {
842     S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
843         << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
844     return true;
845   }
846   return false;
847 }
848 
849 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
850   if (checkArgCount(S, TheCall, 2))
851     return true;
852 
853   if (checkOpenCLSubgroupExt(S, TheCall))
854     return true;
855 
856   // First argument is an ndrange_t type.
857   Expr *NDRangeArg = TheCall->getArg(0);
858   if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
859     S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
860         << TheCall->getDirectCallee() << "'ndrange_t'";
861     return true;
862   }
863 
864   Expr *BlockArg = TheCall->getArg(1);
865   if (!isBlockPointer(BlockArg)) {
866     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
867         << TheCall->getDirectCallee() << "block";
868     return true;
869   }
870   return checkOpenCLBlockArgs(S, BlockArg);
871 }
872 
873 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
874 /// get_kernel_work_group_size
875 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
876 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
877   if (checkArgCount(S, TheCall, 1))
878     return true;
879 
880   Expr *BlockArg = TheCall->getArg(0);
881   if (!isBlockPointer(BlockArg)) {
882     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
883         << TheCall->getDirectCallee() << "block";
884     return true;
885   }
886   return checkOpenCLBlockArgs(S, BlockArg);
887 }
888 
889 /// Diagnose integer type and any valid implicit conversion to it.
890 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
891                                       const QualType &IntType);
892 
893 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
894                                             unsigned Start, unsigned End) {
895   bool IllegalParams = false;
896   for (unsigned I = Start; I <= End; ++I)
897     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
898                                               S.Context.getSizeType());
899   return IllegalParams;
900 }
901 
902 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
903 /// 'local void*' parameter of passed block.
904 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
905                                            Expr *BlockArg,
906                                            unsigned NumNonVarArgs) {
907   const BlockPointerType *BPT =
908       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
909   unsigned NumBlockParams =
910       BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams();
911   unsigned TotalNumArgs = TheCall->getNumArgs();
912 
913   // For each argument passed to the block, a corresponding uint needs to
914   // be passed to describe the size of the local memory.
915   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
916     S.Diag(TheCall->getBeginLoc(),
917            diag::err_opencl_enqueue_kernel_local_size_args);
918     return true;
919   }
920 
921   // Check that the sizes of the local memory are specified by integers.
922   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
923                                          TotalNumArgs - 1);
924 }
925 
926 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
927 /// overload formats specified in Table 6.13.17.1.
928 /// int enqueue_kernel(queue_t queue,
929 ///                    kernel_enqueue_flags_t flags,
930 ///                    const ndrange_t ndrange,
931 ///                    void (^block)(void))
932 /// int enqueue_kernel(queue_t queue,
933 ///                    kernel_enqueue_flags_t flags,
934 ///                    const ndrange_t ndrange,
935 ///                    uint num_events_in_wait_list,
936 ///                    clk_event_t *event_wait_list,
937 ///                    clk_event_t *event_ret,
938 ///                    void (^block)(void))
939 /// int enqueue_kernel(queue_t queue,
940 ///                    kernel_enqueue_flags_t flags,
941 ///                    const ndrange_t ndrange,
942 ///                    void (^block)(local void*, ...),
943 ///                    uint size0, ...)
944 /// int enqueue_kernel(queue_t queue,
945 ///                    kernel_enqueue_flags_t flags,
946 ///                    const ndrange_t ndrange,
947 ///                    uint num_events_in_wait_list,
948 ///                    clk_event_t *event_wait_list,
949 ///                    clk_event_t *event_ret,
950 ///                    void (^block)(local void*, ...),
951 ///                    uint size0, ...)
952 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
953   unsigned NumArgs = TheCall->getNumArgs();
954 
955   if (NumArgs < 4) {
956     S.Diag(TheCall->getBeginLoc(),
957            diag::err_typecheck_call_too_few_args_at_least)
958         << 0 << 4 << NumArgs;
959     return true;
960   }
961 
962   Expr *Arg0 = TheCall->getArg(0);
963   Expr *Arg1 = TheCall->getArg(1);
964   Expr *Arg2 = TheCall->getArg(2);
965   Expr *Arg3 = TheCall->getArg(3);
966 
967   // First argument always needs to be a queue_t type.
968   if (!Arg0->getType()->isQueueT()) {
969     S.Diag(TheCall->getArg(0)->getBeginLoc(),
970            diag::err_opencl_builtin_expected_type)
971         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
972     return true;
973   }
974 
975   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
976   if (!Arg1->getType()->isIntegerType()) {
977     S.Diag(TheCall->getArg(1)->getBeginLoc(),
978            diag::err_opencl_builtin_expected_type)
979         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
980     return true;
981   }
982 
983   // Third argument is always an ndrange_t type.
984   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
985     S.Diag(TheCall->getArg(2)->getBeginLoc(),
986            diag::err_opencl_builtin_expected_type)
987         << TheCall->getDirectCallee() << "'ndrange_t'";
988     return true;
989   }
990 
991   // With four arguments, there is only one form that the function could be
992   // called in: no events and no variable arguments.
993   if (NumArgs == 4) {
994     // check that the last argument is the right block type.
995     if (!isBlockPointer(Arg3)) {
996       S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
997           << TheCall->getDirectCallee() << "block";
998       return true;
999     }
1000     // we have a block type, check the prototype
1001     const BlockPointerType *BPT =
1002         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
1003     if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) {
1004       S.Diag(Arg3->getBeginLoc(),
1005              diag::err_opencl_enqueue_kernel_blocks_no_args);
1006       return true;
1007     }
1008     return false;
1009   }
1010   // we can have block + varargs.
1011   if (isBlockPointer(Arg3))
1012     return (checkOpenCLBlockArgs(S, Arg3) ||
1013             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
1014   // last two cases with either exactly 7 args or 7 args and varargs.
1015   if (NumArgs >= 7) {
1016     // check common block argument.
1017     Expr *Arg6 = TheCall->getArg(6);
1018     if (!isBlockPointer(Arg6)) {
1019       S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1020           << TheCall->getDirectCallee() << "block";
1021       return true;
1022     }
1023     if (checkOpenCLBlockArgs(S, Arg6))
1024       return true;
1025 
1026     // Forth argument has to be any integer type.
1027     if (!Arg3->getType()->isIntegerType()) {
1028       S.Diag(TheCall->getArg(3)->getBeginLoc(),
1029              diag::err_opencl_builtin_expected_type)
1030           << TheCall->getDirectCallee() << "integer";
1031       return true;
1032     }
1033     // check remaining common arguments.
1034     Expr *Arg4 = TheCall->getArg(4);
1035     Expr *Arg5 = TheCall->getArg(5);
1036 
1037     // Fifth argument is always passed as a pointer to clk_event_t.
1038     if (!Arg4->isNullPointerConstant(S.Context,
1039                                      Expr::NPC_ValueDependentIsNotNull) &&
1040         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
1041       S.Diag(TheCall->getArg(4)->getBeginLoc(),
1042              diag::err_opencl_builtin_expected_type)
1043           << TheCall->getDirectCallee()
1044           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1045       return true;
1046     }
1047 
1048     // Sixth argument is always passed as a pointer to clk_event_t.
1049     if (!Arg5->isNullPointerConstant(S.Context,
1050                                      Expr::NPC_ValueDependentIsNotNull) &&
1051         !(Arg5->getType()->isPointerType() &&
1052           Arg5->getType()->getPointeeType()->isClkEventT())) {
1053       S.Diag(TheCall->getArg(5)->getBeginLoc(),
1054              diag::err_opencl_builtin_expected_type)
1055           << TheCall->getDirectCallee()
1056           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1057       return true;
1058     }
1059 
1060     if (NumArgs == 7)
1061       return false;
1062 
1063     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
1064   }
1065 
1066   // None of the specific case has been detected, give generic error
1067   S.Diag(TheCall->getBeginLoc(),
1068          diag::err_opencl_enqueue_kernel_incorrect_args);
1069   return true;
1070 }
1071 
1072 /// Returns OpenCL access qual.
1073 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
1074     return D->getAttr<OpenCLAccessAttr>();
1075 }
1076 
1077 /// Returns true if pipe element type is different from the pointer.
1078 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
1079   const Expr *Arg0 = Call->getArg(0);
1080   // First argument type should always be pipe.
1081   if (!Arg0->getType()->isPipeType()) {
1082     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1083         << Call->getDirectCallee() << Arg0->getSourceRange();
1084     return true;
1085   }
1086   OpenCLAccessAttr *AccessQual =
1087       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
1088   // Validates the access qualifier is compatible with the call.
1089   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
1090   // read_only and write_only, and assumed to be read_only if no qualifier is
1091   // specified.
1092   switch (Call->getDirectCallee()->getBuiltinID()) {
1093   case Builtin::BIread_pipe:
1094   case Builtin::BIreserve_read_pipe:
1095   case Builtin::BIcommit_read_pipe:
1096   case Builtin::BIwork_group_reserve_read_pipe:
1097   case Builtin::BIsub_group_reserve_read_pipe:
1098   case Builtin::BIwork_group_commit_read_pipe:
1099   case Builtin::BIsub_group_commit_read_pipe:
1100     if (!(!AccessQual || AccessQual->isReadOnly())) {
1101       S.Diag(Arg0->getBeginLoc(),
1102              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1103           << "read_only" << Arg0->getSourceRange();
1104       return true;
1105     }
1106     break;
1107   case Builtin::BIwrite_pipe:
1108   case Builtin::BIreserve_write_pipe:
1109   case Builtin::BIcommit_write_pipe:
1110   case Builtin::BIwork_group_reserve_write_pipe:
1111   case Builtin::BIsub_group_reserve_write_pipe:
1112   case Builtin::BIwork_group_commit_write_pipe:
1113   case Builtin::BIsub_group_commit_write_pipe:
1114     if (!(AccessQual && AccessQual->isWriteOnly())) {
1115       S.Diag(Arg0->getBeginLoc(),
1116              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1117           << "write_only" << Arg0->getSourceRange();
1118       return true;
1119     }
1120     break;
1121   default:
1122     break;
1123   }
1124   return false;
1125 }
1126 
1127 /// Returns true if pipe element type is different from the pointer.
1128 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
1129   const Expr *Arg0 = Call->getArg(0);
1130   const Expr *ArgIdx = Call->getArg(Idx);
1131   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
1132   const QualType EltTy = PipeTy->getElementType();
1133   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
1134   // The Idx argument should be a pointer and the type of the pointer and
1135   // the type of pipe element should also be the same.
1136   if (!ArgTy ||
1137       !S.Context.hasSameType(
1138           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
1139     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1140         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
1141         << ArgIdx->getType() << ArgIdx->getSourceRange();
1142     return true;
1143   }
1144   return false;
1145 }
1146 
1147 // Performs semantic analysis for the read/write_pipe call.
1148 // \param S Reference to the semantic analyzer.
1149 // \param Call A pointer to the builtin call.
1150 // \return True if a semantic error has been found, false otherwise.
1151 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
1152   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
1153   // functions have two forms.
1154   switch (Call->getNumArgs()) {
1155   case 2:
1156     if (checkOpenCLPipeArg(S, Call))
1157       return true;
1158     // The call with 2 arguments should be
1159     // read/write_pipe(pipe T, T*).
1160     // Check packet type T.
1161     if (checkOpenCLPipePacketType(S, Call, 1))
1162       return true;
1163     break;
1164 
1165   case 4: {
1166     if (checkOpenCLPipeArg(S, Call))
1167       return true;
1168     // The call with 4 arguments should be
1169     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
1170     // Check reserve_id_t.
1171     if (!Call->getArg(1)->getType()->isReserveIDT()) {
1172       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1173           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1174           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1175       return true;
1176     }
1177 
1178     // Check the index.
1179     const Expr *Arg2 = Call->getArg(2);
1180     if (!Arg2->getType()->isIntegerType() &&
1181         !Arg2->getType()->isUnsignedIntegerType()) {
1182       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1183           << Call->getDirectCallee() << S.Context.UnsignedIntTy
1184           << Arg2->getType() << Arg2->getSourceRange();
1185       return true;
1186     }
1187 
1188     // Check packet type T.
1189     if (checkOpenCLPipePacketType(S, Call, 3))
1190       return true;
1191   } break;
1192   default:
1193     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
1194         << Call->getDirectCallee() << Call->getSourceRange();
1195     return true;
1196   }
1197 
1198   return false;
1199 }
1200 
1201 // Performs a semantic analysis on the {work_group_/sub_group_
1202 //        /_}reserve_{read/write}_pipe
1203 // \param S Reference to the semantic analyzer.
1204 // \param Call The call to the builtin function to be analyzed.
1205 // \return True if a semantic error was found, false otherwise.
1206 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
1207   if (checkArgCount(S, Call, 2))
1208     return true;
1209 
1210   if (checkOpenCLPipeArg(S, Call))
1211     return true;
1212 
1213   // Check the reserve size.
1214   if (!Call->getArg(1)->getType()->isIntegerType() &&
1215       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
1216     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1217         << Call->getDirectCallee() << S.Context.UnsignedIntTy
1218         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1219     return true;
1220   }
1221 
1222   // Since return type of reserve_read/write_pipe built-in function is
1223   // reserve_id_t, which is not defined in the builtin def file , we used int
1224   // as return type and need to override the return type of these functions.
1225   Call->setType(S.Context.OCLReserveIDTy);
1226 
1227   return false;
1228 }
1229 
1230 // Performs a semantic analysis on {work_group_/sub_group_
1231 //        /_}commit_{read/write}_pipe
1232 // \param S Reference to the semantic analyzer.
1233 // \param Call The call to the builtin function to be analyzed.
1234 // \return True if a semantic error was found, false otherwise.
1235 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
1236   if (checkArgCount(S, Call, 2))
1237     return true;
1238 
1239   if (checkOpenCLPipeArg(S, Call))
1240     return true;
1241 
1242   // Check reserve_id_t.
1243   if (!Call->getArg(1)->getType()->isReserveIDT()) {
1244     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1245         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1246         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1247     return true;
1248   }
1249 
1250   return false;
1251 }
1252 
1253 // Performs a semantic analysis on the call to built-in Pipe
1254 //        Query Functions.
1255 // \param S Reference to the semantic analyzer.
1256 // \param Call The call to the builtin function to be analyzed.
1257 // \return True if a semantic error was found, false otherwise.
1258 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
1259   if (checkArgCount(S, Call, 1))
1260     return true;
1261 
1262   if (!Call->getArg(0)->getType()->isPipeType()) {
1263     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1264         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
1265     return true;
1266   }
1267 
1268   return false;
1269 }
1270 
1271 // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
1272 // Performs semantic analysis for the to_global/local/private call.
1273 // \param S Reference to the semantic analyzer.
1274 // \param BuiltinID ID of the builtin function.
1275 // \param Call A pointer to the builtin call.
1276 // \return True if a semantic error has been found, false otherwise.
1277 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
1278                                     CallExpr *Call) {
1279   if (checkArgCount(S, Call, 1))
1280     return true;
1281 
1282   auto RT = Call->getArg(0)->getType();
1283   if (!RT->isPointerType() || RT->getPointeeType()
1284       .getAddressSpace() == LangAS::opencl_constant) {
1285     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
1286         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
1287     return true;
1288   }
1289 
1290   if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
1291     S.Diag(Call->getArg(0)->getBeginLoc(),
1292            diag::warn_opencl_generic_address_space_arg)
1293         << Call->getDirectCallee()->getNameInfo().getAsString()
1294         << Call->getArg(0)->getSourceRange();
1295   }
1296 
1297   RT = RT->getPointeeType();
1298   auto Qual = RT.getQualifiers();
1299   switch (BuiltinID) {
1300   case Builtin::BIto_global:
1301     Qual.setAddressSpace(LangAS::opencl_global);
1302     break;
1303   case Builtin::BIto_local:
1304     Qual.setAddressSpace(LangAS::opencl_local);
1305     break;
1306   case Builtin::BIto_private:
1307     Qual.setAddressSpace(LangAS::opencl_private);
1308     break;
1309   default:
1310     llvm_unreachable("Invalid builtin function");
1311   }
1312   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
1313       RT.getUnqualifiedType(), Qual)));
1314 
1315   return false;
1316 }
1317 
1318 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
1319   if (checkArgCount(S, TheCall, 1))
1320     return ExprError();
1321 
1322   // Compute __builtin_launder's parameter type from the argument.
1323   // The parameter type is:
1324   //  * The type of the argument if it's not an array or function type,
1325   //  Otherwise,
1326   //  * The decayed argument type.
1327   QualType ParamTy = [&]() {
1328     QualType ArgTy = TheCall->getArg(0)->getType();
1329     if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1330       return S.Context.getPointerType(Ty->getElementType());
1331     if (ArgTy->isFunctionType()) {
1332       return S.Context.getPointerType(ArgTy);
1333     }
1334     return ArgTy;
1335   }();
1336 
1337   TheCall->setType(ParamTy);
1338 
1339   auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
1340     if (!ParamTy->isPointerType())
1341       return 0;
1342     if (ParamTy->isFunctionPointerType())
1343       return 1;
1344     if (ParamTy->isVoidPointerType())
1345       return 2;
1346     return llvm::Optional<unsigned>{};
1347   }();
1348   if (DiagSelect.hasValue()) {
1349     S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1350         << DiagSelect.getValue() << TheCall->getSourceRange();
1351     return ExprError();
1352   }
1353 
1354   // We either have an incomplete class type, or we have a class template
1355   // whose instantiation has not been forced. Example:
1356   //
1357   //   template <class T> struct Foo { T value; };
1358   //   Foo<int> *p = nullptr;
1359   //   auto *d = __builtin_launder(p);
1360   if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1361                             diag::err_incomplete_type))
1362     return ExprError();
1363 
1364   assert(ParamTy->getPointeeType()->isObjectType() &&
1365          "Unhandled non-object pointer case");
1366 
1367   InitializedEntity Entity =
1368       InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
1369   ExprResult Arg =
1370       S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1371   if (Arg.isInvalid())
1372     return ExprError();
1373   TheCall->setArg(0, Arg.get());
1374 
1375   return TheCall;
1376 }
1377 
1378 // Emit an error and return true if the current architecture is not in the list
1379 // of supported architectures.
1380 static bool
1381 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1382                           ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
1383   llvm::Triple::ArchType CurArch =
1384       S.getASTContext().getTargetInfo().getTriple().getArch();
1385   if (llvm::is_contained(SupportedArchs, CurArch))
1386     return false;
1387   S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1388       << TheCall->getSourceRange();
1389   return true;
1390 }
1391 
1392 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
1393                                  SourceLocation CallSiteLoc);
1394 
1395 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
1396                                       CallExpr *TheCall) {
1397   switch (TI.getTriple().getArch()) {
1398   default:
1399     // Some builtins don't require additional checking, so just consider these
1400     // acceptable.
1401     return false;
1402   case llvm::Triple::arm:
1403   case llvm::Triple::armeb:
1404   case llvm::Triple::thumb:
1405   case llvm::Triple::thumbeb:
1406     return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
1407   case llvm::Triple::aarch64:
1408   case llvm::Triple::aarch64_32:
1409   case llvm::Triple::aarch64_be:
1410     return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
1411   case llvm::Triple::bpfeb:
1412   case llvm::Triple::bpfel:
1413     return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
1414   case llvm::Triple::hexagon:
1415     return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
1416   case llvm::Triple::mips:
1417   case llvm::Triple::mipsel:
1418   case llvm::Triple::mips64:
1419   case llvm::Triple::mips64el:
1420     return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
1421   case llvm::Triple::systemz:
1422     return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
1423   case llvm::Triple::x86:
1424   case llvm::Triple::x86_64:
1425     return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall);
1426   case llvm::Triple::ppc:
1427   case llvm::Triple::ppcle:
1428   case llvm::Triple::ppc64:
1429   case llvm::Triple::ppc64le:
1430     return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
1431   case llvm::Triple::amdgcn:
1432     return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
1433   case llvm::Triple::riscv32:
1434   case llvm::Triple::riscv64:
1435     return CheckRISCVBuiltinFunctionCall(TI, BuiltinID, TheCall);
1436   }
1437 }
1438 
1439 ExprResult
1440 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
1441                                CallExpr *TheCall) {
1442   ExprResult TheCallResult(TheCall);
1443 
1444   // Find out if any arguments are required to be integer constant expressions.
1445   unsigned ICEArguments = 0;
1446   ASTContext::GetBuiltinTypeError Error;
1447   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
1448   if (Error != ASTContext::GE_None)
1449     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
1450 
1451   // If any arguments are required to be ICE's, check and diagnose.
1452   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
1453     // Skip arguments not required to be ICE's.
1454     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
1455 
1456     llvm::APSInt Result;
1457     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
1458       return true;
1459     ICEArguments &= ~(1 << ArgNo);
1460   }
1461 
1462   switch (BuiltinID) {
1463   case Builtin::BI__builtin___CFStringMakeConstantString:
1464     assert(TheCall->getNumArgs() == 1 &&
1465            "Wrong # arguments to builtin CFStringMakeConstantString");
1466     if (CheckObjCString(TheCall->getArg(0)))
1467       return ExprError();
1468     break;
1469   case Builtin::BI__builtin_ms_va_start:
1470   case Builtin::BI__builtin_stdarg_start:
1471   case Builtin::BI__builtin_va_start:
1472     if (SemaBuiltinVAStart(BuiltinID, TheCall))
1473       return ExprError();
1474     break;
1475   case Builtin::BI__va_start: {
1476     switch (Context.getTargetInfo().getTriple().getArch()) {
1477     case llvm::Triple::aarch64:
1478     case llvm::Triple::arm:
1479     case llvm::Triple::thumb:
1480       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
1481         return ExprError();
1482       break;
1483     default:
1484       if (SemaBuiltinVAStart(BuiltinID, TheCall))
1485         return ExprError();
1486       break;
1487     }
1488     break;
1489   }
1490 
1491   // The acquire, release, and no fence variants are ARM and AArch64 only.
1492   case Builtin::BI_interlockedbittestandset_acq:
1493   case Builtin::BI_interlockedbittestandset_rel:
1494   case Builtin::BI_interlockedbittestandset_nf:
1495   case Builtin::BI_interlockedbittestandreset_acq:
1496   case Builtin::BI_interlockedbittestandreset_rel:
1497   case Builtin::BI_interlockedbittestandreset_nf:
1498     if (CheckBuiltinTargetSupport(
1499             *this, BuiltinID, TheCall,
1500             {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
1501       return ExprError();
1502     break;
1503 
1504   // The 64-bit bittest variants are x64, ARM, and AArch64 only.
1505   case Builtin::BI_bittest64:
1506   case Builtin::BI_bittestandcomplement64:
1507   case Builtin::BI_bittestandreset64:
1508   case Builtin::BI_bittestandset64:
1509   case Builtin::BI_interlockedbittestandreset64:
1510   case Builtin::BI_interlockedbittestandset64:
1511     if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
1512                                   {llvm::Triple::x86_64, llvm::Triple::arm,
1513                                    llvm::Triple::thumb, llvm::Triple::aarch64}))
1514       return ExprError();
1515     break;
1516 
1517   case Builtin::BI__builtin_isgreater:
1518   case Builtin::BI__builtin_isgreaterequal:
1519   case Builtin::BI__builtin_isless:
1520   case Builtin::BI__builtin_islessequal:
1521   case Builtin::BI__builtin_islessgreater:
1522   case Builtin::BI__builtin_isunordered:
1523     if (SemaBuiltinUnorderedCompare(TheCall))
1524       return ExprError();
1525     break;
1526   case Builtin::BI__builtin_fpclassify:
1527     if (SemaBuiltinFPClassification(TheCall, 6))
1528       return ExprError();
1529     break;
1530   case Builtin::BI__builtin_isfinite:
1531   case Builtin::BI__builtin_isinf:
1532   case Builtin::BI__builtin_isinf_sign:
1533   case Builtin::BI__builtin_isnan:
1534   case Builtin::BI__builtin_isnormal:
1535   case Builtin::BI__builtin_signbit:
1536   case Builtin::BI__builtin_signbitf:
1537   case Builtin::BI__builtin_signbitl:
1538     if (SemaBuiltinFPClassification(TheCall, 1))
1539       return ExprError();
1540     break;
1541   case Builtin::BI__builtin_shufflevector:
1542     return SemaBuiltinShuffleVector(TheCall);
1543     // TheCall will be freed by the smart pointer here, but that's fine, since
1544     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1545   case Builtin::BI__builtin_prefetch:
1546     if (SemaBuiltinPrefetch(TheCall))
1547       return ExprError();
1548     break;
1549   case Builtin::BI__builtin_alloca_with_align:
1550     if (SemaBuiltinAllocaWithAlign(TheCall))
1551       return ExprError();
1552     LLVM_FALLTHROUGH;
1553   case Builtin::BI__builtin_alloca:
1554     Diag(TheCall->getBeginLoc(), diag::warn_alloca)
1555         << TheCall->getDirectCallee();
1556     break;
1557   case Builtin::BI__assume:
1558   case Builtin::BI__builtin_assume:
1559     if (SemaBuiltinAssume(TheCall))
1560       return ExprError();
1561     break;
1562   case Builtin::BI__builtin_assume_aligned:
1563     if (SemaBuiltinAssumeAligned(TheCall))
1564       return ExprError();
1565     break;
1566   case Builtin::BI__builtin_dynamic_object_size:
1567   case Builtin::BI__builtin_object_size:
1568     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1569       return ExprError();
1570     break;
1571   case Builtin::BI__builtin_longjmp:
1572     if (SemaBuiltinLongjmp(TheCall))
1573       return ExprError();
1574     break;
1575   case Builtin::BI__builtin_setjmp:
1576     if (SemaBuiltinSetjmp(TheCall))
1577       return ExprError();
1578     break;
1579   case Builtin::BI__builtin_classify_type:
1580     if (checkArgCount(*this, TheCall, 1)) return true;
1581     TheCall->setType(Context.IntTy);
1582     break;
1583   case Builtin::BI__builtin_complex:
1584     if (SemaBuiltinComplex(TheCall))
1585       return ExprError();
1586     break;
1587   case Builtin::BI__builtin_constant_p: {
1588     if (checkArgCount(*this, TheCall, 1)) return true;
1589     ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
1590     if (Arg.isInvalid()) return true;
1591     TheCall->setArg(0, Arg.get());
1592     TheCall->setType(Context.IntTy);
1593     break;
1594   }
1595   case Builtin::BI__builtin_launder:
1596     return SemaBuiltinLaunder(*this, TheCall);
1597   case Builtin::BI__sync_fetch_and_add:
1598   case Builtin::BI__sync_fetch_and_add_1:
1599   case Builtin::BI__sync_fetch_and_add_2:
1600   case Builtin::BI__sync_fetch_and_add_4:
1601   case Builtin::BI__sync_fetch_and_add_8:
1602   case Builtin::BI__sync_fetch_and_add_16:
1603   case Builtin::BI__sync_fetch_and_sub:
1604   case Builtin::BI__sync_fetch_and_sub_1:
1605   case Builtin::BI__sync_fetch_and_sub_2:
1606   case Builtin::BI__sync_fetch_and_sub_4:
1607   case Builtin::BI__sync_fetch_and_sub_8:
1608   case Builtin::BI__sync_fetch_and_sub_16:
1609   case Builtin::BI__sync_fetch_and_or:
1610   case Builtin::BI__sync_fetch_and_or_1:
1611   case Builtin::BI__sync_fetch_and_or_2:
1612   case Builtin::BI__sync_fetch_and_or_4:
1613   case Builtin::BI__sync_fetch_and_or_8:
1614   case Builtin::BI__sync_fetch_and_or_16:
1615   case Builtin::BI__sync_fetch_and_and:
1616   case Builtin::BI__sync_fetch_and_and_1:
1617   case Builtin::BI__sync_fetch_and_and_2:
1618   case Builtin::BI__sync_fetch_and_and_4:
1619   case Builtin::BI__sync_fetch_and_and_8:
1620   case Builtin::BI__sync_fetch_and_and_16:
1621   case Builtin::BI__sync_fetch_and_xor:
1622   case Builtin::BI__sync_fetch_and_xor_1:
1623   case Builtin::BI__sync_fetch_and_xor_2:
1624   case Builtin::BI__sync_fetch_and_xor_4:
1625   case Builtin::BI__sync_fetch_and_xor_8:
1626   case Builtin::BI__sync_fetch_and_xor_16:
1627   case Builtin::BI__sync_fetch_and_nand:
1628   case Builtin::BI__sync_fetch_and_nand_1:
1629   case Builtin::BI__sync_fetch_and_nand_2:
1630   case Builtin::BI__sync_fetch_and_nand_4:
1631   case Builtin::BI__sync_fetch_and_nand_8:
1632   case Builtin::BI__sync_fetch_and_nand_16:
1633   case Builtin::BI__sync_add_and_fetch:
1634   case Builtin::BI__sync_add_and_fetch_1:
1635   case Builtin::BI__sync_add_and_fetch_2:
1636   case Builtin::BI__sync_add_and_fetch_4:
1637   case Builtin::BI__sync_add_and_fetch_8:
1638   case Builtin::BI__sync_add_and_fetch_16:
1639   case Builtin::BI__sync_sub_and_fetch:
1640   case Builtin::BI__sync_sub_and_fetch_1:
1641   case Builtin::BI__sync_sub_and_fetch_2:
1642   case Builtin::BI__sync_sub_and_fetch_4:
1643   case Builtin::BI__sync_sub_and_fetch_8:
1644   case Builtin::BI__sync_sub_and_fetch_16:
1645   case Builtin::BI__sync_and_and_fetch:
1646   case Builtin::BI__sync_and_and_fetch_1:
1647   case Builtin::BI__sync_and_and_fetch_2:
1648   case Builtin::BI__sync_and_and_fetch_4:
1649   case Builtin::BI__sync_and_and_fetch_8:
1650   case Builtin::BI__sync_and_and_fetch_16:
1651   case Builtin::BI__sync_or_and_fetch:
1652   case Builtin::BI__sync_or_and_fetch_1:
1653   case Builtin::BI__sync_or_and_fetch_2:
1654   case Builtin::BI__sync_or_and_fetch_4:
1655   case Builtin::BI__sync_or_and_fetch_8:
1656   case Builtin::BI__sync_or_and_fetch_16:
1657   case Builtin::BI__sync_xor_and_fetch:
1658   case Builtin::BI__sync_xor_and_fetch_1:
1659   case Builtin::BI__sync_xor_and_fetch_2:
1660   case Builtin::BI__sync_xor_and_fetch_4:
1661   case Builtin::BI__sync_xor_and_fetch_8:
1662   case Builtin::BI__sync_xor_and_fetch_16:
1663   case Builtin::BI__sync_nand_and_fetch:
1664   case Builtin::BI__sync_nand_and_fetch_1:
1665   case Builtin::BI__sync_nand_and_fetch_2:
1666   case Builtin::BI__sync_nand_and_fetch_4:
1667   case Builtin::BI__sync_nand_and_fetch_8:
1668   case Builtin::BI__sync_nand_and_fetch_16:
1669   case Builtin::BI__sync_val_compare_and_swap:
1670   case Builtin::BI__sync_val_compare_and_swap_1:
1671   case Builtin::BI__sync_val_compare_and_swap_2:
1672   case Builtin::BI__sync_val_compare_and_swap_4:
1673   case Builtin::BI__sync_val_compare_and_swap_8:
1674   case Builtin::BI__sync_val_compare_and_swap_16:
1675   case Builtin::BI__sync_bool_compare_and_swap:
1676   case Builtin::BI__sync_bool_compare_and_swap_1:
1677   case Builtin::BI__sync_bool_compare_and_swap_2:
1678   case Builtin::BI__sync_bool_compare_and_swap_4:
1679   case Builtin::BI__sync_bool_compare_and_swap_8:
1680   case Builtin::BI__sync_bool_compare_and_swap_16:
1681   case Builtin::BI__sync_lock_test_and_set:
1682   case Builtin::BI__sync_lock_test_and_set_1:
1683   case Builtin::BI__sync_lock_test_and_set_2:
1684   case Builtin::BI__sync_lock_test_and_set_4:
1685   case Builtin::BI__sync_lock_test_and_set_8:
1686   case Builtin::BI__sync_lock_test_and_set_16:
1687   case Builtin::BI__sync_lock_release:
1688   case Builtin::BI__sync_lock_release_1:
1689   case Builtin::BI__sync_lock_release_2:
1690   case Builtin::BI__sync_lock_release_4:
1691   case Builtin::BI__sync_lock_release_8:
1692   case Builtin::BI__sync_lock_release_16:
1693   case Builtin::BI__sync_swap:
1694   case Builtin::BI__sync_swap_1:
1695   case Builtin::BI__sync_swap_2:
1696   case Builtin::BI__sync_swap_4:
1697   case Builtin::BI__sync_swap_8:
1698   case Builtin::BI__sync_swap_16:
1699     return SemaBuiltinAtomicOverloaded(TheCallResult);
1700   case Builtin::BI__sync_synchronize:
1701     Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1702         << TheCall->getCallee()->getSourceRange();
1703     break;
1704   case Builtin::BI__builtin_nontemporal_load:
1705   case Builtin::BI__builtin_nontemporal_store:
1706     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1707   case Builtin::BI__builtin_memcpy_inline: {
1708     clang::Expr *SizeOp = TheCall->getArg(2);
1709     // We warn about copying to or from `nullptr` pointers when `size` is
1710     // greater than 0. When `size` is value dependent we cannot evaluate its
1711     // value so we bail out.
1712     if (SizeOp->isValueDependent())
1713       break;
1714     if (!SizeOp->EvaluateKnownConstInt(Context).isNullValue()) {
1715       CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
1716       CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
1717     }
1718     break;
1719   }
1720 #define BUILTIN(ID, TYPE, ATTRS)
1721 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1722   case Builtin::BI##ID: \
1723     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1724 #include "clang/Basic/Builtins.def"
1725   case Builtin::BI__annotation:
1726     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1727       return ExprError();
1728     break;
1729   case Builtin::BI__builtin_annotation:
1730     if (SemaBuiltinAnnotation(*this, TheCall))
1731       return ExprError();
1732     break;
1733   case Builtin::BI__builtin_addressof:
1734     if (SemaBuiltinAddressof(*this, TheCall))
1735       return ExprError();
1736     break;
1737   case Builtin::BI__builtin_is_aligned:
1738   case Builtin::BI__builtin_align_up:
1739   case Builtin::BI__builtin_align_down:
1740     if (SemaBuiltinAlignment(*this, TheCall, BuiltinID))
1741       return ExprError();
1742     break;
1743   case Builtin::BI__builtin_add_overflow:
1744   case Builtin::BI__builtin_sub_overflow:
1745   case Builtin::BI__builtin_mul_overflow:
1746     if (SemaBuiltinOverflow(*this, TheCall, BuiltinID))
1747       return ExprError();
1748     break;
1749   case Builtin::BI__builtin_operator_new:
1750   case Builtin::BI__builtin_operator_delete: {
1751     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1752     ExprResult Res =
1753         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1754     if (Res.isInvalid())
1755       CorrectDelayedTyposInExpr(TheCallResult.get());
1756     return Res;
1757   }
1758   case Builtin::BI__builtin_dump_struct: {
1759     // We first want to ensure we are called with 2 arguments
1760     if (checkArgCount(*this, TheCall, 2))
1761       return ExprError();
1762     // Ensure that the first argument is of type 'struct XX *'
1763     const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1764     const QualType PtrArgType = PtrArg->getType();
1765     if (!PtrArgType->isPointerType() ||
1766         !PtrArgType->getPointeeType()->isRecordType()) {
1767       Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1768           << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1769           << "structure pointer";
1770       return ExprError();
1771     }
1772 
1773     // Ensure that the second argument is of type 'FunctionType'
1774     const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1775     const QualType FnPtrArgType = FnPtrArg->getType();
1776     if (!FnPtrArgType->isPointerType()) {
1777       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1778           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1779           << FnPtrArgType << "'int (*)(const char *, ...)'";
1780       return ExprError();
1781     }
1782 
1783     const auto *FuncType =
1784         FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1785 
1786     if (!FuncType) {
1787       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1788           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1789           << FnPtrArgType << "'int (*)(const char *, ...)'";
1790       return ExprError();
1791     }
1792 
1793     if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1794       if (!FT->getNumParams()) {
1795         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1796             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1797             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1798         return ExprError();
1799       }
1800       QualType PT = FT->getParamType(0);
1801       if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1802           !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1803           !PT->getPointeeType().isConstQualified()) {
1804         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1805             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1806             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1807         return ExprError();
1808       }
1809     }
1810 
1811     TheCall->setType(Context.IntTy);
1812     break;
1813   }
1814   case Builtin::BI__builtin_expect_with_probability: {
1815     // We first want to ensure we are called with 3 arguments
1816     if (checkArgCount(*this, TheCall, 3))
1817       return ExprError();
1818     // then check probability is constant float in range [0.0, 1.0]
1819     const Expr *ProbArg = TheCall->getArg(2);
1820     SmallVector<PartialDiagnosticAt, 8> Notes;
1821     Expr::EvalResult Eval;
1822     Eval.Diag = &Notes;
1823     if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
1824         !Eval.Val.isFloat()) {
1825       Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
1826           << ProbArg->getSourceRange();
1827       for (const PartialDiagnosticAt &PDiag : Notes)
1828         Diag(PDiag.first, PDiag.second);
1829       return ExprError();
1830     }
1831     llvm::APFloat Probability = Eval.Val.getFloat();
1832     bool LoseInfo = false;
1833     Probability.convert(llvm::APFloat::IEEEdouble(),
1834                         llvm::RoundingMode::Dynamic, &LoseInfo);
1835     if (!(Probability >= llvm::APFloat(0.0) &&
1836           Probability <= llvm::APFloat(1.0))) {
1837       Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
1838           << ProbArg->getSourceRange();
1839       return ExprError();
1840     }
1841     break;
1842   }
1843   case Builtin::BI__builtin_preserve_access_index:
1844     if (SemaBuiltinPreserveAI(*this, TheCall))
1845       return ExprError();
1846     break;
1847   case Builtin::BI__builtin_call_with_static_chain:
1848     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1849       return ExprError();
1850     break;
1851   case Builtin::BI__exception_code:
1852   case Builtin::BI_exception_code:
1853     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1854                                  diag::err_seh___except_block))
1855       return ExprError();
1856     break;
1857   case Builtin::BI__exception_info:
1858   case Builtin::BI_exception_info:
1859     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1860                                  diag::err_seh___except_filter))
1861       return ExprError();
1862     break;
1863   case Builtin::BI__GetExceptionInfo:
1864     if (checkArgCount(*this, TheCall, 1))
1865       return ExprError();
1866 
1867     if (CheckCXXThrowOperand(
1868             TheCall->getBeginLoc(),
1869             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1870             TheCall))
1871       return ExprError();
1872 
1873     TheCall->setType(Context.VoidPtrTy);
1874     break;
1875   // OpenCL v2.0, s6.13.16 - Pipe functions
1876   case Builtin::BIread_pipe:
1877   case Builtin::BIwrite_pipe:
1878     // Since those two functions are declared with var args, we need a semantic
1879     // check for the argument.
1880     if (SemaBuiltinRWPipe(*this, TheCall))
1881       return ExprError();
1882     break;
1883   case Builtin::BIreserve_read_pipe:
1884   case Builtin::BIreserve_write_pipe:
1885   case Builtin::BIwork_group_reserve_read_pipe:
1886   case Builtin::BIwork_group_reserve_write_pipe:
1887     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1888       return ExprError();
1889     break;
1890   case Builtin::BIsub_group_reserve_read_pipe:
1891   case Builtin::BIsub_group_reserve_write_pipe:
1892     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1893         SemaBuiltinReserveRWPipe(*this, TheCall))
1894       return ExprError();
1895     break;
1896   case Builtin::BIcommit_read_pipe:
1897   case Builtin::BIcommit_write_pipe:
1898   case Builtin::BIwork_group_commit_read_pipe:
1899   case Builtin::BIwork_group_commit_write_pipe:
1900     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1901       return ExprError();
1902     break;
1903   case Builtin::BIsub_group_commit_read_pipe:
1904   case Builtin::BIsub_group_commit_write_pipe:
1905     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1906         SemaBuiltinCommitRWPipe(*this, TheCall))
1907       return ExprError();
1908     break;
1909   case Builtin::BIget_pipe_num_packets:
1910   case Builtin::BIget_pipe_max_packets:
1911     if (SemaBuiltinPipePackets(*this, TheCall))
1912       return ExprError();
1913     break;
1914   case Builtin::BIto_global:
1915   case Builtin::BIto_local:
1916   case Builtin::BIto_private:
1917     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1918       return ExprError();
1919     break;
1920   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1921   case Builtin::BIenqueue_kernel:
1922     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1923       return ExprError();
1924     break;
1925   case Builtin::BIget_kernel_work_group_size:
1926   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1927     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1928       return ExprError();
1929     break;
1930   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1931   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1932     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1933       return ExprError();
1934     break;
1935   case Builtin::BI__builtin_os_log_format:
1936     Cleanup.setExprNeedsCleanups(true);
1937     LLVM_FALLTHROUGH;
1938   case Builtin::BI__builtin_os_log_format_buffer_size:
1939     if (SemaBuiltinOSLogFormat(TheCall))
1940       return ExprError();
1941     break;
1942   case Builtin::BI__builtin_frame_address:
1943   case Builtin::BI__builtin_return_address: {
1944     if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
1945       return ExprError();
1946 
1947     // -Wframe-address warning if non-zero passed to builtin
1948     // return/frame address.
1949     Expr::EvalResult Result;
1950     if (!TheCall->getArg(0)->isValueDependent() &&
1951         TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
1952         Result.Val.getInt() != 0)
1953       Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
1954           << ((BuiltinID == Builtin::BI__builtin_return_address)
1955                   ? "__builtin_return_address"
1956                   : "__builtin_frame_address")
1957           << TheCall->getSourceRange();
1958     break;
1959   }
1960 
1961   case Builtin::BI__builtin_matrix_transpose:
1962     return SemaBuiltinMatrixTranspose(TheCall, TheCallResult);
1963 
1964   case Builtin::BI__builtin_matrix_column_major_load:
1965     return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
1966 
1967   case Builtin::BI__builtin_matrix_column_major_store:
1968     return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
1969 
1970   case Builtin::BI__builtin_get_device_side_mangled_name: {
1971     auto Check = [](CallExpr *TheCall) {
1972       if (TheCall->getNumArgs() != 1)
1973         return false;
1974       auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());
1975       if (!DRE)
1976         return false;
1977       auto *D = DRE->getDecl();
1978       if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D))
1979         return false;
1980       return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
1981              D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
1982     };
1983     if (!Check(TheCall)) {
1984       Diag(TheCall->getBeginLoc(),
1985            diag::err_hip_invalid_args_builtin_mangled_name);
1986       return ExprError();
1987     }
1988   }
1989   }
1990 
1991   // Since the target specific builtins for each arch overlap, only check those
1992   // of the arch we are compiling for.
1993   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1994     if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
1995       assert(Context.getAuxTargetInfo() &&
1996              "Aux Target Builtin, but not an aux target?");
1997 
1998       if (CheckTSBuiltinFunctionCall(
1999               *Context.getAuxTargetInfo(),
2000               Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
2001         return ExprError();
2002     } else {
2003       if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
2004                                      TheCall))
2005         return ExprError();
2006     }
2007   }
2008 
2009   return TheCallResult;
2010 }
2011 
2012 // Get the valid immediate range for the specified NEON type code.
2013 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
2014   NeonTypeFlags Type(t);
2015   int IsQuad = ForceQuad ? true : Type.isQuad();
2016   switch (Type.getEltType()) {
2017   case NeonTypeFlags::Int8:
2018   case NeonTypeFlags::Poly8:
2019     return shift ? 7 : (8 << IsQuad) - 1;
2020   case NeonTypeFlags::Int16:
2021   case NeonTypeFlags::Poly16:
2022     return shift ? 15 : (4 << IsQuad) - 1;
2023   case NeonTypeFlags::Int32:
2024     return shift ? 31 : (2 << IsQuad) - 1;
2025   case NeonTypeFlags::Int64:
2026   case NeonTypeFlags::Poly64:
2027     return shift ? 63 : (1 << IsQuad) - 1;
2028   case NeonTypeFlags::Poly128:
2029     return shift ? 127 : (1 << IsQuad) - 1;
2030   case NeonTypeFlags::Float16:
2031     assert(!shift && "cannot shift float types!");
2032     return (4 << IsQuad) - 1;
2033   case NeonTypeFlags::Float32:
2034     assert(!shift && "cannot shift float types!");
2035     return (2 << IsQuad) - 1;
2036   case NeonTypeFlags::Float64:
2037     assert(!shift && "cannot shift float types!");
2038     return (1 << IsQuad) - 1;
2039   case NeonTypeFlags::BFloat16:
2040     assert(!shift && "cannot shift float types!");
2041     return (4 << IsQuad) - 1;
2042   }
2043   llvm_unreachable("Invalid NeonTypeFlag!");
2044 }
2045 
2046 /// getNeonEltType - Return the QualType corresponding to the elements of
2047 /// the vector type specified by the NeonTypeFlags.  This is used to check
2048 /// the pointer arguments for Neon load/store intrinsics.
2049 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
2050                                bool IsPolyUnsigned, bool IsInt64Long) {
2051   switch (Flags.getEltType()) {
2052   case NeonTypeFlags::Int8:
2053     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
2054   case NeonTypeFlags::Int16:
2055     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
2056   case NeonTypeFlags::Int32:
2057     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
2058   case NeonTypeFlags::Int64:
2059     if (IsInt64Long)
2060       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
2061     else
2062       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
2063                                 : Context.LongLongTy;
2064   case NeonTypeFlags::Poly8:
2065     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
2066   case NeonTypeFlags::Poly16:
2067     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
2068   case NeonTypeFlags::Poly64:
2069     if (IsInt64Long)
2070       return Context.UnsignedLongTy;
2071     else
2072       return Context.UnsignedLongLongTy;
2073   case NeonTypeFlags::Poly128:
2074     break;
2075   case NeonTypeFlags::Float16:
2076     return Context.HalfTy;
2077   case NeonTypeFlags::Float32:
2078     return Context.FloatTy;
2079   case NeonTypeFlags::Float64:
2080     return Context.DoubleTy;
2081   case NeonTypeFlags::BFloat16:
2082     return Context.BFloat16Ty;
2083   }
2084   llvm_unreachable("Invalid NeonTypeFlag!");
2085 }
2086 
2087 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2088   // Range check SVE intrinsics that take immediate values.
2089   SmallVector<std::tuple<int,int,int>, 3> ImmChecks;
2090 
2091   switch (BuiltinID) {
2092   default:
2093     return false;
2094 #define GET_SVE_IMMEDIATE_CHECK
2095 #include "clang/Basic/arm_sve_sema_rangechecks.inc"
2096 #undef GET_SVE_IMMEDIATE_CHECK
2097   }
2098 
2099   // Perform all the immediate checks for this builtin call.
2100   bool HasError = false;
2101   for (auto &I : ImmChecks) {
2102     int ArgNum, CheckTy, ElementSizeInBits;
2103     std::tie(ArgNum, CheckTy, ElementSizeInBits) = I;
2104 
2105     typedef bool(*OptionSetCheckFnTy)(int64_t Value);
2106 
2107     // Function that checks whether the operand (ArgNum) is an immediate
2108     // that is one of the predefined values.
2109     auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm,
2110                                    int ErrDiag) -> bool {
2111       // We can't check the value of a dependent argument.
2112       Expr *Arg = TheCall->getArg(ArgNum);
2113       if (Arg->isTypeDependent() || Arg->isValueDependent())
2114         return false;
2115 
2116       // Check constant-ness first.
2117       llvm::APSInt Imm;
2118       if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm))
2119         return true;
2120 
2121       if (!CheckImm(Imm.getSExtValue()))
2122         return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange();
2123       return false;
2124     };
2125 
2126     switch ((SVETypeFlags::ImmCheckType)CheckTy) {
2127     case SVETypeFlags::ImmCheck0_31:
2128       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31))
2129         HasError = true;
2130       break;
2131     case SVETypeFlags::ImmCheck0_13:
2132       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13))
2133         HasError = true;
2134       break;
2135     case SVETypeFlags::ImmCheck1_16:
2136       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16))
2137         HasError = true;
2138       break;
2139     case SVETypeFlags::ImmCheck0_7:
2140       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7))
2141         HasError = true;
2142       break;
2143     case SVETypeFlags::ImmCheckExtract:
2144       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2145                                       (2048 / ElementSizeInBits) - 1))
2146         HasError = true;
2147       break;
2148     case SVETypeFlags::ImmCheckShiftRight:
2149       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits))
2150         HasError = true;
2151       break;
2152     case SVETypeFlags::ImmCheckShiftRightNarrow:
2153       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1,
2154                                       ElementSizeInBits / 2))
2155         HasError = true;
2156       break;
2157     case SVETypeFlags::ImmCheckShiftLeft:
2158       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2159                                       ElementSizeInBits - 1))
2160         HasError = true;
2161       break;
2162     case SVETypeFlags::ImmCheckLaneIndex:
2163       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2164                                       (128 / (1 * ElementSizeInBits)) - 1))
2165         HasError = true;
2166       break;
2167     case SVETypeFlags::ImmCheckLaneIndexCompRotate:
2168       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2169                                       (128 / (2 * ElementSizeInBits)) - 1))
2170         HasError = true;
2171       break;
2172     case SVETypeFlags::ImmCheckLaneIndexDot:
2173       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2174                                       (128 / (4 * ElementSizeInBits)) - 1))
2175         HasError = true;
2176       break;
2177     case SVETypeFlags::ImmCheckComplexRot90_270:
2178       if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; },
2179                               diag::err_rotation_argument_to_cadd))
2180         HasError = true;
2181       break;
2182     case SVETypeFlags::ImmCheckComplexRotAll90:
2183       if (CheckImmediateInSet(
2184               [](int64_t V) {
2185                 return V == 0 || V == 90 || V == 180 || V == 270;
2186               },
2187               diag::err_rotation_argument_to_cmla))
2188         HasError = true;
2189       break;
2190     case SVETypeFlags::ImmCheck0_1:
2191       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1))
2192         HasError = true;
2193       break;
2194     case SVETypeFlags::ImmCheck0_2:
2195       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2))
2196         HasError = true;
2197       break;
2198     case SVETypeFlags::ImmCheck0_3:
2199       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3))
2200         HasError = true;
2201       break;
2202     }
2203   }
2204 
2205   return HasError;
2206 }
2207 
2208 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI,
2209                                         unsigned BuiltinID, CallExpr *TheCall) {
2210   llvm::APSInt Result;
2211   uint64_t mask = 0;
2212   unsigned TV = 0;
2213   int PtrArgNum = -1;
2214   bool HasConstPtr = false;
2215   switch (BuiltinID) {
2216 #define GET_NEON_OVERLOAD_CHECK
2217 #include "clang/Basic/arm_neon.inc"
2218 #include "clang/Basic/arm_fp16.inc"
2219 #undef GET_NEON_OVERLOAD_CHECK
2220   }
2221 
2222   // For NEON intrinsics which are overloaded on vector element type, validate
2223   // the immediate which specifies which variant to emit.
2224   unsigned ImmArg = TheCall->getNumArgs()-1;
2225   if (mask) {
2226     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
2227       return true;
2228 
2229     TV = Result.getLimitedValue(64);
2230     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
2231       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
2232              << TheCall->getArg(ImmArg)->getSourceRange();
2233   }
2234 
2235   if (PtrArgNum >= 0) {
2236     // Check that pointer arguments have the specified type.
2237     Expr *Arg = TheCall->getArg(PtrArgNum);
2238     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
2239       Arg = ICE->getSubExpr();
2240     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
2241     QualType RHSTy = RHS.get()->getType();
2242 
2243     llvm::Triple::ArchType Arch = TI.getTriple().getArch();
2244     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
2245                           Arch == llvm::Triple::aarch64_32 ||
2246                           Arch == llvm::Triple::aarch64_be;
2247     bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong;
2248     QualType EltTy =
2249         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
2250     if (HasConstPtr)
2251       EltTy = EltTy.withConst();
2252     QualType LHSTy = Context.getPointerType(EltTy);
2253     AssignConvertType ConvTy;
2254     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
2255     if (RHS.isInvalid())
2256       return true;
2257     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
2258                                  RHS.get(), AA_Assigning))
2259       return true;
2260   }
2261 
2262   // For NEON intrinsics which take an immediate value as part of the
2263   // instruction, range check them here.
2264   unsigned i = 0, l = 0, u = 0;
2265   switch (BuiltinID) {
2266   default:
2267     return false;
2268   #define GET_NEON_IMMEDIATE_CHECK
2269   #include "clang/Basic/arm_neon.inc"
2270   #include "clang/Basic/arm_fp16.inc"
2271   #undef GET_NEON_IMMEDIATE_CHECK
2272   }
2273 
2274   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2275 }
2276 
2277 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2278   switch (BuiltinID) {
2279   default:
2280     return false;
2281   #include "clang/Basic/arm_mve_builtin_sema.inc"
2282   }
2283 }
2284 
2285 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2286                                        CallExpr *TheCall) {
2287   bool Err = false;
2288   switch (BuiltinID) {
2289   default:
2290     return false;
2291 #include "clang/Basic/arm_cde_builtin_sema.inc"
2292   }
2293 
2294   if (Err)
2295     return true;
2296 
2297   return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true);
2298 }
2299 
2300 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI,
2301                                         const Expr *CoprocArg, bool WantCDE) {
2302   if (isConstantEvaluated())
2303     return false;
2304 
2305   // We can't check the value of a dependent argument.
2306   if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent())
2307     return false;
2308 
2309   llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context);
2310   int64_t CoprocNo = CoprocNoAP.getExtValue();
2311   assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative");
2312 
2313   uint32_t CDECoprocMask = TI.getARMCDECoprocMask();
2314   bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo));
2315 
2316   if (IsCDECoproc != WantCDE)
2317     return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc)
2318            << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange();
2319 
2320   return false;
2321 }
2322 
2323 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
2324                                         unsigned MaxWidth) {
2325   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
2326           BuiltinID == ARM::BI__builtin_arm_ldaex ||
2327           BuiltinID == ARM::BI__builtin_arm_strex ||
2328           BuiltinID == ARM::BI__builtin_arm_stlex ||
2329           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2330           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2331           BuiltinID == AArch64::BI__builtin_arm_strex ||
2332           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
2333          "unexpected ARM builtin");
2334   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
2335                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
2336                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2337                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
2338 
2339   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2340 
2341   // Ensure that we have the proper number of arguments.
2342   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
2343     return true;
2344 
2345   // Inspect the pointer argument of the atomic builtin.  This should always be
2346   // a pointer type, whose element is an integral scalar or pointer type.
2347   // Because it is a pointer type, we don't have to worry about any implicit
2348   // casts here.
2349   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
2350   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
2351   if (PointerArgRes.isInvalid())
2352     return true;
2353   PointerArg = PointerArgRes.get();
2354 
2355   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2356   if (!pointerType) {
2357     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
2358         << PointerArg->getType() << PointerArg->getSourceRange();
2359     return true;
2360   }
2361 
2362   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
2363   // task is to insert the appropriate casts into the AST. First work out just
2364   // what the appropriate type is.
2365   QualType ValType = pointerType->getPointeeType();
2366   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
2367   if (IsLdrex)
2368     AddrType.addConst();
2369 
2370   // Issue a warning if the cast is dodgy.
2371   CastKind CastNeeded = CK_NoOp;
2372   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
2373     CastNeeded = CK_BitCast;
2374     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
2375         << PointerArg->getType() << Context.getPointerType(AddrType)
2376         << AA_Passing << PointerArg->getSourceRange();
2377   }
2378 
2379   // Finally, do the cast and replace the argument with the corrected version.
2380   AddrType = Context.getPointerType(AddrType);
2381   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
2382   if (PointerArgRes.isInvalid())
2383     return true;
2384   PointerArg = PointerArgRes.get();
2385 
2386   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
2387 
2388   // In general, we allow ints, floats and pointers to be loaded and stored.
2389   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2390       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
2391     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
2392         << PointerArg->getType() << PointerArg->getSourceRange();
2393     return true;
2394   }
2395 
2396   // But ARM doesn't have instructions to deal with 128-bit versions.
2397   if (Context.getTypeSize(ValType) > MaxWidth) {
2398     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
2399     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
2400         << PointerArg->getType() << PointerArg->getSourceRange();
2401     return true;
2402   }
2403 
2404   switch (ValType.getObjCLifetime()) {
2405   case Qualifiers::OCL_None:
2406   case Qualifiers::OCL_ExplicitNone:
2407     // okay
2408     break;
2409 
2410   case Qualifiers::OCL_Weak:
2411   case Qualifiers::OCL_Strong:
2412   case Qualifiers::OCL_Autoreleasing:
2413     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
2414         << ValType << PointerArg->getSourceRange();
2415     return true;
2416   }
2417 
2418   if (IsLdrex) {
2419     TheCall->setType(ValType);
2420     return false;
2421   }
2422 
2423   // Initialize the argument to be stored.
2424   ExprResult ValArg = TheCall->getArg(0);
2425   InitializedEntity Entity = InitializedEntity::InitializeParameter(
2426       Context, ValType, /*consume*/ false);
2427   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2428   if (ValArg.isInvalid())
2429     return true;
2430   TheCall->setArg(0, ValArg.get());
2431 
2432   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
2433   // but the custom checker bypasses all default analysis.
2434   TheCall->setType(Context.IntTy);
2435   return false;
2436 }
2437 
2438 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2439                                        CallExpr *TheCall) {
2440   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
2441       BuiltinID == ARM::BI__builtin_arm_ldaex ||
2442       BuiltinID == ARM::BI__builtin_arm_strex ||
2443       BuiltinID == ARM::BI__builtin_arm_stlex) {
2444     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
2445   }
2446 
2447   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
2448     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2449       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
2450   }
2451 
2452   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2453       BuiltinID == ARM::BI__builtin_arm_wsr64)
2454     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
2455 
2456   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
2457       BuiltinID == ARM::BI__builtin_arm_rsrp ||
2458       BuiltinID == ARM::BI__builtin_arm_wsr ||
2459       BuiltinID == ARM::BI__builtin_arm_wsrp)
2460     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2461 
2462   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2463     return true;
2464   if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
2465     return true;
2466   if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall))
2467     return true;
2468 
2469   // For intrinsics which take an immediate value as part of the instruction,
2470   // range check them here.
2471   // FIXME: VFP Intrinsics should error if VFP not present.
2472   switch (BuiltinID) {
2473   default: return false;
2474   case ARM::BI__builtin_arm_ssat:
2475     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
2476   case ARM::BI__builtin_arm_usat:
2477     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
2478   case ARM::BI__builtin_arm_ssat16:
2479     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
2480   case ARM::BI__builtin_arm_usat16:
2481     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2482   case ARM::BI__builtin_arm_vcvtr_f:
2483   case ARM::BI__builtin_arm_vcvtr_d:
2484     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
2485   case ARM::BI__builtin_arm_dmb:
2486   case ARM::BI__builtin_arm_dsb:
2487   case ARM::BI__builtin_arm_isb:
2488   case ARM::BI__builtin_arm_dbg:
2489     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
2490   case ARM::BI__builtin_arm_cdp:
2491   case ARM::BI__builtin_arm_cdp2:
2492   case ARM::BI__builtin_arm_mcr:
2493   case ARM::BI__builtin_arm_mcr2:
2494   case ARM::BI__builtin_arm_mrc:
2495   case ARM::BI__builtin_arm_mrc2:
2496   case ARM::BI__builtin_arm_mcrr:
2497   case ARM::BI__builtin_arm_mcrr2:
2498   case ARM::BI__builtin_arm_mrrc:
2499   case ARM::BI__builtin_arm_mrrc2:
2500   case ARM::BI__builtin_arm_ldc:
2501   case ARM::BI__builtin_arm_ldcl:
2502   case ARM::BI__builtin_arm_ldc2:
2503   case ARM::BI__builtin_arm_ldc2l:
2504   case ARM::BI__builtin_arm_stc:
2505   case ARM::BI__builtin_arm_stcl:
2506   case ARM::BI__builtin_arm_stc2:
2507   case ARM::BI__builtin_arm_stc2l:
2508     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) ||
2509            CheckARMCoprocessorImmediate(TI, TheCall->getArg(0),
2510                                         /*WantCDE*/ false);
2511   }
2512 }
2513 
2514 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI,
2515                                            unsigned BuiltinID,
2516                                            CallExpr *TheCall) {
2517   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2518       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2519       BuiltinID == AArch64::BI__builtin_arm_strex ||
2520       BuiltinID == AArch64::BI__builtin_arm_stlex) {
2521     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
2522   }
2523 
2524   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
2525     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2526       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
2527       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
2528       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
2529   }
2530 
2531   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2532       BuiltinID == AArch64::BI__builtin_arm_wsr64)
2533     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2534 
2535   // Memory Tagging Extensions (MTE) Intrinsics
2536   if (BuiltinID == AArch64::BI__builtin_arm_irg ||
2537       BuiltinID == AArch64::BI__builtin_arm_addg ||
2538       BuiltinID == AArch64::BI__builtin_arm_gmi ||
2539       BuiltinID == AArch64::BI__builtin_arm_ldg ||
2540       BuiltinID == AArch64::BI__builtin_arm_stg ||
2541       BuiltinID == AArch64::BI__builtin_arm_subp) {
2542     return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
2543   }
2544 
2545   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
2546       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2547       BuiltinID == AArch64::BI__builtin_arm_wsr ||
2548       BuiltinID == AArch64::BI__builtin_arm_wsrp)
2549     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2550 
2551   // Only check the valid encoding range. Any constant in this range would be
2552   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
2553   // an exception for incorrect registers. This matches MSVC behavior.
2554   if (BuiltinID == AArch64::BI_ReadStatusReg ||
2555       BuiltinID == AArch64::BI_WriteStatusReg)
2556     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
2557 
2558   if (BuiltinID == AArch64::BI__getReg)
2559     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
2560 
2561   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2562     return true;
2563 
2564   if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall))
2565     return true;
2566 
2567   // For intrinsics which take an immediate value as part of the instruction,
2568   // range check them here.
2569   unsigned i = 0, l = 0, u = 0;
2570   switch (BuiltinID) {
2571   default: return false;
2572   case AArch64::BI__builtin_arm_dmb:
2573   case AArch64::BI__builtin_arm_dsb:
2574   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
2575   case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
2576   }
2577 
2578   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2579 }
2580 
2581 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) {
2582   if (Arg->getType()->getAsPlaceholderType())
2583     return false;
2584 
2585   // The first argument needs to be a record field access.
2586   // If it is an array element access, we delay decision
2587   // to BPF backend to check whether the access is a
2588   // field access or not.
2589   return (Arg->IgnoreParens()->getObjectKind() == OK_BitField ||
2590           dyn_cast<MemberExpr>(Arg->IgnoreParens()) ||
2591           dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens()));
2592 }
2593 
2594 static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S,
2595                             QualType VectorTy, QualType EltTy) {
2596   QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType();
2597   if (!Context.hasSameType(VectorEltTy, EltTy)) {
2598     S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types)
2599         << Call->getSourceRange() << VectorEltTy << EltTy;
2600     return false;
2601   }
2602   return true;
2603 }
2604 
2605 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) {
2606   QualType ArgType = Arg->getType();
2607   if (ArgType->getAsPlaceholderType())
2608     return false;
2609 
2610   // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type
2611   // format:
2612   //   1. __builtin_preserve_type_info(*(<type> *)0, flag);
2613   //   2. <type> var;
2614   //      __builtin_preserve_type_info(var, flag);
2615   if (!dyn_cast<DeclRefExpr>(Arg->IgnoreParens()) &&
2616       !dyn_cast<UnaryOperator>(Arg->IgnoreParens()))
2617     return false;
2618 
2619   // Typedef type.
2620   if (ArgType->getAs<TypedefType>())
2621     return true;
2622 
2623   // Record type or Enum type.
2624   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2625   if (const auto *RT = Ty->getAs<RecordType>()) {
2626     if (!RT->getDecl()->getDeclName().isEmpty())
2627       return true;
2628   } else if (const auto *ET = Ty->getAs<EnumType>()) {
2629     if (!ET->getDecl()->getDeclName().isEmpty())
2630       return true;
2631   }
2632 
2633   return false;
2634 }
2635 
2636 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) {
2637   QualType ArgType = Arg->getType();
2638   if (ArgType->getAsPlaceholderType())
2639     return false;
2640 
2641   // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type
2642   // format:
2643   //   __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>,
2644   //                                 flag);
2645   const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens());
2646   if (!UO)
2647     return false;
2648 
2649   const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr());
2650   if (!CE)
2651     return false;
2652   if (CE->getCastKind() != CK_IntegralToPointer &&
2653       CE->getCastKind() != CK_NullToPointer)
2654     return false;
2655 
2656   // The integer must be from an EnumConstantDecl.
2657   const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr());
2658   if (!DR)
2659     return false;
2660 
2661   const EnumConstantDecl *Enumerator =
2662       dyn_cast<EnumConstantDecl>(DR->getDecl());
2663   if (!Enumerator)
2664     return false;
2665 
2666   // The type must be EnumType.
2667   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2668   const auto *ET = Ty->getAs<EnumType>();
2669   if (!ET)
2670     return false;
2671 
2672   // The enum value must be supported.
2673   for (auto *EDI : ET->getDecl()->enumerators()) {
2674     if (EDI == Enumerator)
2675       return true;
2676   }
2677 
2678   return false;
2679 }
2680 
2681 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
2682                                        CallExpr *TheCall) {
2683   assert((BuiltinID == BPF::BI__builtin_preserve_field_info ||
2684           BuiltinID == BPF::BI__builtin_btf_type_id ||
2685           BuiltinID == BPF::BI__builtin_preserve_type_info ||
2686           BuiltinID == BPF::BI__builtin_preserve_enum_value) &&
2687          "unexpected BPF builtin");
2688 
2689   if (checkArgCount(*this, TheCall, 2))
2690     return true;
2691 
2692   // The second argument needs to be a constant int
2693   Expr *Arg = TheCall->getArg(1);
2694   Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context);
2695   diag::kind kind;
2696   if (!Value) {
2697     if (BuiltinID == BPF::BI__builtin_preserve_field_info)
2698       kind = diag::err_preserve_field_info_not_const;
2699     else if (BuiltinID == BPF::BI__builtin_btf_type_id)
2700       kind = diag::err_btf_type_id_not_const;
2701     else if (BuiltinID == BPF::BI__builtin_preserve_type_info)
2702       kind = diag::err_preserve_type_info_not_const;
2703     else
2704       kind = diag::err_preserve_enum_value_not_const;
2705     Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange();
2706     return true;
2707   }
2708 
2709   // The first argument
2710   Arg = TheCall->getArg(0);
2711   bool InvalidArg = false;
2712   bool ReturnUnsignedInt = true;
2713   if (BuiltinID == BPF::BI__builtin_preserve_field_info) {
2714     if (!isValidBPFPreserveFieldInfoArg(Arg)) {
2715       InvalidArg = true;
2716       kind = diag::err_preserve_field_info_not_field;
2717     }
2718   } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) {
2719     if (!isValidBPFPreserveTypeInfoArg(Arg)) {
2720       InvalidArg = true;
2721       kind = diag::err_preserve_type_info_invalid;
2722     }
2723   } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) {
2724     if (!isValidBPFPreserveEnumValueArg(Arg)) {
2725       InvalidArg = true;
2726       kind = diag::err_preserve_enum_value_invalid;
2727     }
2728     ReturnUnsignedInt = false;
2729   } else if (BuiltinID == BPF::BI__builtin_btf_type_id) {
2730     ReturnUnsignedInt = false;
2731   }
2732 
2733   if (InvalidArg) {
2734     Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange();
2735     return true;
2736   }
2737 
2738   if (ReturnUnsignedInt)
2739     TheCall->setType(Context.UnsignedIntTy);
2740   else
2741     TheCall->setType(Context.UnsignedLongTy);
2742   return false;
2743 }
2744 
2745 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2746   struct ArgInfo {
2747     uint8_t OpNum;
2748     bool IsSigned;
2749     uint8_t BitWidth;
2750     uint8_t Align;
2751   };
2752   struct BuiltinInfo {
2753     unsigned BuiltinID;
2754     ArgInfo Infos[2];
2755   };
2756 
2757   static BuiltinInfo Infos[] = {
2758     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
2759     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
2760     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
2761     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  1 }} },
2762     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
2763     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
2764     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
2765     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
2766     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
2767     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
2768     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
2769 
2770     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
2771     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
2772     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
2773     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
2774     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
2775     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
2776     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
2777     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
2778     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
2779     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
2780     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
2781 
2782     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
2783     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
2784     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
2785     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
2786     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
2787     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
2788     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
2789     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
2790     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
2791     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
2792     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
2793     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
2794     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
2795     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
2796     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
2797     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
2798     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
2799     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
2800     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
2801     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
2802     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
2803     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
2804     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
2805     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
2806     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
2807     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
2808     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
2809     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
2810     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
2811     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
2812     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
2813     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
2814     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
2815     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
2816     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
2817     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
2818     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
2819     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
2820     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
2821     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
2822     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
2823     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
2824     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
2825     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
2826     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
2827     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
2828     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
2829     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
2830     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
2831     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
2832     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
2833     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
2834                                                       {{ 1, false, 6,  0 }} },
2835     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
2836     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
2837     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
2838     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
2839     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
2840     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
2841     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
2842                                                       {{ 1, false, 5,  0 }} },
2843     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
2844     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
2845     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
2846     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
2847     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
2848     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
2849                                                        { 2, false, 5,  0 }} },
2850     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
2851                                                        { 2, false, 6,  0 }} },
2852     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
2853                                                        { 3, false, 5,  0 }} },
2854     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
2855                                                        { 3, false, 6,  0 }} },
2856     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
2857     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
2858     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
2859     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
2860     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
2861     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
2862     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
2863     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
2864     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
2865     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
2866     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
2867     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
2868     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
2869     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
2870     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
2871     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
2872                                                       {{ 2, false, 4,  0 },
2873                                                        { 3, false, 5,  0 }} },
2874     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
2875                                                       {{ 2, false, 4,  0 },
2876                                                        { 3, false, 5,  0 }} },
2877     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
2878                                                       {{ 2, false, 4,  0 },
2879                                                        { 3, false, 5,  0 }} },
2880     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
2881                                                       {{ 2, false, 4,  0 },
2882                                                        { 3, false, 5,  0 }} },
2883     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
2884     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
2885     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
2886     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
2887     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
2888     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
2889     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
2890     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
2891     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
2892     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
2893     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
2894                                                        { 2, false, 5,  0 }} },
2895     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
2896                                                        { 2, false, 6,  0 }} },
2897     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
2898     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
2899     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
2900     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
2901     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
2902     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
2903     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
2904     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
2905     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
2906                                                       {{ 1, false, 4,  0 }} },
2907     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
2908     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
2909                                                       {{ 1, false, 4,  0 }} },
2910     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
2911     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
2912     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
2913     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
2914     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
2915     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
2916     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
2917     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
2918     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
2919     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
2920     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
2921     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
2922     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
2923     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
2924     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
2925     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
2926     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
2927     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
2928     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
2929     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
2930                                                       {{ 3, false, 1,  0 }} },
2931     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
2932     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
2933     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
2934     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
2935                                                       {{ 3, false, 1,  0 }} },
2936     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
2937     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
2938     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
2939     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
2940                                                       {{ 3, false, 1,  0 }} },
2941   };
2942 
2943   // Use a dynamically initialized static to sort the table exactly once on
2944   // first run.
2945   static const bool SortOnce =
2946       (llvm::sort(Infos,
2947                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
2948                    return LHS.BuiltinID < RHS.BuiltinID;
2949                  }),
2950        true);
2951   (void)SortOnce;
2952 
2953   const BuiltinInfo *F = llvm::partition_point(
2954       Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
2955   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
2956     return false;
2957 
2958   bool Error = false;
2959 
2960   for (const ArgInfo &A : F->Infos) {
2961     // Ignore empty ArgInfo elements.
2962     if (A.BitWidth == 0)
2963       continue;
2964 
2965     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
2966     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
2967     if (!A.Align) {
2968       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
2969     } else {
2970       unsigned M = 1 << A.Align;
2971       Min *= M;
2972       Max *= M;
2973       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
2974                SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
2975     }
2976   }
2977   return Error;
2978 }
2979 
2980 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
2981                                            CallExpr *TheCall) {
2982   return CheckHexagonBuiltinArgument(BuiltinID, TheCall);
2983 }
2984 
2985 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI,
2986                                         unsigned BuiltinID, CallExpr *TheCall) {
2987   return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) ||
2988          CheckMipsBuiltinArgument(BuiltinID, TheCall);
2989 }
2990 
2991 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
2992                                CallExpr *TheCall) {
2993 
2994   if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
2995       BuiltinID <= Mips::BI__builtin_mips_lwx) {
2996     if (!TI.hasFeature("dsp"))
2997       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
2998   }
2999 
3000   if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
3001       BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
3002     if (!TI.hasFeature("dspr2"))
3003       return Diag(TheCall->getBeginLoc(),
3004                   diag::err_mips_builtin_requires_dspr2);
3005   }
3006 
3007   if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
3008       BuiltinID <= Mips::BI__builtin_msa_xori_b) {
3009     if (!TI.hasFeature("msa"))
3010       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
3011   }
3012 
3013   return false;
3014 }
3015 
3016 // CheckMipsBuiltinArgument - Checks the constant value passed to the
3017 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
3018 // ordering for DSP is unspecified. MSA is ordered by the data format used
3019 // by the underlying instruction i.e., df/m, df/n and then by size.
3020 //
3021 // FIXME: The size tests here should instead be tablegen'd along with the
3022 //        definitions from include/clang/Basic/BuiltinsMips.def.
3023 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
3024 //        be too.
3025 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
3026   unsigned i = 0, l = 0, u = 0, m = 0;
3027   switch (BuiltinID) {
3028   default: return false;
3029   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
3030   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
3031   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
3032   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
3033   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
3034   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
3035   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
3036   // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
3037   // df/m field.
3038   // These intrinsics take an unsigned 3 bit immediate.
3039   case Mips::BI__builtin_msa_bclri_b:
3040   case Mips::BI__builtin_msa_bnegi_b:
3041   case Mips::BI__builtin_msa_bseti_b:
3042   case Mips::BI__builtin_msa_sat_s_b:
3043   case Mips::BI__builtin_msa_sat_u_b:
3044   case Mips::BI__builtin_msa_slli_b:
3045   case Mips::BI__builtin_msa_srai_b:
3046   case Mips::BI__builtin_msa_srari_b:
3047   case Mips::BI__builtin_msa_srli_b:
3048   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
3049   case Mips::BI__builtin_msa_binsli_b:
3050   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
3051   // These intrinsics take an unsigned 4 bit immediate.
3052   case Mips::BI__builtin_msa_bclri_h:
3053   case Mips::BI__builtin_msa_bnegi_h:
3054   case Mips::BI__builtin_msa_bseti_h:
3055   case Mips::BI__builtin_msa_sat_s_h:
3056   case Mips::BI__builtin_msa_sat_u_h:
3057   case Mips::BI__builtin_msa_slli_h:
3058   case Mips::BI__builtin_msa_srai_h:
3059   case Mips::BI__builtin_msa_srari_h:
3060   case Mips::BI__builtin_msa_srli_h:
3061   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
3062   case Mips::BI__builtin_msa_binsli_h:
3063   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
3064   // These intrinsics take an unsigned 5 bit immediate.
3065   // The first block of intrinsics actually have an unsigned 5 bit field,
3066   // not a df/n field.
3067   case Mips::BI__builtin_msa_cfcmsa:
3068   case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
3069   case Mips::BI__builtin_msa_clei_u_b:
3070   case Mips::BI__builtin_msa_clei_u_h:
3071   case Mips::BI__builtin_msa_clei_u_w:
3072   case Mips::BI__builtin_msa_clei_u_d:
3073   case Mips::BI__builtin_msa_clti_u_b:
3074   case Mips::BI__builtin_msa_clti_u_h:
3075   case Mips::BI__builtin_msa_clti_u_w:
3076   case Mips::BI__builtin_msa_clti_u_d:
3077   case Mips::BI__builtin_msa_maxi_u_b:
3078   case Mips::BI__builtin_msa_maxi_u_h:
3079   case Mips::BI__builtin_msa_maxi_u_w:
3080   case Mips::BI__builtin_msa_maxi_u_d:
3081   case Mips::BI__builtin_msa_mini_u_b:
3082   case Mips::BI__builtin_msa_mini_u_h:
3083   case Mips::BI__builtin_msa_mini_u_w:
3084   case Mips::BI__builtin_msa_mini_u_d:
3085   case Mips::BI__builtin_msa_addvi_b:
3086   case Mips::BI__builtin_msa_addvi_h:
3087   case Mips::BI__builtin_msa_addvi_w:
3088   case Mips::BI__builtin_msa_addvi_d:
3089   case Mips::BI__builtin_msa_bclri_w:
3090   case Mips::BI__builtin_msa_bnegi_w:
3091   case Mips::BI__builtin_msa_bseti_w:
3092   case Mips::BI__builtin_msa_sat_s_w:
3093   case Mips::BI__builtin_msa_sat_u_w:
3094   case Mips::BI__builtin_msa_slli_w:
3095   case Mips::BI__builtin_msa_srai_w:
3096   case Mips::BI__builtin_msa_srari_w:
3097   case Mips::BI__builtin_msa_srli_w:
3098   case Mips::BI__builtin_msa_srlri_w:
3099   case Mips::BI__builtin_msa_subvi_b:
3100   case Mips::BI__builtin_msa_subvi_h:
3101   case Mips::BI__builtin_msa_subvi_w:
3102   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
3103   case Mips::BI__builtin_msa_binsli_w:
3104   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
3105   // These intrinsics take an unsigned 6 bit immediate.
3106   case Mips::BI__builtin_msa_bclri_d:
3107   case Mips::BI__builtin_msa_bnegi_d:
3108   case Mips::BI__builtin_msa_bseti_d:
3109   case Mips::BI__builtin_msa_sat_s_d:
3110   case Mips::BI__builtin_msa_sat_u_d:
3111   case Mips::BI__builtin_msa_slli_d:
3112   case Mips::BI__builtin_msa_srai_d:
3113   case Mips::BI__builtin_msa_srari_d:
3114   case Mips::BI__builtin_msa_srli_d:
3115   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
3116   case Mips::BI__builtin_msa_binsli_d:
3117   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
3118   // These intrinsics take a signed 5 bit immediate.
3119   case Mips::BI__builtin_msa_ceqi_b:
3120   case Mips::BI__builtin_msa_ceqi_h:
3121   case Mips::BI__builtin_msa_ceqi_w:
3122   case Mips::BI__builtin_msa_ceqi_d:
3123   case Mips::BI__builtin_msa_clti_s_b:
3124   case Mips::BI__builtin_msa_clti_s_h:
3125   case Mips::BI__builtin_msa_clti_s_w:
3126   case Mips::BI__builtin_msa_clti_s_d:
3127   case Mips::BI__builtin_msa_clei_s_b:
3128   case Mips::BI__builtin_msa_clei_s_h:
3129   case Mips::BI__builtin_msa_clei_s_w:
3130   case Mips::BI__builtin_msa_clei_s_d:
3131   case Mips::BI__builtin_msa_maxi_s_b:
3132   case Mips::BI__builtin_msa_maxi_s_h:
3133   case Mips::BI__builtin_msa_maxi_s_w:
3134   case Mips::BI__builtin_msa_maxi_s_d:
3135   case Mips::BI__builtin_msa_mini_s_b:
3136   case Mips::BI__builtin_msa_mini_s_h:
3137   case Mips::BI__builtin_msa_mini_s_w:
3138   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
3139   // These intrinsics take an unsigned 8 bit immediate.
3140   case Mips::BI__builtin_msa_andi_b:
3141   case Mips::BI__builtin_msa_nori_b:
3142   case Mips::BI__builtin_msa_ori_b:
3143   case Mips::BI__builtin_msa_shf_b:
3144   case Mips::BI__builtin_msa_shf_h:
3145   case Mips::BI__builtin_msa_shf_w:
3146   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
3147   case Mips::BI__builtin_msa_bseli_b:
3148   case Mips::BI__builtin_msa_bmnzi_b:
3149   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
3150   // df/n format
3151   // These intrinsics take an unsigned 4 bit immediate.
3152   case Mips::BI__builtin_msa_copy_s_b:
3153   case Mips::BI__builtin_msa_copy_u_b:
3154   case Mips::BI__builtin_msa_insve_b:
3155   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
3156   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
3157   // These intrinsics take an unsigned 3 bit immediate.
3158   case Mips::BI__builtin_msa_copy_s_h:
3159   case Mips::BI__builtin_msa_copy_u_h:
3160   case Mips::BI__builtin_msa_insve_h:
3161   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
3162   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3163   // These intrinsics take an unsigned 2 bit immediate.
3164   case Mips::BI__builtin_msa_copy_s_w:
3165   case Mips::BI__builtin_msa_copy_u_w:
3166   case Mips::BI__builtin_msa_insve_w:
3167   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
3168   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3169   // These intrinsics take an unsigned 1 bit immediate.
3170   case Mips::BI__builtin_msa_copy_s_d:
3171   case Mips::BI__builtin_msa_copy_u_d:
3172   case Mips::BI__builtin_msa_insve_d:
3173   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
3174   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3175   // Memory offsets and immediate loads.
3176   // These intrinsics take a signed 10 bit immediate.
3177   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
3178   case Mips::BI__builtin_msa_ldi_h:
3179   case Mips::BI__builtin_msa_ldi_w:
3180   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
3181   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3182   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3183   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3184   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3185   case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break;
3186   case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break;
3187   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3188   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3189   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3190   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
3191   case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break;
3192   case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break;
3193   }
3194 
3195   if (!m)
3196     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3197 
3198   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3199          SemaBuiltinConstantArgMultiple(TheCall, i, m);
3200 }
3201 
3202 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str,
3203 /// advancing the pointer over the consumed characters. The decoded type is
3204 /// returned. If the decoded type represents a constant integer with a
3205 /// constraint on its value then Mask is set to that value. The type descriptors
3206 /// used in Str are specific to PPC MMA builtins and are documented in the file
3207 /// defining the PPC builtins.
3208 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str,
3209                                         unsigned &Mask) {
3210   bool RequireICE = false;
3211   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3212   switch (*Str++) {
3213   case 'V':
3214     return Context.getVectorType(Context.UnsignedCharTy, 16,
3215                                  VectorType::VectorKind::AltiVecVector);
3216   case 'i': {
3217     char *End;
3218     unsigned size = strtoul(Str, &End, 10);
3219     assert(End != Str && "Missing constant parameter constraint");
3220     Str = End;
3221     Mask = size;
3222     return Context.IntTy;
3223   }
3224   case 'W': {
3225     char *End;
3226     unsigned size = strtoul(Str, &End, 10);
3227     assert(End != Str && "Missing PowerPC MMA type size");
3228     Str = End;
3229     QualType Type;
3230     switch (size) {
3231   #define PPC_VECTOR_TYPE(typeName, Id, size) \
3232     case size: Type = Context.Id##Ty; break;
3233   #include "clang/Basic/PPCTypes.def"
3234     default: llvm_unreachable("Invalid PowerPC MMA vector type");
3235     }
3236     bool CheckVectorArgs = false;
3237     while (!CheckVectorArgs) {
3238       switch (*Str++) {
3239       case '*':
3240         Type = Context.getPointerType(Type);
3241         break;
3242       case 'C':
3243         Type = Type.withConst();
3244         break;
3245       default:
3246         CheckVectorArgs = true;
3247         --Str;
3248         break;
3249       }
3250     }
3251     return Type;
3252   }
3253   default:
3254     return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true);
3255   }
3256 }
3257 
3258 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3259                                        CallExpr *TheCall) {
3260   unsigned i = 0, l = 0, u = 0;
3261   bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
3262                       BuiltinID == PPC::BI__builtin_divdeu ||
3263                       BuiltinID == PPC::BI__builtin_bpermd;
3264   bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64;
3265   bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
3266                        BuiltinID == PPC::BI__builtin_divweu ||
3267                        BuiltinID == PPC::BI__builtin_divde ||
3268                        BuiltinID == PPC::BI__builtin_divdeu;
3269 
3270   if (Is64BitBltin && !IsTarget64Bit)
3271     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3272            << TheCall->getSourceRange();
3273 
3274   if ((IsBltinExtDiv && !TI.hasFeature("extdiv")) ||
3275       (BuiltinID == PPC::BI__builtin_bpermd && !TI.hasFeature("bpermd")))
3276     return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3277            << TheCall->getSourceRange();
3278 
3279   auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool {
3280     if (!TI.hasFeature("vsx"))
3281       return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3282              << TheCall->getSourceRange();
3283     return false;
3284   };
3285 
3286   switch (BuiltinID) {
3287   default: return false;
3288   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3289   case PPC::BI__builtin_altivec_crypto_vshasigmad:
3290     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3291            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3292   case PPC::BI__builtin_altivec_dss:
3293     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
3294   case PPC::BI__builtin_tbegin:
3295   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
3296   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
3297   case PPC::BI__builtin_tabortwc:
3298   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
3299   case PPC::BI__builtin_tabortwci:
3300   case PPC::BI__builtin_tabortdci:
3301     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3302            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
3303   case PPC::BI__builtin_altivec_dst:
3304   case PPC::BI__builtin_altivec_dstt:
3305   case PPC::BI__builtin_altivec_dstst:
3306   case PPC::BI__builtin_altivec_dststt:
3307     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
3308   case PPC::BI__builtin_vsx_xxpermdi:
3309   case PPC::BI__builtin_vsx_xxsldwi:
3310     return SemaBuiltinVSX(TheCall);
3311   case PPC::BI__builtin_unpack_vector_int128:
3312     return SemaVSXCheck(TheCall) ||
3313            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3314   case PPC::BI__builtin_pack_vector_int128:
3315     return SemaVSXCheck(TheCall);
3316   case PPC::BI__builtin_altivec_vgnb:
3317      return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7);
3318   case PPC::BI__builtin_altivec_vec_replace_elt:
3319   case PPC::BI__builtin_altivec_vec_replace_unaligned: {
3320     QualType VecTy = TheCall->getArg(0)->getType();
3321     QualType EltTy = TheCall->getArg(1)->getType();
3322     unsigned Width = Context.getIntWidth(EltTy);
3323     return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) ||
3324            !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy);
3325   }
3326   case PPC::BI__builtin_vsx_xxeval:
3327      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255);
3328   case PPC::BI__builtin_altivec_vsldbi:
3329      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3330   case PPC::BI__builtin_altivec_vsrdbi:
3331      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3332   case PPC::BI__builtin_vsx_xxpermx:
3333      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7);
3334 #define CUSTOM_BUILTIN(Name, Intr, Types, Acc) \
3335   case PPC::BI__builtin_##Name: \
3336     return SemaBuiltinPPCMMACall(TheCall, Types);
3337 #include "clang/Basic/BuiltinsPPC.def"
3338   }
3339   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3340 }
3341 
3342 // Check if the given type is a non-pointer PPC MMA type. This function is used
3343 // in Sema to prevent invalid uses of restricted PPC MMA types.
3344 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) {
3345   if (Type->isPointerType() || Type->isArrayType())
3346     return false;
3347 
3348   QualType CoreType = Type.getCanonicalType().getUnqualifiedType();
3349 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty
3350   if (false
3351 #include "clang/Basic/PPCTypes.def"
3352      ) {
3353     Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type);
3354     return true;
3355   }
3356   return false;
3357 }
3358 
3359 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID,
3360                                           CallExpr *TheCall) {
3361   // position of memory order and scope arguments in the builtin
3362   unsigned OrderIndex, ScopeIndex;
3363   switch (BuiltinID) {
3364   case AMDGPU::BI__builtin_amdgcn_atomic_inc32:
3365   case AMDGPU::BI__builtin_amdgcn_atomic_inc64:
3366   case AMDGPU::BI__builtin_amdgcn_atomic_dec32:
3367   case AMDGPU::BI__builtin_amdgcn_atomic_dec64:
3368     OrderIndex = 2;
3369     ScopeIndex = 3;
3370     break;
3371   case AMDGPU::BI__builtin_amdgcn_fence:
3372     OrderIndex = 0;
3373     ScopeIndex = 1;
3374     break;
3375   default:
3376     return false;
3377   }
3378 
3379   ExprResult Arg = TheCall->getArg(OrderIndex);
3380   auto ArgExpr = Arg.get();
3381   Expr::EvalResult ArgResult;
3382 
3383   if (!ArgExpr->EvaluateAsInt(ArgResult, Context))
3384     return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int)
3385            << ArgExpr->getType();
3386   auto Ord = ArgResult.Val.getInt().getZExtValue();
3387 
3388   // Check valididty of memory ordering as per C11 / C++11's memody model.
3389   // Only fence needs check. Atomic dec/inc allow all memory orders.
3390   if (!llvm::isValidAtomicOrderingCABI(Ord))
3391     return Diag(ArgExpr->getBeginLoc(),
3392                 diag::warn_atomic_op_has_invalid_memory_order)
3393            << ArgExpr->getSourceRange();
3394   switch (static_cast<llvm::AtomicOrderingCABI>(Ord)) {
3395   case llvm::AtomicOrderingCABI::relaxed:
3396   case llvm::AtomicOrderingCABI::consume:
3397     if (BuiltinID == AMDGPU::BI__builtin_amdgcn_fence)
3398       return Diag(ArgExpr->getBeginLoc(),
3399                   diag::warn_atomic_op_has_invalid_memory_order)
3400              << ArgExpr->getSourceRange();
3401     break;
3402   case llvm::AtomicOrderingCABI::acquire:
3403   case llvm::AtomicOrderingCABI::release:
3404   case llvm::AtomicOrderingCABI::acq_rel:
3405   case llvm::AtomicOrderingCABI::seq_cst:
3406     break;
3407   }
3408 
3409   Arg = TheCall->getArg(ScopeIndex);
3410   ArgExpr = Arg.get();
3411   Expr::EvalResult ArgResult1;
3412   // Check that sync scope is a constant literal
3413   if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context))
3414     return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal)
3415            << ArgExpr->getType();
3416 
3417   return false;
3418 }
3419 
3420 bool Sema::CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum) {
3421   llvm::APSInt Result;
3422 
3423   // We can't check the value of a dependent argument.
3424   Expr *Arg = TheCall->getArg(ArgNum);
3425   if (Arg->isTypeDependent() || Arg->isValueDependent())
3426     return false;
3427 
3428   // Check constant-ness first.
3429   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3430     return true;
3431 
3432   int64_t Val = Result.getSExtValue();
3433   if ((Val >= 0 && Val <= 3) || (Val >= 5 && Val <= 7))
3434     return false;
3435 
3436   return Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_invalid_lmul)
3437          << Arg->getSourceRange();
3438 }
3439 
3440 bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI,
3441                                          unsigned BuiltinID,
3442                                          CallExpr *TheCall) {
3443   // CodeGenFunction can also detect this, but this gives a better error
3444   // message.
3445   bool FeatureMissing = false;
3446   SmallVector<StringRef> ReqFeatures;
3447   StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID);
3448   Features.split(ReqFeatures, ',');
3449 
3450   // Check if each required feature is included
3451   for (StringRef F : ReqFeatures) {
3452     if (TI.hasFeature(F))
3453       continue;
3454 
3455     // If the feature is 64bit, alter the string so it will print better in
3456     // the diagnostic.
3457     if (F == "64bit")
3458       F = "RV64";
3459 
3460     // Convert features like "zbr" and "experimental-zbr" to "Zbr".
3461     F.consume_front("experimental-");
3462     std::string FeatureStr = F.str();
3463     FeatureStr[0] = std::toupper(FeatureStr[0]);
3464 
3465     // Error message
3466     FeatureMissing = true;
3467     Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_requires_extension)
3468         << TheCall->getSourceRange() << StringRef(FeatureStr);
3469   }
3470 
3471   if (FeatureMissing)
3472     return true;
3473 
3474   switch (BuiltinID) {
3475   case RISCV::BI__builtin_rvv_vsetvli:
3476     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3) ||
3477            CheckRISCVLMUL(TheCall, 2);
3478   case RISCV::BI__builtin_rvv_vsetvlimax:
3479     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3) ||
3480            CheckRISCVLMUL(TheCall, 1);
3481   }
3482 
3483   return false;
3484 }
3485 
3486 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3487                                            CallExpr *TheCall) {
3488   if (BuiltinID == SystemZ::BI__builtin_tabort) {
3489     Expr *Arg = TheCall->getArg(0);
3490     if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context))
3491       if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256)
3492         return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
3493                << Arg->getSourceRange();
3494   }
3495 
3496   // For intrinsics which take an immediate value as part of the instruction,
3497   // range check them here.
3498   unsigned i = 0, l = 0, u = 0;
3499   switch (BuiltinID) {
3500   default: return false;
3501   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3502   case SystemZ::BI__builtin_s390_verimb:
3503   case SystemZ::BI__builtin_s390_verimh:
3504   case SystemZ::BI__builtin_s390_verimf:
3505   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
3506   case SystemZ::BI__builtin_s390_vfaeb:
3507   case SystemZ::BI__builtin_s390_vfaeh:
3508   case SystemZ::BI__builtin_s390_vfaef:
3509   case SystemZ::BI__builtin_s390_vfaebs:
3510   case SystemZ::BI__builtin_s390_vfaehs:
3511   case SystemZ::BI__builtin_s390_vfaefs:
3512   case SystemZ::BI__builtin_s390_vfaezb:
3513   case SystemZ::BI__builtin_s390_vfaezh:
3514   case SystemZ::BI__builtin_s390_vfaezf:
3515   case SystemZ::BI__builtin_s390_vfaezbs:
3516   case SystemZ::BI__builtin_s390_vfaezhs:
3517   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
3518   case SystemZ::BI__builtin_s390_vfisb:
3519   case SystemZ::BI__builtin_s390_vfidb:
3520     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3521            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3522   case SystemZ::BI__builtin_s390_vftcisb:
3523   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3524   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3525   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3526   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3527   case SystemZ::BI__builtin_s390_vstrcb:
3528   case SystemZ::BI__builtin_s390_vstrch:
3529   case SystemZ::BI__builtin_s390_vstrcf:
3530   case SystemZ::BI__builtin_s390_vstrczb:
3531   case SystemZ::BI__builtin_s390_vstrczh:
3532   case SystemZ::BI__builtin_s390_vstrczf:
3533   case SystemZ::BI__builtin_s390_vstrcbs:
3534   case SystemZ::BI__builtin_s390_vstrchs:
3535   case SystemZ::BI__builtin_s390_vstrcfs:
3536   case SystemZ::BI__builtin_s390_vstrczbs:
3537   case SystemZ::BI__builtin_s390_vstrczhs:
3538   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
3539   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3540   case SystemZ::BI__builtin_s390_vfminsb:
3541   case SystemZ::BI__builtin_s390_vfmaxsb:
3542   case SystemZ::BI__builtin_s390_vfmindb:
3543   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
3544   case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
3545   case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
3546   }
3547   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3548 }
3549 
3550 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3551 /// This checks that the target supports __builtin_cpu_supports and
3552 /// that the string argument is constant and valid.
3553 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI,
3554                                    CallExpr *TheCall) {
3555   Expr *Arg = TheCall->getArg(0);
3556 
3557   // Check if the argument is a string literal.
3558   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3559     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3560            << Arg->getSourceRange();
3561 
3562   // Check the contents of the string.
3563   StringRef Feature =
3564       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3565   if (!TI.validateCpuSupports(Feature))
3566     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
3567            << Arg->getSourceRange();
3568   return false;
3569 }
3570 
3571 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3572 /// This checks that the target supports __builtin_cpu_is and
3573 /// that the string argument is constant and valid.
3574 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) {
3575   Expr *Arg = TheCall->getArg(0);
3576 
3577   // Check if the argument is a string literal.
3578   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3579     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3580            << Arg->getSourceRange();
3581 
3582   // Check the contents of the string.
3583   StringRef Feature =
3584       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3585   if (!TI.validateCpuIs(Feature))
3586     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
3587            << Arg->getSourceRange();
3588   return false;
3589 }
3590 
3591 // Check if the rounding mode is legal.
3592 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3593   // Indicates if this instruction has rounding control or just SAE.
3594   bool HasRC = false;
3595 
3596   unsigned ArgNum = 0;
3597   switch (BuiltinID) {
3598   default:
3599     return false;
3600   case X86::BI__builtin_ia32_vcvttsd2si32:
3601   case X86::BI__builtin_ia32_vcvttsd2si64:
3602   case X86::BI__builtin_ia32_vcvttsd2usi32:
3603   case X86::BI__builtin_ia32_vcvttsd2usi64:
3604   case X86::BI__builtin_ia32_vcvttss2si32:
3605   case X86::BI__builtin_ia32_vcvttss2si64:
3606   case X86::BI__builtin_ia32_vcvttss2usi32:
3607   case X86::BI__builtin_ia32_vcvttss2usi64:
3608     ArgNum = 1;
3609     break;
3610   case X86::BI__builtin_ia32_maxpd512:
3611   case X86::BI__builtin_ia32_maxps512:
3612   case X86::BI__builtin_ia32_minpd512:
3613   case X86::BI__builtin_ia32_minps512:
3614     ArgNum = 2;
3615     break;
3616   case X86::BI__builtin_ia32_cvtps2pd512_mask:
3617   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
3618   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
3619   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
3620   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
3621   case X86::BI__builtin_ia32_cvttps2dq512_mask:
3622   case X86::BI__builtin_ia32_cvttps2qq512_mask:
3623   case X86::BI__builtin_ia32_cvttps2udq512_mask:
3624   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
3625   case X86::BI__builtin_ia32_exp2pd_mask:
3626   case X86::BI__builtin_ia32_exp2ps_mask:
3627   case X86::BI__builtin_ia32_getexppd512_mask:
3628   case X86::BI__builtin_ia32_getexpps512_mask:
3629   case X86::BI__builtin_ia32_rcp28pd_mask:
3630   case X86::BI__builtin_ia32_rcp28ps_mask:
3631   case X86::BI__builtin_ia32_rsqrt28pd_mask:
3632   case X86::BI__builtin_ia32_rsqrt28ps_mask:
3633   case X86::BI__builtin_ia32_vcomisd:
3634   case X86::BI__builtin_ia32_vcomiss:
3635   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
3636     ArgNum = 3;
3637     break;
3638   case X86::BI__builtin_ia32_cmppd512_mask:
3639   case X86::BI__builtin_ia32_cmpps512_mask:
3640   case X86::BI__builtin_ia32_cmpsd_mask:
3641   case X86::BI__builtin_ia32_cmpss_mask:
3642   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
3643   case X86::BI__builtin_ia32_getexpsd128_round_mask:
3644   case X86::BI__builtin_ia32_getexpss128_round_mask:
3645   case X86::BI__builtin_ia32_getmantpd512_mask:
3646   case X86::BI__builtin_ia32_getmantps512_mask:
3647   case X86::BI__builtin_ia32_maxsd_round_mask:
3648   case X86::BI__builtin_ia32_maxss_round_mask:
3649   case X86::BI__builtin_ia32_minsd_round_mask:
3650   case X86::BI__builtin_ia32_minss_round_mask:
3651   case X86::BI__builtin_ia32_rcp28sd_round_mask:
3652   case X86::BI__builtin_ia32_rcp28ss_round_mask:
3653   case X86::BI__builtin_ia32_reducepd512_mask:
3654   case X86::BI__builtin_ia32_reduceps512_mask:
3655   case X86::BI__builtin_ia32_rndscalepd_mask:
3656   case X86::BI__builtin_ia32_rndscaleps_mask:
3657   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
3658   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
3659     ArgNum = 4;
3660     break;
3661   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3662   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3663   case X86::BI__builtin_ia32_fixupimmps512_mask:
3664   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3665   case X86::BI__builtin_ia32_fixupimmsd_mask:
3666   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3667   case X86::BI__builtin_ia32_fixupimmss_mask:
3668   case X86::BI__builtin_ia32_fixupimmss_maskz:
3669   case X86::BI__builtin_ia32_getmantsd_round_mask:
3670   case X86::BI__builtin_ia32_getmantss_round_mask:
3671   case X86::BI__builtin_ia32_rangepd512_mask:
3672   case X86::BI__builtin_ia32_rangeps512_mask:
3673   case X86::BI__builtin_ia32_rangesd128_round_mask:
3674   case X86::BI__builtin_ia32_rangess128_round_mask:
3675   case X86::BI__builtin_ia32_reducesd_mask:
3676   case X86::BI__builtin_ia32_reducess_mask:
3677   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3678   case X86::BI__builtin_ia32_rndscaless_round_mask:
3679     ArgNum = 5;
3680     break;
3681   case X86::BI__builtin_ia32_vcvtsd2si64:
3682   case X86::BI__builtin_ia32_vcvtsd2si32:
3683   case X86::BI__builtin_ia32_vcvtsd2usi32:
3684   case X86::BI__builtin_ia32_vcvtsd2usi64:
3685   case X86::BI__builtin_ia32_vcvtss2si32:
3686   case X86::BI__builtin_ia32_vcvtss2si64:
3687   case X86::BI__builtin_ia32_vcvtss2usi32:
3688   case X86::BI__builtin_ia32_vcvtss2usi64:
3689   case X86::BI__builtin_ia32_sqrtpd512:
3690   case X86::BI__builtin_ia32_sqrtps512:
3691     ArgNum = 1;
3692     HasRC = true;
3693     break;
3694   case X86::BI__builtin_ia32_addpd512:
3695   case X86::BI__builtin_ia32_addps512:
3696   case X86::BI__builtin_ia32_divpd512:
3697   case X86::BI__builtin_ia32_divps512:
3698   case X86::BI__builtin_ia32_mulpd512:
3699   case X86::BI__builtin_ia32_mulps512:
3700   case X86::BI__builtin_ia32_subpd512:
3701   case X86::BI__builtin_ia32_subps512:
3702   case X86::BI__builtin_ia32_cvtsi2sd64:
3703   case X86::BI__builtin_ia32_cvtsi2ss32:
3704   case X86::BI__builtin_ia32_cvtsi2ss64:
3705   case X86::BI__builtin_ia32_cvtusi2sd64:
3706   case X86::BI__builtin_ia32_cvtusi2ss32:
3707   case X86::BI__builtin_ia32_cvtusi2ss64:
3708     ArgNum = 2;
3709     HasRC = true;
3710     break;
3711   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
3712   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
3713   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
3714   case X86::BI__builtin_ia32_cvtpd2dq512_mask:
3715   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
3716   case X86::BI__builtin_ia32_cvtpd2udq512_mask:
3717   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
3718   case X86::BI__builtin_ia32_cvtps2dq512_mask:
3719   case X86::BI__builtin_ia32_cvtps2qq512_mask:
3720   case X86::BI__builtin_ia32_cvtps2udq512_mask:
3721   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
3722   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
3723   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
3724   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
3725   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
3726     ArgNum = 3;
3727     HasRC = true;
3728     break;
3729   case X86::BI__builtin_ia32_addss_round_mask:
3730   case X86::BI__builtin_ia32_addsd_round_mask:
3731   case X86::BI__builtin_ia32_divss_round_mask:
3732   case X86::BI__builtin_ia32_divsd_round_mask:
3733   case X86::BI__builtin_ia32_mulss_round_mask:
3734   case X86::BI__builtin_ia32_mulsd_round_mask:
3735   case X86::BI__builtin_ia32_subss_round_mask:
3736   case X86::BI__builtin_ia32_subsd_round_mask:
3737   case X86::BI__builtin_ia32_scalefpd512_mask:
3738   case X86::BI__builtin_ia32_scalefps512_mask:
3739   case X86::BI__builtin_ia32_scalefsd_round_mask:
3740   case X86::BI__builtin_ia32_scalefss_round_mask:
3741   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
3742   case X86::BI__builtin_ia32_sqrtsd_round_mask:
3743   case X86::BI__builtin_ia32_sqrtss_round_mask:
3744   case X86::BI__builtin_ia32_vfmaddsd3_mask:
3745   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
3746   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
3747   case X86::BI__builtin_ia32_vfmaddss3_mask:
3748   case X86::BI__builtin_ia32_vfmaddss3_maskz:
3749   case X86::BI__builtin_ia32_vfmaddss3_mask3:
3750   case X86::BI__builtin_ia32_vfmaddpd512_mask:
3751   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
3752   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
3753   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
3754   case X86::BI__builtin_ia32_vfmaddps512_mask:
3755   case X86::BI__builtin_ia32_vfmaddps512_maskz:
3756   case X86::BI__builtin_ia32_vfmaddps512_mask3:
3757   case X86::BI__builtin_ia32_vfmsubps512_mask3:
3758   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
3759   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
3760   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
3761   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
3762   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
3763   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
3764   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
3765   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
3766     ArgNum = 4;
3767     HasRC = true;
3768     break;
3769   }
3770 
3771   llvm::APSInt Result;
3772 
3773   // We can't check the value of a dependent argument.
3774   Expr *Arg = TheCall->getArg(ArgNum);
3775   if (Arg->isTypeDependent() || Arg->isValueDependent())
3776     return false;
3777 
3778   // Check constant-ness first.
3779   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3780     return true;
3781 
3782   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
3783   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
3784   // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
3785   // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
3786   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
3787       Result == 8/*ROUND_NO_EXC*/ ||
3788       (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
3789       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
3790     return false;
3791 
3792   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
3793          << Arg->getSourceRange();
3794 }
3795 
3796 // Check if the gather/scatter scale is legal.
3797 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
3798                                              CallExpr *TheCall) {
3799   unsigned ArgNum = 0;
3800   switch (BuiltinID) {
3801   default:
3802     return false;
3803   case X86::BI__builtin_ia32_gatherpfdpd:
3804   case X86::BI__builtin_ia32_gatherpfdps:
3805   case X86::BI__builtin_ia32_gatherpfqpd:
3806   case X86::BI__builtin_ia32_gatherpfqps:
3807   case X86::BI__builtin_ia32_scatterpfdpd:
3808   case X86::BI__builtin_ia32_scatterpfdps:
3809   case X86::BI__builtin_ia32_scatterpfqpd:
3810   case X86::BI__builtin_ia32_scatterpfqps:
3811     ArgNum = 3;
3812     break;
3813   case X86::BI__builtin_ia32_gatherd_pd:
3814   case X86::BI__builtin_ia32_gatherd_pd256:
3815   case X86::BI__builtin_ia32_gatherq_pd:
3816   case X86::BI__builtin_ia32_gatherq_pd256:
3817   case X86::BI__builtin_ia32_gatherd_ps:
3818   case X86::BI__builtin_ia32_gatherd_ps256:
3819   case X86::BI__builtin_ia32_gatherq_ps:
3820   case X86::BI__builtin_ia32_gatherq_ps256:
3821   case X86::BI__builtin_ia32_gatherd_q:
3822   case X86::BI__builtin_ia32_gatherd_q256:
3823   case X86::BI__builtin_ia32_gatherq_q:
3824   case X86::BI__builtin_ia32_gatherq_q256:
3825   case X86::BI__builtin_ia32_gatherd_d:
3826   case X86::BI__builtin_ia32_gatherd_d256:
3827   case X86::BI__builtin_ia32_gatherq_d:
3828   case X86::BI__builtin_ia32_gatherq_d256:
3829   case X86::BI__builtin_ia32_gather3div2df:
3830   case X86::BI__builtin_ia32_gather3div2di:
3831   case X86::BI__builtin_ia32_gather3div4df:
3832   case X86::BI__builtin_ia32_gather3div4di:
3833   case X86::BI__builtin_ia32_gather3div4sf:
3834   case X86::BI__builtin_ia32_gather3div4si:
3835   case X86::BI__builtin_ia32_gather3div8sf:
3836   case X86::BI__builtin_ia32_gather3div8si:
3837   case X86::BI__builtin_ia32_gather3siv2df:
3838   case X86::BI__builtin_ia32_gather3siv2di:
3839   case X86::BI__builtin_ia32_gather3siv4df:
3840   case X86::BI__builtin_ia32_gather3siv4di:
3841   case X86::BI__builtin_ia32_gather3siv4sf:
3842   case X86::BI__builtin_ia32_gather3siv4si:
3843   case X86::BI__builtin_ia32_gather3siv8sf:
3844   case X86::BI__builtin_ia32_gather3siv8si:
3845   case X86::BI__builtin_ia32_gathersiv8df:
3846   case X86::BI__builtin_ia32_gathersiv16sf:
3847   case X86::BI__builtin_ia32_gatherdiv8df:
3848   case X86::BI__builtin_ia32_gatherdiv16sf:
3849   case X86::BI__builtin_ia32_gathersiv8di:
3850   case X86::BI__builtin_ia32_gathersiv16si:
3851   case X86::BI__builtin_ia32_gatherdiv8di:
3852   case X86::BI__builtin_ia32_gatherdiv16si:
3853   case X86::BI__builtin_ia32_scatterdiv2df:
3854   case X86::BI__builtin_ia32_scatterdiv2di:
3855   case X86::BI__builtin_ia32_scatterdiv4df:
3856   case X86::BI__builtin_ia32_scatterdiv4di:
3857   case X86::BI__builtin_ia32_scatterdiv4sf:
3858   case X86::BI__builtin_ia32_scatterdiv4si:
3859   case X86::BI__builtin_ia32_scatterdiv8sf:
3860   case X86::BI__builtin_ia32_scatterdiv8si:
3861   case X86::BI__builtin_ia32_scattersiv2df:
3862   case X86::BI__builtin_ia32_scattersiv2di:
3863   case X86::BI__builtin_ia32_scattersiv4df:
3864   case X86::BI__builtin_ia32_scattersiv4di:
3865   case X86::BI__builtin_ia32_scattersiv4sf:
3866   case X86::BI__builtin_ia32_scattersiv4si:
3867   case X86::BI__builtin_ia32_scattersiv8sf:
3868   case X86::BI__builtin_ia32_scattersiv8si:
3869   case X86::BI__builtin_ia32_scattersiv8df:
3870   case X86::BI__builtin_ia32_scattersiv16sf:
3871   case X86::BI__builtin_ia32_scatterdiv8df:
3872   case X86::BI__builtin_ia32_scatterdiv16sf:
3873   case X86::BI__builtin_ia32_scattersiv8di:
3874   case X86::BI__builtin_ia32_scattersiv16si:
3875   case X86::BI__builtin_ia32_scatterdiv8di:
3876   case X86::BI__builtin_ia32_scatterdiv16si:
3877     ArgNum = 4;
3878     break;
3879   }
3880 
3881   llvm::APSInt Result;
3882 
3883   // We can't check the value of a dependent argument.
3884   Expr *Arg = TheCall->getArg(ArgNum);
3885   if (Arg->isTypeDependent() || Arg->isValueDependent())
3886     return false;
3887 
3888   // Check constant-ness first.
3889   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3890     return true;
3891 
3892   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
3893     return false;
3894 
3895   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
3896          << Arg->getSourceRange();
3897 }
3898 
3899 enum { TileRegLow = 0, TileRegHigh = 7 };
3900 
3901 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
3902                                              ArrayRef<int> ArgNums) {
3903   for (int ArgNum : ArgNums) {
3904     if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh))
3905       return true;
3906   }
3907   return false;
3908 }
3909 
3910 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall,
3911                                         ArrayRef<int> ArgNums) {
3912   // Because the max number of tile register is TileRegHigh + 1, so here we use
3913   // each bit to represent the usage of them in bitset.
3914   std::bitset<TileRegHigh + 1> ArgValues;
3915   for (int ArgNum : ArgNums) {
3916     Expr *Arg = TheCall->getArg(ArgNum);
3917     if (Arg->isTypeDependent() || Arg->isValueDependent())
3918       continue;
3919 
3920     llvm::APSInt Result;
3921     if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3922       return true;
3923     int ArgExtValue = Result.getExtValue();
3924     assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) &&
3925            "Incorrect tile register num.");
3926     if (ArgValues.test(ArgExtValue))
3927       return Diag(TheCall->getBeginLoc(),
3928                   diag::err_x86_builtin_tile_arg_duplicate)
3929              << TheCall->getArg(ArgNum)->getSourceRange();
3930     ArgValues.set(ArgExtValue);
3931   }
3932   return false;
3933 }
3934 
3935 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
3936                                                 ArrayRef<int> ArgNums) {
3937   return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) ||
3938          CheckX86BuiltinTileDuplicate(TheCall, ArgNums);
3939 }
3940 
3941 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) {
3942   switch (BuiltinID) {
3943   default:
3944     return false;
3945   case X86::BI__builtin_ia32_tileloadd64:
3946   case X86::BI__builtin_ia32_tileloaddt164:
3947   case X86::BI__builtin_ia32_tilestored64:
3948   case X86::BI__builtin_ia32_tilezero:
3949     return CheckX86BuiltinTileArgumentsRange(TheCall, 0);
3950   case X86::BI__builtin_ia32_tdpbssd:
3951   case X86::BI__builtin_ia32_tdpbsud:
3952   case X86::BI__builtin_ia32_tdpbusd:
3953   case X86::BI__builtin_ia32_tdpbuud:
3954   case X86::BI__builtin_ia32_tdpbf16ps:
3955     return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2});
3956   }
3957 }
3958 static bool isX86_32Builtin(unsigned BuiltinID) {
3959   // These builtins only work on x86-32 targets.
3960   switch (BuiltinID) {
3961   case X86::BI__builtin_ia32_readeflags_u32:
3962   case X86::BI__builtin_ia32_writeeflags_u32:
3963     return true;
3964   }
3965 
3966   return false;
3967 }
3968 
3969 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3970                                        CallExpr *TheCall) {
3971   if (BuiltinID == X86::BI__builtin_cpu_supports)
3972     return SemaBuiltinCpuSupports(*this, TI, TheCall);
3973 
3974   if (BuiltinID == X86::BI__builtin_cpu_is)
3975     return SemaBuiltinCpuIs(*this, TI, TheCall);
3976 
3977   // Check for 32-bit only builtins on a 64-bit target.
3978   const llvm::Triple &TT = TI.getTriple();
3979   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
3980     return Diag(TheCall->getCallee()->getBeginLoc(),
3981                 diag::err_32_bit_builtin_64_bit_tgt);
3982 
3983   // If the intrinsic has rounding or SAE make sure its valid.
3984   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
3985     return true;
3986 
3987   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
3988   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
3989     return true;
3990 
3991   // If the intrinsic has a tile arguments, make sure they are valid.
3992   if (CheckX86BuiltinTileArguments(BuiltinID, TheCall))
3993     return true;
3994 
3995   // For intrinsics which take an immediate value as part of the instruction,
3996   // range check them here.
3997   int i = 0, l = 0, u = 0;
3998   switch (BuiltinID) {
3999   default:
4000     return false;
4001   case X86::BI__builtin_ia32_vec_ext_v2si:
4002   case X86::BI__builtin_ia32_vec_ext_v2di:
4003   case X86::BI__builtin_ia32_vextractf128_pd256:
4004   case X86::BI__builtin_ia32_vextractf128_ps256:
4005   case X86::BI__builtin_ia32_vextractf128_si256:
4006   case X86::BI__builtin_ia32_extract128i256:
4007   case X86::BI__builtin_ia32_extractf64x4_mask:
4008   case X86::BI__builtin_ia32_extracti64x4_mask:
4009   case X86::BI__builtin_ia32_extractf32x8_mask:
4010   case X86::BI__builtin_ia32_extracti32x8_mask:
4011   case X86::BI__builtin_ia32_extractf64x2_256_mask:
4012   case X86::BI__builtin_ia32_extracti64x2_256_mask:
4013   case X86::BI__builtin_ia32_extractf32x4_256_mask:
4014   case X86::BI__builtin_ia32_extracti32x4_256_mask:
4015     i = 1; l = 0; u = 1;
4016     break;
4017   case X86::BI__builtin_ia32_vec_set_v2di:
4018   case X86::BI__builtin_ia32_vinsertf128_pd256:
4019   case X86::BI__builtin_ia32_vinsertf128_ps256:
4020   case X86::BI__builtin_ia32_vinsertf128_si256:
4021   case X86::BI__builtin_ia32_insert128i256:
4022   case X86::BI__builtin_ia32_insertf32x8:
4023   case X86::BI__builtin_ia32_inserti32x8:
4024   case X86::BI__builtin_ia32_insertf64x4:
4025   case X86::BI__builtin_ia32_inserti64x4:
4026   case X86::BI__builtin_ia32_insertf64x2_256:
4027   case X86::BI__builtin_ia32_inserti64x2_256:
4028   case X86::BI__builtin_ia32_insertf32x4_256:
4029   case X86::BI__builtin_ia32_inserti32x4_256:
4030     i = 2; l = 0; u = 1;
4031     break;
4032   case X86::BI__builtin_ia32_vpermilpd:
4033   case X86::BI__builtin_ia32_vec_ext_v4hi:
4034   case X86::BI__builtin_ia32_vec_ext_v4si:
4035   case X86::BI__builtin_ia32_vec_ext_v4sf:
4036   case X86::BI__builtin_ia32_vec_ext_v4di:
4037   case X86::BI__builtin_ia32_extractf32x4_mask:
4038   case X86::BI__builtin_ia32_extracti32x4_mask:
4039   case X86::BI__builtin_ia32_extractf64x2_512_mask:
4040   case X86::BI__builtin_ia32_extracti64x2_512_mask:
4041     i = 1; l = 0; u = 3;
4042     break;
4043   case X86::BI_mm_prefetch:
4044   case X86::BI__builtin_ia32_vec_ext_v8hi:
4045   case X86::BI__builtin_ia32_vec_ext_v8si:
4046     i = 1; l = 0; u = 7;
4047     break;
4048   case X86::BI__builtin_ia32_sha1rnds4:
4049   case X86::BI__builtin_ia32_blendpd:
4050   case X86::BI__builtin_ia32_shufpd:
4051   case X86::BI__builtin_ia32_vec_set_v4hi:
4052   case X86::BI__builtin_ia32_vec_set_v4si:
4053   case X86::BI__builtin_ia32_vec_set_v4di:
4054   case X86::BI__builtin_ia32_shuf_f32x4_256:
4055   case X86::BI__builtin_ia32_shuf_f64x2_256:
4056   case X86::BI__builtin_ia32_shuf_i32x4_256:
4057   case X86::BI__builtin_ia32_shuf_i64x2_256:
4058   case X86::BI__builtin_ia32_insertf64x2_512:
4059   case X86::BI__builtin_ia32_inserti64x2_512:
4060   case X86::BI__builtin_ia32_insertf32x4:
4061   case X86::BI__builtin_ia32_inserti32x4:
4062     i = 2; l = 0; u = 3;
4063     break;
4064   case X86::BI__builtin_ia32_vpermil2pd:
4065   case X86::BI__builtin_ia32_vpermil2pd256:
4066   case X86::BI__builtin_ia32_vpermil2ps:
4067   case X86::BI__builtin_ia32_vpermil2ps256:
4068     i = 3; l = 0; u = 3;
4069     break;
4070   case X86::BI__builtin_ia32_cmpb128_mask:
4071   case X86::BI__builtin_ia32_cmpw128_mask:
4072   case X86::BI__builtin_ia32_cmpd128_mask:
4073   case X86::BI__builtin_ia32_cmpq128_mask:
4074   case X86::BI__builtin_ia32_cmpb256_mask:
4075   case X86::BI__builtin_ia32_cmpw256_mask:
4076   case X86::BI__builtin_ia32_cmpd256_mask:
4077   case X86::BI__builtin_ia32_cmpq256_mask:
4078   case X86::BI__builtin_ia32_cmpb512_mask:
4079   case X86::BI__builtin_ia32_cmpw512_mask:
4080   case X86::BI__builtin_ia32_cmpd512_mask:
4081   case X86::BI__builtin_ia32_cmpq512_mask:
4082   case X86::BI__builtin_ia32_ucmpb128_mask:
4083   case X86::BI__builtin_ia32_ucmpw128_mask:
4084   case X86::BI__builtin_ia32_ucmpd128_mask:
4085   case X86::BI__builtin_ia32_ucmpq128_mask:
4086   case X86::BI__builtin_ia32_ucmpb256_mask:
4087   case X86::BI__builtin_ia32_ucmpw256_mask:
4088   case X86::BI__builtin_ia32_ucmpd256_mask:
4089   case X86::BI__builtin_ia32_ucmpq256_mask:
4090   case X86::BI__builtin_ia32_ucmpb512_mask:
4091   case X86::BI__builtin_ia32_ucmpw512_mask:
4092   case X86::BI__builtin_ia32_ucmpd512_mask:
4093   case X86::BI__builtin_ia32_ucmpq512_mask:
4094   case X86::BI__builtin_ia32_vpcomub:
4095   case X86::BI__builtin_ia32_vpcomuw:
4096   case X86::BI__builtin_ia32_vpcomud:
4097   case X86::BI__builtin_ia32_vpcomuq:
4098   case X86::BI__builtin_ia32_vpcomb:
4099   case X86::BI__builtin_ia32_vpcomw:
4100   case X86::BI__builtin_ia32_vpcomd:
4101   case X86::BI__builtin_ia32_vpcomq:
4102   case X86::BI__builtin_ia32_vec_set_v8hi:
4103   case X86::BI__builtin_ia32_vec_set_v8si:
4104     i = 2; l = 0; u = 7;
4105     break;
4106   case X86::BI__builtin_ia32_vpermilpd256:
4107   case X86::BI__builtin_ia32_roundps:
4108   case X86::BI__builtin_ia32_roundpd:
4109   case X86::BI__builtin_ia32_roundps256:
4110   case X86::BI__builtin_ia32_roundpd256:
4111   case X86::BI__builtin_ia32_getmantpd128_mask:
4112   case X86::BI__builtin_ia32_getmantpd256_mask:
4113   case X86::BI__builtin_ia32_getmantps128_mask:
4114   case X86::BI__builtin_ia32_getmantps256_mask:
4115   case X86::BI__builtin_ia32_getmantpd512_mask:
4116   case X86::BI__builtin_ia32_getmantps512_mask:
4117   case X86::BI__builtin_ia32_vec_ext_v16qi:
4118   case X86::BI__builtin_ia32_vec_ext_v16hi:
4119     i = 1; l = 0; u = 15;
4120     break;
4121   case X86::BI__builtin_ia32_pblendd128:
4122   case X86::BI__builtin_ia32_blendps:
4123   case X86::BI__builtin_ia32_blendpd256:
4124   case X86::BI__builtin_ia32_shufpd256:
4125   case X86::BI__builtin_ia32_roundss:
4126   case X86::BI__builtin_ia32_roundsd:
4127   case X86::BI__builtin_ia32_rangepd128_mask:
4128   case X86::BI__builtin_ia32_rangepd256_mask:
4129   case X86::BI__builtin_ia32_rangepd512_mask:
4130   case X86::BI__builtin_ia32_rangeps128_mask:
4131   case X86::BI__builtin_ia32_rangeps256_mask:
4132   case X86::BI__builtin_ia32_rangeps512_mask:
4133   case X86::BI__builtin_ia32_getmantsd_round_mask:
4134   case X86::BI__builtin_ia32_getmantss_round_mask:
4135   case X86::BI__builtin_ia32_vec_set_v16qi:
4136   case X86::BI__builtin_ia32_vec_set_v16hi:
4137     i = 2; l = 0; u = 15;
4138     break;
4139   case X86::BI__builtin_ia32_vec_ext_v32qi:
4140     i = 1; l = 0; u = 31;
4141     break;
4142   case X86::BI__builtin_ia32_cmpps:
4143   case X86::BI__builtin_ia32_cmpss:
4144   case X86::BI__builtin_ia32_cmppd:
4145   case X86::BI__builtin_ia32_cmpsd:
4146   case X86::BI__builtin_ia32_cmpps256:
4147   case X86::BI__builtin_ia32_cmppd256:
4148   case X86::BI__builtin_ia32_cmpps128_mask:
4149   case X86::BI__builtin_ia32_cmppd128_mask:
4150   case X86::BI__builtin_ia32_cmpps256_mask:
4151   case X86::BI__builtin_ia32_cmppd256_mask:
4152   case X86::BI__builtin_ia32_cmpps512_mask:
4153   case X86::BI__builtin_ia32_cmppd512_mask:
4154   case X86::BI__builtin_ia32_cmpsd_mask:
4155   case X86::BI__builtin_ia32_cmpss_mask:
4156   case X86::BI__builtin_ia32_vec_set_v32qi:
4157     i = 2; l = 0; u = 31;
4158     break;
4159   case X86::BI__builtin_ia32_permdf256:
4160   case X86::BI__builtin_ia32_permdi256:
4161   case X86::BI__builtin_ia32_permdf512:
4162   case X86::BI__builtin_ia32_permdi512:
4163   case X86::BI__builtin_ia32_vpermilps:
4164   case X86::BI__builtin_ia32_vpermilps256:
4165   case X86::BI__builtin_ia32_vpermilpd512:
4166   case X86::BI__builtin_ia32_vpermilps512:
4167   case X86::BI__builtin_ia32_pshufd:
4168   case X86::BI__builtin_ia32_pshufd256:
4169   case X86::BI__builtin_ia32_pshufd512:
4170   case X86::BI__builtin_ia32_pshufhw:
4171   case X86::BI__builtin_ia32_pshufhw256:
4172   case X86::BI__builtin_ia32_pshufhw512:
4173   case X86::BI__builtin_ia32_pshuflw:
4174   case X86::BI__builtin_ia32_pshuflw256:
4175   case X86::BI__builtin_ia32_pshuflw512:
4176   case X86::BI__builtin_ia32_vcvtps2ph:
4177   case X86::BI__builtin_ia32_vcvtps2ph_mask:
4178   case X86::BI__builtin_ia32_vcvtps2ph256:
4179   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
4180   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
4181   case X86::BI__builtin_ia32_rndscaleps_128_mask:
4182   case X86::BI__builtin_ia32_rndscalepd_128_mask:
4183   case X86::BI__builtin_ia32_rndscaleps_256_mask:
4184   case X86::BI__builtin_ia32_rndscalepd_256_mask:
4185   case X86::BI__builtin_ia32_rndscaleps_mask:
4186   case X86::BI__builtin_ia32_rndscalepd_mask:
4187   case X86::BI__builtin_ia32_reducepd128_mask:
4188   case X86::BI__builtin_ia32_reducepd256_mask:
4189   case X86::BI__builtin_ia32_reducepd512_mask:
4190   case X86::BI__builtin_ia32_reduceps128_mask:
4191   case X86::BI__builtin_ia32_reduceps256_mask:
4192   case X86::BI__builtin_ia32_reduceps512_mask:
4193   case X86::BI__builtin_ia32_prold512:
4194   case X86::BI__builtin_ia32_prolq512:
4195   case X86::BI__builtin_ia32_prold128:
4196   case X86::BI__builtin_ia32_prold256:
4197   case X86::BI__builtin_ia32_prolq128:
4198   case X86::BI__builtin_ia32_prolq256:
4199   case X86::BI__builtin_ia32_prord512:
4200   case X86::BI__builtin_ia32_prorq512:
4201   case X86::BI__builtin_ia32_prord128:
4202   case X86::BI__builtin_ia32_prord256:
4203   case X86::BI__builtin_ia32_prorq128:
4204   case X86::BI__builtin_ia32_prorq256:
4205   case X86::BI__builtin_ia32_fpclasspd128_mask:
4206   case X86::BI__builtin_ia32_fpclasspd256_mask:
4207   case X86::BI__builtin_ia32_fpclassps128_mask:
4208   case X86::BI__builtin_ia32_fpclassps256_mask:
4209   case X86::BI__builtin_ia32_fpclassps512_mask:
4210   case X86::BI__builtin_ia32_fpclasspd512_mask:
4211   case X86::BI__builtin_ia32_fpclasssd_mask:
4212   case X86::BI__builtin_ia32_fpclassss_mask:
4213   case X86::BI__builtin_ia32_pslldqi128_byteshift:
4214   case X86::BI__builtin_ia32_pslldqi256_byteshift:
4215   case X86::BI__builtin_ia32_pslldqi512_byteshift:
4216   case X86::BI__builtin_ia32_psrldqi128_byteshift:
4217   case X86::BI__builtin_ia32_psrldqi256_byteshift:
4218   case X86::BI__builtin_ia32_psrldqi512_byteshift:
4219   case X86::BI__builtin_ia32_kshiftliqi:
4220   case X86::BI__builtin_ia32_kshiftlihi:
4221   case X86::BI__builtin_ia32_kshiftlisi:
4222   case X86::BI__builtin_ia32_kshiftlidi:
4223   case X86::BI__builtin_ia32_kshiftriqi:
4224   case X86::BI__builtin_ia32_kshiftrihi:
4225   case X86::BI__builtin_ia32_kshiftrisi:
4226   case X86::BI__builtin_ia32_kshiftridi:
4227     i = 1; l = 0; u = 255;
4228     break;
4229   case X86::BI__builtin_ia32_vperm2f128_pd256:
4230   case X86::BI__builtin_ia32_vperm2f128_ps256:
4231   case X86::BI__builtin_ia32_vperm2f128_si256:
4232   case X86::BI__builtin_ia32_permti256:
4233   case X86::BI__builtin_ia32_pblendw128:
4234   case X86::BI__builtin_ia32_pblendw256:
4235   case X86::BI__builtin_ia32_blendps256:
4236   case X86::BI__builtin_ia32_pblendd256:
4237   case X86::BI__builtin_ia32_palignr128:
4238   case X86::BI__builtin_ia32_palignr256:
4239   case X86::BI__builtin_ia32_palignr512:
4240   case X86::BI__builtin_ia32_alignq512:
4241   case X86::BI__builtin_ia32_alignd512:
4242   case X86::BI__builtin_ia32_alignd128:
4243   case X86::BI__builtin_ia32_alignd256:
4244   case X86::BI__builtin_ia32_alignq128:
4245   case X86::BI__builtin_ia32_alignq256:
4246   case X86::BI__builtin_ia32_vcomisd:
4247   case X86::BI__builtin_ia32_vcomiss:
4248   case X86::BI__builtin_ia32_shuf_f32x4:
4249   case X86::BI__builtin_ia32_shuf_f64x2:
4250   case X86::BI__builtin_ia32_shuf_i32x4:
4251   case X86::BI__builtin_ia32_shuf_i64x2:
4252   case X86::BI__builtin_ia32_shufpd512:
4253   case X86::BI__builtin_ia32_shufps:
4254   case X86::BI__builtin_ia32_shufps256:
4255   case X86::BI__builtin_ia32_shufps512:
4256   case X86::BI__builtin_ia32_dbpsadbw128:
4257   case X86::BI__builtin_ia32_dbpsadbw256:
4258   case X86::BI__builtin_ia32_dbpsadbw512:
4259   case X86::BI__builtin_ia32_vpshldd128:
4260   case X86::BI__builtin_ia32_vpshldd256:
4261   case X86::BI__builtin_ia32_vpshldd512:
4262   case X86::BI__builtin_ia32_vpshldq128:
4263   case X86::BI__builtin_ia32_vpshldq256:
4264   case X86::BI__builtin_ia32_vpshldq512:
4265   case X86::BI__builtin_ia32_vpshldw128:
4266   case X86::BI__builtin_ia32_vpshldw256:
4267   case X86::BI__builtin_ia32_vpshldw512:
4268   case X86::BI__builtin_ia32_vpshrdd128:
4269   case X86::BI__builtin_ia32_vpshrdd256:
4270   case X86::BI__builtin_ia32_vpshrdd512:
4271   case X86::BI__builtin_ia32_vpshrdq128:
4272   case X86::BI__builtin_ia32_vpshrdq256:
4273   case X86::BI__builtin_ia32_vpshrdq512:
4274   case X86::BI__builtin_ia32_vpshrdw128:
4275   case X86::BI__builtin_ia32_vpshrdw256:
4276   case X86::BI__builtin_ia32_vpshrdw512:
4277     i = 2; l = 0; u = 255;
4278     break;
4279   case X86::BI__builtin_ia32_fixupimmpd512_mask:
4280   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
4281   case X86::BI__builtin_ia32_fixupimmps512_mask:
4282   case X86::BI__builtin_ia32_fixupimmps512_maskz:
4283   case X86::BI__builtin_ia32_fixupimmsd_mask:
4284   case X86::BI__builtin_ia32_fixupimmsd_maskz:
4285   case X86::BI__builtin_ia32_fixupimmss_mask:
4286   case X86::BI__builtin_ia32_fixupimmss_maskz:
4287   case X86::BI__builtin_ia32_fixupimmpd128_mask:
4288   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
4289   case X86::BI__builtin_ia32_fixupimmpd256_mask:
4290   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
4291   case X86::BI__builtin_ia32_fixupimmps128_mask:
4292   case X86::BI__builtin_ia32_fixupimmps128_maskz:
4293   case X86::BI__builtin_ia32_fixupimmps256_mask:
4294   case X86::BI__builtin_ia32_fixupimmps256_maskz:
4295   case X86::BI__builtin_ia32_pternlogd512_mask:
4296   case X86::BI__builtin_ia32_pternlogd512_maskz:
4297   case X86::BI__builtin_ia32_pternlogq512_mask:
4298   case X86::BI__builtin_ia32_pternlogq512_maskz:
4299   case X86::BI__builtin_ia32_pternlogd128_mask:
4300   case X86::BI__builtin_ia32_pternlogd128_maskz:
4301   case X86::BI__builtin_ia32_pternlogd256_mask:
4302   case X86::BI__builtin_ia32_pternlogd256_maskz:
4303   case X86::BI__builtin_ia32_pternlogq128_mask:
4304   case X86::BI__builtin_ia32_pternlogq128_maskz:
4305   case X86::BI__builtin_ia32_pternlogq256_mask:
4306   case X86::BI__builtin_ia32_pternlogq256_maskz:
4307     i = 3; l = 0; u = 255;
4308     break;
4309   case X86::BI__builtin_ia32_gatherpfdpd:
4310   case X86::BI__builtin_ia32_gatherpfdps:
4311   case X86::BI__builtin_ia32_gatherpfqpd:
4312   case X86::BI__builtin_ia32_gatherpfqps:
4313   case X86::BI__builtin_ia32_scatterpfdpd:
4314   case X86::BI__builtin_ia32_scatterpfdps:
4315   case X86::BI__builtin_ia32_scatterpfqpd:
4316   case X86::BI__builtin_ia32_scatterpfqps:
4317     i = 4; l = 2; u = 3;
4318     break;
4319   case X86::BI__builtin_ia32_reducesd_mask:
4320   case X86::BI__builtin_ia32_reducess_mask:
4321   case X86::BI__builtin_ia32_rndscalesd_round_mask:
4322   case X86::BI__builtin_ia32_rndscaless_round_mask:
4323     i = 4; l = 0; u = 255;
4324     break;
4325   }
4326 
4327   // Note that we don't force a hard error on the range check here, allowing
4328   // template-generated or macro-generated dead code to potentially have out-of-
4329   // range values. These need to code generate, but don't need to necessarily
4330   // make any sense. We use a warning that defaults to an error.
4331   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
4332 }
4333 
4334 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
4335 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
4336 /// Returns true when the format fits the function and the FormatStringInfo has
4337 /// been populated.
4338 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
4339                                FormatStringInfo *FSI) {
4340   FSI->HasVAListArg = Format->getFirstArg() == 0;
4341   FSI->FormatIdx = Format->getFormatIdx() - 1;
4342   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
4343 
4344   // The way the format attribute works in GCC, the implicit this argument
4345   // of member functions is counted. However, it doesn't appear in our own
4346   // lists, so decrement format_idx in that case.
4347   if (IsCXXMember) {
4348     if(FSI->FormatIdx == 0)
4349       return false;
4350     --FSI->FormatIdx;
4351     if (FSI->FirstDataArg != 0)
4352       --FSI->FirstDataArg;
4353   }
4354   return true;
4355 }
4356 
4357 /// Checks if a the given expression evaluates to null.
4358 ///
4359 /// Returns true if the value evaluates to null.
4360 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4361   // If the expression has non-null type, it doesn't evaluate to null.
4362   if (auto nullability
4363         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
4364     if (*nullability == NullabilityKind::NonNull)
4365       return false;
4366   }
4367 
4368   // As a special case, transparent unions initialized with zero are
4369   // considered null for the purposes of the nonnull attribute.
4370   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
4371     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
4372       if (const CompoundLiteralExpr *CLE =
4373           dyn_cast<CompoundLiteralExpr>(Expr))
4374         if (const InitListExpr *ILE =
4375             dyn_cast<InitListExpr>(CLE->getInitializer()))
4376           Expr = ILE->getInit(0);
4377   }
4378 
4379   bool Result;
4380   return (!Expr->isValueDependent() &&
4381           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
4382           !Result);
4383 }
4384 
4385 static void CheckNonNullArgument(Sema &S,
4386                                  const Expr *ArgExpr,
4387                                  SourceLocation CallSiteLoc) {
4388   if (CheckNonNullExpr(S, ArgExpr))
4389     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
4390                           S.PDiag(diag::warn_null_arg)
4391                               << ArgExpr->getSourceRange());
4392 }
4393 
4394 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
4395   FormatStringInfo FSI;
4396   if ((GetFormatStringType(Format) == FST_NSString) &&
4397       getFormatStringInfo(Format, false, &FSI)) {
4398     Idx = FSI.FormatIdx;
4399     return true;
4400   }
4401   return false;
4402 }
4403 
4404 /// Diagnose use of %s directive in an NSString which is being passed
4405 /// as formatting string to formatting method.
4406 static void
4407 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
4408                                         const NamedDecl *FDecl,
4409                                         Expr **Args,
4410                                         unsigned NumArgs) {
4411   unsigned Idx = 0;
4412   bool Format = false;
4413   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
4414   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
4415     Idx = 2;
4416     Format = true;
4417   }
4418   else
4419     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4420       if (S.GetFormatNSStringIdx(I, Idx)) {
4421         Format = true;
4422         break;
4423       }
4424     }
4425   if (!Format || NumArgs <= Idx)
4426     return;
4427   const Expr *FormatExpr = Args[Idx];
4428   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
4429     FormatExpr = CSCE->getSubExpr();
4430   const StringLiteral *FormatString;
4431   if (const ObjCStringLiteral *OSL =
4432       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
4433     FormatString = OSL->getString();
4434   else
4435     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
4436   if (!FormatString)
4437     return;
4438   if (S.FormatStringHasSArg(FormatString)) {
4439     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
4440       << "%s" << 1 << 1;
4441     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
4442       << FDecl->getDeclName();
4443   }
4444 }
4445 
4446 /// Determine whether the given type has a non-null nullability annotation.
4447 static bool isNonNullType(ASTContext &ctx, QualType type) {
4448   if (auto nullability = type->getNullability(ctx))
4449     return *nullability == NullabilityKind::NonNull;
4450 
4451   return false;
4452 }
4453 
4454 static void CheckNonNullArguments(Sema &S,
4455                                   const NamedDecl *FDecl,
4456                                   const FunctionProtoType *Proto,
4457                                   ArrayRef<const Expr *> Args,
4458                                   SourceLocation CallSiteLoc) {
4459   assert((FDecl || Proto) && "Need a function declaration or prototype");
4460 
4461   // Already checked by by constant evaluator.
4462   if (S.isConstantEvaluated())
4463     return;
4464   // Check the attributes attached to the method/function itself.
4465   llvm::SmallBitVector NonNullArgs;
4466   if (FDecl) {
4467     // Handle the nonnull attribute on the function/method declaration itself.
4468     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4469       if (!NonNull->args_size()) {
4470         // Easy case: all pointer arguments are nonnull.
4471         for (const auto *Arg : Args)
4472           if (S.isValidPointerAttrType(Arg->getType()))
4473             CheckNonNullArgument(S, Arg, CallSiteLoc);
4474         return;
4475       }
4476 
4477       for (const ParamIdx &Idx : NonNull->args()) {
4478         unsigned IdxAST = Idx.getASTIndex();
4479         if (IdxAST >= Args.size())
4480           continue;
4481         if (NonNullArgs.empty())
4482           NonNullArgs.resize(Args.size());
4483         NonNullArgs.set(IdxAST);
4484       }
4485     }
4486   }
4487 
4488   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4489     // Handle the nonnull attribute on the parameters of the
4490     // function/method.
4491     ArrayRef<ParmVarDecl*> parms;
4492     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4493       parms = FD->parameters();
4494     else
4495       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4496 
4497     unsigned ParamIndex = 0;
4498     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4499          I != E; ++I, ++ParamIndex) {
4500       const ParmVarDecl *PVD = *I;
4501       if (PVD->hasAttr<NonNullAttr>() ||
4502           isNonNullType(S.Context, PVD->getType())) {
4503         if (NonNullArgs.empty())
4504           NonNullArgs.resize(Args.size());
4505 
4506         NonNullArgs.set(ParamIndex);
4507       }
4508     }
4509   } else {
4510     // If we have a non-function, non-method declaration but no
4511     // function prototype, try to dig out the function prototype.
4512     if (!Proto) {
4513       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4514         QualType type = VD->getType().getNonReferenceType();
4515         if (auto pointerType = type->getAs<PointerType>())
4516           type = pointerType->getPointeeType();
4517         else if (auto blockType = type->getAs<BlockPointerType>())
4518           type = blockType->getPointeeType();
4519         // FIXME: data member pointers?
4520 
4521         // Dig out the function prototype, if there is one.
4522         Proto = type->getAs<FunctionProtoType>();
4523       }
4524     }
4525 
4526     // Fill in non-null argument information from the nullability
4527     // information on the parameter types (if we have them).
4528     if (Proto) {
4529       unsigned Index = 0;
4530       for (auto paramType : Proto->getParamTypes()) {
4531         if (isNonNullType(S.Context, paramType)) {
4532           if (NonNullArgs.empty())
4533             NonNullArgs.resize(Args.size());
4534 
4535           NonNullArgs.set(Index);
4536         }
4537 
4538         ++Index;
4539       }
4540     }
4541   }
4542 
4543   // Check for non-null arguments.
4544   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4545        ArgIndex != ArgIndexEnd; ++ArgIndex) {
4546     if (NonNullArgs[ArgIndex])
4547       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
4548   }
4549 }
4550 
4551 /// Warn if a pointer or reference argument passed to a function points to an
4552 /// object that is less aligned than the parameter. This can happen when
4553 /// creating a typedef with a lower alignment than the original type and then
4554 /// calling functions defined in terms of the original type.
4555 void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
4556                              StringRef ParamName, QualType ArgTy,
4557                              QualType ParamTy) {
4558 
4559   // If a function accepts a pointer or reference type
4560   if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
4561     return;
4562 
4563   // If the parameter is a pointer type, get the pointee type for the
4564   // argument too. If the parameter is a reference type, don't try to get
4565   // the pointee type for the argument.
4566   if (ParamTy->isPointerType())
4567     ArgTy = ArgTy->getPointeeType();
4568 
4569   // Remove reference or pointer
4570   ParamTy = ParamTy->getPointeeType();
4571 
4572   // Find expected alignment, and the actual alignment of the passed object.
4573   // getTypeAlignInChars requires complete types
4574   if (ParamTy->isIncompleteType() || ArgTy->isIncompleteType())
4575     return;
4576 
4577   CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
4578   CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
4579 
4580   // If the argument is less aligned than the parameter, there is a
4581   // potential alignment issue.
4582   if (ArgAlign < ParamAlign)
4583     Diag(Loc, diag::warn_param_mismatched_alignment)
4584         << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
4585         << ParamName << FDecl;
4586 }
4587 
4588 /// Handles the checks for format strings, non-POD arguments to vararg
4589 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
4590 /// attributes.
4591 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
4592                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
4593                      bool IsMemberFunction, SourceLocation Loc,
4594                      SourceRange Range, VariadicCallType CallType) {
4595   // FIXME: We should check as much as we can in the template definition.
4596   if (CurContext->isDependentContext())
4597     return;
4598 
4599   // Printf and scanf checking.
4600   llvm::SmallBitVector CheckedVarArgs;
4601   if (FDecl) {
4602     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4603       // Only create vector if there are format attributes.
4604       CheckedVarArgs.resize(Args.size());
4605 
4606       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4607                            CheckedVarArgs);
4608     }
4609   }
4610 
4611   // Refuse POD arguments that weren't caught by the format string
4612   // checks above.
4613   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4614   if (CallType != VariadicDoesNotApply &&
4615       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4616     unsigned NumParams = Proto ? Proto->getNumParams()
4617                        : FDecl && isa<FunctionDecl>(FDecl)
4618                            ? cast<FunctionDecl>(FDecl)->getNumParams()
4619                        : FDecl && isa<ObjCMethodDecl>(FDecl)
4620                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
4621                        : 0;
4622 
4623     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4624       // Args[ArgIdx] can be null in malformed code.
4625       if (const Expr *Arg = Args[ArgIdx]) {
4626         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4627           checkVariadicArgument(Arg, CallType);
4628       }
4629     }
4630   }
4631 
4632   if (FDecl || Proto) {
4633     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4634 
4635     // Type safety checking.
4636     if (FDecl) {
4637       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4638         CheckArgumentWithTypeTag(I, Args, Loc);
4639     }
4640   }
4641 
4642   // Check that passed arguments match the alignment of original arguments.
4643   // Try to get the missing prototype from the declaration.
4644   if (!Proto && FDecl) {
4645     const auto *FT = FDecl->getFunctionType();
4646     if (isa_and_nonnull<FunctionProtoType>(FT))
4647       Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
4648   }
4649   if (Proto) {
4650     // For variadic functions, we may have more args than parameters.
4651     // For some K&R functions, we may have less args than parameters.
4652     const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
4653     for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
4654       // Args[ArgIdx] can be null in malformed code.
4655       if (const Expr *Arg = Args[ArgIdx]) {
4656         QualType ParamTy = Proto->getParamType(ArgIdx);
4657         QualType ArgTy = Arg->getType();
4658         CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
4659                           ArgTy, ParamTy);
4660       }
4661     }
4662   }
4663 
4664   if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
4665     auto *AA = FDecl->getAttr<AllocAlignAttr>();
4666     const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
4667     if (!Arg->isValueDependent()) {
4668       Expr::EvalResult Align;
4669       if (Arg->EvaluateAsInt(Align, Context)) {
4670         const llvm::APSInt &I = Align.Val.getInt();
4671         if (!I.isPowerOf2())
4672           Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
4673               << Arg->getSourceRange();
4674 
4675         if (I > Sema::MaximumAlignment)
4676           Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
4677               << Arg->getSourceRange() << Sema::MaximumAlignment;
4678       }
4679     }
4680   }
4681 
4682   if (FD)
4683     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4684 }
4685 
4686 /// CheckConstructorCall - Check a constructor call for correctness and safety
4687 /// properties not enforced by the C type system.
4688 void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
4689                                 ArrayRef<const Expr *> Args,
4690                                 const FunctionProtoType *Proto,
4691                                 SourceLocation Loc) {
4692   VariadicCallType CallType =
4693       Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4694 
4695   auto *Ctor = cast<CXXConstructorDecl>(FDecl);
4696   CheckArgAlignment(Loc, FDecl, "'this'", Context.getPointerType(ThisType),
4697                     Context.getPointerType(Ctor->getThisObjectType()));
4698 
4699   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4700             Loc, SourceRange(), CallType);
4701 }
4702 
4703 /// CheckFunctionCall - Check a direct function call for various correctness
4704 /// and safety properties not strictly enforced by the C type system.
4705 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
4706                              const FunctionProtoType *Proto) {
4707   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4708                               isa<CXXMethodDecl>(FDecl);
4709   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4710                           IsMemberOperatorCall;
4711   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4712                                                   TheCall->getCallee());
4713   Expr** Args = TheCall->getArgs();
4714   unsigned NumArgs = TheCall->getNumArgs();
4715 
4716   Expr *ImplicitThis = nullptr;
4717   if (IsMemberOperatorCall) {
4718     // If this is a call to a member operator, hide the first argument
4719     // from checkCall.
4720     // FIXME: Our choice of AST representation here is less than ideal.
4721     ImplicitThis = Args[0];
4722     ++Args;
4723     --NumArgs;
4724   } else if (IsMemberFunction)
4725     ImplicitThis =
4726         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4727 
4728   if (ImplicitThis) {
4729     // ImplicitThis may or may not be a pointer, depending on whether . or -> is
4730     // used.
4731     QualType ThisType = ImplicitThis->getType();
4732     if (!ThisType->isPointerType()) {
4733       assert(!ThisType->isReferenceType());
4734       ThisType = Context.getPointerType(ThisType);
4735     }
4736 
4737     QualType ThisTypeFromDecl =
4738         Context.getPointerType(cast<CXXMethodDecl>(FDecl)->getThisObjectType());
4739 
4740     CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
4741                       ThisTypeFromDecl);
4742   }
4743 
4744   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
4745             IsMemberFunction, TheCall->getRParenLoc(),
4746             TheCall->getCallee()->getSourceRange(), CallType);
4747 
4748   IdentifierInfo *FnInfo = FDecl->getIdentifier();
4749   // None of the checks below are needed for functions that don't have
4750   // simple names (e.g., C++ conversion functions).
4751   if (!FnInfo)
4752     return false;
4753 
4754   CheckTCBEnforcement(TheCall, FDecl);
4755 
4756   CheckAbsoluteValueFunction(TheCall, FDecl);
4757   CheckMaxUnsignedZero(TheCall, FDecl);
4758 
4759   if (getLangOpts().ObjC)
4760     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
4761 
4762   unsigned CMId = FDecl->getMemoryFunctionKind();
4763 
4764   // Handle memory setting and copying functions.
4765   switch (CMId) {
4766   case 0:
4767     return false;
4768   case Builtin::BIstrlcpy: // fallthrough
4769   case Builtin::BIstrlcat:
4770     CheckStrlcpycatArguments(TheCall, FnInfo);
4771     break;
4772   case Builtin::BIstrncat:
4773     CheckStrncatArguments(TheCall, FnInfo);
4774     break;
4775   case Builtin::BIfree:
4776     CheckFreeArguments(TheCall);
4777     break;
4778   default:
4779     CheckMemaccessArguments(TheCall, CMId, FnInfo);
4780   }
4781 
4782   return false;
4783 }
4784 
4785 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
4786                                ArrayRef<const Expr *> Args) {
4787   VariadicCallType CallType =
4788       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
4789 
4790   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
4791             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
4792             CallType);
4793 
4794   return false;
4795 }
4796 
4797 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4798                             const FunctionProtoType *Proto) {
4799   QualType Ty;
4800   if (const auto *V = dyn_cast<VarDecl>(NDecl))
4801     Ty = V->getType().getNonReferenceType();
4802   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4803     Ty = F->getType().getNonReferenceType();
4804   else
4805     return false;
4806 
4807   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4808       !Ty->isFunctionProtoType())
4809     return false;
4810 
4811   VariadicCallType CallType;
4812   if (!Proto || !Proto->isVariadic()) {
4813     CallType = VariadicDoesNotApply;
4814   } else if (Ty->isBlockPointerType()) {
4815     CallType = VariadicBlock;
4816   } else { // Ty->isFunctionPointerType()
4817     CallType = VariadicFunction;
4818   }
4819 
4820   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4821             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4822             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4823             TheCall->getCallee()->getSourceRange(), CallType);
4824 
4825   return false;
4826 }
4827 
4828 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
4829 /// such as function pointers returned from functions.
4830 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4831   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4832                                                   TheCall->getCallee());
4833   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4834             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4835             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4836             TheCall->getCallee()->getSourceRange(), CallType);
4837 
4838   return false;
4839 }
4840 
4841 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4842   if (!llvm::isValidAtomicOrderingCABI(Ordering))
4843     return false;
4844 
4845   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4846   switch (Op) {
4847   case AtomicExpr::AO__c11_atomic_init:
4848   case AtomicExpr::AO__opencl_atomic_init:
4849     llvm_unreachable("There is no ordering argument for an init");
4850 
4851   case AtomicExpr::AO__c11_atomic_load:
4852   case AtomicExpr::AO__opencl_atomic_load:
4853   case AtomicExpr::AO__atomic_load_n:
4854   case AtomicExpr::AO__atomic_load:
4855     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4856            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4857 
4858   case AtomicExpr::AO__c11_atomic_store:
4859   case AtomicExpr::AO__opencl_atomic_store:
4860   case AtomicExpr::AO__atomic_store:
4861   case AtomicExpr::AO__atomic_store_n:
4862     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4863            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4864            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4865 
4866   default:
4867     return true;
4868   }
4869 }
4870 
4871 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
4872                                          AtomicExpr::AtomicOp Op) {
4873   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4874   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4875   MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
4876   return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
4877                          DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
4878                          Op);
4879 }
4880 
4881 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
4882                                  SourceLocation RParenLoc, MultiExprArg Args,
4883                                  AtomicExpr::AtomicOp Op,
4884                                  AtomicArgumentOrder ArgOrder) {
4885   // All the non-OpenCL operations take one of the following forms.
4886   // The OpenCL operations take the __c11 forms with one extra argument for
4887   // synchronization scope.
4888   enum {
4889     // C    __c11_atomic_init(A *, C)
4890     Init,
4891 
4892     // C    __c11_atomic_load(A *, int)
4893     Load,
4894 
4895     // void __atomic_load(A *, CP, int)
4896     LoadCopy,
4897 
4898     // void __atomic_store(A *, CP, int)
4899     Copy,
4900 
4901     // C    __c11_atomic_add(A *, M, int)
4902     Arithmetic,
4903 
4904     // C    __atomic_exchange_n(A *, CP, int)
4905     Xchg,
4906 
4907     // void __atomic_exchange(A *, C *, CP, int)
4908     GNUXchg,
4909 
4910     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4911     C11CmpXchg,
4912 
4913     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4914     GNUCmpXchg
4915   } Form = Init;
4916 
4917   const unsigned NumForm = GNUCmpXchg + 1;
4918   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
4919   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
4920   // where:
4921   //   C is an appropriate type,
4922   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4923   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4924   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4925   //   the int parameters are for orderings.
4926 
4927   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4928       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4929       "need to update code for modified forms");
4930   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
4931                     AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
4932                         AtomicExpr::AO__atomic_load,
4933                 "need to update code for modified C11 atomics");
4934   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
4935                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
4936   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
4937                Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
4938                IsOpenCL;
4939   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4940              Op == AtomicExpr::AO__atomic_store_n ||
4941              Op == AtomicExpr::AO__atomic_exchange_n ||
4942              Op == AtomicExpr::AO__atomic_compare_exchange_n;
4943   bool IsAddSub = false;
4944 
4945   switch (Op) {
4946   case AtomicExpr::AO__c11_atomic_init:
4947   case AtomicExpr::AO__opencl_atomic_init:
4948     Form = Init;
4949     break;
4950 
4951   case AtomicExpr::AO__c11_atomic_load:
4952   case AtomicExpr::AO__opencl_atomic_load:
4953   case AtomicExpr::AO__atomic_load_n:
4954     Form = Load;
4955     break;
4956 
4957   case AtomicExpr::AO__atomic_load:
4958     Form = LoadCopy;
4959     break;
4960 
4961   case AtomicExpr::AO__c11_atomic_store:
4962   case AtomicExpr::AO__opencl_atomic_store:
4963   case AtomicExpr::AO__atomic_store:
4964   case AtomicExpr::AO__atomic_store_n:
4965     Form = Copy;
4966     break;
4967 
4968   case AtomicExpr::AO__c11_atomic_fetch_add:
4969   case AtomicExpr::AO__c11_atomic_fetch_sub:
4970   case AtomicExpr::AO__opencl_atomic_fetch_add:
4971   case AtomicExpr::AO__opencl_atomic_fetch_sub:
4972   case AtomicExpr::AO__atomic_fetch_add:
4973   case AtomicExpr::AO__atomic_fetch_sub:
4974   case AtomicExpr::AO__atomic_add_fetch:
4975   case AtomicExpr::AO__atomic_sub_fetch:
4976     IsAddSub = true;
4977     Form = Arithmetic;
4978     break;
4979   case AtomicExpr::AO__c11_atomic_fetch_and:
4980   case AtomicExpr::AO__c11_atomic_fetch_or:
4981   case AtomicExpr::AO__c11_atomic_fetch_xor:
4982   case AtomicExpr::AO__opencl_atomic_fetch_and:
4983   case AtomicExpr::AO__opencl_atomic_fetch_or:
4984   case AtomicExpr::AO__opencl_atomic_fetch_xor:
4985   case AtomicExpr::AO__atomic_fetch_and:
4986   case AtomicExpr::AO__atomic_fetch_or:
4987   case AtomicExpr::AO__atomic_fetch_xor:
4988   case AtomicExpr::AO__atomic_fetch_nand:
4989   case AtomicExpr::AO__atomic_and_fetch:
4990   case AtomicExpr::AO__atomic_or_fetch:
4991   case AtomicExpr::AO__atomic_xor_fetch:
4992   case AtomicExpr::AO__atomic_nand_fetch:
4993     Form = Arithmetic;
4994     break;
4995   case AtomicExpr::AO__c11_atomic_fetch_min:
4996   case AtomicExpr::AO__c11_atomic_fetch_max:
4997   case AtomicExpr::AO__opencl_atomic_fetch_min:
4998   case AtomicExpr::AO__opencl_atomic_fetch_max:
4999   case AtomicExpr::AO__atomic_min_fetch:
5000   case AtomicExpr::AO__atomic_max_fetch:
5001   case AtomicExpr::AO__atomic_fetch_min:
5002   case AtomicExpr::AO__atomic_fetch_max:
5003     Form = Arithmetic;
5004     break;
5005 
5006   case AtomicExpr::AO__c11_atomic_exchange:
5007   case AtomicExpr::AO__opencl_atomic_exchange:
5008   case AtomicExpr::AO__atomic_exchange_n:
5009     Form = Xchg;
5010     break;
5011 
5012   case AtomicExpr::AO__atomic_exchange:
5013     Form = GNUXchg;
5014     break;
5015 
5016   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
5017   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
5018   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
5019   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
5020     Form = C11CmpXchg;
5021     break;
5022 
5023   case AtomicExpr::AO__atomic_compare_exchange:
5024   case AtomicExpr::AO__atomic_compare_exchange_n:
5025     Form = GNUCmpXchg;
5026     break;
5027   }
5028 
5029   unsigned AdjustedNumArgs = NumArgs[Form];
5030   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
5031     ++AdjustedNumArgs;
5032   // Check we have the right number of arguments.
5033   if (Args.size() < AdjustedNumArgs) {
5034     Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
5035         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5036         << ExprRange;
5037     return ExprError();
5038   } else if (Args.size() > AdjustedNumArgs) {
5039     Diag(Args[AdjustedNumArgs]->getBeginLoc(),
5040          diag::err_typecheck_call_too_many_args)
5041         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5042         << ExprRange;
5043     return ExprError();
5044   }
5045 
5046   // Inspect the first argument of the atomic operation.
5047   Expr *Ptr = Args[0];
5048   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
5049   if (ConvertedPtr.isInvalid())
5050     return ExprError();
5051 
5052   Ptr = ConvertedPtr.get();
5053   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
5054   if (!pointerType) {
5055     Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
5056         << Ptr->getType() << Ptr->getSourceRange();
5057     return ExprError();
5058   }
5059 
5060   // For a __c11 builtin, this should be a pointer to an _Atomic type.
5061   QualType AtomTy = pointerType->getPointeeType(); // 'A'
5062   QualType ValType = AtomTy; // 'C'
5063   if (IsC11) {
5064     if (!AtomTy->isAtomicType()) {
5065       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
5066           << Ptr->getType() << Ptr->getSourceRange();
5067       return ExprError();
5068     }
5069     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
5070         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
5071       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
5072           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
5073           << Ptr->getSourceRange();
5074       return ExprError();
5075     }
5076     ValType = AtomTy->castAs<AtomicType>()->getValueType();
5077   } else if (Form != Load && Form != LoadCopy) {
5078     if (ValType.isConstQualified()) {
5079       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
5080           << Ptr->getType() << Ptr->getSourceRange();
5081       return ExprError();
5082     }
5083   }
5084 
5085   // For an arithmetic operation, the implied arithmetic must be well-formed.
5086   if (Form == Arithmetic) {
5087     // gcc does not enforce these rules for GNU atomics, but we do so for
5088     // sanity.
5089     auto IsAllowedValueType = [&](QualType ValType) {
5090       if (ValType->isIntegerType())
5091         return true;
5092       if (ValType->isPointerType())
5093         return true;
5094       if (!ValType->isFloatingType())
5095         return false;
5096       // LLVM Parser does not allow atomicrmw with x86_fp80 type.
5097       if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
5098           &Context.getTargetInfo().getLongDoubleFormat() ==
5099               &llvm::APFloat::x87DoubleExtended())
5100         return false;
5101       return true;
5102     };
5103     if (IsAddSub && !IsAllowedValueType(ValType)) {
5104       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_ptr_or_fp)
5105           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5106       return ExprError();
5107     }
5108     if (!IsAddSub && !ValType->isIntegerType()) {
5109       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
5110           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5111       return ExprError();
5112     }
5113     if (IsC11 && ValType->isPointerType() &&
5114         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
5115                             diag::err_incomplete_type)) {
5116       return ExprError();
5117     }
5118   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
5119     // For __atomic_*_n operations, the value type must be a scalar integral or
5120     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
5121     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
5122         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5123     return ExprError();
5124   }
5125 
5126   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
5127       !AtomTy->isScalarType()) {
5128     // For GNU atomics, require a trivially-copyable type. This is not part of
5129     // the GNU atomics specification, but we enforce it for sanity.
5130     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
5131         << Ptr->getType() << Ptr->getSourceRange();
5132     return ExprError();
5133   }
5134 
5135   switch (ValType.getObjCLifetime()) {
5136   case Qualifiers::OCL_None:
5137   case Qualifiers::OCL_ExplicitNone:
5138     // okay
5139     break;
5140 
5141   case Qualifiers::OCL_Weak:
5142   case Qualifiers::OCL_Strong:
5143   case Qualifiers::OCL_Autoreleasing:
5144     // FIXME: Can this happen? By this point, ValType should be known
5145     // to be trivially copyable.
5146     Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
5147         << ValType << Ptr->getSourceRange();
5148     return ExprError();
5149   }
5150 
5151   // All atomic operations have an overload which takes a pointer to a volatile
5152   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
5153   // into the result or the other operands. Similarly atomic_load takes a
5154   // pointer to a const 'A'.
5155   ValType.removeLocalVolatile();
5156   ValType.removeLocalConst();
5157   QualType ResultType = ValType;
5158   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
5159       Form == Init)
5160     ResultType = Context.VoidTy;
5161   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
5162     ResultType = Context.BoolTy;
5163 
5164   // The type of a parameter passed 'by value'. In the GNU atomics, such
5165   // arguments are actually passed as pointers.
5166   QualType ByValType = ValType; // 'CP'
5167   bool IsPassedByAddress = false;
5168   if (!IsC11 && !IsN) {
5169     ByValType = Ptr->getType();
5170     IsPassedByAddress = true;
5171   }
5172 
5173   SmallVector<Expr *, 5> APIOrderedArgs;
5174   if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
5175     APIOrderedArgs.push_back(Args[0]);
5176     switch (Form) {
5177     case Init:
5178     case Load:
5179       APIOrderedArgs.push_back(Args[1]); // Val1/Order
5180       break;
5181     case LoadCopy:
5182     case Copy:
5183     case Arithmetic:
5184     case Xchg:
5185       APIOrderedArgs.push_back(Args[2]); // Val1
5186       APIOrderedArgs.push_back(Args[1]); // Order
5187       break;
5188     case GNUXchg:
5189       APIOrderedArgs.push_back(Args[2]); // Val1
5190       APIOrderedArgs.push_back(Args[3]); // Val2
5191       APIOrderedArgs.push_back(Args[1]); // Order
5192       break;
5193     case C11CmpXchg:
5194       APIOrderedArgs.push_back(Args[2]); // Val1
5195       APIOrderedArgs.push_back(Args[4]); // Val2
5196       APIOrderedArgs.push_back(Args[1]); // Order
5197       APIOrderedArgs.push_back(Args[3]); // OrderFail
5198       break;
5199     case GNUCmpXchg:
5200       APIOrderedArgs.push_back(Args[2]); // Val1
5201       APIOrderedArgs.push_back(Args[4]); // Val2
5202       APIOrderedArgs.push_back(Args[5]); // Weak
5203       APIOrderedArgs.push_back(Args[1]); // Order
5204       APIOrderedArgs.push_back(Args[3]); // OrderFail
5205       break;
5206     }
5207   } else
5208     APIOrderedArgs.append(Args.begin(), Args.end());
5209 
5210   // The first argument's non-CV pointer type is used to deduce the type of
5211   // subsequent arguments, except for:
5212   //  - weak flag (always converted to bool)
5213   //  - memory order (always converted to int)
5214   //  - scope  (always converted to int)
5215   for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
5216     QualType Ty;
5217     if (i < NumVals[Form] + 1) {
5218       switch (i) {
5219       case 0:
5220         // The first argument is always a pointer. It has a fixed type.
5221         // It is always dereferenced, a nullptr is undefined.
5222         CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5223         // Nothing else to do: we already know all we want about this pointer.
5224         continue;
5225       case 1:
5226         // The second argument is the non-atomic operand. For arithmetic, this
5227         // is always passed by value, and for a compare_exchange it is always
5228         // passed by address. For the rest, GNU uses by-address and C11 uses
5229         // by-value.
5230         assert(Form != Load);
5231         if (Form == Arithmetic && ValType->isPointerType())
5232           Ty = Context.getPointerDiffType();
5233         else if (Form == Init || Form == Arithmetic)
5234           Ty = ValType;
5235         else if (Form == Copy || Form == Xchg) {
5236           if (IsPassedByAddress) {
5237             // The value pointer is always dereferenced, a nullptr is undefined.
5238             CheckNonNullArgument(*this, APIOrderedArgs[i],
5239                                  ExprRange.getBegin());
5240           }
5241           Ty = ByValType;
5242         } else {
5243           Expr *ValArg = APIOrderedArgs[i];
5244           // The value pointer is always dereferenced, a nullptr is undefined.
5245           CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
5246           LangAS AS = LangAS::Default;
5247           // Keep address space of non-atomic pointer type.
5248           if (const PointerType *PtrTy =
5249                   ValArg->getType()->getAs<PointerType>()) {
5250             AS = PtrTy->getPointeeType().getAddressSpace();
5251           }
5252           Ty = Context.getPointerType(
5253               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
5254         }
5255         break;
5256       case 2:
5257         // The third argument to compare_exchange / GNU exchange is the desired
5258         // value, either by-value (for the C11 and *_n variant) or as a pointer.
5259         if (IsPassedByAddress)
5260           CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5261         Ty = ByValType;
5262         break;
5263       case 3:
5264         // The fourth argument to GNU compare_exchange is a 'weak' flag.
5265         Ty = Context.BoolTy;
5266         break;
5267       }
5268     } else {
5269       // The order(s) and scope are always converted to int.
5270       Ty = Context.IntTy;
5271     }
5272 
5273     InitializedEntity Entity =
5274         InitializedEntity::InitializeParameter(Context, Ty, false);
5275     ExprResult Arg = APIOrderedArgs[i];
5276     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5277     if (Arg.isInvalid())
5278       return true;
5279     APIOrderedArgs[i] = Arg.get();
5280   }
5281 
5282   // Permute the arguments into a 'consistent' order.
5283   SmallVector<Expr*, 5> SubExprs;
5284   SubExprs.push_back(Ptr);
5285   switch (Form) {
5286   case Init:
5287     // Note, AtomicExpr::getVal1() has a special case for this atomic.
5288     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5289     break;
5290   case Load:
5291     SubExprs.push_back(APIOrderedArgs[1]); // Order
5292     break;
5293   case LoadCopy:
5294   case Copy:
5295   case Arithmetic:
5296   case Xchg:
5297     SubExprs.push_back(APIOrderedArgs[2]); // Order
5298     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5299     break;
5300   case GNUXchg:
5301     // Note, AtomicExpr::getVal2() has a special case for this atomic.
5302     SubExprs.push_back(APIOrderedArgs[3]); // Order
5303     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5304     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5305     break;
5306   case C11CmpXchg:
5307     SubExprs.push_back(APIOrderedArgs[3]); // Order
5308     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5309     SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
5310     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5311     break;
5312   case GNUCmpXchg:
5313     SubExprs.push_back(APIOrderedArgs[4]); // Order
5314     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5315     SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
5316     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5317     SubExprs.push_back(APIOrderedArgs[3]); // Weak
5318     break;
5319   }
5320 
5321   if (SubExprs.size() >= 2 && Form != Init) {
5322     if (Optional<llvm::APSInt> Result =
5323             SubExprs[1]->getIntegerConstantExpr(Context))
5324       if (!isValidOrderingForOp(Result->getSExtValue(), Op))
5325         Diag(SubExprs[1]->getBeginLoc(),
5326              diag::warn_atomic_op_has_invalid_memory_order)
5327             << SubExprs[1]->getSourceRange();
5328   }
5329 
5330   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
5331     auto *Scope = Args[Args.size() - 1];
5332     if (Optional<llvm::APSInt> Result =
5333             Scope->getIntegerConstantExpr(Context)) {
5334       if (!ScopeModel->isValid(Result->getZExtValue()))
5335         Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
5336             << Scope->getSourceRange();
5337     }
5338     SubExprs.push_back(Scope);
5339   }
5340 
5341   AtomicExpr *AE = new (Context)
5342       AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
5343 
5344   if ((Op == AtomicExpr::AO__c11_atomic_load ||
5345        Op == AtomicExpr::AO__c11_atomic_store ||
5346        Op == AtomicExpr::AO__opencl_atomic_load ||
5347        Op == AtomicExpr::AO__opencl_atomic_store ) &&
5348       Context.AtomicUsesUnsupportedLibcall(AE))
5349     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
5350         << ((Op == AtomicExpr::AO__c11_atomic_load ||
5351              Op == AtomicExpr::AO__opencl_atomic_load)
5352                 ? 0
5353                 : 1);
5354 
5355   if (ValType->isExtIntType()) {
5356     Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_ext_int_prohibit);
5357     return ExprError();
5358   }
5359 
5360   return AE;
5361 }
5362 
5363 /// checkBuiltinArgument - Given a call to a builtin function, perform
5364 /// normal type-checking on the given argument, updating the call in
5365 /// place.  This is useful when a builtin function requires custom
5366 /// type-checking for some of its arguments but not necessarily all of
5367 /// them.
5368 ///
5369 /// Returns true on error.
5370 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
5371   FunctionDecl *Fn = E->getDirectCallee();
5372   assert(Fn && "builtin call without direct callee!");
5373 
5374   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
5375   InitializedEntity Entity =
5376     InitializedEntity::InitializeParameter(S.Context, Param);
5377 
5378   ExprResult Arg = E->getArg(0);
5379   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
5380   if (Arg.isInvalid())
5381     return true;
5382 
5383   E->setArg(ArgIndex, Arg.get());
5384   return false;
5385 }
5386 
5387 /// We have a call to a function like __sync_fetch_and_add, which is an
5388 /// overloaded function based on the pointer type of its first argument.
5389 /// The main BuildCallExpr routines have already promoted the types of
5390 /// arguments because all of these calls are prototyped as void(...).
5391 ///
5392 /// This function goes through and does final semantic checking for these
5393 /// builtins, as well as generating any warnings.
5394 ExprResult
5395 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
5396   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
5397   Expr *Callee = TheCall->getCallee();
5398   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
5399   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5400 
5401   // Ensure that we have at least one argument to do type inference from.
5402   if (TheCall->getNumArgs() < 1) {
5403     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5404         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
5405     return ExprError();
5406   }
5407 
5408   // Inspect the first argument of the atomic builtin.  This should always be
5409   // a pointer type, whose element is an integral scalar or pointer type.
5410   // Because it is a pointer type, we don't have to worry about any implicit
5411   // casts here.
5412   // FIXME: We don't allow floating point scalars as input.
5413   Expr *FirstArg = TheCall->getArg(0);
5414   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
5415   if (FirstArgResult.isInvalid())
5416     return ExprError();
5417   FirstArg = FirstArgResult.get();
5418   TheCall->setArg(0, FirstArg);
5419 
5420   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5421   if (!pointerType) {
5422     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
5423         << FirstArg->getType() << FirstArg->getSourceRange();
5424     return ExprError();
5425   }
5426 
5427   QualType ValType = pointerType->getPointeeType();
5428   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5429       !ValType->isBlockPointerType()) {
5430     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
5431         << FirstArg->getType() << FirstArg->getSourceRange();
5432     return ExprError();
5433   }
5434 
5435   if (ValType.isConstQualified()) {
5436     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
5437         << FirstArg->getType() << FirstArg->getSourceRange();
5438     return ExprError();
5439   }
5440 
5441   switch (ValType.getObjCLifetime()) {
5442   case Qualifiers::OCL_None:
5443   case Qualifiers::OCL_ExplicitNone:
5444     // okay
5445     break;
5446 
5447   case Qualifiers::OCL_Weak:
5448   case Qualifiers::OCL_Strong:
5449   case Qualifiers::OCL_Autoreleasing:
5450     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
5451         << ValType << FirstArg->getSourceRange();
5452     return ExprError();
5453   }
5454 
5455   // Strip any qualifiers off ValType.
5456   ValType = ValType.getUnqualifiedType();
5457 
5458   // The majority of builtins return a value, but a few have special return
5459   // types, so allow them to override appropriately below.
5460   QualType ResultType = ValType;
5461 
5462   // We need to figure out which concrete builtin this maps onto.  For example,
5463   // __sync_fetch_and_add with a 2 byte object turns into
5464   // __sync_fetch_and_add_2.
5465 #define BUILTIN_ROW(x) \
5466   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5467     Builtin::BI##x##_8, Builtin::BI##x##_16 }
5468 
5469   static const unsigned BuiltinIndices[][5] = {
5470     BUILTIN_ROW(__sync_fetch_and_add),
5471     BUILTIN_ROW(__sync_fetch_and_sub),
5472     BUILTIN_ROW(__sync_fetch_and_or),
5473     BUILTIN_ROW(__sync_fetch_and_and),
5474     BUILTIN_ROW(__sync_fetch_and_xor),
5475     BUILTIN_ROW(__sync_fetch_and_nand),
5476 
5477     BUILTIN_ROW(__sync_add_and_fetch),
5478     BUILTIN_ROW(__sync_sub_and_fetch),
5479     BUILTIN_ROW(__sync_and_and_fetch),
5480     BUILTIN_ROW(__sync_or_and_fetch),
5481     BUILTIN_ROW(__sync_xor_and_fetch),
5482     BUILTIN_ROW(__sync_nand_and_fetch),
5483 
5484     BUILTIN_ROW(__sync_val_compare_and_swap),
5485     BUILTIN_ROW(__sync_bool_compare_and_swap),
5486     BUILTIN_ROW(__sync_lock_test_and_set),
5487     BUILTIN_ROW(__sync_lock_release),
5488     BUILTIN_ROW(__sync_swap)
5489   };
5490 #undef BUILTIN_ROW
5491 
5492   // Determine the index of the size.
5493   unsigned SizeIndex;
5494   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
5495   case 1: SizeIndex = 0; break;
5496   case 2: SizeIndex = 1; break;
5497   case 4: SizeIndex = 2; break;
5498   case 8: SizeIndex = 3; break;
5499   case 16: SizeIndex = 4; break;
5500   default:
5501     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
5502         << FirstArg->getType() << FirstArg->getSourceRange();
5503     return ExprError();
5504   }
5505 
5506   // Each of these builtins has one pointer argument, followed by some number of
5507   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5508   // that we ignore.  Find out which row of BuiltinIndices to read from as well
5509   // as the number of fixed args.
5510   unsigned BuiltinID = FDecl->getBuiltinID();
5511   unsigned BuiltinIndex, NumFixed = 1;
5512   bool WarnAboutSemanticsChange = false;
5513   switch (BuiltinID) {
5514   default: llvm_unreachable("Unknown overloaded atomic builtin!");
5515   case Builtin::BI__sync_fetch_and_add:
5516   case Builtin::BI__sync_fetch_and_add_1:
5517   case Builtin::BI__sync_fetch_and_add_2:
5518   case Builtin::BI__sync_fetch_and_add_4:
5519   case Builtin::BI__sync_fetch_and_add_8:
5520   case Builtin::BI__sync_fetch_and_add_16:
5521     BuiltinIndex = 0;
5522     break;
5523 
5524   case Builtin::BI__sync_fetch_and_sub:
5525   case Builtin::BI__sync_fetch_and_sub_1:
5526   case Builtin::BI__sync_fetch_and_sub_2:
5527   case Builtin::BI__sync_fetch_and_sub_4:
5528   case Builtin::BI__sync_fetch_and_sub_8:
5529   case Builtin::BI__sync_fetch_and_sub_16:
5530     BuiltinIndex = 1;
5531     break;
5532 
5533   case Builtin::BI__sync_fetch_and_or:
5534   case Builtin::BI__sync_fetch_and_or_1:
5535   case Builtin::BI__sync_fetch_and_or_2:
5536   case Builtin::BI__sync_fetch_and_or_4:
5537   case Builtin::BI__sync_fetch_and_or_8:
5538   case Builtin::BI__sync_fetch_and_or_16:
5539     BuiltinIndex = 2;
5540     break;
5541 
5542   case Builtin::BI__sync_fetch_and_and:
5543   case Builtin::BI__sync_fetch_and_and_1:
5544   case Builtin::BI__sync_fetch_and_and_2:
5545   case Builtin::BI__sync_fetch_and_and_4:
5546   case Builtin::BI__sync_fetch_and_and_8:
5547   case Builtin::BI__sync_fetch_and_and_16:
5548     BuiltinIndex = 3;
5549     break;
5550 
5551   case Builtin::BI__sync_fetch_and_xor:
5552   case Builtin::BI__sync_fetch_and_xor_1:
5553   case Builtin::BI__sync_fetch_and_xor_2:
5554   case Builtin::BI__sync_fetch_and_xor_4:
5555   case Builtin::BI__sync_fetch_and_xor_8:
5556   case Builtin::BI__sync_fetch_and_xor_16:
5557     BuiltinIndex = 4;
5558     break;
5559 
5560   case Builtin::BI__sync_fetch_and_nand:
5561   case Builtin::BI__sync_fetch_and_nand_1:
5562   case Builtin::BI__sync_fetch_and_nand_2:
5563   case Builtin::BI__sync_fetch_and_nand_4:
5564   case Builtin::BI__sync_fetch_and_nand_8:
5565   case Builtin::BI__sync_fetch_and_nand_16:
5566     BuiltinIndex = 5;
5567     WarnAboutSemanticsChange = true;
5568     break;
5569 
5570   case Builtin::BI__sync_add_and_fetch:
5571   case Builtin::BI__sync_add_and_fetch_1:
5572   case Builtin::BI__sync_add_and_fetch_2:
5573   case Builtin::BI__sync_add_and_fetch_4:
5574   case Builtin::BI__sync_add_and_fetch_8:
5575   case Builtin::BI__sync_add_and_fetch_16:
5576     BuiltinIndex = 6;
5577     break;
5578 
5579   case Builtin::BI__sync_sub_and_fetch:
5580   case Builtin::BI__sync_sub_and_fetch_1:
5581   case Builtin::BI__sync_sub_and_fetch_2:
5582   case Builtin::BI__sync_sub_and_fetch_4:
5583   case Builtin::BI__sync_sub_and_fetch_8:
5584   case Builtin::BI__sync_sub_and_fetch_16:
5585     BuiltinIndex = 7;
5586     break;
5587 
5588   case Builtin::BI__sync_and_and_fetch:
5589   case Builtin::BI__sync_and_and_fetch_1:
5590   case Builtin::BI__sync_and_and_fetch_2:
5591   case Builtin::BI__sync_and_and_fetch_4:
5592   case Builtin::BI__sync_and_and_fetch_8:
5593   case Builtin::BI__sync_and_and_fetch_16:
5594     BuiltinIndex = 8;
5595     break;
5596 
5597   case Builtin::BI__sync_or_and_fetch:
5598   case Builtin::BI__sync_or_and_fetch_1:
5599   case Builtin::BI__sync_or_and_fetch_2:
5600   case Builtin::BI__sync_or_and_fetch_4:
5601   case Builtin::BI__sync_or_and_fetch_8:
5602   case Builtin::BI__sync_or_and_fetch_16:
5603     BuiltinIndex = 9;
5604     break;
5605 
5606   case Builtin::BI__sync_xor_and_fetch:
5607   case Builtin::BI__sync_xor_and_fetch_1:
5608   case Builtin::BI__sync_xor_and_fetch_2:
5609   case Builtin::BI__sync_xor_and_fetch_4:
5610   case Builtin::BI__sync_xor_and_fetch_8:
5611   case Builtin::BI__sync_xor_and_fetch_16:
5612     BuiltinIndex = 10;
5613     break;
5614 
5615   case Builtin::BI__sync_nand_and_fetch:
5616   case Builtin::BI__sync_nand_and_fetch_1:
5617   case Builtin::BI__sync_nand_and_fetch_2:
5618   case Builtin::BI__sync_nand_and_fetch_4:
5619   case Builtin::BI__sync_nand_and_fetch_8:
5620   case Builtin::BI__sync_nand_and_fetch_16:
5621     BuiltinIndex = 11;
5622     WarnAboutSemanticsChange = true;
5623     break;
5624 
5625   case Builtin::BI__sync_val_compare_and_swap:
5626   case Builtin::BI__sync_val_compare_and_swap_1:
5627   case Builtin::BI__sync_val_compare_and_swap_2:
5628   case Builtin::BI__sync_val_compare_and_swap_4:
5629   case Builtin::BI__sync_val_compare_and_swap_8:
5630   case Builtin::BI__sync_val_compare_and_swap_16:
5631     BuiltinIndex = 12;
5632     NumFixed = 2;
5633     break;
5634 
5635   case Builtin::BI__sync_bool_compare_and_swap:
5636   case Builtin::BI__sync_bool_compare_and_swap_1:
5637   case Builtin::BI__sync_bool_compare_and_swap_2:
5638   case Builtin::BI__sync_bool_compare_and_swap_4:
5639   case Builtin::BI__sync_bool_compare_and_swap_8:
5640   case Builtin::BI__sync_bool_compare_and_swap_16:
5641     BuiltinIndex = 13;
5642     NumFixed = 2;
5643     ResultType = Context.BoolTy;
5644     break;
5645 
5646   case Builtin::BI__sync_lock_test_and_set:
5647   case Builtin::BI__sync_lock_test_and_set_1:
5648   case Builtin::BI__sync_lock_test_and_set_2:
5649   case Builtin::BI__sync_lock_test_and_set_4:
5650   case Builtin::BI__sync_lock_test_and_set_8:
5651   case Builtin::BI__sync_lock_test_and_set_16:
5652     BuiltinIndex = 14;
5653     break;
5654 
5655   case Builtin::BI__sync_lock_release:
5656   case Builtin::BI__sync_lock_release_1:
5657   case Builtin::BI__sync_lock_release_2:
5658   case Builtin::BI__sync_lock_release_4:
5659   case Builtin::BI__sync_lock_release_8:
5660   case Builtin::BI__sync_lock_release_16:
5661     BuiltinIndex = 15;
5662     NumFixed = 0;
5663     ResultType = Context.VoidTy;
5664     break;
5665 
5666   case Builtin::BI__sync_swap:
5667   case Builtin::BI__sync_swap_1:
5668   case Builtin::BI__sync_swap_2:
5669   case Builtin::BI__sync_swap_4:
5670   case Builtin::BI__sync_swap_8:
5671   case Builtin::BI__sync_swap_16:
5672     BuiltinIndex = 16;
5673     break;
5674   }
5675 
5676   // Now that we know how many fixed arguments we expect, first check that we
5677   // have at least that many.
5678   if (TheCall->getNumArgs() < 1+NumFixed) {
5679     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5680         << 0 << 1 + NumFixed << TheCall->getNumArgs()
5681         << Callee->getSourceRange();
5682     return ExprError();
5683   }
5684 
5685   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5686       << Callee->getSourceRange();
5687 
5688   if (WarnAboutSemanticsChange) {
5689     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
5690         << Callee->getSourceRange();
5691   }
5692 
5693   // Get the decl for the concrete builtin from this, we can tell what the
5694   // concrete integer type we should convert to is.
5695   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5696   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
5697   FunctionDecl *NewBuiltinDecl;
5698   if (NewBuiltinID == BuiltinID)
5699     NewBuiltinDecl = FDecl;
5700   else {
5701     // Perform builtin lookup to avoid redeclaring it.
5702     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
5703     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5704     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5705     assert(Res.getFoundDecl());
5706     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
5707     if (!NewBuiltinDecl)
5708       return ExprError();
5709   }
5710 
5711   // The first argument --- the pointer --- has a fixed type; we
5712   // deduce the types of the rest of the arguments accordingly.  Walk
5713   // the remaining arguments, converting them to the deduced value type.
5714   for (unsigned i = 0; i != NumFixed; ++i) {
5715     ExprResult Arg = TheCall->getArg(i+1);
5716 
5717     // GCC does an implicit conversion to the pointer or integer ValType.  This
5718     // can fail in some cases (1i -> int**), check for this error case now.
5719     // Initialize the argument.
5720     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5721                                                    ValType, /*consume*/ false);
5722     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5723     if (Arg.isInvalid())
5724       return ExprError();
5725 
5726     // Okay, we have something that *can* be converted to the right type.  Check
5727     // to see if there is a potentially weird extension going on here.  This can
5728     // happen when you do an atomic operation on something like an char* and
5729     // pass in 42.  The 42 gets converted to char.  This is even more strange
5730     // for things like 45.123 -> char, etc.
5731     // FIXME: Do this check.
5732     TheCall->setArg(i+1, Arg.get());
5733   }
5734 
5735   // Create a new DeclRefExpr to refer to the new decl.
5736   DeclRefExpr *NewDRE = DeclRefExpr::Create(
5737       Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
5738       /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
5739       DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
5740 
5741   // Set the callee in the CallExpr.
5742   // FIXME: This loses syntactic information.
5743   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5744   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5745                                               CK_BuiltinFnToFnPtr);
5746   TheCall->setCallee(PromotedCall.get());
5747 
5748   // Change the result type of the call to match the original value type. This
5749   // is arbitrary, but the codegen for these builtins ins design to handle it
5750   // gracefully.
5751   TheCall->setType(ResultType);
5752 
5753   // Prohibit use of _ExtInt with atomic builtins.
5754   // The arguments would have already been converted to the first argument's
5755   // type, so only need to check the first argument.
5756   const auto *ExtIntValType = ValType->getAs<ExtIntType>();
5757   if (ExtIntValType && !llvm::isPowerOf2_64(ExtIntValType->getNumBits())) {
5758     Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
5759     return ExprError();
5760   }
5761 
5762   return TheCallResult;
5763 }
5764 
5765 /// SemaBuiltinNontemporalOverloaded - We have a call to
5766 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
5767 /// overloaded function based on the pointer type of its last argument.
5768 ///
5769 /// This function goes through and does final semantic checking for these
5770 /// builtins.
5771 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5772   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5773   DeclRefExpr *DRE =
5774       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5775   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5776   unsigned BuiltinID = FDecl->getBuiltinID();
5777   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5778           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5779          "Unexpected nontemporal load/store builtin!");
5780   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5781   unsigned numArgs = isStore ? 2 : 1;
5782 
5783   // Ensure that we have the proper number of arguments.
5784   if (checkArgCount(*this, TheCall, numArgs))
5785     return ExprError();
5786 
5787   // Inspect the last argument of the nontemporal builtin.  This should always
5788   // be a pointer type, from which we imply the type of the memory access.
5789   // Because it is a pointer type, we don't have to worry about any implicit
5790   // casts here.
5791   Expr *PointerArg = TheCall->getArg(numArgs - 1);
5792   ExprResult PointerArgResult =
5793       DefaultFunctionArrayLvalueConversion(PointerArg);
5794 
5795   if (PointerArgResult.isInvalid())
5796     return ExprError();
5797   PointerArg = PointerArgResult.get();
5798   TheCall->setArg(numArgs - 1, PointerArg);
5799 
5800   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5801   if (!pointerType) {
5802     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
5803         << PointerArg->getType() << PointerArg->getSourceRange();
5804     return ExprError();
5805   }
5806 
5807   QualType ValType = pointerType->getPointeeType();
5808 
5809   // Strip any qualifiers off ValType.
5810   ValType = ValType.getUnqualifiedType();
5811   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5812       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5813       !ValType->isVectorType()) {
5814     Diag(DRE->getBeginLoc(),
5815          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5816         << PointerArg->getType() << PointerArg->getSourceRange();
5817     return ExprError();
5818   }
5819 
5820   if (!isStore) {
5821     TheCall->setType(ValType);
5822     return TheCallResult;
5823   }
5824 
5825   ExprResult ValArg = TheCall->getArg(0);
5826   InitializedEntity Entity = InitializedEntity::InitializeParameter(
5827       Context, ValType, /*consume*/ false);
5828   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
5829   if (ValArg.isInvalid())
5830     return ExprError();
5831 
5832   TheCall->setArg(0, ValArg.get());
5833   TheCall->setType(Context.VoidTy);
5834   return TheCallResult;
5835 }
5836 
5837 /// CheckObjCString - Checks that the argument to the builtin
5838 /// CFString constructor is correct
5839 /// Note: It might also make sense to do the UTF-16 conversion here (would
5840 /// simplify the backend).
5841 bool Sema::CheckObjCString(Expr *Arg) {
5842   Arg = Arg->IgnoreParenCasts();
5843   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
5844 
5845   if (!Literal || !Literal->isAscii()) {
5846     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
5847         << Arg->getSourceRange();
5848     return true;
5849   }
5850 
5851   if (Literal->containsNonAsciiOrNull()) {
5852     StringRef String = Literal->getString();
5853     unsigned NumBytes = String.size();
5854     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
5855     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
5856     llvm::UTF16 *ToPtr = &ToBuf[0];
5857 
5858     llvm::ConversionResult Result =
5859         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
5860                                  ToPtr + NumBytes, llvm::strictConversion);
5861     // Check for conversion failure.
5862     if (Result != llvm::conversionOK)
5863       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
5864           << Arg->getSourceRange();
5865   }
5866   return false;
5867 }
5868 
5869 /// CheckObjCString - Checks that the format string argument to the os_log()
5870 /// and os_trace() functions is correct, and converts it to const char *.
5871 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5872   Arg = Arg->IgnoreParenCasts();
5873   auto *Literal = dyn_cast<StringLiteral>(Arg);
5874   if (!Literal) {
5875     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
5876       Literal = ObjcLiteral->getString();
5877     }
5878   }
5879 
5880   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
5881     return ExprError(
5882         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
5883         << Arg->getSourceRange());
5884   }
5885 
5886   ExprResult Result(Literal);
5887   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
5888   InitializedEntity Entity =
5889       InitializedEntity::InitializeParameter(Context, ResultTy, false);
5890   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
5891   return Result;
5892 }
5893 
5894 /// Check that the user is calling the appropriate va_start builtin for the
5895 /// target and calling convention.
5896 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5897   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5898   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
5899   bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
5900                     TT.getArch() == llvm::Triple::aarch64_32);
5901   bool IsWindows = TT.isOSWindows();
5902   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5903   if (IsX64 || IsAArch64) {
5904     CallingConv CC = CC_C;
5905     if (const FunctionDecl *FD = S.getCurFunctionDecl())
5906       CC = FD->getType()->castAs<FunctionType>()->getCallConv();
5907     if (IsMSVAStart) {
5908       // Don't allow this in System V ABI functions.
5909       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
5910         return S.Diag(Fn->getBeginLoc(),
5911                       diag::err_ms_va_start_used_in_sysv_function);
5912     } else {
5913       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
5914       // On x64 Windows, don't allow this in System V ABI functions.
5915       // (Yes, that means there's no corresponding way to support variadic
5916       // System V ABI functions on Windows.)
5917       if ((IsWindows && CC == CC_X86_64SysV) ||
5918           (!IsWindows && CC == CC_Win64))
5919         return S.Diag(Fn->getBeginLoc(),
5920                       diag::err_va_start_used_in_wrong_abi_function)
5921                << !IsWindows;
5922     }
5923     return false;
5924   }
5925 
5926   if (IsMSVAStart)
5927     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
5928   return false;
5929 }
5930 
5931 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
5932                                              ParmVarDecl **LastParam = nullptr) {
5933   // Determine whether the current function, block, or obj-c method is variadic
5934   // and get its parameter list.
5935   bool IsVariadic = false;
5936   ArrayRef<ParmVarDecl *> Params;
5937   DeclContext *Caller = S.CurContext;
5938   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
5939     IsVariadic = Block->isVariadic();
5940     Params = Block->parameters();
5941   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
5942     IsVariadic = FD->isVariadic();
5943     Params = FD->parameters();
5944   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
5945     IsVariadic = MD->isVariadic();
5946     // FIXME: This isn't correct for methods (results in bogus warning).
5947     Params = MD->parameters();
5948   } else if (isa<CapturedDecl>(Caller)) {
5949     // We don't support va_start in a CapturedDecl.
5950     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
5951     return true;
5952   } else {
5953     // This must be some other declcontext that parses exprs.
5954     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
5955     return true;
5956   }
5957 
5958   if (!IsVariadic) {
5959     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
5960     return true;
5961   }
5962 
5963   if (LastParam)
5964     *LastParam = Params.empty() ? nullptr : Params.back();
5965 
5966   return false;
5967 }
5968 
5969 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
5970 /// for validity.  Emit an error and return true on failure; return false
5971 /// on success.
5972 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5973   Expr *Fn = TheCall->getCallee();
5974 
5975   if (checkVAStartABI(*this, BuiltinID, Fn))
5976     return true;
5977 
5978   if (checkArgCount(*this, TheCall, 2))
5979     return true;
5980 
5981   // Type-check the first argument normally.
5982   if (checkBuiltinArgument(*this, TheCall, 0))
5983     return true;
5984 
5985   // Check that the current function is variadic, and get its last parameter.
5986   ParmVarDecl *LastParam;
5987   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
5988     return true;
5989 
5990   // Verify that the second argument to the builtin is the last argument of the
5991   // current function or method.
5992   bool SecondArgIsLastNamedArgument = false;
5993   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
5994 
5995   // These are valid if SecondArgIsLastNamedArgument is false after the next
5996   // block.
5997   QualType Type;
5998   SourceLocation ParamLoc;
5999   bool IsCRegister = false;
6000 
6001   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
6002     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
6003       SecondArgIsLastNamedArgument = PV == LastParam;
6004 
6005       Type = PV->getType();
6006       ParamLoc = PV->getLocation();
6007       IsCRegister =
6008           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
6009     }
6010   }
6011 
6012   if (!SecondArgIsLastNamedArgument)
6013     Diag(TheCall->getArg(1)->getBeginLoc(),
6014          diag::warn_second_arg_of_va_start_not_last_named_param);
6015   else if (IsCRegister || Type->isReferenceType() ||
6016            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
6017              // Promotable integers are UB, but enumerations need a bit of
6018              // extra checking to see what their promotable type actually is.
6019              if (!Type->isPromotableIntegerType())
6020                return false;
6021              if (!Type->isEnumeralType())
6022                return true;
6023              const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
6024              return !(ED &&
6025                       Context.typesAreCompatible(ED->getPromotionType(), Type));
6026            }()) {
6027     unsigned Reason = 0;
6028     if (Type->isReferenceType())  Reason = 1;
6029     else if (IsCRegister)         Reason = 2;
6030     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
6031     Diag(ParamLoc, diag::note_parameter_type) << Type;
6032   }
6033 
6034   TheCall->setType(Context.VoidTy);
6035   return false;
6036 }
6037 
6038 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
6039   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
6040   //                 const char *named_addr);
6041 
6042   Expr *Func = Call->getCallee();
6043 
6044   if (Call->getNumArgs() < 3)
6045     return Diag(Call->getEndLoc(),
6046                 diag::err_typecheck_call_too_few_args_at_least)
6047            << 0 /*function call*/ << 3 << Call->getNumArgs();
6048 
6049   // Type-check the first argument normally.
6050   if (checkBuiltinArgument(*this, Call, 0))
6051     return true;
6052 
6053   // Check that the current function is variadic.
6054   if (checkVAStartIsInVariadicFunction(*this, Func))
6055     return true;
6056 
6057   // __va_start on Windows does not validate the parameter qualifiers
6058 
6059   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
6060   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
6061 
6062   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
6063   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
6064 
6065   const QualType &ConstCharPtrTy =
6066       Context.getPointerType(Context.CharTy.withConst());
6067   if (!Arg1Ty->isPointerType() ||
6068       Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
6069     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6070         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
6071         << 0                                      /* qualifier difference */
6072         << 3                                      /* parameter mismatch */
6073         << 2 << Arg1->getType() << ConstCharPtrTy;
6074 
6075   const QualType SizeTy = Context.getSizeType();
6076   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
6077     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6078         << Arg2->getType() << SizeTy << 1 /* different class */
6079         << 0                              /* qualifier difference */
6080         << 3                              /* parameter mismatch */
6081         << 3 << Arg2->getType() << SizeTy;
6082 
6083   return false;
6084 }
6085 
6086 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
6087 /// friends.  This is declared to take (...), so we have to check everything.
6088 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
6089   if (checkArgCount(*this, TheCall, 2))
6090     return true;
6091 
6092   ExprResult OrigArg0 = TheCall->getArg(0);
6093   ExprResult OrigArg1 = TheCall->getArg(1);
6094 
6095   // Do standard promotions between the two arguments, returning their common
6096   // type.
6097   QualType Res = UsualArithmeticConversions(
6098       OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
6099   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
6100     return true;
6101 
6102   // Make sure any conversions are pushed back into the call; this is
6103   // type safe since unordered compare builtins are declared as "_Bool
6104   // foo(...)".
6105   TheCall->setArg(0, OrigArg0.get());
6106   TheCall->setArg(1, OrigArg1.get());
6107 
6108   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
6109     return false;
6110 
6111   // If the common type isn't a real floating type, then the arguments were
6112   // invalid for this operation.
6113   if (Res.isNull() || !Res->isRealFloatingType())
6114     return Diag(OrigArg0.get()->getBeginLoc(),
6115                 diag::err_typecheck_call_invalid_ordered_compare)
6116            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
6117            << SourceRange(OrigArg0.get()->getBeginLoc(),
6118                           OrigArg1.get()->getEndLoc());
6119 
6120   return false;
6121 }
6122 
6123 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
6124 /// __builtin_isnan and friends.  This is declared to take (...), so we have
6125 /// to check everything. We expect the last argument to be a floating point
6126 /// value.
6127 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
6128   if (checkArgCount(*this, TheCall, NumArgs))
6129     return true;
6130 
6131   // __builtin_fpclassify is the only case where NumArgs != 1, so we can count
6132   // on all preceding parameters just being int.  Try all of those.
6133   for (unsigned i = 0; i < NumArgs - 1; ++i) {
6134     Expr *Arg = TheCall->getArg(i);
6135 
6136     if (Arg->isTypeDependent())
6137       return false;
6138 
6139     ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);
6140 
6141     if (Res.isInvalid())
6142       return true;
6143     TheCall->setArg(i, Res.get());
6144   }
6145 
6146   Expr *OrigArg = TheCall->getArg(NumArgs-1);
6147 
6148   if (OrigArg->isTypeDependent())
6149     return false;
6150 
6151   // Usual Unary Conversions will convert half to float, which we want for
6152   // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
6153   // type how it is, but do normal L->Rvalue conversions.
6154   if (Context.getTargetInfo().useFP16ConversionIntrinsics())
6155     OrigArg = UsualUnaryConversions(OrigArg).get();
6156   else
6157     OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
6158   TheCall->setArg(NumArgs - 1, OrigArg);
6159 
6160   // This operation requires a non-_Complex floating-point number.
6161   if (!OrigArg->getType()->isRealFloatingType())
6162     return Diag(OrigArg->getBeginLoc(),
6163                 diag::err_typecheck_call_invalid_unary_fp)
6164            << OrigArg->getType() << OrigArg->getSourceRange();
6165 
6166   return false;
6167 }
6168 
6169 /// Perform semantic analysis for a call to __builtin_complex.
6170 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) {
6171   if (checkArgCount(*this, TheCall, 2))
6172     return true;
6173 
6174   bool Dependent = false;
6175   for (unsigned I = 0; I != 2; ++I) {
6176     Expr *Arg = TheCall->getArg(I);
6177     QualType T = Arg->getType();
6178     if (T->isDependentType()) {
6179       Dependent = true;
6180       continue;
6181     }
6182 
6183     // Despite supporting _Complex int, GCC requires a real floating point type
6184     // for the operands of __builtin_complex.
6185     if (!T->isRealFloatingType()) {
6186       return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
6187              << Arg->getType() << Arg->getSourceRange();
6188     }
6189 
6190     ExprResult Converted = DefaultLvalueConversion(Arg);
6191     if (Converted.isInvalid())
6192       return true;
6193     TheCall->setArg(I, Converted.get());
6194   }
6195 
6196   if (Dependent) {
6197     TheCall->setType(Context.DependentTy);
6198     return false;
6199   }
6200 
6201   Expr *Real = TheCall->getArg(0);
6202   Expr *Imag = TheCall->getArg(1);
6203   if (!Context.hasSameType(Real->getType(), Imag->getType())) {
6204     return Diag(Real->getBeginLoc(),
6205                 diag::err_typecheck_call_different_arg_types)
6206            << Real->getType() << Imag->getType()
6207            << Real->getSourceRange() << Imag->getSourceRange();
6208   }
6209 
6210   // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers;
6211   // don't allow this builtin to form those types either.
6212   // FIXME: Should we allow these types?
6213   if (Real->getType()->isFloat16Type())
6214     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6215            << "_Float16";
6216   if (Real->getType()->isHalfType())
6217     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6218            << "half";
6219 
6220   TheCall->setType(Context.getComplexType(Real->getType()));
6221   return false;
6222 }
6223 
6224 // Customized Sema Checking for VSX builtins that have the following signature:
6225 // vector [...] builtinName(vector [...], vector [...], const int);
6226 // Which takes the same type of vectors (any legal vector type) for the first
6227 // two arguments and takes compile time constant for the third argument.
6228 // Example builtins are :
6229 // vector double vec_xxpermdi(vector double, vector double, int);
6230 // vector short vec_xxsldwi(vector short, vector short, int);
6231 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
6232   unsigned ExpectedNumArgs = 3;
6233   if (checkArgCount(*this, TheCall, ExpectedNumArgs))
6234     return true;
6235 
6236   // Check the third argument is a compile time constant
6237   if (!TheCall->getArg(2)->isIntegerConstantExpr(Context))
6238     return Diag(TheCall->getBeginLoc(),
6239                 diag::err_vsx_builtin_nonconstant_argument)
6240            << 3 /* argument index */ << TheCall->getDirectCallee()
6241            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
6242                           TheCall->getArg(2)->getEndLoc());
6243 
6244   QualType Arg1Ty = TheCall->getArg(0)->getType();
6245   QualType Arg2Ty = TheCall->getArg(1)->getType();
6246 
6247   // Check the type of argument 1 and argument 2 are vectors.
6248   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
6249   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
6250       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
6251     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
6252            << TheCall->getDirectCallee()
6253            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6254                           TheCall->getArg(1)->getEndLoc());
6255   }
6256 
6257   // Check the first two arguments are the same type.
6258   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
6259     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
6260            << TheCall->getDirectCallee()
6261            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6262                           TheCall->getArg(1)->getEndLoc());
6263   }
6264 
6265   // When default clang type checking is turned off and the customized type
6266   // checking is used, the returning type of the function must be explicitly
6267   // set. Otherwise it is _Bool by default.
6268   TheCall->setType(Arg1Ty);
6269 
6270   return false;
6271 }
6272 
6273 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
6274 // This is declared to take (...), so we have to check everything.
6275 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
6276   if (TheCall->getNumArgs() < 2)
6277     return ExprError(Diag(TheCall->getEndLoc(),
6278                           diag::err_typecheck_call_too_few_args_at_least)
6279                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
6280                      << TheCall->getSourceRange());
6281 
6282   // Determine which of the following types of shufflevector we're checking:
6283   // 1) unary, vector mask: (lhs, mask)
6284   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
6285   QualType resType = TheCall->getArg(0)->getType();
6286   unsigned numElements = 0;
6287 
6288   if (!TheCall->getArg(0)->isTypeDependent() &&
6289       !TheCall->getArg(1)->isTypeDependent()) {
6290     QualType LHSType = TheCall->getArg(0)->getType();
6291     QualType RHSType = TheCall->getArg(1)->getType();
6292 
6293     if (!LHSType->isVectorType() || !RHSType->isVectorType())
6294       return ExprError(
6295           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
6296           << TheCall->getDirectCallee()
6297           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6298                          TheCall->getArg(1)->getEndLoc()));
6299 
6300     numElements = LHSType->castAs<VectorType>()->getNumElements();
6301     unsigned numResElements = TheCall->getNumArgs() - 2;
6302 
6303     // Check to see if we have a call with 2 vector arguments, the unary shuffle
6304     // with mask.  If so, verify that RHS is an integer vector type with the
6305     // same number of elts as lhs.
6306     if (TheCall->getNumArgs() == 2) {
6307       if (!RHSType->hasIntegerRepresentation() ||
6308           RHSType->castAs<VectorType>()->getNumElements() != numElements)
6309         return ExprError(Diag(TheCall->getBeginLoc(),
6310                               diag::err_vec_builtin_incompatible_vector)
6311                          << TheCall->getDirectCallee()
6312                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
6313                                         TheCall->getArg(1)->getEndLoc()));
6314     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
6315       return ExprError(Diag(TheCall->getBeginLoc(),
6316                             diag::err_vec_builtin_incompatible_vector)
6317                        << TheCall->getDirectCallee()
6318                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6319                                       TheCall->getArg(1)->getEndLoc()));
6320     } else if (numElements != numResElements) {
6321       QualType eltType = LHSType->castAs<VectorType>()->getElementType();
6322       resType = Context.getVectorType(eltType, numResElements,
6323                                       VectorType::GenericVector);
6324     }
6325   }
6326 
6327   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
6328     if (TheCall->getArg(i)->isTypeDependent() ||
6329         TheCall->getArg(i)->isValueDependent())
6330       continue;
6331 
6332     Optional<llvm::APSInt> Result;
6333     if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context)))
6334       return ExprError(Diag(TheCall->getBeginLoc(),
6335                             diag::err_shufflevector_nonconstant_argument)
6336                        << TheCall->getArg(i)->getSourceRange());
6337 
6338     // Allow -1 which will be translated to undef in the IR.
6339     if (Result->isSigned() && Result->isAllOnesValue())
6340       continue;
6341 
6342     if (Result->getActiveBits() > 64 ||
6343         Result->getZExtValue() >= numElements * 2)
6344       return ExprError(Diag(TheCall->getBeginLoc(),
6345                             diag::err_shufflevector_argument_too_large)
6346                        << TheCall->getArg(i)->getSourceRange());
6347   }
6348 
6349   SmallVector<Expr*, 32> exprs;
6350 
6351   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
6352     exprs.push_back(TheCall->getArg(i));
6353     TheCall->setArg(i, nullptr);
6354   }
6355 
6356   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
6357                                          TheCall->getCallee()->getBeginLoc(),
6358                                          TheCall->getRParenLoc());
6359 }
6360 
6361 /// SemaConvertVectorExpr - Handle __builtin_convertvector
6362 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
6363                                        SourceLocation BuiltinLoc,
6364                                        SourceLocation RParenLoc) {
6365   ExprValueKind VK = VK_RValue;
6366   ExprObjectKind OK = OK_Ordinary;
6367   QualType DstTy = TInfo->getType();
6368   QualType SrcTy = E->getType();
6369 
6370   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
6371     return ExprError(Diag(BuiltinLoc,
6372                           diag::err_convertvector_non_vector)
6373                      << E->getSourceRange());
6374   if (!DstTy->isVectorType() && !DstTy->isDependentType())
6375     return ExprError(Diag(BuiltinLoc,
6376                           diag::err_convertvector_non_vector_type));
6377 
6378   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
6379     unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
6380     unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
6381     if (SrcElts != DstElts)
6382       return ExprError(Diag(BuiltinLoc,
6383                             diag::err_convertvector_incompatible_vector)
6384                        << E->getSourceRange());
6385   }
6386 
6387   return new (Context)
6388       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
6389 }
6390 
6391 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
6392 // This is declared to take (const void*, ...) and can take two
6393 // optional constant int args.
6394 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
6395   unsigned NumArgs = TheCall->getNumArgs();
6396 
6397   if (NumArgs > 3)
6398     return Diag(TheCall->getEndLoc(),
6399                 diag::err_typecheck_call_too_many_args_at_most)
6400            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6401 
6402   // Argument 0 is checked for us and the remaining arguments must be
6403   // constant integers.
6404   for (unsigned i = 1; i != NumArgs; ++i)
6405     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
6406       return true;
6407 
6408   return false;
6409 }
6410 
6411 /// SemaBuiltinAssume - Handle __assume (MS Extension).
6412 // __assume does not evaluate its arguments, and should warn if its argument
6413 // has side effects.
6414 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
6415   Expr *Arg = TheCall->getArg(0);
6416   if (Arg->isInstantiationDependent()) return false;
6417 
6418   if (Arg->HasSideEffects(Context))
6419     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
6420         << Arg->getSourceRange()
6421         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
6422 
6423   return false;
6424 }
6425 
6426 /// Handle __builtin_alloca_with_align. This is declared
6427 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
6428 /// than 8.
6429 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
6430   // The alignment must be a constant integer.
6431   Expr *Arg = TheCall->getArg(1);
6432 
6433   // We can't check the value of a dependent argument.
6434   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6435     if (const auto *UE =
6436             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
6437       if (UE->getKind() == UETT_AlignOf ||
6438           UE->getKind() == UETT_PreferredAlignOf)
6439         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
6440             << Arg->getSourceRange();
6441 
6442     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
6443 
6444     if (!Result.isPowerOf2())
6445       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6446              << Arg->getSourceRange();
6447 
6448     if (Result < Context.getCharWidth())
6449       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
6450              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6451 
6452     if (Result > std::numeric_limits<int32_t>::max())
6453       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
6454              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6455   }
6456 
6457   return false;
6458 }
6459 
6460 /// Handle __builtin_assume_aligned. This is declared
6461 /// as (const void*, size_t, ...) and can take one optional constant int arg.
6462 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
6463   unsigned NumArgs = TheCall->getNumArgs();
6464 
6465   if (NumArgs > 3)
6466     return Diag(TheCall->getEndLoc(),
6467                 diag::err_typecheck_call_too_many_args_at_most)
6468            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6469 
6470   // The alignment must be a constant integer.
6471   Expr *Arg = TheCall->getArg(1);
6472 
6473   // We can't check the value of a dependent argument.
6474   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6475     llvm::APSInt Result;
6476     if (SemaBuiltinConstantArg(TheCall, 1, Result))
6477       return true;
6478 
6479     if (!Result.isPowerOf2())
6480       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6481              << Arg->getSourceRange();
6482 
6483     if (Result > Sema::MaximumAlignment)
6484       Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
6485           << Arg->getSourceRange() << Sema::MaximumAlignment;
6486   }
6487 
6488   if (NumArgs > 2) {
6489     ExprResult Arg(TheCall->getArg(2));
6490     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6491       Context.getSizeType(), false);
6492     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6493     if (Arg.isInvalid()) return true;
6494     TheCall->setArg(2, Arg.get());
6495   }
6496 
6497   return false;
6498 }
6499 
6500 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
6501   unsigned BuiltinID =
6502       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
6503   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6504 
6505   unsigned NumArgs = TheCall->getNumArgs();
6506   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6507   if (NumArgs < NumRequiredArgs) {
6508     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
6509            << 0 /* function call */ << NumRequiredArgs << NumArgs
6510            << TheCall->getSourceRange();
6511   }
6512   if (NumArgs >= NumRequiredArgs + 0x100) {
6513     return Diag(TheCall->getEndLoc(),
6514                 diag::err_typecheck_call_too_many_args_at_most)
6515            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6516            << TheCall->getSourceRange();
6517   }
6518   unsigned i = 0;
6519 
6520   // For formatting call, check buffer arg.
6521   if (!IsSizeCall) {
6522     ExprResult Arg(TheCall->getArg(i));
6523     InitializedEntity Entity = InitializedEntity::InitializeParameter(
6524         Context, Context.VoidPtrTy, false);
6525     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6526     if (Arg.isInvalid())
6527       return true;
6528     TheCall->setArg(i, Arg.get());
6529     i++;
6530   }
6531 
6532   // Check string literal arg.
6533   unsigned FormatIdx = i;
6534   {
6535     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
6536     if (Arg.isInvalid())
6537       return true;
6538     TheCall->setArg(i, Arg.get());
6539     i++;
6540   }
6541 
6542   // Make sure variadic args are scalar.
6543   unsigned FirstDataArg = i;
6544   while (i < NumArgs) {
6545     ExprResult Arg = DefaultVariadicArgumentPromotion(
6546         TheCall->getArg(i), VariadicFunction, nullptr);
6547     if (Arg.isInvalid())
6548       return true;
6549     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
6550     if (ArgSize.getQuantity() >= 0x100) {
6551       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
6552              << i << (int)ArgSize.getQuantity() << 0xff
6553              << TheCall->getSourceRange();
6554     }
6555     TheCall->setArg(i, Arg.get());
6556     i++;
6557   }
6558 
6559   // Check formatting specifiers. NOTE: We're only doing this for the non-size
6560   // call to avoid duplicate diagnostics.
6561   if (!IsSizeCall) {
6562     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6563     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6564     bool Success = CheckFormatArguments(
6565         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
6566         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
6567         CheckedVarArgs);
6568     if (!Success)
6569       return true;
6570   }
6571 
6572   if (IsSizeCall) {
6573     TheCall->setType(Context.getSizeType());
6574   } else {
6575     TheCall->setType(Context.VoidPtrTy);
6576   }
6577   return false;
6578 }
6579 
6580 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
6581 /// TheCall is a constant expression.
6582 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
6583                                   llvm::APSInt &Result) {
6584   Expr *Arg = TheCall->getArg(ArgNum);
6585   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6586   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6587 
6588   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
6589 
6590   Optional<llvm::APSInt> R;
6591   if (!(R = Arg->getIntegerConstantExpr(Context)))
6592     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6593            << FDecl->getDeclName() << Arg->getSourceRange();
6594   Result = *R;
6595   return false;
6596 }
6597 
6598 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
6599 /// TheCall is a constant expression in the range [Low, High].
6600 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
6601                                        int Low, int High, bool RangeIsError) {
6602   if (isConstantEvaluated())
6603     return false;
6604   llvm::APSInt Result;
6605 
6606   // We can't check the value of a dependent argument.
6607   Expr *Arg = TheCall->getArg(ArgNum);
6608   if (Arg->isTypeDependent() || Arg->isValueDependent())
6609     return false;
6610 
6611   // Check constant-ness first.
6612   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6613     return true;
6614 
6615   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6616     if (RangeIsError)
6617       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
6618              << Result.toString(10) << Low << High << Arg->getSourceRange();
6619     else
6620       // Defer the warning until we know if the code will be emitted so that
6621       // dead code can ignore this.
6622       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6623                           PDiag(diag::warn_argument_invalid_range)
6624                               << Result.toString(10) << Low << High
6625                               << Arg->getSourceRange());
6626   }
6627 
6628   return false;
6629 }
6630 
6631 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
6632 /// TheCall is a constant expression is a multiple of Num..
6633 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
6634                                           unsigned Num) {
6635   llvm::APSInt Result;
6636 
6637   // We can't check the value of a dependent argument.
6638   Expr *Arg = TheCall->getArg(ArgNum);
6639   if (Arg->isTypeDependent() || Arg->isValueDependent())
6640     return false;
6641 
6642   // Check constant-ness first.
6643   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6644     return true;
6645 
6646   if (Result.getSExtValue() % Num != 0)
6647     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6648            << Num << Arg->getSourceRange();
6649 
6650   return false;
6651 }
6652 
6653 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
6654 /// constant expression representing a power of 2.
6655 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
6656   llvm::APSInt Result;
6657 
6658   // We can't check the value of a dependent argument.
6659   Expr *Arg = TheCall->getArg(ArgNum);
6660   if (Arg->isTypeDependent() || Arg->isValueDependent())
6661     return false;
6662 
6663   // Check constant-ness first.
6664   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6665     return true;
6666 
6667   // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
6668   // and only if x is a power of 2.
6669   if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
6670     return false;
6671 
6672   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
6673          << Arg->getSourceRange();
6674 }
6675 
6676 static bool IsShiftedByte(llvm::APSInt Value) {
6677   if (Value.isNegative())
6678     return false;
6679 
6680   // Check if it's a shifted byte, by shifting it down
6681   while (true) {
6682     // If the value fits in the bottom byte, the check passes.
6683     if (Value < 0x100)
6684       return true;
6685 
6686     // Otherwise, if the value has _any_ bits in the bottom byte, the check
6687     // fails.
6688     if ((Value & 0xFF) != 0)
6689       return false;
6690 
6691     // If the bottom 8 bits are all 0, but something above that is nonzero,
6692     // then shifting the value right by 8 bits won't affect whether it's a
6693     // shifted byte or not. So do that, and go round again.
6694     Value >>= 8;
6695   }
6696 }
6697 
6698 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
6699 /// a constant expression representing an arbitrary byte value shifted left by
6700 /// a multiple of 8 bits.
6701 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
6702                                              unsigned ArgBits) {
6703   llvm::APSInt Result;
6704 
6705   // We can't check the value of a dependent argument.
6706   Expr *Arg = TheCall->getArg(ArgNum);
6707   if (Arg->isTypeDependent() || Arg->isValueDependent())
6708     return false;
6709 
6710   // Check constant-ness first.
6711   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6712     return true;
6713 
6714   // Truncate to the given size.
6715   Result = Result.getLoBits(ArgBits);
6716   Result.setIsUnsigned(true);
6717 
6718   if (IsShiftedByte(Result))
6719     return false;
6720 
6721   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
6722          << Arg->getSourceRange();
6723 }
6724 
6725 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
6726 /// TheCall is a constant expression representing either a shifted byte value,
6727 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
6728 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
6729 /// Arm MVE intrinsics.
6730 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
6731                                                    int ArgNum,
6732                                                    unsigned ArgBits) {
6733   llvm::APSInt Result;
6734 
6735   // We can't check the value of a dependent argument.
6736   Expr *Arg = TheCall->getArg(ArgNum);
6737   if (Arg->isTypeDependent() || Arg->isValueDependent())
6738     return false;
6739 
6740   // Check constant-ness first.
6741   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6742     return true;
6743 
6744   // Truncate to the given size.
6745   Result = Result.getLoBits(ArgBits);
6746   Result.setIsUnsigned(true);
6747 
6748   // Check to see if it's in either of the required forms.
6749   if (IsShiftedByte(Result) ||
6750       (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
6751     return false;
6752 
6753   return Diag(TheCall->getBeginLoc(),
6754               diag::err_argument_not_shifted_byte_or_xxff)
6755          << Arg->getSourceRange();
6756 }
6757 
6758 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
6759 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
6760   if (BuiltinID == AArch64::BI__builtin_arm_irg) {
6761     if (checkArgCount(*this, TheCall, 2))
6762       return true;
6763     Expr *Arg0 = TheCall->getArg(0);
6764     Expr *Arg1 = TheCall->getArg(1);
6765 
6766     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6767     if (FirstArg.isInvalid())
6768       return true;
6769     QualType FirstArgType = FirstArg.get()->getType();
6770     if (!FirstArgType->isAnyPointerType())
6771       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6772                << "first" << FirstArgType << Arg0->getSourceRange();
6773     TheCall->setArg(0, FirstArg.get());
6774 
6775     ExprResult SecArg = DefaultLvalueConversion(Arg1);
6776     if (SecArg.isInvalid())
6777       return true;
6778     QualType SecArgType = SecArg.get()->getType();
6779     if (!SecArgType->isIntegerType())
6780       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6781                << "second" << SecArgType << Arg1->getSourceRange();
6782 
6783     // Derive the return type from the pointer argument.
6784     TheCall->setType(FirstArgType);
6785     return false;
6786   }
6787 
6788   if (BuiltinID == AArch64::BI__builtin_arm_addg) {
6789     if (checkArgCount(*this, TheCall, 2))
6790       return true;
6791 
6792     Expr *Arg0 = TheCall->getArg(0);
6793     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6794     if (FirstArg.isInvalid())
6795       return true;
6796     QualType FirstArgType = FirstArg.get()->getType();
6797     if (!FirstArgType->isAnyPointerType())
6798       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6799                << "first" << FirstArgType << Arg0->getSourceRange();
6800     TheCall->setArg(0, FirstArg.get());
6801 
6802     // Derive the return type from the pointer argument.
6803     TheCall->setType(FirstArgType);
6804 
6805     // Second arg must be an constant in range [0,15]
6806     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6807   }
6808 
6809   if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
6810     if (checkArgCount(*this, TheCall, 2))
6811       return true;
6812     Expr *Arg0 = TheCall->getArg(0);
6813     Expr *Arg1 = TheCall->getArg(1);
6814 
6815     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6816     if (FirstArg.isInvalid())
6817       return true;
6818     QualType FirstArgType = FirstArg.get()->getType();
6819     if (!FirstArgType->isAnyPointerType())
6820       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6821                << "first" << FirstArgType << Arg0->getSourceRange();
6822 
6823     QualType SecArgType = Arg1->getType();
6824     if (!SecArgType->isIntegerType())
6825       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6826                << "second" << SecArgType << Arg1->getSourceRange();
6827     TheCall->setType(Context.IntTy);
6828     return false;
6829   }
6830 
6831   if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
6832       BuiltinID == AArch64::BI__builtin_arm_stg) {
6833     if (checkArgCount(*this, TheCall, 1))
6834       return true;
6835     Expr *Arg0 = TheCall->getArg(0);
6836     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6837     if (FirstArg.isInvalid())
6838       return true;
6839 
6840     QualType FirstArgType = FirstArg.get()->getType();
6841     if (!FirstArgType->isAnyPointerType())
6842       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6843                << "first" << FirstArgType << Arg0->getSourceRange();
6844     TheCall->setArg(0, FirstArg.get());
6845 
6846     // Derive the return type from the pointer argument.
6847     if (BuiltinID == AArch64::BI__builtin_arm_ldg)
6848       TheCall->setType(FirstArgType);
6849     return false;
6850   }
6851 
6852   if (BuiltinID == AArch64::BI__builtin_arm_subp) {
6853     Expr *ArgA = TheCall->getArg(0);
6854     Expr *ArgB = TheCall->getArg(1);
6855 
6856     ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
6857     ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
6858 
6859     if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
6860       return true;
6861 
6862     QualType ArgTypeA = ArgExprA.get()->getType();
6863     QualType ArgTypeB = ArgExprB.get()->getType();
6864 
6865     auto isNull = [&] (Expr *E) -> bool {
6866       return E->isNullPointerConstant(
6867                         Context, Expr::NPC_ValueDependentIsNotNull); };
6868 
6869     // argument should be either a pointer or null
6870     if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
6871       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6872         << "first" << ArgTypeA << ArgA->getSourceRange();
6873 
6874     if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
6875       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6876         << "second" << ArgTypeB << ArgB->getSourceRange();
6877 
6878     // Ensure Pointee types are compatible
6879     if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
6880         ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
6881       QualType pointeeA = ArgTypeA->getPointeeType();
6882       QualType pointeeB = ArgTypeB->getPointeeType();
6883       if (!Context.typesAreCompatible(
6884              Context.getCanonicalType(pointeeA).getUnqualifiedType(),
6885              Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
6886         return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
6887           << ArgTypeA <<  ArgTypeB << ArgA->getSourceRange()
6888           << ArgB->getSourceRange();
6889       }
6890     }
6891 
6892     // at least one argument should be pointer type
6893     if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
6894       return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
6895         <<  ArgTypeA << ArgTypeB << ArgA->getSourceRange();
6896 
6897     if (isNull(ArgA)) // adopt type of the other pointer
6898       ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
6899 
6900     if (isNull(ArgB))
6901       ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
6902 
6903     TheCall->setArg(0, ArgExprA.get());
6904     TheCall->setArg(1, ArgExprB.get());
6905     TheCall->setType(Context.LongLongTy);
6906     return false;
6907   }
6908   assert(false && "Unhandled ARM MTE intrinsic");
6909   return true;
6910 }
6911 
6912 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
6913 /// TheCall is an ARM/AArch64 special register string literal.
6914 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
6915                                     int ArgNum, unsigned ExpectedFieldNum,
6916                                     bool AllowName) {
6917   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
6918                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
6919                       BuiltinID == ARM::BI__builtin_arm_rsr ||
6920                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
6921                       BuiltinID == ARM::BI__builtin_arm_wsr ||
6922                       BuiltinID == ARM::BI__builtin_arm_wsrp;
6923   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
6924                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
6925                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
6926                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
6927                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
6928                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
6929   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
6930 
6931   // We can't check the value of a dependent argument.
6932   Expr *Arg = TheCall->getArg(ArgNum);
6933   if (Arg->isTypeDependent() || Arg->isValueDependent())
6934     return false;
6935 
6936   // Check if the argument is a string literal.
6937   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
6938     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
6939            << Arg->getSourceRange();
6940 
6941   // Check the type of special register given.
6942   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
6943   SmallVector<StringRef, 6> Fields;
6944   Reg.split(Fields, ":");
6945 
6946   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
6947     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6948            << Arg->getSourceRange();
6949 
6950   // If the string is the name of a register then we cannot check that it is
6951   // valid here but if the string is of one the forms described in ACLE then we
6952   // can check that the supplied fields are integers and within the valid
6953   // ranges.
6954   if (Fields.size() > 1) {
6955     bool FiveFields = Fields.size() == 5;
6956 
6957     bool ValidString = true;
6958     if (IsARMBuiltin) {
6959       ValidString &= Fields[0].startswith_lower("cp") ||
6960                      Fields[0].startswith_lower("p");
6961       if (ValidString)
6962         Fields[0] =
6963           Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
6964 
6965       ValidString &= Fields[2].startswith_lower("c");
6966       if (ValidString)
6967         Fields[2] = Fields[2].drop_front(1);
6968 
6969       if (FiveFields) {
6970         ValidString &= Fields[3].startswith_lower("c");
6971         if (ValidString)
6972           Fields[3] = Fields[3].drop_front(1);
6973       }
6974     }
6975 
6976     SmallVector<int, 5> Ranges;
6977     if (FiveFields)
6978       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
6979     else
6980       Ranges.append({15, 7, 15});
6981 
6982     for (unsigned i=0; i<Fields.size(); ++i) {
6983       int IntField;
6984       ValidString &= !Fields[i].getAsInteger(10, IntField);
6985       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
6986     }
6987 
6988     if (!ValidString)
6989       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6990              << Arg->getSourceRange();
6991   } else if (IsAArch64Builtin && Fields.size() == 1) {
6992     // If the register name is one of those that appear in the condition below
6993     // and the special register builtin being used is one of the write builtins,
6994     // then we require that the argument provided for writing to the register
6995     // is an integer constant expression. This is because it will be lowered to
6996     // an MSR (immediate) instruction, so we need to know the immediate at
6997     // compile time.
6998     if (TheCall->getNumArgs() != 2)
6999       return false;
7000 
7001     std::string RegLower = Reg.lower();
7002     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
7003         RegLower != "pan" && RegLower != "uao")
7004       return false;
7005 
7006     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
7007   }
7008 
7009   return false;
7010 }
7011 
7012 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity.
7013 /// Emit an error and return true on failure; return false on success.
7014 /// TypeStr is a string containing the type descriptor of the value returned by
7015 /// the builtin and the descriptors of the expected type of the arguments.
7016 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, const char *TypeStr) {
7017 
7018   assert((TypeStr[0] != '\0') &&
7019          "Invalid types in PPC MMA builtin declaration");
7020 
7021   unsigned Mask = 0;
7022   unsigned ArgNum = 0;
7023 
7024   // The first type in TypeStr is the type of the value returned by the
7025   // builtin. So we first read that type and change the type of TheCall.
7026   QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7027   TheCall->setType(type);
7028 
7029   while (*TypeStr != '\0') {
7030     Mask = 0;
7031     QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7032     if (ArgNum >= TheCall->getNumArgs()) {
7033       ArgNum++;
7034       break;
7035     }
7036 
7037     Expr *Arg = TheCall->getArg(ArgNum);
7038     QualType ArgType = Arg->getType();
7039 
7040     if ((ExpectedType->isVoidPointerType() && !ArgType->isPointerType()) ||
7041         (!ExpectedType->isVoidPointerType() &&
7042            ArgType.getCanonicalType() != ExpectedType))
7043       return Diag(Arg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
7044              << ArgType << ExpectedType << 1 << 0 << 0;
7045 
7046     // If the value of the Mask is not 0, we have a constraint in the size of
7047     // the integer argument so here we ensure the argument is a constant that
7048     // is in the valid range.
7049     if (Mask != 0 &&
7050         SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true))
7051       return true;
7052 
7053     ArgNum++;
7054   }
7055 
7056   // In case we exited early from the previous loop, there are other types to
7057   // read from TypeStr. So we need to read them all to ensure we have the right
7058   // number of arguments in TheCall and if it is not the case, to display a
7059   // better error message.
7060   while (*TypeStr != '\0') {
7061     (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7062     ArgNum++;
7063   }
7064   if (checkArgCount(*this, TheCall, ArgNum))
7065     return true;
7066 
7067   return false;
7068 }
7069 
7070 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
7071 /// This checks that the target supports __builtin_longjmp and
7072 /// that val is a constant 1.
7073 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
7074   if (!Context.getTargetInfo().hasSjLjLowering())
7075     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
7076            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7077 
7078   Expr *Arg = TheCall->getArg(1);
7079   llvm::APSInt Result;
7080 
7081   // TODO: This is less than ideal. Overload this to take a value.
7082   if (SemaBuiltinConstantArg(TheCall, 1, Result))
7083     return true;
7084 
7085   if (Result != 1)
7086     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
7087            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
7088 
7089   return false;
7090 }
7091 
7092 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
7093 /// This checks that the target supports __builtin_setjmp.
7094 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
7095   if (!Context.getTargetInfo().hasSjLjLowering())
7096     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
7097            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7098   return false;
7099 }
7100 
7101 namespace {
7102 
7103 class UncoveredArgHandler {
7104   enum { Unknown = -1, AllCovered = -2 };
7105 
7106   signed FirstUncoveredArg = Unknown;
7107   SmallVector<const Expr *, 4> DiagnosticExprs;
7108 
7109 public:
7110   UncoveredArgHandler() = default;
7111 
7112   bool hasUncoveredArg() const {
7113     return (FirstUncoveredArg >= 0);
7114   }
7115 
7116   unsigned getUncoveredArg() const {
7117     assert(hasUncoveredArg() && "no uncovered argument");
7118     return FirstUncoveredArg;
7119   }
7120 
7121   void setAllCovered() {
7122     // A string has been found with all arguments covered, so clear out
7123     // the diagnostics.
7124     DiagnosticExprs.clear();
7125     FirstUncoveredArg = AllCovered;
7126   }
7127 
7128   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
7129     assert(NewFirstUncoveredArg >= 0 && "Outside range");
7130 
7131     // Don't update if a previous string covers all arguments.
7132     if (FirstUncoveredArg == AllCovered)
7133       return;
7134 
7135     // UncoveredArgHandler tracks the highest uncovered argument index
7136     // and with it all the strings that match this index.
7137     if (NewFirstUncoveredArg == FirstUncoveredArg)
7138       DiagnosticExprs.push_back(StrExpr);
7139     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
7140       DiagnosticExprs.clear();
7141       DiagnosticExprs.push_back(StrExpr);
7142       FirstUncoveredArg = NewFirstUncoveredArg;
7143     }
7144   }
7145 
7146   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
7147 };
7148 
7149 enum StringLiteralCheckType {
7150   SLCT_NotALiteral,
7151   SLCT_UncheckedLiteral,
7152   SLCT_CheckedLiteral
7153 };
7154 
7155 } // namespace
7156 
7157 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
7158                                      BinaryOperatorKind BinOpKind,
7159                                      bool AddendIsRight) {
7160   unsigned BitWidth = Offset.getBitWidth();
7161   unsigned AddendBitWidth = Addend.getBitWidth();
7162   // There might be negative interim results.
7163   if (Addend.isUnsigned()) {
7164     Addend = Addend.zext(++AddendBitWidth);
7165     Addend.setIsSigned(true);
7166   }
7167   // Adjust the bit width of the APSInts.
7168   if (AddendBitWidth > BitWidth) {
7169     Offset = Offset.sext(AddendBitWidth);
7170     BitWidth = AddendBitWidth;
7171   } else if (BitWidth > AddendBitWidth) {
7172     Addend = Addend.sext(BitWidth);
7173   }
7174 
7175   bool Ov = false;
7176   llvm::APSInt ResOffset = Offset;
7177   if (BinOpKind == BO_Add)
7178     ResOffset = Offset.sadd_ov(Addend, Ov);
7179   else {
7180     assert(AddendIsRight && BinOpKind == BO_Sub &&
7181            "operator must be add or sub with addend on the right");
7182     ResOffset = Offset.ssub_ov(Addend, Ov);
7183   }
7184 
7185   // We add an offset to a pointer here so we should support an offset as big as
7186   // possible.
7187   if (Ov) {
7188     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
7189            "index (intermediate) result too big");
7190     Offset = Offset.sext(2 * BitWidth);
7191     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
7192     return;
7193   }
7194 
7195   Offset = ResOffset;
7196 }
7197 
7198 namespace {
7199 
7200 // This is a wrapper class around StringLiteral to support offsetted string
7201 // literals as format strings. It takes the offset into account when returning
7202 // the string and its length or the source locations to display notes correctly.
7203 class FormatStringLiteral {
7204   const StringLiteral *FExpr;
7205   int64_t Offset;
7206 
7207  public:
7208   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
7209       : FExpr(fexpr), Offset(Offset) {}
7210 
7211   StringRef getString() const {
7212     return FExpr->getString().drop_front(Offset);
7213   }
7214 
7215   unsigned getByteLength() const {
7216     return FExpr->getByteLength() - getCharByteWidth() * Offset;
7217   }
7218 
7219   unsigned getLength() const { return FExpr->getLength() - Offset; }
7220   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
7221 
7222   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
7223 
7224   QualType getType() const { return FExpr->getType(); }
7225 
7226   bool isAscii() const { return FExpr->isAscii(); }
7227   bool isWide() const { return FExpr->isWide(); }
7228   bool isUTF8() const { return FExpr->isUTF8(); }
7229   bool isUTF16() const { return FExpr->isUTF16(); }
7230   bool isUTF32() const { return FExpr->isUTF32(); }
7231   bool isPascal() const { return FExpr->isPascal(); }
7232 
7233   SourceLocation getLocationOfByte(
7234       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
7235       const TargetInfo &Target, unsigned *StartToken = nullptr,
7236       unsigned *StartTokenByteOffset = nullptr) const {
7237     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
7238                                     StartToken, StartTokenByteOffset);
7239   }
7240 
7241   SourceLocation getBeginLoc() const LLVM_READONLY {
7242     return FExpr->getBeginLoc().getLocWithOffset(Offset);
7243   }
7244 
7245   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
7246 };
7247 
7248 }  // namespace
7249 
7250 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
7251                               const Expr *OrigFormatExpr,
7252                               ArrayRef<const Expr *> Args,
7253                               bool HasVAListArg, unsigned format_idx,
7254                               unsigned firstDataArg,
7255                               Sema::FormatStringType Type,
7256                               bool inFunctionCall,
7257                               Sema::VariadicCallType CallType,
7258                               llvm::SmallBitVector &CheckedVarArgs,
7259                               UncoveredArgHandler &UncoveredArg,
7260                               bool IgnoreStringsWithoutSpecifiers);
7261 
7262 // Determine if an expression is a string literal or constant string.
7263 // If this function returns false on the arguments to a function expecting a
7264 // format string, we will usually need to emit a warning.
7265 // True string literals are then checked by CheckFormatString.
7266 static StringLiteralCheckType
7267 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
7268                       bool HasVAListArg, unsigned format_idx,
7269                       unsigned firstDataArg, Sema::FormatStringType Type,
7270                       Sema::VariadicCallType CallType, bool InFunctionCall,
7271                       llvm::SmallBitVector &CheckedVarArgs,
7272                       UncoveredArgHandler &UncoveredArg,
7273                       llvm::APSInt Offset,
7274                       bool IgnoreStringsWithoutSpecifiers = false) {
7275   if (S.isConstantEvaluated())
7276     return SLCT_NotALiteral;
7277  tryAgain:
7278   assert(Offset.isSigned() && "invalid offset");
7279 
7280   if (E->isTypeDependent() || E->isValueDependent())
7281     return SLCT_NotALiteral;
7282 
7283   E = E->IgnoreParenCasts();
7284 
7285   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
7286     // Technically -Wformat-nonliteral does not warn about this case.
7287     // The behavior of printf and friends in this case is implementation
7288     // dependent.  Ideally if the format string cannot be null then
7289     // it should have a 'nonnull' attribute in the function prototype.
7290     return SLCT_UncheckedLiteral;
7291 
7292   switch (E->getStmtClass()) {
7293   case Stmt::BinaryConditionalOperatorClass:
7294   case Stmt::ConditionalOperatorClass: {
7295     // The expression is a literal if both sub-expressions were, and it was
7296     // completely checked only if both sub-expressions were checked.
7297     const AbstractConditionalOperator *C =
7298         cast<AbstractConditionalOperator>(E);
7299 
7300     // Determine whether it is necessary to check both sub-expressions, for
7301     // example, because the condition expression is a constant that can be
7302     // evaluated at compile time.
7303     bool CheckLeft = true, CheckRight = true;
7304 
7305     bool Cond;
7306     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
7307                                                  S.isConstantEvaluated())) {
7308       if (Cond)
7309         CheckRight = false;
7310       else
7311         CheckLeft = false;
7312     }
7313 
7314     // We need to maintain the offsets for the right and the left hand side
7315     // separately to check if every possible indexed expression is a valid
7316     // string literal. They might have different offsets for different string
7317     // literals in the end.
7318     StringLiteralCheckType Left;
7319     if (!CheckLeft)
7320       Left = SLCT_UncheckedLiteral;
7321     else {
7322       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
7323                                    HasVAListArg, format_idx, firstDataArg,
7324                                    Type, CallType, InFunctionCall,
7325                                    CheckedVarArgs, UncoveredArg, Offset,
7326                                    IgnoreStringsWithoutSpecifiers);
7327       if (Left == SLCT_NotALiteral || !CheckRight) {
7328         return Left;
7329       }
7330     }
7331 
7332     StringLiteralCheckType Right = checkFormatStringExpr(
7333         S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
7334         Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7335         IgnoreStringsWithoutSpecifiers);
7336 
7337     return (CheckLeft && Left < Right) ? Left : Right;
7338   }
7339 
7340   case Stmt::ImplicitCastExprClass:
7341     E = cast<ImplicitCastExpr>(E)->getSubExpr();
7342     goto tryAgain;
7343 
7344   case Stmt::OpaqueValueExprClass:
7345     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
7346       E = src;
7347       goto tryAgain;
7348     }
7349     return SLCT_NotALiteral;
7350 
7351   case Stmt::PredefinedExprClass:
7352     // While __func__, etc., are technically not string literals, they
7353     // cannot contain format specifiers and thus are not a security
7354     // liability.
7355     return SLCT_UncheckedLiteral;
7356 
7357   case Stmt::DeclRefExprClass: {
7358     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7359 
7360     // As an exception, do not flag errors for variables binding to
7361     // const string literals.
7362     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
7363       bool isConstant = false;
7364       QualType T = DR->getType();
7365 
7366       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
7367         isConstant = AT->getElementType().isConstant(S.Context);
7368       } else if (const PointerType *PT = T->getAs<PointerType>()) {
7369         isConstant = T.isConstant(S.Context) &&
7370                      PT->getPointeeType().isConstant(S.Context);
7371       } else if (T->isObjCObjectPointerType()) {
7372         // In ObjC, there is usually no "const ObjectPointer" type,
7373         // so don't check if the pointee type is constant.
7374         isConstant = T.isConstant(S.Context);
7375       }
7376 
7377       if (isConstant) {
7378         if (const Expr *Init = VD->getAnyInitializer()) {
7379           // Look through initializers like const char c[] = { "foo" }
7380           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
7381             if (InitList->isStringLiteralInit())
7382               Init = InitList->getInit(0)->IgnoreParenImpCasts();
7383           }
7384           return checkFormatStringExpr(S, Init, Args,
7385                                        HasVAListArg, format_idx,
7386                                        firstDataArg, Type, CallType,
7387                                        /*InFunctionCall*/ false, CheckedVarArgs,
7388                                        UncoveredArg, Offset);
7389         }
7390       }
7391 
7392       // For vprintf* functions (i.e., HasVAListArg==true), we add a
7393       // special check to see if the format string is a function parameter
7394       // of the function calling the printf function.  If the function
7395       // has an attribute indicating it is a printf-like function, then we
7396       // should suppress warnings concerning non-literals being used in a call
7397       // to a vprintf function.  For example:
7398       //
7399       // void
7400       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
7401       //      va_list ap;
7402       //      va_start(ap, fmt);
7403       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
7404       //      ...
7405       // }
7406       if (HasVAListArg) {
7407         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
7408           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
7409             int PVIndex = PV->getFunctionScopeIndex() + 1;
7410             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
7411               // adjust for implicit parameter
7412               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
7413                 if (MD->isInstance())
7414                   ++PVIndex;
7415               // We also check if the formats are compatible.
7416               // We can't pass a 'scanf' string to a 'printf' function.
7417               if (PVIndex == PVFormat->getFormatIdx() &&
7418                   Type == S.GetFormatStringType(PVFormat))
7419                 return SLCT_UncheckedLiteral;
7420             }
7421           }
7422         }
7423       }
7424     }
7425 
7426     return SLCT_NotALiteral;
7427   }
7428 
7429   case Stmt::CallExprClass:
7430   case Stmt::CXXMemberCallExprClass: {
7431     const CallExpr *CE = cast<CallExpr>(E);
7432     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
7433       bool IsFirst = true;
7434       StringLiteralCheckType CommonResult;
7435       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
7436         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
7437         StringLiteralCheckType Result = checkFormatStringExpr(
7438             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7439             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7440             IgnoreStringsWithoutSpecifiers);
7441         if (IsFirst) {
7442           CommonResult = Result;
7443           IsFirst = false;
7444         }
7445       }
7446       if (!IsFirst)
7447         return CommonResult;
7448 
7449       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
7450         unsigned BuiltinID = FD->getBuiltinID();
7451         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
7452             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
7453           const Expr *Arg = CE->getArg(0);
7454           return checkFormatStringExpr(S, Arg, Args,
7455                                        HasVAListArg, format_idx,
7456                                        firstDataArg, Type, CallType,
7457                                        InFunctionCall, CheckedVarArgs,
7458                                        UncoveredArg, Offset,
7459                                        IgnoreStringsWithoutSpecifiers);
7460         }
7461       }
7462     }
7463 
7464     return SLCT_NotALiteral;
7465   }
7466   case Stmt::ObjCMessageExprClass: {
7467     const auto *ME = cast<ObjCMessageExpr>(E);
7468     if (const auto *MD = ME->getMethodDecl()) {
7469       if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
7470         // As a special case heuristic, if we're using the method -[NSBundle
7471         // localizedStringForKey:value:table:], ignore any key strings that lack
7472         // format specifiers. The idea is that if the key doesn't have any
7473         // format specifiers then its probably just a key to map to the
7474         // localized strings. If it does have format specifiers though, then its
7475         // likely that the text of the key is the format string in the
7476         // programmer's language, and should be checked.
7477         const ObjCInterfaceDecl *IFace;
7478         if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
7479             IFace->getIdentifier()->isStr("NSBundle") &&
7480             MD->getSelector().isKeywordSelector(
7481                 {"localizedStringForKey", "value", "table"})) {
7482           IgnoreStringsWithoutSpecifiers = true;
7483         }
7484 
7485         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
7486         return checkFormatStringExpr(
7487             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7488             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7489             IgnoreStringsWithoutSpecifiers);
7490       }
7491     }
7492 
7493     return SLCT_NotALiteral;
7494   }
7495   case Stmt::ObjCStringLiteralClass:
7496   case Stmt::StringLiteralClass: {
7497     const StringLiteral *StrE = nullptr;
7498 
7499     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
7500       StrE = ObjCFExpr->getString();
7501     else
7502       StrE = cast<StringLiteral>(E);
7503 
7504     if (StrE) {
7505       if (Offset.isNegative() || Offset > StrE->getLength()) {
7506         // TODO: It would be better to have an explicit warning for out of
7507         // bounds literals.
7508         return SLCT_NotALiteral;
7509       }
7510       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
7511       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
7512                         firstDataArg, Type, InFunctionCall, CallType,
7513                         CheckedVarArgs, UncoveredArg,
7514                         IgnoreStringsWithoutSpecifiers);
7515       return SLCT_CheckedLiteral;
7516     }
7517 
7518     return SLCT_NotALiteral;
7519   }
7520   case Stmt::BinaryOperatorClass: {
7521     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
7522 
7523     // A string literal + an int offset is still a string literal.
7524     if (BinOp->isAdditiveOp()) {
7525       Expr::EvalResult LResult, RResult;
7526 
7527       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
7528           LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7529       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
7530           RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7531 
7532       if (LIsInt != RIsInt) {
7533         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
7534 
7535         if (LIsInt) {
7536           if (BinOpKind == BO_Add) {
7537             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
7538             E = BinOp->getRHS();
7539             goto tryAgain;
7540           }
7541         } else {
7542           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
7543           E = BinOp->getLHS();
7544           goto tryAgain;
7545         }
7546       }
7547     }
7548 
7549     return SLCT_NotALiteral;
7550   }
7551   case Stmt::UnaryOperatorClass: {
7552     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
7553     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
7554     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
7555       Expr::EvalResult IndexResult;
7556       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
7557                                        Expr::SE_NoSideEffects,
7558                                        S.isConstantEvaluated())) {
7559         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
7560                    /*RHS is int*/ true);
7561         E = ASE->getBase();
7562         goto tryAgain;
7563       }
7564     }
7565 
7566     return SLCT_NotALiteral;
7567   }
7568 
7569   default:
7570     return SLCT_NotALiteral;
7571   }
7572 }
7573 
7574 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
7575   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
7576       .Case("scanf", FST_Scanf)
7577       .Cases("printf", "printf0", FST_Printf)
7578       .Cases("NSString", "CFString", FST_NSString)
7579       .Case("strftime", FST_Strftime)
7580       .Case("strfmon", FST_Strfmon)
7581       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
7582       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
7583       .Case("os_trace", FST_OSLog)
7584       .Case("os_log", FST_OSLog)
7585       .Default(FST_Unknown);
7586 }
7587 
7588 /// CheckFormatArguments - Check calls to printf and scanf (and similar
7589 /// functions) for correct use of format strings.
7590 /// Returns true if a format string has been fully checked.
7591 bool Sema::CheckFormatArguments(const FormatAttr *Format,
7592                                 ArrayRef<const Expr *> Args,
7593                                 bool IsCXXMember,
7594                                 VariadicCallType CallType,
7595                                 SourceLocation Loc, SourceRange Range,
7596                                 llvm::SmallBitVector &CheckedVarArgs) {
7597   FormatStringInfo FSI;
7598   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
7599     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
7600                                 FSI.FirstDataArg, GetFormatStringType(Format),
7601                                 CallType, Loc, Range, CheckedVarArgs);
7602   return false;
7603 }
7604 
7605 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
7606                                 bool HasVAListArg, unsigned format_idx,
7607                                 unsigned firstDataArg, FormatStringType Type,
7608                                 VariadicCallType CallType,
7609                                 SourceLocation Loc, SourceRange Range,
7610                                 llvm::SmallBitVector &CheckedVarArgs) {
7611   // CHECK: printf/scanf-like function is called with no format string.
7612   if (format_idx >= Args.size()) {
7613     Diag(Loc, diag::warn_missing_format_string) << Range;
7614     return false;
7615   }
7616 
7617   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
7618 
7619   // CHECK: format string is not a string literal.
7620   //
7621   // Dynamically generated format strings are difficult to
7622   // automatically vet at compile time.  Requiring that format strings
7623   // are string literals: (1) permits the checking of format strings by
7624   // the compiler and thereby (2) can practically remove the source of
7625   // many format string exploits.
7626 
7627   // Format string can be either ObjC string (e.g. @"%d") or
7628   // C string (e.g. "%d")
7629   // ObjC string uses the same format specifiers as C string, so we can use
7630   // the same format string checking logic for both ObjC and C strings.
7631   UncoveredArgHandler UncoveredArg;
7632   StringLiteralCheckType CT =
7633       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
7634                             format_idx, firstDataArg, Type, CallType,
7635                             /*IsFunctionCall*/ true, CheckedVarArgs,
7636                             UncoveredArg,
7637                             /*no string offset*/ llvm::APSInt(64, false) = 0);
7638 
7639   // Generate a diagnostic where an uncovered argument is detected.
7640   if (UncoveredArg.hasUncoveredArg()) {
7641     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
7642     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
7643     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
7644   }
7645 
7646   if (CT != SLCT_NotALiteral)
7647     // Literal format string found, check done!
7648     return CT == SLCT_CheckedLiteral;
7649 
7650   // Strftime is particular as it always uses a single 'time' argument,
7651   // so it is safe to pass a non-literal string.
7652   if (Type == FST_Strftime)
7653     return false;
7654 
7655   // Do not emit diag when the string param is a macro expansion and the
7656   // format is either NSString or CFString. This is a hack to prevent
7657   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
7658   // which are usually used in place of NS and CF string literals.
7659   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
7660   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
7661     return false;
7662 
7663   // If there are no arguments specified, warn with -Wformat-security, otherwise
7664   // warn only with -Wformat-nonliteral.
7665   if (Args.size() == firstDataArg) {
7666     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
7667       << OrigFormatExpr->getSourceRange();
7668     switch (Type) {
7669     default:
7670       break;
7671     case FST_Kprintf:
7672     case FST_FreeBSDKPrintf:
7673     case FST_Printf:
7674       Diag(FormatLoc, diag::note_format_security_fixit)
7675         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
7676       break;
7677     case FST_NSString:
7678       Diag(FormatLoc, diag::note_format_security_fixit)
7679         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
7680       break;
7681     }
7682   } else {
7683     Diag(FormatLoc, diag::warn_format_nonliteral)
7684       << OrigFormatExpr->getSourceRange();
7685   }
7686   return false;
7687 }
7688 
7689 namespace {
7690 
7691 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
7692 protected:
7693   Sema &S;
7694   const FormatStringLiteral *FExpr;
7695   const Expr *OrigFormatExpr;
7696   const Sema::FormatStringType FSType;
7697   const unsigned FirstDataArg;
7698   const unsigned NumDataArgs;
7699   const char *Beg; // Start of format string.
7700   const bool HasVAListArg;
7701   ArrayRef<const Expr *> Args;
7702   unsigned FormatIdx;
7703   llvm::SmallBitVector CoveredArgs;
7704   bool usesPositionalArgs = false;
7705   bool atFirstArg = true;
7706   bool inFunctionCall;
7707   Sema::VariadicCallType CallType;
7708   llvm::SmallBitVector &CheckedVarArgs;
7709   UncoveredArgHandler &UncoveredArg;
7710 
7711 public:
7712   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
7713                      const Expr *origFormatExpr,
7714                      const Sema::FormatStringType type, unsigned firstDataArg,
7715                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
7716                      ArrayRef<const Expr *> Args, unsigned formatIdx,
7717                      bool inFunctionCall, Sema::VariadicCallType callType,
7718                      llvm::SmallBitVector &CheckedVarArgs,
7719                      UncoveredArgHandler &UncoveredArg)
7720       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
7721         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
7722         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
7723         inFunctionCall(inFunctionCall), CallType(callType),
7724         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
7725     CoveredArgs.resize(numDataArgs);
7726     CoveredArgs.reset();
7727   }
7728 
7729   void DoneProcessing();
7730 
7731   void HandleIncompleteSpecifier(const char *startSpecifier,
7732                                  unsigned specifierLen) override;
7733 
7734   void HandleInvalidLengthModifier(
7735                            const analyze_format_string::FormatSpecifier &FS,
7736                            const analyze_format_string::ConversionSpecifier &CS,
7737                            const char *startSpecifier, unsigned specifierLen,
7738                            unsigned DiagID);
7739 
7740   void HandleNonStandardLengthModifier(
7741                     const analyze_format_string::FormatSpecifier &FS,
7742                     const char *startSpecifier, unsigned specifierLen);
7743 
7744   void HandleNonStandardConversionSpecifier(
7745                     const analyze_format_string::ConversionSpecifier &CS,
7746                     const char *startSpecifier, unsigned specifierLen);
7747 
7748   void HandlePosition(const char *startPos, unsigned posLen) override;
7749 
7750   void HandleInvalidPosition(const char *startSpecifier,
7751                              unsigned specifierLen,
7752                              analyze_format_string::PositionContext p) override;
7753 
7754   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
7755 
7756   void HandleNullChar(const char *nullCharacter) override;
7757 
7758   template <typename Range>
7759   static void
7760   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
7761                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
7762                        bool IsStringLocation, Range StringRange,
7763                        ArrayRef<FixItHint> Fixit = None);
7764 
7765 protected:
7766   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
7767                                         const char *startSpec,
7768                                         unsigned specifierLen,
7769                                         const char *csStart, unsigned csLen);
7770 
7771   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
7772                                          const char *startSpec,
7773                                          unsigned specifierLen);
7774 
7775   SourceRange getFormatStringRange();
7776   CharSourceRange getSpecifierRange(const char *startSpecifier,
7777                                     unsigned specifierLen);
7778   SourceLocation getLocationOfByte(const char *x);
7779 
7780   const Expr *getDataArg(unsigned i) const;
7781 
7782   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
7783                     const analyze_format_string::ConversionSpecifier &CS,
7784                     const char *startSpecifier, unsigned specifierLen,
7785                     unsigned argIndex);
7786 
7787   template <typename Range>
7788   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
7789                             bool IsStringLocation, Range StringRange,
7790                             ArrayRef<FixItHint> Fixit = None);
7791 };
7792 
7793 } // namespace
7794 
7795 SourceRange CheckFormatHandler::getFormatStringRange() {
7796   return OrigFormatExpr->getSourceRange();
7797 }
7798 
7799 CharSourceRange CheckFormatHandler::
7800 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
7801   SourceLocation Start = getLocationOfByte(startSpecifier);
7802   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
7803 
7804   // Advance the end SourceLocation by one due to half-open ranges.
7805   End = End.getLocWithOffset(1);
7806 
7807   return CharSourceRange::getCharRange(Start, End);
7808 }
7809 
7810 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
7811   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
7812                                   S.getLangOpts(), S.Context.getTargetInfo());
7813 }
7814 
7815 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
7816                                                    unsigned specifierLen){
7817   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
7818                        getLocationOfByte(startSpecifier),
7819                        /*IsStringLocation*/true,
7820                        getSpecifierRange(startSpecifier, specifierLen));
7821 }
7822 
7823 void CheckFormatHandler::HandleInvalidLengthModifier(
7824     const analyze_format_string::FormatSpecifier &FS,
7825     const analyze_format_string::ConversionSpecifier &CS,
7826     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
7827   using namespace analyze_format_string;
7828 
7829   const LengthModifier &LM = FS.getLengthModifier();
7830   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7831 
7832   // See if we know how to fix this length modifier.
7833   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7834   if (FixedLM) {
7835     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7836                          getLocationOfByte(LM.getStart()),
7837                          /*IsStringLocation*/true,
7838                          getSpecifierRange(startSpecifier, specifierLen));
7839 
7840     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7841       << FixedLM->toString()
7842       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7843 
7844   } else {
7845     FixItHint Hint;
7846     if (DiagID == diag::warn_format_nonsensical_length)
7847       Hint = FixItHint::CreateRemoval(LMRange);
7848 
7849     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7850                          getLocationOfByte(LM.getStart()),
7851                          /*IsStringLocation*/true,
7852                          getSpecifierRange(startSpecifier, specifierLen),
7853                          Hint);
7854   }
7855 }
7856 
7857 void CheckFormatHandler::HandleNonStandardLengthModifier(
7858     const analyze_format_string::FormatSpecifier &FS,
7859     const char *startSpecifier, unsigned specifierLen) {
7860   using namespace analyze_format_string;
7861 
7862   const LengthModifier &LM = FS.getLengthModifier();
7863   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7864 
7865   // See if we know how to fix this length modifier.
7866   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7867   if (FixedLM) {
7868     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7869                            << LM.toString() << 0,
7870                          getLocationOfByte(LM.getStart()),
7871                          /*IsStringLocation*/true,
7872                          getSpecifierRange(startSpecifier, specifierLen));
7873 
7874     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7875       << FixedLM->toString()
7876       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7877 
7878   } else {
7879     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7880                            << LM.toString() << 0,
7881                          getLocationOfByte(LM.getStart()),
7882                          /*IsStringLocation*/true,
7883                          getSpecifierRange(startSpecifier, specifierLen));
7884   }
7885 }
7886 
7887 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
7888     const analyze_format_string::ConversionSpecifier &CS,
7889     const char *startSpecifier, unsigned specifierLen) {
7890   using namespace analyze_format_string;
7891 
7892   // See if we know how to fix this conversion specifier.
7893   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
7894   if (FixedCS) {
7895     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7896                           << CS.toString() << /*conversion specifier*/1,
7897                          getLocationOfByte(CS.getStart()),
7898                          /*IsStringLocation*/true,
7899                          getSpecifierRange(startSpecifier, specifierLen));
7900 
7901     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
7902     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
7903       << FixedCS->toString()
7904       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
7905   } else {
7906     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7907                           << CS.toString() << /*conversion specifier*/1,
7908                          getLocationOfByte(CS.getStart()),
7909                          /*IsStringLocation*/true,
7910                          getSpecifierRange(startSpecifier, specifierLen));
7911   }
7912 }
7913 
7914 void CheckFormatHandler::HandlePosition(const char *startPos,
7915                                         unsigned posLen) {
7916   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
7917                                getLocationOfByte(startPos),
7918                                /*IsStringLocation*/true,
7919                                getSpecifierRange(startPos, posLen));
7920 }
7921 
7922 void
7923 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
7924                                      analyze_format_string::PositionContext p) {
7925   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
7926                          << (unsigned) p,
7927                        getLocationOfByte(startPos), /*IsStringLocation*/true,
7928                        getSpecifierRange(startPos, posLen));
7929 }
7930 
7931 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
7932                                             unsigned posLen) {
7933   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
7934                                getLocationOfByte(startPos),
7935                                /*IsStringLocation*/true,
7936                                getSpecifierRange(startPos, posLen));
7937 }
7938 
7939 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
7940   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
7941     // The presence of a null character is likely an error.
7942     EmitFormatDiagnostic(
7943       S.PDiag(diag::warn_printf_format_string_contains_null_char),
7944       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
7945       getFormatStringRange());
7946   }
7947 }
7948 
7949 // Note that this may return NULL if there was an error parsing or building
7950 // one of the argument expressions.
7951 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
7952   return Args[FirstDataArg + i];
7953 }
7954 
7955 void CheckFormatHandler::DoneProcessing() {
7956   // Does the number of data arguments exceed the number of
7957   // format conversions in the format string?
7958   if (!HasVAListArg) {
7959       // Find any arguments that weren't covered.
7960     CoveredArgs.flip();
7961     signed notCoveredArg = CoveredArgs.find_first();
7962     if (notCoveredArg >= 0) {
7963       assert((unsigned)notCoveredArg < NumDataArgs);
7964       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
7965     } else {
7966       UncoveredArg.setAllCovered();
7967     }
7968   }
7969 }
7970 
7971 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
7972                                    const Expr *ArgExpr) {
7973   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
7974          "Invalid state");
7975 
7976   if (!ArgExpr)
7977     return;
7978 
7979   SourceLocation Loc = ArgExpr->getBeginLoc();
7980 
7981   if (S.getSourceManager().isInSystemMacro(Loc))
7982     return;
7983 
7984   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
7985   for (auto E : DiagnosticExprs)
7986     PDiag << E->getSourceRange();
7987 
7988   CheckFormatHandler::EmitFormatDiagnostic(
7989                                   S, IsFunctionCall, DiagnosticExprs[0],
7990                                   PDiag, Loc, /*IsStringLocation*/false,
7991                                   DiagnosticExprs[0]->getSourceRange());
7992 }
7993 
7994 bool
7995 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
7996                                                      SourceLocation Loc,
7997                                                      const char *startSpec,
7998                                                      unsigned specifierLen,
7999                                                      const char *csStart,
8000                                                      unsigned csLen) {
8001   bool keepGoing = true;
8002   if (argIndex < NumDataArgs) {
8003     // Consider the argument coverered, even though the specifier doesn't
8004     // make sense.
8005     CoveredArgs.set(argIndex);
8006   }
8007   else {
8008     // If argIndex exceeds the number of data arguments we
8009     // don't issue a warning because that is just a cascade of warnings (and
8010     // they may have intended '%%' anyway). We don't want to continue processing
8011     // the format string after this point, however, as we will like just get
8012     // gibberish when trying to match arguments.
8013     keepGoing = false;
8014   }
8015 
8016   StringRef Specifier(csStart, csLen);
8017 
8018   // If the specifier in non-printable, it could be the first byte of a UTF-8
8019   // sequence. In that case, print the UTF-8 code point. If not, print the byte
8020   // hex value.
8021   std::string CodePointStr;
8022   if (!llvm::sys::locale::isPrint(*csStart)) {
8023     llvm::UTF32 CodePoint;
8024     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
8025     const llvm::UTF8 *E =
8026         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
8027     llvm::ConversionResult Result =
8028         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
8029 
8030     if (Result != llvm::conversionOK) {
8031       unsigned char FirstChar = *csStart;
8032       CodePoint = (llvm::UTF32)FirstChar;
8033     }
8034 
8035     llvm::raw_string_ostream OS(CodePointStr);
8036     if (CodePoint < 256)
8037       OS << "\\x" << llvm::format("%02x", CodePoint);
8038     else if (CodePoint <= 0xFFFF)
8039       OS << "\\u" << llvm::format("%04x", CodePoint);
8040     else
8041       OS << "\\U" << llvm::format("%08x", CodePoint);
8042     OS.flush();
8043     Specifier = CodePointStr;
8044   }
8045 
8046   EmitFormatDiagnostic(
8047       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
8048       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
8049 
8050   return keepGoing;
8051 }
8052 
8053 void
8054 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
8055                                                       const char *startSpec,
8056                                                       unsigned specifierLen) {
8057   EmitFormatDiagnostic(
8058     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
8059     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
8060 }
8061 
8062 bool
8063 CheckFormatHandler::CheckNumArgs(
8064   const analyze_format_string::FormatSpecifier &FS,
8065   const analyze_format_string::ConversionSpecifier &CS,
8066   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
8067 
8068   if (argIndex >= NumDataArgs) {
8069     PartialDiagnostic PDiag = FS.usesPositionalArg()
8070       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
8071            << (argIndex+1) << NumDataArgs)
8072       : S.PDiag(diag::warn_printf_insufficient_data_args);
8073     EmitFormatDiagnostic(
8074       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
8075       getSpecifierRange(startSpecifier, specifierLen));
8076 
8077     // Since more arguments than conversion tokens are given, by extension
8078     // all arguments are covered, so mark this as so.
8079     UncoveredArg.setAllCovered();
8080     return false;
8081   }
8082   return true;
8083 }
8084 
8085 template<typename Range>
8086 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
8087                                               SourceLocation Loc,
8088                                               bool IsStringLocation,
8089                                               Range StringRange,
8090                                               ArrayRef<FixItHint> FixIt) {
8091   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
8092                        Loc, IsStringLocation, StringRange, FixIt);
8093 }
8094 
8095 /// If the format string is not within the function call, emit a note
8096 /// so that the function call and string are in diagnostic messages.
8097 ///
8098 /// \param InFunctionCall if true, the format string is within the function
8099 /// call and only one diagnostic message will be produced.  Otherwise, an
8100 /// extra note will be emitted pointing to location of the format string.
8101 ///
8102 /// \param ArgumentExpr the expression that is passed as the format string
8103 /// argument in the function call.  Used for getting locations when two
8104 /// diagnostics are emitted.
8105 ///
8106 /// \param PDiag the callee should already have provided any strings for the
8107 /// diagnostic message.  This function only adds locations and fixits
8108 /// to diagnostics.
8109 ///
8110 /// \param Loc primary location for diagnostic.  If two diagnostics are
8111 /// required, one will be at Loc and a new SourceLocation will be created for
8112 /// the other one.
8113 ///
8114 /// \param IsStringLocation if true, Loc points to the format string should be
8115 /// used for the note.  Otherwise, Loc points to the argument list and will
8116 /// be used with PDiag.
8117 ///
8118 /// \param StringRange some or all of the string to highlight.  This is
8119 /// templated so it can accept either a CharSourceRange or a SourceRange.
8120 ///
8121 /// \param FixIt optional fix it hint for the format string.
8122 template <typename Range>
8123 void CheckFormatHandler::EmitFormatDiagnostic(
8124     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
8125     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
8126     Range StringRange, ArrayRef<FixItHint> FixIt) {
8127   if (InFunctionCall) {
8128     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
8129     D << StringRange;
8130     D << FixIt;
8131   } else {
8132     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
8133       << ArgumentExpr->getSourceRange();
8134 
8135     const Sema::SemaDiagnosticBuilder &Note =
8136       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
8137              diag::note_format_string_defined);
8138 
8139     Note << StringRange;
8140     Note << FixIt;
8141   }
8142 }
8143 
8144 //===--- CHECK: Printf format string checking ------------------------------===//
8145 
8146 namespace {
8147 
8148 class CheckPrintfHandler : public CheckFormatHandler {
8149 public:
8150   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8151                      const Expr *origFormatExpr,
8152                      const Sema::FormatStringType type, unsigned firstDataArg,
8153                      unsigned numDataArgs, bool isObjC, const char *beg,
8154                      bool hasVAListArg, ArrayRef<const Expr *> Args,
8155                      unsigned formatIdx, bool inFunctionCall,
8156                      Sema::VariadicCallType CallType,
8157                      llvm::SmallBitVector &CheckedVarArgs,
8158                      UncoveredArgHandler &UncoveredArg)
8159       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8160                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
8161                            inFunctionCall, CallType, CheckedVarArgs,
8162                            UncoveredArg) {}
8163 
8164   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
8165 
8166   /// Returns true if '%@' specifiers are allowed in the format string.
8167   bool allowsObjCArg() const {
8168     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
8169            FSType == Sema::FST_OSTrace;
8170   }
8171 
8172   bool HandleInvalidPrintfConversionSpecifier(
8173                                       const analyze_printf::PrintfSpecifier &FS,
8174                                       const char *startSpecifier,
8175                                       unsigned specifierLen) override;
8176 
8177   void handleInvalidMaskType(StringRef MaskType) override;
8178 
8179   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8180                              const char *startSpecifier,
8181                              unsigned specifierLen) override;
8182   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8183                        const char *StartSpecifier,
8184                        unsigned SpecifierLen,
8185                        const Expr *E);
8186 
8187   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
8188                     const char *startSpecifier, unsigned specifierLen);
8189   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
8190                            const analyze_printf::OptionalAmount &Amt,
8191                            unsigned type,
8192                            const char *startSpecifier, unsigned specifierLen);
8193   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8194                   const analyze_printf::OptionalFlag &flag,
8195                   const char *startSpecifier, unsigned specifierLen);
8196   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
8197                          const analyze_printf::OptionalFlag &ignoredFlag,
8198                          const analyze_printf::OptionalFlag &flag,
8199                          const char *startSpecifier, unsigned specifierLen);
8200   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
8201                            const Expr *E);
8202 
8203   void HandleEmptyObjCModifierFlag(const char *startFlag,
8204                                    unsigned flagLen) override;
8205 
8206   void HandleInvalidObjCModifierFlag(const char *startFlag,
8207                                             unsigned flagLen) override;
8208 
8209   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
8210                                            const char *flagsEnd,
8211                                            const char *conversionPosition)
8212                                              override;
8213 };
8214 
8215 } // namespace
8216 
8217 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
8218                                       const analyze_printf::PrintfSpecifier &FS,
8219                                       const char *startSpecifier,
8220                                       unsigned specifierLen) {
8221   const analyze_printf::PrintfConversionSpecifier &CS =
8222     FS.getConversionSpecifier();
8223 
8224   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8225                                           getLocationOfByte(CS.getStart()),
8226                                           startSpecifier, specifierLen,
8227                                           CS.getStart(), CS.getLength());
8228 }
8229 
8230 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
8231   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
8232 }
8233 
8234 bool CheckPrintfHandler::HandleAmount(
8235                                const analyze_format_string::OptionalAmount &Amt,
8236                                unsigned k, const char *startSpecifier,
8237                                unsigned specifierLen) {
8238   if (Amt.hasDataArgument()) {
8239     if (!HasVAListArg) {
8240       unsigned argIndex = Amt.getArgIndex();
8241       if (argIndex >= NumDataArgs) {
8242         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
8243                                << k,
8244                              getLocationOfByte(Amt.getStart()),
8245                              /*IsStringLocation*/true,
8246                              getSpecifierRange(startSpecifier, specifierLen));
8247         // Don't do any more checking.  We will just emit
8248         // spurious errors.
8249         return false;
8250       }
8251 
8252       // Type check the data argument.  It should be an 'int'.
8253       // Although not in conformance with C99, we also allow the argument to be
8254       // an 'unsigned int' as that is a reasonably safe case.  GCC also
8255       // doesn't emit a warning for that case.
8256       CoveredArgs.set(argIndex);
8257       const Expr *Arg = getDataArg(argIndex);
8258       if (!Arg)
8259         return false;
8260 
8261       QualType T = Arg->getType();
8262 
8263       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
8264       assert(AT.isValid());
8265 
8266       if (!AT.matchesType(S.Context, T)) {
8267         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
8268                                << k << AT.getRepresentativeTypeName(S.Context)
8269                                << T << Arg->getSourceRange(),
8270                              getLocationOfByte(Amt.getStart()),
8271                              /*IsStringLocation*/true,
8272                              getSpecifierRange(startSpecifier, specifierLen));
8273         // Don't do any more checking.  We will just emit
8274         // spurious errors.
8275         return false;
8276       }
8277     }
8278   }
8279   return true;
8280 }
8281 
8282 void CheckPrintfHandler::HandleInvalidAmount(
8283                                       const analyze_printf::PrintfSpecifier &FS,
8284                                       const analyze_printf::OptionalAmount &Amt,
8285                                       unsigned type,
8286                                       const char *startSpecifier,
8287                                       unsigned specifierLen) {
8288   const analyze_printf::PrintfConversionSpecifier &CS =
8289     FS.getConversionSpecifier();
8290 
8291   FixItHint fixit =
8292     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
8293       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
8294                                  Amt.getConstantLength()))
8295       : FixItHint();
8296 
8297   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
8298                          << type << CS.toString(),
8299                        getLocationOfByte(Amt.getStart()),
8300                        /*IsStringLocation*/true,
8301                        getSpecifierRange(startSpecifier, specifierLen),
8302                        fixit);
8303 }
8304 
8305 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8306                                     const analyze_printf::OptionalFlag &flag,
8307                                     const char *startSpecifier,
8308                                     unsigned specifierLen) {
8309   // Warn about pointless flag with a fixit removal.
8310   const analyze_printf::PrintfConversionSpecifier &CS =
8311     FS.getConversionSpecifier();
8312   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
8313                          << flag.toString() << CS.toString(),
8314                        getLocationOfByte(flag.getPosition()),
8315                        /*IsStringLocation*/true,
8316                        getSpecifierRange(startSpecifier, specifierLen),
8317                        FixItHint::CreateRemoval(
8318                          getSpecifierRange(flag.getPosition(), 1)));
8319 }
8320 
8321 void CheckPrintfHandler::HandleIgnoredFlag(
8322                                 const analyze_printf::PrintfSpecifier &FS,
8323                                 const analyze_printf::OptionalFlag &ignoredFlag,
8324                                 const analyze_printf::OptionalFlag &flag,
8325                                 const char *startSpecifier,
8326                                 unsigned specifierLen) {
8327   // Warn about ignored flag with a fixit removal.
8328   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
8329                          << ignoredFlag.toString() << flag.toString(),
8330                        getLocationOfByte(ignoredFlag.getPosition()),
8331                        /*IsStringLocation*/true,
8332                        getSpecifierRange(startSpecifier, specifierLen),
8333                        FixItHint::CreateRemoval(
8334                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
8335 }
8336 
8337 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
8338                                                      unsigned flagLen) {
8339   // Warn about an empty flag.
8340   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
8341                        getLocationOfByte(startFlag),
8342                        /*IsStringLocation*/true,
8343                        getSpecifierRange(startFlag, flagLen));
8344 }
8345 
8346 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
8347                                                        unsigned flagLen) {
8348   // Warn about an invalid flag.
8349   auto Range = getSpecifierRange(startFlag, flagLen);
8350   StringRef flag(startFlag, flagLen);
8351   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
8352                       getLocationOfByte(startFlag),
8353                       /*IsStringLocation*/true,
8354                       Range, FixItHint::CreateRemoval(Range));
8355 }
8356 
8357 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
8358     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
8359     // Warn about using '[...]' without a '@' conversion.
8360     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
8361     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
8362     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
8363                          getLocationOfByte(conversionPosition),
8364                          /*IsStringLocation*/true,
8365                          Range, FixItHint::CreateRemoval(Range));
8366 }
8367 
8368 // Determines if the specified is a C++ class or struct containing
8369 // a member with the specified name and kind (e.g. a CXXMethodDecl named
8370 // "c_str()").
8371 template<typename MemberKind>
8372 static llvm::SmallPtrSet<MemberKind*, 1>
8373 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
8374   const RecordType *RT = Ty->getAs<RecordType>();
8375   llvm::SmallPtrSet<MemberKind*, 1> Results;
8376 
8377   if (!RT)
8378     return Results;
8379   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
8380   if (!RD || !RD->getDefinition())
8381     return Results;
8382 
8383   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
8384                  Sema::LookupMemberName);
8385   R.suppressDiagnostics();
8386 
8387   // We just need to include all members of the right kind turned up by the
8388   // filter, at this point.
8389   if (S.LookupQualifiedName(R, RT->getDecl()))
8390     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8391       NamedDecl *decl = (*I)->getUnderlyingDecl();
8392       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
8393         Results.insert(FK);
8394     }
8395   return Results;
8396 }
8397 
8398 /// Check if we could call '.c_str()' on an object.
8399 ///
8400 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
8401 /// allow the call, or if it would be ambiguous).
8402 bool Sema::hasCStrMethod(const Expr *E) {
8403   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8404 
8405   MethodSet Results =
8406       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
8407   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8408        MI != ME; ++MI)
8409     if ((*MI)->getMinRequiredArguments() == 0)
8410       return true;
8411   return false;
8412 }
8413 
8414 // Check if a (w)string was passed when a (w)char* was needed, and offer a
8415 // better diagnostic if so. AT is assumed to be valid.
8416 // Returns true when a c_str() conversion method is found.
8417 bool CheckPrintfHandler::checkForCStrMembers(
8418     const analyze_printf::ArgType &AT, const Expr *E) {
8419   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8420 
8421   MethodSet Results =
8422       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
8423 
8424   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8425        MI != ME; ++MI) {
8426     const CXXMethodDecl *Method = *MI;
8427     if (Method->getMinRequiredArguments() == 0 &&
8428         AT.matchesType(S.Context, Method->getReturnType())) {
8429       // FIXME: Suggest parens if the expression needs them.
8430       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
8431       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
8432           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
8433       return true;
8434     }
8435   }
8436 
8437   return false;
8438 }
8439 
8440 bool
8441 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
8442                                             &FS,
8443                                           const char *startSpecifier,
8444                                           unsigned specifierLen) {
8445   using namespace analyze_format_string;
8446   using namespace analyze_printf;
8447 
8448   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
8449 
8450   if (FS.consumesDataArgument()) {
8451     if (atFirstArg) {
8452         atFirstArg = false;
8453         usesPositionalArgs = FS.usesPositionalArg();
8454     }
8455     else if (usesPositionalArgs != FS.usesPositionalArg()) {
8456       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8457                                         startSpecifier, specifierLen);
8458       return false;
8459     }
8460   }
8461 
8462   // First check if the field width, precision, and conversion specifier
8463   // have matching data arguments.
8464   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
8465                     startSpecifier, specifierLen)) {
8466     return false;
8467   }
8468 
8469   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
8470                     startSpecifier, specifierLen)) {
8471     return false;
8472   }
8473 
8474   if (!CS.consumesDataArgument()) {
8475     // FIXME: Technically specifying a precision or field width here
8476     // makes no sense.  Worth issuing a warning at some point.
8477     return true;
8478   }
8479 
8480   // Consume the argument.
8481   unsigned argIndex = FS.getArgIndex();
8482   if (argIndex < NumDataArgs) {
8483     // The check to see if the argIndex is valid will come later.
8484     // We set the bit here because we may exit early from this
8485     // function if we encounter some other error.
8486     CoveredArgs.set(argIndex);
8487   }
8488 
8489   // FreeBSD kernel extensions.
8490   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
8491       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
8492     // We need at least two arguments.
8493     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
8494       return false;
8495 
8496     // Claim the second argument.
8497     CoveredArgs.set(argIndex + 1);
8498 
8499     // Type check the first argument (int for %b, pointer for %D)
8500     const Expr *Ex = getDataArg(argIndex);
8501     const analyze_printf::ArgType &AT =
8502       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
8503         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
8504     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
8505       EmitFormatDiagnostic(
8506           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8507               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
8508               << false << Ex->getSourceRange(),
8509           Ex->getBeginLoc(), /*IsStringLocation*/ false,
8510           getSpecifierRange(startSpecifier, specifierLen));
8511 
8512     // Type check the second argument (char * for both %b and %D)
8513     Ex = getDataArg(argIndex + 1);
8514     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
8515     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
8516       EmitFormatDiagnostic(
8517           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8518               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
8519               << false << Ex->getSourceRange(),
8520           Ex->getBeginLoc(), /*IsStringLocation*/ false,
8521           getSpecifierRange(startSpecifier, specifierLen));
8522 
8523      return true;
8524   }
8525 
8526   // Check for using an Objective-C specific conversion specifier
8527   // in a non-ObjC literal.
8528   if (!allowsObjCArg() && CS.isObjCArg()) {
8529     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8530                                                   specifierLen);
8531   }
8532 
8533   // %P can only be used with os_log.
8534   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
8535     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8536                                                   specifierLen);
8537   }
8538 
8539   // %n is not allowed with os_log.
8540   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
8541     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
8542                          getLocationOfByte(CS.getStart()),
8543                          /*IsStringLocation*/ false,
8544                          getSpecifierRange(startSpecifier, specifierLen));
8545 
8546     return true;
8547   }
8548 
8549   // Only scalars are allowed for os_trace.
8550   if (FSType == Sema::FST_OSTrace &&
8551       (CS.getKind() == ConversionSpecifier::PArg ||
8552        CS.getKind() == ConversionSpecifier::sArg ||
8553        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
8554     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8555                                                   specifierLen);
8556   }
8557 
8558   // Check for use of public/private annotation outside of os_log().
8559   if (FSType != Sema::FST_OSLog) {
8560     if (FS.isPublic().isSet()) {
8561       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8562                                << "public",
8563                            getLocationOfByte(FS.isPublic().getPosition()),
8564                            /*IsStringLocation*/ false,
8565                            getSpecifierRange(startSpecifier, specifierLen));
8566     }
8567     if (FS.isPrivate().isSet()) {
8568       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8569                                << "private",
8570                            getLocationOfByte(FS.isPrivate().getPosition()),
8571                            /*IsStringLocation*/ false,
8572                            getSpecifierRange(startSpecifier, specifierLen));
8573     }
8574   }
8575 
8576   // Check for invalid use of field width
8577   if (!FS.hasValidFieldWidth()) {
8578     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
8579         startSpecifier, specifierLen);
8580   }
8581 
8582   // Check for invalid use of precision
8583   if (!FS.hasValidPrecision()) {
8584     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
8585         startSpecifier, specifierLen);
8586   }
8587 
8588   // Precision is mandatory for %P specifier.
8589   if (CS.getKind() == ConversionSpecifier::PArg &&
8590       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
8591     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
8592                          getLocationOfByte(startSpecifier),
8593                          /*IsStringLocation*/ false,
8594                          getSpecifierRange(startSpecifier, specifierLen));
8595   }
8596 
8597   // Check each flag does not conflict with any other component.
8598   if (!FS.hasValidThousandsGroupingPrefix())
8599     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
8600   if (!FS.hasValidLeadingZeros())
8601     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
8602   if (!FS.hasValidPlusPrefix())
8603     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
8604   if (!FS.hasValidSpacePrefix())
8605     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
8606   if (!FS.hasValidAlternativeForm())
8607     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
8608   if (!FS.hasValidLeftJustified())
8609     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
8610 
8611   // Check that flags are not ignored by another flag
8612   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
8613     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
8614         startSpecifier, specifierLen);
8615   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
8616     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
8617             startSpecifier, specifierLen);
8618 
8619   // Check the length modifier is valid with the given conversion specifier.
8620   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8621                                  S.getLangOpts()))
8622     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8623                                 diag::warn_format_nonsensical_length);
8624   else if (!FS.hasStandardLengthModifier())
8625     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8626   else if (!FS.hasStandardLengthConversionCombination())
8627     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8628                                 diag::warn_format_non_standard_conversion_spec);
8629 
8630   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8631     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8632 
8633   // The remaining checks depend on the data arguments.
8634   if (HasVAListArg)
8635     return true;
8636 
8637   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8638     return false;
8639 
8640   const Expr *Arg = getDataArg(argIndex);
8641   if (!Arg)
8642     return true;
8643 
8644   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
8645 }
8646 
8647 static bool requiresParensToAddCast(const Expr *E) {
8648   // FIXME: We should have a general way to reason about operator
8649   // precedence and whether parens are actually needed here.
8650   // Take care of a few common cases where they aren't.
8651   const Expr *Inside = E->IgnoreImpCasts();
8652   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
8653     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
8654 
8655   switch (Inside->getStmtClass()) {
8656   case Stmt::ArraySubscriptExprClass:
8657   case Stmt::CallExprClass:
8658   case Stmt::CharacterLiteralClass:
8659   case Stmt::CXXBoolLiteralExprClass:
8660   case Stmt::DeclRefExprClass:
8661   case Stmt::FloatingLiteralClass:
8662   case Stmt::IntegerLiteralClass:
8663   case Stmt::MemberExprClass:
8664   case Stmt::ObjCArrayLiteralClass:
8665   case Stmt::ObjCBoolLiteralExprClass:
8666   case Stmt::ObjCBoxedExprClass:
8667   case Stmt::ObjCDictionaryLiteralClass:
8668   case Stmt::ObjCEncodeExprClass:
8669   case Stmt::ObjCIvarRefExprClass:
8670   case Stmt::ObjCMessageExprClass:
8671   case Stmt::ObjCPropertyRefExprClass:
8672   case Stmt::ObjCStringLiteralClass:
8673   case Stmt::ObjCSubscriptRefExprClass:
8674   case Stmt::ParenExprClass:
8675   case Stmt::StringLiteralClass:
8676   case Stmt::UnaryOperatorClass:
8677     return false;
8678   default:
8679     return true;
8680   }
8681 }
8682 
8683 static std::pair<QualType, StringRef>
8684 shouldNotPrintDirectly(const ASTContext &Context,
8685                        QualType IntendedTy,
8686                        const Expr *E) {
8687   // Use a 'while' to peel off layers of typedefs.
8688   QualType TyTy = IntendedTy;
8689   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
8690     StringRef Name = UserTy->getDecl()->getName();
8691     QualType CastTy = llvm::StringSwitch<QualType>(Name)
8692       .Case("CFIndex", Context.getNSIntegerType())
8693       .Case("NSInteger", Context.getNSIntegerType())
8694       .Case("NSUInteger", Context.getNSUIntegerType())
8695       .Case("SInt32", Context.IntTy)
8696       .Case("UInt32", Context.UnsignedIntTy)
8697       .Default(QualType());
8698 
8699     if (!CastTy.isNull())
8700       return std::make_pair(CastTy, Name);
8701 
8702     TyTy = UserTy->desugar();
8703   }
8704 
8705   // Strip parens if necessary.
8706   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
8707     return shouldNotPrintDirectly(Context,
8708                                   PE->getSubExpr()->getType(),
8709                                   PE->getSubExpr());
8710 
8711   // If this is a conditional expression, then its result type is constructed
8712   // via usual arithmetic conversions and thus there might be no necessary
8713   // typedef sugar there.  Recurse to operands to check for NSInteger &
8714   // Co. usage condition.
8715   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8716     QualType TrueTy, FalseTy;
8717     StringRef TrueName, FalseName;
8718 
8719     std::tie(TrueTy, TrueName) =
8720       shouldNotPrintDirectly(Context,
8721                              CO->getTrueExpr()->getType(),
8722                              CO->getTrueExpr());
8723     std::tie(FalseTy, FalseName) =
8724       shouldNotPrintDirectly(Context,
8725                              CO->getFalseExpr()->getType(),
8726                              CO->getFalseExpr());
8727 
8728     if (TrueTy == FalseTy)
8729       return std::make_pair(TrueTy, TrueName);
8730     else if (TrueTy.isNull())
8731       return std::make_pair(FalseTy, FalseName);
8732     else if (FalseTy.isNull())
8733       return std::make_pair(TrueTy, TrueName);
8734   }
8735 
8736   return std::make_pair(QualType(), StringRef());
8737 }
8738 
8739 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
8740 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
8741 /// type do not count.
8742 static bool
8743 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
8744   QualType From = ICE->getSubExpr()->getType();
8745   QualType To = ICE->getType();
8746   // It's an integer promotion if the destination type is the promoted
8747   // source type.
8748   if (ICE->getCastKind() == CK_IntegralCast &&
8749       From->isPromotableIntegerType() &&
8750       S.Context.getPromotedIntegerType(From) == To)
8751     return true;
8752   // Look through vector types, since we do default argument promotion for
8753   // those in OpenCL.
8754   if (const auto *VecTy = From->getAs<ExtVectorType>())
8755     From = VecTy->getElementType();
8756   if (const auto *VecTy = To->getAs<ExtVectorType>())
8757     To = VecTy->getElementType();
8758   // It's a floating promotion if the source type is a lower rank.
8759   return ICE->getCastKind() == CK_FloatingCast &&
8760          S.Context.getFloatingTypeOrder(From, To) < 0;
8761 }
8762 
8763 bool
8764 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8765                                     const char *StartSpecifier,
8766                                     unsigned SpecifierLen,
8767                                     const Expr *E) {
8768   using namespace analyze_format_string;
8769   using namespace analyze_printf;
8770 
8771   // Now type check the data expression that matches the
8772   // format specifier.
8773   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
8774   if (!AT.isValid())
8775     return true;
8776 
8777   QualType ExprTy = E->getType();
8778   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
8779     ExprTy = TET->getUnderlyingExpr()->getType();
8780   }
8781 
8782   // Diagnose attempts to print a boolean value as a character. Unlike other
8783   // -Wformat diagnostics, this is fine from a type perspective, but it still
8784   // doesn't make sense.
8785   if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
8786       E->isKnownToHaveBooleanValue()) {
8787     const CharSourceRange &CSR =
8788         getSpecifierRange(StartSpecifier, SpecifierLen);
8789     SmallString<4> FSString;
8790     llvm::raw_svector_ostream os(FSString);
8791     FS.toString(os);
8792     EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
8793                              << FSString,
8794                          E->getExprLoc(), false, CSR);
8795     return true;
8796   }
8797 
8798   analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
8799   if (Match == analyze_printf::ArgType::Match)
8800     return true;
8801 
8802   // Look through argument promotions for our error message's reported type.
8803   // This includes the integral and floating promotions, but excludes array
8804   // and function pointer decay (seeing that an argument intended to be a
8805   // string has type 'char [6]' is probably more confusing than 'char *') and
8806   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
8807   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8808     if (isArithmeticArgumentPromotion(S, ICE)) {
8809       E = ICE->getSubExpr();
8810       ExprTy = E->getType();
8811 
8812       // Check if we didn't match because of an implicit cast from a 'char'
8813       // or 'short' to an 'int'.  This is done because printf is a varargs
8814       // function.
8815       if (ICE->getType() == S.Context.IntTy ||
8816           ICE->getType() == S.Context.UnsignedIntTy) {
8817         // All further checking is done on the subexpression
8818         const analyze_printf::ArgType::MatchKind ImplicitMatch =
8819             AT.matchesType(S.Context, ExprTy);
8820         if (ImplicitMatch == analyze_printf::ArgType::Match)
8821           return true;
8822         if (ImplicitMatch == ArgType::NoMatchPedantic ||
8823             ImplicitMatch == ArgType::NoMatchTypeConfusion)
8824           Match = ImplicitMatch;
8825       }
8826     }
8827   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
8828     // Special case for 'a', which has type 'int' in C.
8829     // Note, however, that we do /not/ want to treat multibyte constants like
8830     // 'MooV' as characters! This form is deprecated but still exists. In
8831     // addition, don't treat expressions as of type 'char' if one byte length
8832     // modifier is provided.
8833     if (ExprTy == S.Context.IntTy &&
8834         FS.getLengthModifier().getKind() != LengthModifier::AsChar)
8835       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
8836         ExprTy = S.Context.CharTy;
8837   }
8838 
8839   // Look through enums to their underlying type.
8840   bool IsEnum = false;
8841   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
8842     ExprTy = EnumTy->getDecl()->getIntegerType();
8843     IsEnum = true;
8844   }
8845 
8846   // %C in an Objective-C context prints a unichar, not a wchar_t.
8847   // If the argument is an integer of some kind, believe the %C and suggest
8848   // a cast instead of changing the conversion specifier.
8849   QualType IntendedTy = ExprTy;
8850   if (isObjCContext() &&
8851       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
8852     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
8853         !ExprTy->isCharType()) {
8854       // 'unichar' is defined as a typedef of unsigned short, but we should
8855       // prefer using the typedef if it is visible.
8856       IntendedTy = S.Context.UnsignedShortTy;
8857 
8858       // While we are here, check if the value is an IntegerLiteral that happens
8859       // to be within the valid range.
8860       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
8861         const llvm::APInt &V = IL->getValue();
8862         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
8863           return true;
8864       }
8865 
8866       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
8867                           Sema::LookupOrdinaryName);
8868       if (S.LookupName(Result, S.getCurScope())) {
8869         NamedDecl *ND = Result.getFoundDecl();
8870         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
8871           if (TD->getUnderlyingType() == IntendedTy)
8872             IntendedTy = S.Context.getTypedefType(TD);
8873       }
8874     }
8875   }
8876 
8877   // Special-case some of Darwin's platform-independence types by suggesting
8878   // casts to primitive types that are known to be large enough.
8879   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
8880   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
8881     QualType CastTy;
8882     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
8883     if (!CastTy.isNull()) {
8884       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
8885       // (long in ASTContext). Only complain to pedants.
8886       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
8887           (AT.isSizeT() || AT.isPtrdiffT()) &&
8888           AT.matchesType(S.Context, CastTy))
8889         Match = ArgType::NoMatchPedantic;
8890       IntendedTy = CastTy;
8891       ShouldNotPrintDirectly = true;
8892     }
8893   }
8894 
8895   // We may be able to offer a FixItHint if it is a supported type.
8896   PrintfSpecifier fixedFS = FS;
8897   bool Success =
8898       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
8899 
8900   if (Success) {
8901     // Get the fix string from the fixed format specifier
8902     SmallString<16> buf;
8903     llvm::raw_svector_ostream os(buf);
8904     fixedFS.toString(os);
8905 
8906     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
8907 
8908     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
8909       unsigned Diag;
8910       switch (Match) {
8911       case ArgType::Match: llvm_unreachable("expected non-matching");
8912       case ArgType::NoMatchPedantic:
8913         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8914         break;
8915       case ArgType::NoMatchTypeConfusion:
8916         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8917         break;
8918       case ArgType::NoMatch:
8919         Diag = diag::warn_format_conversion_argument_type_mismatch;
8920         break;
8921       }
8922 
8923       // In this case, the specifier is wrong and should be changed to match
8924       // the argument.
8925       EmitFormatDiagnostic(S.PDiag(Diag)
8926                                << AT.getRepresentativeTypeName(S.Context)
8927                                << IntendedTy << IsEnum << E->getSourceRange(),
8928                            E->getBeginLoc(),
8929                            /*IsStringLocation*/ false, SpecRange,
8930                            FixItHint::CreateReplacement(SpecRange, os.str()));
8931     } else {
8932       // The canonical type for formatting this value is different from the
8933       // actual type of the expression. (This occurs, for example, with Darwin's
8934       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
8935       // should be printed as 'long' for 64-bit compatibility.)
8936       // Rather than emitting a normal format/argument mismatch, we want to
8937       // add a cast to the recommended type (and correct the format string
8938       // if necessary).
8939       SmallString<16> CastBuf;
8940       llvm::raw_svector_ostream CastFix(CastBuf);
8941       CastFix << "(";
8942       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
8943       CastFix << ")";
8944 
8945       SmallVector<FixItHint,4> Hints;
8946       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
8947         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
8948 
8949       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
8950         // If there's already a cast present, just replace it.
8951         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
8952         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
8953 
8954       } else if (!requiresParensToAddCast(E)) {
8955         // If the expression has high enough precedence,
8956         // just write the C-style cast.
8957         Hints.push_back(
8958             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8959       } else {
8960         // Otherwise, add parens around the expression as well as the cast.
8961         CastFix << "(";
8962         Hints.push_back(
8963             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8964 
8965         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
8966         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
8967       }
8968 
8969       if (ShouldNotPrintDirectly) {
8970         // The expression has a type that should not be printed directly.
8971         // We extract the name from the typedef because we don't want to show
8972         // the underlying type in the diagnostic.
8973         StringRef Name;
8974         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
8975           Name = TypedefTy->getDecl()->getName();
8976         else
8977           Name = CastTyName;
8978         unsigned Diag = Match == ArgType::NoMatchPedantic
8979                             ? diag::warn_format_argument_needs_cast_pedantic
8980                             : diag::warn_format_argument_needs_cast;
8981         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
8982                                            << E->getSourceRange(),
8983                              E->getBeginLoc(), /*IsStringLocation=*/false,
8984                              SpecRange, Hints);
8985       } else {
8986         // In this case, the expression could be printed using a different
8987         // specifier, but we've decided that the specifier is probably correct
8988         // and we should cast instead. Just use the normal warning message.
8989         EmitFormatDiagnostic(
8990             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8991                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
8992                 << E->getSourceRange(),
8993             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
8994       }
8995     }
8996   } else {
8997     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
8998                                                    SpecifierLen);
8999     // Since the warning for passing non-POD types to variadic functions
9000     // was deferred until now, we emit a warning for non-POD
9001     // arguments here.
9002     switch (S.isValidVarArgType(ExprTy)) {
9003     case Sema::VAK_Valid:
9004     case Sema::VAK_ValidInCXX11: {
9005       unsigned Diag;
9006       switch (Match) {
9007       case ArgType::Match: llvm_unreachable("expected non-matching");
9008       case ArgType::NoMatchPedantic:
9009         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9010         break;
9011       case ArgType::NoMatchTypeConfusion:
9012         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9013         break;
9014       case ArgType::NoMatch:
9015         Diag = diag::warn_format_conversion_argument_type_mismatch;
9016         break;
9017       }
9018 
9019       EmitFormatDiagnostic(
9020           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
9021                         << IsEnum << CSR << E->getSourceRange(),
9022           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9023       break;
9024     }
9025     case Sema::VAK_Undefined:
9026     case Sema::VAK_MSVCUndefined:
9027       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
9028                                << S.getLangOpts().CPlusPlus11 << ExprTy
9029                                << CallType
9030                                << AT.getRepresentativeTypeName(S.Context) << CSR
9031                                << E->getSourceRange(),
9032                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9033       checkForCStrMembers(AT, E);
9034       break;
9035 
9036     case Sema::VAK_Invalid:
9037       if (ExprTy->isObjCObjectType())
9038         EmitFormatDiagnostic(
9039             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
9040                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9041                 << AT.getRepresentativeTypeName(S.Context) << CSR
9042                 << E->getSourceRange(),
9043             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9044       else
9045         // FIXME: If this is an initializer list, suggest removing the braces
9046         // or inserting a cast to the target type.
9047         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
9048             << isa<InitListExpr>(E) << ExprTy << CallType
9049             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
9050       break;
9051     }
9052 
9053     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
9054            "format string specifier index out of range");
9055     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
9056   }
9057 
9058   return true;
9059 }
9060 
9061 //===--- CHECK: Scanf format string checking ------------------------------===//
9062 
9063 namespace {
9064 
9065 class CheckScanfHandler : public CheckFormatHandler {
9066 public:
9067   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
9068                     const Expr *origFormatExpr, Sema::FormatStringType type,
9069                     unsigned firstDataArg, unsigned numDataArgs,
9070                     const char *beg, bool hasVAListArg,
9071                     ArrayRef<const Expr *> Args, unsigned formatIdx,
9072                     bool inFunctionCall, Sema::VariadicCallType CallType,
9073                     llvm::SmallBitVector &CheckedVarArgs,
9074                     UncoveredArgHandler &UncoveredArg)
9075       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
9076                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
9077                            inFunctionCall, CallType, CheckedVarArgs,
9078                            UncoveredArg) {}
9079 
9080   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
9081                             const char *startSpecifier,
9082                             unsigned specifierLen) override;
9083 
9084   bool HandleInvalidScanfConversionSpecifier(
9085           const analyze_scanf::ScanfSpecifier &FS,
9086           const char *startSpecifier,
9087           unsigned specifierLen) override;
9088 
9089   void HandleIncompleteScanList(const char *start, const char *end) override;
9090 };
9091 
9092 } // namespace
9093 
9094 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
9095                                                  const char *end) {
9096   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
9097                        getLocationOfByte(end), /*IsStringLocation*/true,
9098                        getSpecifierRange(start, end - start));
9099 }
9100 
9101 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
9102                                         const analyze_scanf::ScanfSpecifier &FS,
9103                                         const char *startSpecifier,
9104                                         unsigned specifierLen) {
9105   const analyze_scanf::ScanfConversionSpecifier &CS =
9106     FS.getConversionSpecifier();
9107 
9108   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
9109                                           getLocationOfByte(CS.getStart()),
9110                                           startSpecifier, specifierLen,
9111                                           CS.getStart(), CS.getLength());
9112 }
9113 
9114 bool CheckScanfHandler::HandleScanfSpecifier(
9115                                        const analyze_scanf::ScanfSpecifier &FS,
9116                                        const char *startSpecifier,
9117                                        unsigned specifierLen) {
9118   using namespace analyze_scanf;
9119   using namespace analyze_format_string;
9120 
9121   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
9122 
9123   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
9124   // be used to decide if we are using positional arguments consistently.
9125   if (FS.consumesDataArgument()) {
9126     if (atFirstArg) {
9127       atFirstArg = false;
9128       usesPositionalArgs = FS.usesPositionalArg();
9129     }
9130     else if (usesPositionalArgs != FS.usesPositionalArg()) {
9131       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9132                                         startSpecifier, specifierLen);
9133       return false;
9134     }
9135   }
9136 
9137   // Check if the field with is non-zero.
9138   const OptionalAmount &Amt = FS.getFieldWidth();
9139   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
9140     if (Amt.getConstantAmount() == 0) {
9141       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
9142                                                    Amt.getConstantLength());
9143       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
9144                            getLocationOfByte(Amt.getStart()),
9145                            /*IsStringLocation*/true, R,
9146                            FixItHint::CreateRemoval(R));
9147     }
9148   }
9149 
9150   if (!FS.consumesDataArgument()) {
9151     // FIXME: Technically specifying a precision or field width here
9152     // makes no sense.  Worth issuing a warning at some point.
9153     return true;
9154   }
9155 
9156   // Consume the argument.
9157   unsigned argIndex = FS.getArgIndex();
9158   if (argIndex < NumDataArgs) {
9159       // The check to see if the argIndex is valid will come later.
9160       // We set the bit here because we may exit early from this
9161       // function if we encounter some other error.
9162     CoveredArgs.set(argIndex);
9163   }
9164 
9165   // Check the length modifier is valid with the given conversion specifier.
9166   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
9167                                  S.getLangOpts()))
9168     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9169                                 diag::warn_format_nonsensical_length);
9170   else if (!FS.hasStandardLengthModifier())
9171     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9172   else if (!FS.hasStandardLengthConversionCombination())
9173     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9174                                 diag::warn_format_non_standard_conversion_spec);
9175 
9176   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
9177     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9178 
9179   // The remaining checks depend on the data arguments.
9180   if (HasVAListArg)
9181     return true;
9182 
9183   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9184     return false;
9185 
9186   // Check that the argument type matches the format specifier.
9187   const Expr *Ex = getDataArg(argIndex);
9188   if (!Ex)
9189     return true;
9190 
9191   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
9192 
9193   if (!AT.isValid()) {
9194     return true;
9195   }
9196 
9197   analyze_format_string::ArgType::MatchKind Match =
9198       AT.matchesType(S.Context, Ex->getType());
9199   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
9200   if (Match == analyze_format_string::ArgType::Match)
9201     return true;
9202 
9203   ScanfSpecifier fixedFS = FS;
9204   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
9205                                  S.getLangOpts(), S.Context);
9206 
9207   unsigned Diag =
9208       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9209                : diag::warn_format_conversion_argument_type_mismatch;
9210 
9211   if (Success) {
9212     // Get the fix string from the fixed format specifier.
9213     SmallString<128> buf;
9214     llvm::raw_svector_ostream os(buf);
9215     fixedFS.toString(os);
9216 
9217     EmitFormatDiagnostic(
9218         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
9219                       << Ex->getType() << false << Ex->getSourceRange(),
9220         Ex->getBeginLoc(),
9221         /*IsStringLocation*/ false,
9222         getSpecifierRange(startSpecifier, specifierLen),
9223         FixItHint::CreateReplacement(
9224             getSpecifierRange(startSpecifier, specifierLen), os.str()));
9225   } else {
9226     EmitFormatDiagnostic(S.PDiag(Diag)
9227                              << AT.getRepresentativeTypeName(S.Context)
9228                              << Ex->getType() << false << Ex->getSourceRange(),
9229                          Ex->getBeginLoc(),
9230                          /*IsStringLocation*/ false,
9231                          getSpecifierRange(startSpecifier, specifierLen));
9232   }
9233 
9234   return true;
9235 }
9236 
9237 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
9238                               const Expr *OrigFormatExpr,
9239                               ArrayRef<const Expr *> Args,
9240                               bool HasVAListArg, unsigned format_idx,
9241                               unsigned firstDataArg,
9242                               Sema::FormatStringType Type,
9243                               bool inFunctionCall,
9244                               Sema::VariadicCallType CallType,
9245                               llvm::SmallBitVector &CheckedVarArgs,
9246                               UncoveredArgHandler &UncoveredArg,
9247                               bool IgnoreStringsWithoutSpecifiers) {
9248   // CHECK: is the format string a wide literal?
9249   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
9250     CheckFormatHandler::EmitFormatDiagnostic(
9251         S, inFunctionCall, Args[format_idx],
9252         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
9253         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9254     return;
9255   }
9256 
9257   // Str - The format string.  NOTE: this is NOT null-terminated!
9258   StringRef StrRef = FExpr->getString();
9259   const char *Str = StrRef.data();
9260   // Account for cases where the string literal is truncated in a declaration.
9261   const ConstantArrayType *T =
9262     S.Context.getAsConstantArrayType(FExpr->getType());
9263   assert(T && "String literal not of constant array type!");
9264   size_t TypeSize = T->getSize().getZExtValue();
9265   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9266   const unsigned numDataArgs = Args.size() - firstDataArg;
9267 
9268   if (IgnoreStringsWithoutSpecifiers &&
9269       !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
9270           Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
9271     return;
9272 
9273   // Emit a warning if the string literal is truncated and does not contain an
9274   // embedded null character.
9275   if (TypeSize <= StrRef.size() &&
9276       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
9277     CheckFormatHandler::EmitFormatDiagnostic(
9278         S, inFunctionCall, Args[format_idx],
9279         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
9280         FExpr->getBeginLoc(),
9281         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
9282     return;
9283   }
9284 
9285   // CHECK: empty format string?
9286   if (StrLen == 0 && numDataArgs > 0) {
9287     CheckFormatHandler::EmitFormatDiagnostic(
9288         S, inFunctionCall, Args[format_idx],
9289         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
9290         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9291     return;
9292   }
9293 
9294   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
9295       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
9296       Type == Sema::FST_OSTrace) {
9297     CheckPrintfHandler H(
9298         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
9299         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
9300         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
9301         CheckedVarArgs, UncoveredArg);
9302 
9303     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
9304                                                   S.getLangOpts(),
9305                                                   S.Context.getTargetInfo(),
9306                                             Type == Sema::FST_FreeBSDKPrintf))
9307       H.DoneProcessing();
9308   } else if (Type == Sema::FST_Scanf) {
9309     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9310                         numDataArgs, Str, HasVAListArg, Args, format_idx,
9311                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
9312 
9313     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
9314                                                  S.getLangOpts(),
9315                                                  S.Context.getTargetInfo()))
9316       H.DoneProcessing();
9317   } // TODO: handle other formats
9318 }
9319 
9320 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
9321   // Str - The format string.  NOTE: this is NOT null-terminated!
9322   StringRef StrRef = FExpr->getString();
9323   const char *Str = StrRef.data();
9324   // Account for cases where the string literal is truncated in a declaration.
9325   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
9326   assert(T && "String literal not of constant array type!");
9327   size_t TypeSize = T->getSize().getZExtValue();
9328   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9329   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
9330                                                          getLangOpts(),
9331                                                          Context.getTargetInfo());
9332 }
9333 
9334 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
9335 
9336 // Returns the related absolute value function that is larger, of 0 if one
9337 // does not exist.
9338 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
9339   switch (AbsFunction) {
9340   default:
9341     return 0;
9342 
9343   case Builtin::BI__builtin_abs:
9344     return Builtin::BI__builtin_labs;
9345   case Builtin::BI__builtin_labs:
9346     return Builtin::BI__builtin_llabs;
9347   case Builtin::BI__builtin_llabs:
9348     return 0;
9349 
9350   case Builtin::BI__builtin_fabsf:
9351     return Builtin::BI__builtin_fabs;
9352   case Builtin::BI__builtin_fabs:
9353     return Builtin::BI__builtin_fabsl;
9354   case Builtin::BI__builtin_fabsl:
9355     return 0;
9356 
9357   case Builtin::BI__builtin_cabsf:
9358     return Builtin::BI__builtin_cabs;
9359   case Builtin::BI__builtin_cabs:
9360     return Builtin::BI__builtin_cabsl;
9361   case Builtin::BI__builtin_cabsl:
9362     return 0;
9363 
9364   case Builtin::BIabs:
9365     return Builtin::BIlabs;
9366   case Builtin::BIlabs:
9367     return Builtin::BIllabs;
9368   case Builtin::BIllabs:
9369     return 0;
9370 
9371   case Builtin::BIfabsf:
9372     return Builtin::BIfabs;
9373   case Builtin::BIfabs:
9374     return Builtin::BIfabsl;
9375   case Builtin::BIfabsl:
9376     return 0;
9377 
9378   case Builtin::BIcabsf:
9379    return Builtin::BIcabs;
9380   case Builtin::BIcabs:
9381     return Builtin::BIcabsl;
9382   case Builtin::BIcabsl:
9383     return 0;
9384   }
9385 }
9386 
9387 // Returns the argument type of the absolute value function.
9388 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
9389                                              unsigned AbsType) {
9390   if (AbsType == 0)
9391     return QualType();
9392 
9393   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
9394   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
9395   if (Error != ASTContext::GE_None)
9396     return QualType();
9397 
9398   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
9399   if (!FT)
9400     return QualType();
9401 
9402   if (FT->getNumParams() != 1)
9403     return QualType();
9404 
9405   return FT->getParamType(0);
9406 }
9407 
9408 // Returns the best absolute value function, or zero, based on type and
9409 // current absolute value function.
9410 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
9411                                    unsigned AbsFunctionKind) {
9412   unsigned BestKind = 0;
9413   uint64_t ArgSize = Context.getTypeSize(ArgType);
9414   for (unsigned Kind = AbsFunctionKind; Kind != 0;
9415        Kind = getLargerAbsoluteValueFunction(Kind)) {
9416     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
9417     if (Context.getTypeSize(ParamType) >= ArgSize) {
9418       if (BestKind == 0)
9419         BestKind = Kind;
9420       else if (Context.hasSameType(ParamType, ArgType)) {
9421         BestKind = Kind;
9422         break;
9423       }
9424     }
9425   }
9426   return BestKind;
9427 }
9428 
9429 enum AbsoluteValueKind {
9430   AVK_Integer,
9431   AVK_Floating,
9432   AVK_Complex
9433 };
9434 
9435 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
9436   if (T->isIntegralOrEnumerationType())
9437     return AVK_Integer;
9438   if (T->isRealFloatingType())
9439     return AVK_Floating;
9440   if (T->isAnyComplexType())
9441     return AVK_Complex;
9442 
9443   llvm_unreachable("Type not integer, floating, or complex");
9444 }
9445 
9446 // Changes the absolute value function to a different type.  Preserves whether
9447 // the function is a builtin.
9448 static unsigned changeAbsFunction(unsigned AbsKind,
9449                                   AbsoluteValueKind ValueKind) {
9450   switch (ValueKind) {
9451   case AVK_Integer:
9452     switch (AbsKind) {
9453     default:
9454       return 0;
9455     case Builtin::BI__builtin_fabsf:
9456     case Builtin::BI__builtin_fabs:
9457     case Builtin::BI__builtin_fabsl:
9458     case Builtin::BI__builtin_cabsf:
9459     case Builtin::BI__builtin_cabs:
9460     case Builtin::BI__builtin_cabsl:
9461       return Builtin::BI__builtin_abs;
9462     case Builtin::BIfabsf:
9463     case Builtin::BIfabs:
9464     case Builtin::BIfabsl:
9465     case Builtin::BIcabsf:
9466     case Builtin::BIcabs:
9467     case Builtin::BIcabsl:
9468       return Builtin::BIabs;
9469     }
9470   case AVK_Floating:
9471     switch (AbsKind) {
9472     default:
9473       return 0;
9474     case Builtin::BI__builtin_abs:
9475     case Builtin::BI__builtin_labs:
9476     case Builtin::BI__builtin_llabs:
9477     case Builtin::BI__builtin_cabsf:
9478     case Builtin::BI__builtin_cabs:
9479     case Builtin::BI__builtin_cabsl:
9480       return Builtin::BI__builtin_fabsf;
9481     case Builtin::BIabs:
9482     case Builtin::BIlabs:
9483     case Builtin::BIllabs:
9484     case Builtin::BIcabsf:
9485     case Builtin::BIcabs:
9486     case Builtin::BIcabsl:
9487       return Builtin::BIfabsf;
9488     }
9489   case AVK_Complex:
9490     switch (AbsKind) {
9491     default:
9492       return 0;
9493     case Builtin::BI__builtin_abs:
9494     case Builtin::BI__builtin_labs:
9495     case Builtin::BI__builtin_llabs:
9496     case Builtin::BI__builtin_fabsf:
9497     case Builtin::BI__builtin_fabs:
9498     case Builtin::BI__builtin_fabsl:
9499       return Builtin::BI__builtin_cabsf;
9500     case Builtin::BIabs:
9501     case Builtin::BIlabs:
9502     case Builtin::BIllabs:
9503     case Builtin::BIfabsf:
9504     case Builtin::BIfabs:
9505     case Builtin::BIfabsl:
9506       return Builtin::BIcabsf;
9507     }
9508   }
9509   llvm_unreachable("Unable to convert function");
9510 }
9511 
9512 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
9513   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
9514   if (!FnInfo)
9515     return 0;
9516 
9517   switch (FDecl->getBuiltinID()) {
9518   default:
9519     return 0;
9520   case Builtin::BI__builtin_abs:
9521   case Builtin::BI__builtin_fabs:
9522   case Builtin::BI__builtin_fabsf:
9523   case Builtin::BI__builtin_fabsl:
9524   case Builtin::BI__builtin_labs:
9525   case Builtin::BI__builtin_llabs:
9526   case Builtin::BI__builtin_cabs:
9527   case Builtin::BI__builtin_cabsf:
9528   case Builtin::BI__builtin_cabsl:
9529   case Builtin::BIabs:
9530   case Builtin::BIlabs:
9531   case Builtin::BIllabs:
9532   case Builtin::BIfabs:
9533   case Builtin::BIfabsf:
9534   case Builtin::BIfabsl:
9535   case Builtin::BIcabs:
9536   case Builtin::BIcabsf:
9537   case Builtin::BIcabsl:
9538     return FDecl->getBuiltinID();
9539   }
9540   llvm_unreachable("Unknown Builtin type");
9541 }
9542 
9543 // If the replacement is valid, emit a note with replacement function.
9544 // Additionally, suggest including the proper header if not already included.
9545 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
9546                             unsigned AbsKind, QualType ArgType) {
9547   bool EmitHeaderHint = true;
9548   const char *HeaderName = nullptr;
9549   const char *FunctionName = nullptr;
9550   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
9551     FunctionName = "std::abs";
9552     if (ArgType->isIntegralOrEnumerationType()) {
9553       HeaderName = "cstdlib";
9554     } else if (ArgType->isRealFloatingType()) {
9555       HeaderName = "cmath";
9556     } else {
9557       llvm_unreachable("Invalid Type");
9558     }
9559 
9560     // Lookup all std::abs
9561     if (NamespaceDecl *Std = S.getStdNamespace()) {
9562       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
9563       R.suppressDiagnostics();
9564       S.LookupQualifiedName(R, Std);
9565 
9566       for (const auto *I : R) {
9567         const FunctionDecl *FDecl = nullptr;
9568         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
9569           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
9570         } else {
9571           FDecl = dyn_cast<FunctionDecl>(I);
9572         }
9573         if (!FDecl)
9574           continue;
9575 
9576         // Found std::abs(), check that they are the right ones.
9577         if (FDecl->getNumParams() != 1)
9578           continue;
9579 
9580         // Check that the parameter type can handle the argument.
9581         QualType ParamType = FDecl->getParamDecl(0)->getType();
9582         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
9583             S.Context.getTypeSize(ArgType) <=
9584                 S.Context.getTypeSize(ParamType)) {
9585           // Found a function, don't need the header hint.
9586           EmitHeaderHint = false;
9587           break;
9588         }
9589       }
9590     }
9591   } else {
9592     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
9593     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
9594 
9595     if (HeaderName) {
9596       DeclarationName DN(&S.Context.Idents.get(FunctionName));
9597       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
9598       R.suppressDiagnostics();
9599       S.LookupName(R, S.getCurScope());
9600 
9601       if (R.isSingleResult()) {
9602         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
9603         if (FD && FD->getBuiltinID() == AbsKind) {
9604           EmitHeaderHint = false;
9605         } else {
9606           return;
9607         }
9608       } else if (!R.empty()) {
9609         return;
9610       }
9611     }
9612   }
9613 
9614   S.Diag(Loc, diag::note_replace_abs_function)
9615       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
9616 
9617   if (!HeaderName)
9618     return;
9619 
9620   if (!EmitHeaderHint)
9621     return;
9622 
9623   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
9624                                                     << FunctionName;
9625 }
9626 
9627 template <std::size_t StrLen>
9628 static bool IsStdFunction(const FunctionDecl *FDecl,
9629                           const char (&Str)[StrLen]) {
9630   if (!FDecl)
9631     return false;
9632   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
9633     return false;
9634   if (!FDecl->isInStdNamespace())
9635     return false;
9636 
9637   return true;
9638 }
9639 
9640 // Warn when using the wrong abs() function.
9641 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
9642                                       const FunctionDecl *FDecl) {
9643   if (Call->getNumArgs() != 1)
9644     return;
9645 
9646   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
9647   bool IsStdAbs = IsStdFunction(FDecl, "abs");
9648   if (AbsKind == 0 && !IsStdAbs)
9649     return;
9650 
9651   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9652   QualType ParamType = Call->getArg(0)->getType();
9653 
9654   // Unsigned types cannot be negative.  Suggest removing the absolute value
9655   // function call.
9656   if (ArgType->isUnsignedIntegerType()) {
9657     const char *FunctionName =
9658         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
9659     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
9660     Diag(Call->getExprLoc(), diag::note_remove_abs)
9661         << FunctionName
9662         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
9663     return;
9664   }
9665 
9666   // Taking the absolute value of a pointer is very suspicious, they probably
9667   // wanted to index into an array, dereference a pointer, call a function, etc.
9668   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
9669     unsigned DiagType = 0;
9670     if (ArgType->isFunctionType())
9671       DiagType = 1;
9672     else if (ArgType->isArrayType())
9673       DiagType = 2;
9674 
9675     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
9676     return;
9677   }
9678 
9679   // std::abs has overloads which prevent most of the absolute value problems
9680   // from occurring.
9681   if (IsStdAbs)
9682     return;
9683 
9684   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
9685   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
9686 
9687   // The argument and parameter are the same kind.  Check if they are the right
9688   // size.
9689   if (ArgValueKind == ParamValueKind) {
9690     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
9691       return;
9692 
9693     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
9694     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
9695         << FDecl << ArgType << ParamType;
9696 
9697     if (NewAbsKind == 0)
9698       return;
9699 
9700     emitReplacement(*this, Call->getExprLoc(),
9701                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9702     return;
9703   }
9704 
9705   // ArgValueKind != ParamValueKind
9706   // The wrong type of absolute value function was used.  Attempt to find the
9707   // proper one.
9708   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
9709   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
9710   if (NewAbsKind == 0)
9711     return;
9712 
9713   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
9714       << FDecl << ParamValueKind << ArgValueKind;
9715 
9716   emitReplacement(*this, Call->getExprLoc(),
9717                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9718 }
9719 
9720 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
9721 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
9722                                 const FunctionDecl *FDecl) {
9723   if (!Call || !FDecl) return;
9724 
9725   // Ignore template specializations and macros.
9726   if (inTemplateInstantiation()) return;
9727   if (Call->getExprLoc().isMacroID()) return;
9728 
9729   // Only care about the one template argument, two function parameter std::max
9730   if (Call->getNumArgs() != 2) return;
9731   if (!IsStdFunction(FDecl, "max")) return;
9732   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
9733   if (!ArgList) return;
9734   if (ArgList->size() != 1) return;
9735 
9736   // Check that template type argument is unsigned integer.
9737   const auto& TA = ArgList->get(0);
9738   if (TA.getKind() != TemplateArgument::Type) return;
9739   QualType ArgType = TA.getAsType();
9740   if (!ArgType->isUnsignedIntegerType()) return;
9741 
9742   // See if either argument is a literal zero.
9743   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
9744     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
9745     if (!MTE) return false;
9746     const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
9747     if (!Num) return false;
9748     if (Num->getValue() != 0) return false;
9749     return true;
9750   };
9751 
9752   const Expr *FirstArg = Call->getArg(0);
9753   const Expr *SecondArg = Call->getArg(1);
9754   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
9755   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
9756 
9757   // Only warn when exactly one argument is zero.
9758   if (IsFirstArgZero == IsSecondArgZero) return;
9759 
9760   SourceRange FirstRange = FirstArg->getSourceRange();
9761   SourceRange SecondRange = SecondArg->getSourceRange();
9762 
9763   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
9764 
9765   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
9766       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
9767 
9768   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
9769   SourceRange RemovalRange;
9770   if (IsFirstArgZero) {
9771     RemovalRange = SourceRange(FirstRange.getBegin(),
9772                                SecondRange.getBegin().getLocWithOffset(-1));
9773   } else {
9774     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
9775                                SecondRange.getEnd());
9776   }
9777 
9778   Diag(Call->getExprLoc(), diag::note_remove_max_call)
9779         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
9780         << FixItHint::CreateRemoval(RemovalRange);
9781 }
9782 
9783 //===--- CHECK: Standard memory functions ---------------------------------===//
9784 
9785 /// Takes the expression passed to the size_t parameter of functions
9786 /// such as memcmp, strncat, etc and warns if it's a comparison.
9787 ///
9788 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
9789 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
9790                                            IdentifierInfo *FnName,
9791                                            SourceLocation FnLoc,
9792                                            SourceLocation RParenLoc) {
9793   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
9794   if (!Size)
9795     return false;
9796 
9797   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
9798   if (!Size->isComparisonOp() && !Size->isLogicalOp())
9799     return false;
9800 
9801   SourceRange SizeRange = Size->getSourceRange();
9802   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
9803       << SizeRange << FnName;
9804   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
9805       << FnName
9806       << FixItHint::CreateInsertion(
9807              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
9808       << FixItHint::CreateRemoval(RParenLoc);
9809   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
9810       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
9811       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
9812                                     ")");
9813 
9814   return true;
9815 }
9816 
9817 /// Determine whether the given type is or contains a dynamic class type
9818 /// (e.g., whether it has a vtable).
9819 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
9820                                                      bool &IsContained) {
9821   // Look through array types while ignoring qualifiers.
9822   const Type *Ty = T->getBaseElementTypeUnsafe();
9823   IsContained = false;
9824 
9825   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
9826   RD = RD ? RD->getDefinition() : nullptr;
9827   if (!RD || RD->isInvalidDecl())
9828     return nullptr;
9829 
9830   if (RD->isDynamicClass())
9831     return RD;
9832 
9833   // Check all the fields.  If any bases were dynamic, the class is dynamic.
9834   // It's impossible for a class to transitively contain itself by value, so
9835   // infinite recursion is impossible.
9836   for (auto *FD : RD->fields()) {
9837     bool SubContained;
9838     if (const CXXRecordDecl *ContainedRD =
9839             getContainedDynamicClass(FD->getType(), SubContained)) {
9840       IsContained = true;
9841       return ContainedRD;
9842     }
9843   }
9844 
9845   return nullptr;
9846 }
9847 
9848 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
9849   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
9850     if (Unary->getKind() == UETT_SizeOf)
9851       return Unary;
9852   return nullptr;
9853 }
9854 
9855 /// If E is a sizeof expression, returns its argument expression,
9856 /// otherwise returns NULL.
9857 static const Expr *getSizeOfExprArg(const Expr *E) {
9858   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9859     if (!SizeOf->isArgumentType())
9860       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
9861   return nullptr;
9862 }
9863 
9864 /// If E is a sizeof expression, returns its argument type.
9865 static QualType getSizeOfArgType(const Expr *E) {
9866   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9867     return SizeOf->getTypeOfArgument();
9868   return QualType();
9869 }
9870 
9871 namespace {
9872 
9873 struct SearchNonTrivialToInitializeField
9874     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
9875   using Super =
9876       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
9877 
9878   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
9879 
9880   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
9881                      SourceLocation SL) {
9882     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9883       asDerived().visitArray(PDIK, AT, SL);
9884       return;
9885     }
9886 
9887     Super::visitWithKind(PDIK, FT, SL);
9888   }
9889 
9890   void visitARCStrong(QualType FT, SourceLocation SL) {
9891     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9892   }
9893   void visitARCWeak(QualType FT, SourceLocation SL) {
9894     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9895   }
9896   void visitStruct(QualType FT, SourceLocation SL) {
9897     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9898       visit(FD->getType(), FD->getLocation());
9899   }
9900   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
9901                   const ArrayType *AT, SourceLocation SL) {
9902     visit(getContext().getBaseElementType(AT), SL);
9903   }
9904   void visitTrivial(QualType FT, SourceLocation SL) {}
9905 
9906   static void diag(QualType RT, const Expr *E, Sema &S) {
9907     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
9908   }
9909 
9910   ASTContext &getContext() { return S.getASTContext(); }
9911 
9912   const Expr *E;
9913   Sema &S;
9914 };
9915 
9916 struct SearchNonTrivialToCopyField
9917     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
9918   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
9919 
9920   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
9921 
9922   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
9923                      SourceLocation SL) {
9924     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9925       asDerived().visitArray(PCK, AT, SL);
9926       return;
9927     }
9928 
9929     Super::visitWithKind(PCK, FT, SL);
9930   }
9931 
9932   void visitARCStrong(QualType FT, SourceLocation SL) {
9933     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9934   }
9935   void visitARCWeak(QualType FT, SourceLocation SL) {
9936     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9937   }
9938   void visitStruct(QualType FT, SourceLocation SL) {
9939     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9940       visit(FD->getType(), FD->getLocation());
9941   }
9942   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
9943                   SourceLocation SL) {
9944     visit(getContext().getBaseElementType(AT), SL);
9945   }
9946   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
9947                 SourceLocation SL) {}
9948   void visitTrivial(QualType FT, SourceLocation SL) {}
9949   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
9950 
9951   static void diag(QualType RT, const Expr *E, Sema &S) {
9952     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
9953   }
9954 
9955   ASTContext &getContext() { return S.getASTContext(); }
9956 
9957   const Expr *E;
9958   Sema &S;
9959 };
9960 
9961 }
9962 
9963 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
9964 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
9965   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
9966 
9967   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
9968     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
9969       return false;
9970 
9971     return doesExprLikelyComputeSize(BO->getLHS()) ||
9972            doesExprLikelyComputeSize(BO->getRHS());
9973   }
9974 
9975   return getAsSizeOfExpr(SizeofExpr) != nullptr;
9976 }
9977 
9978 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
9979 ///
9980 /// \code
9981 ///   #define MACRO 0
9982 ///   foo(MACRO);
9983 ///   foo(0);
9984 /// \endcode
9985 ///
9986 /// This should return true for the first call to foo, but not for the second
9987 /// (regardless of whether foo is a macro or function).
9988 static bool isArgumentExpandedFromMacro(SourceManager &SM,
9989                                         SourceLocation CallLoc,
9990                                         SourceLocation ArgLoc) {
9991   if (!CallLoc.isMacroID())
9992     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
9993 
9994   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
9995          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
9996 }
9997 
9998 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
9999 /// last two arguments transposed.
10000 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
10001   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
10002     return;
10003 
10004   const Expr *SizeArg =
10005     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
10006 
10007   auto isLiteralZero = [](const Expr *E) {
10008     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
10009   };
10010 
10011   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
10012   SourceLocation CallLoc = Call->getRParenLoc();
10013   SourceManager &SM = S.getSourceManager();
10014   if (isLiteralZero(SizeArg) &&
10015       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
10016 
10017     SourceLocation DiagLoc = SizeArg->getExprLoc();
10018 
10019     // Some platforms #define bzero to __builtin_memset. See if this is the
10020     // case, and if so, emit a better diagnostic.
10021     if (BId == Builtin::BIbzero ||
10022         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
10023                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
10024       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
10025       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
10026     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
10027       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
10028       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
10029     }
10030     return;
10031   }
10032 
10033   // If the second argument to a memset is a sizeof expression and the third
10034   // isn't, this is also likely an error. This should catch
10035   // 'memset(buf, sizeof(buf), 0xff)'.
10036   if (BId == Builtin::BImemset &&
10037       doesExprLikelyComputeSize(Call->getArg(1)) &&
10038       !doesExprLikelyComputeSize(Call->getArg(2))) {
10039     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
10040     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
10041     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
10042     return;
10043   }
10044 }
10045 
10046 /// Check for dangerous or invalid arguments to memset().
10047 ///
10048 /// This issues warnings on known problematic, dangerous or unspecified
10049 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
10050 /// function calls.
10051 ///
10052 /// \param Call The call expression to diagnose.
10053 void Sema::CheckMemaccessArguments(const CallExpr *Call,
10054                                    unsigned BId,
10055                                    IdentifierInfo *FnName) {
10056   assert(BId != 0);
10057 
10058   // It is possible to have a non-standard definition of memset.  Validate
10059   // we have enough arguments, and if not, abort further checking.
10060   unsigned ExpectedNumArgs =
10061       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
10062   if (Call->getNumArgs() < ExpectedNumArgs)
10063     return;
10064 
10065   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
10066                       BId == Builtin::BIstrndup ? 1 : 2);
10067   unsigned LenArg =
10068       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
10069   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
10070 
10071   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
10072                                      Call->getBeginLoc(), Call->getRParenLoc()))
10073     return;
10074 
10075   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
10076   CheckMemaccessSize(*this, BId, Call);
10077 
10078   // We have special checking when the length is a sizeof expression.
10079   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
10080   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
10081   llvm::FoldingSetNodeID SizeOfArgID;
10082 
10083   // Although widely used, 'bzero' is not a standard function. Be more strict
10084   // with the argument types before allowing diagnostics and only allow the
10085   // form bzero(ptr, sizeof(...)).
10086   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10087   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
10088     return;
10089 
10090   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
10091     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
10092     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
10093 
10094     QualType DestTy = Dest->getType();
10095     QualType PointeeTy;
10096     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
10097       PointeeTy = DestPtrTy->getPointeeType();
10098 
10099       // Never warn about void type pointers. This can be used to suppress
10100       // false positives.
10101       if (PointeeTy->isVoidType())
10102         continue;
10103 
10104       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
10105       // actually comparing the expressions for equality. Because computing the
10106       // expression IDs can be expensive, we only do this if the diagnostic is
10107       // enabled.
10108       if (SizeOfArg &&
10109           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
10110                            SizeOfArg->getExprLoc())) {
10111         // We only compute IDs for expressions if the warning is enabled, and
10112         // cache the sizeof arg's ID.
10113         if (SizeOfArgID == llvm::FoldingSetNodeID())
10114           SizeOfArg->Profile(SizeOfArgID, Context, true);
10115         llvm::FoldingSetNodeID DestID;
10116         Dest->Profile(DestID, Context, true);
10117         if (DestID == SizeOfArgID) {
10118           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
10119           //       over sizeof(src) as well.
10120           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
10121           StringRef ReadableName = FnName->getName();
10122 
10123           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
10124             if (UnaryOp->getOpcode() == UO_AddrOf)
10125               ActionIdx = 1; // If its an address-of operator, just remove it.
10126           if (!PointeeTy->isIncompleteType() &&
10127               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
10128             ActionIdx = 2; // If the pointee's size is sizeof(char),
10129                            // suggest an explicit length.
10130 
10131           // If the function is defined as a builtin macro, do not show macro
10132           // expansion.
10133           SourceLocation SL = SizeOfArg->getExprLoc();
10134           SourceRange DSR = Dest->getSourceRange();
10135           SourceRange SSR = SizeOfArg->getSourceRange();
10136           SourceManager &SM = getSourceManager();
10137 
10138           if (SM.isMacroArgExpansion(SL)) {
10139             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
10140             SL = SM.getSpellingLoc(SL);
10141             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
10142                              SM.getSpellingLoc(DSR.getEnd()));
10143             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
10144                              SM.getSpellingLoc(SSR.getEnd()));
10145           }
10146 
10147           DiagRuntimeBehavior(SL, SizeOfArg,
10148                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
10149                                 << ReadableName
10150                                 << PointeeTy
10151                                 << DestTy
10152                                 << DSR
10153                                 << SSR);
10154           DiagRuntimeBehavior(SL, SizeOfArg,
10155                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
10156                                 << ActionIdx
10157                                 << SSR);
10158 
10159           break;
10160         }
10161       }
10162 
10163       // Also check for cases where the sizeof argument is the exact same
10164       // type as the memory argument, and where it points to a user-defined
10165       // record type.
10166       if (SizeOfArgTy != QualType()) {
10167         if (PointeeTy->isRecordType() &&
10168             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
10169           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
10170                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
10171                                 << FnName << SizeOfArgTy << ArgIdx
10172                                 << PointeeTy << Dest->getSourceRange()
10173                                 << LenExpr->getSourceRange());
10174           break;
10175         }
10176       }
10177     } else if (DestTy->isArrayType()) {
10178       PointeeTy = DestTy;
10179     }
10180 
10181     if (PointeeTy == QualType())
10182       continue;
10183 
10184     // Always complain about dynamic classes.
10185     bool IsContained;
10186     if (const CXXRecordDecl *ContainedRD =
10187             getContainedDynamicClass(PointeeTy, IsContained)) {
10188 
10189       unsigned OperationType = 0;
10190       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
10191       // "overwritten" if we're warning about the destination for any call
10192       // but memcmp; otherwise a verb appropriate to the call.
10193       if (ArgIdx != 0 || IsCmp) {
10194         if (BId == Builtin::BImemcpy)
10195           OperationType = 1;
10196         else if(BId == Builtin::BImemmove)
10197           OperationType = 2;
10198         else if (IsCmp)
10199           OperationType = 3;
10200       }
10201 
10202       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10203                           PDiag(diag::warn_dyn_class_memaccess)
10204                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
10205                               << IsContained << ContainedRD << OperationType
10206                               << Call->getCallee()->getSourceRange());
10207     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
10208              BId != Builtin::BImemset)
10209       DiagRuntimeBehavior(
10210         Dest->getExprLoc(), Dest,
10211         PDiag(diag::warn_arc_object_memaccess)
10212           << ArgIdx << FnName << PointeeTy
10213           << Call->getCallee()->getSourceRange());
10214     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
10215       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10216           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
10217         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10218                             PDiag(diag::warn_cstruct_memaccess)
10219                                 << ArgIdx << FnName << PointeeTy << 0);
10220         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
10221       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10222                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
10223         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10224                             PDiag(diag::warn_cstruct_memaccess)
10225                                 << ArgIdx << FnName << PointeeTy << 1);
10226         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
10227       } else {
10228         continue;
10229       }
10230     } else
10231       continue;
10232 
10233     DiagRuntimeBehavior(
10234       Dest->getExprLoc(), Dest,
10235       PDiag(diag::note_bad_memaccess_silence)
10236         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
10237     break;
10238   }
10239 }
10240 
10241 // A little helper routine: ignore addition and subtraction of integer literals.
10242 // This intentionally does not ignore all integer constant expressions because
10243 // we don't want to remove sizeof().
10244 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
10245   Ex = Ex->IgnoreParenCasts();
10246 
10247   while (true) {
10248     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
10249     if (!BO || !BO->isAdditiveOp())
10250       break;
10251 
10252     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
10253     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
10254 
10255     if (isa<IntegerLiteral>(RHS))
10256       Ex = LHS;
10257     else if (isa<IntegerLiteral>(LHS))
10258       Ex = RHS;
10259     else
10260       break;
10261   }
10262 
10263   return Ex;
10264 }
10265 
10266 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
10267                                                       ASTContext &Context) {
10268   // Only handle constant-sized or VLAs, but not flexible members.
10269   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
10270     // Only issue the FIXIT for arrays of size > 1.
10271     if (CAT->getSize().getSExtValue() <= 1)
10272       return false;
10273   } else if (!Ty->isVariableArrayType()) {
10274     return false;
10275   }
10276   return true;
10277 }
10278 
10279 // Warn if the user has made the 'size' argument to strlcpy or strlcat
10280 // be the size of the source, instead of the destination.
10281 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
10282                                     IdentifierInfo *FnName) {
10283 
10284   // Don't crash if the user has the wrong number of arguments
10285   unsigned NumArgs = Call->getNumArgs();
10286   if ((NumArgs != 3) && (NumArgs != 4))
10287     return;
10288 
10289   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
10290   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
10291   const Expr *CompareWithSrc = nullptr;
10292 
10293   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
10294                                      Call->getBeginLoc(), Call->getRParenLoc()))
10295     return;
10296 
10297   // Look for 'strlcpy(dst, x, sizeof(x))'
10298   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
10299     CompareWithSrc = Ex;
10300   else {
10301     // Look for 'strlcpy(dst, x, strlen(x))'
10302     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
10303       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
10304           SizeCall->getNumArgs() == 1)
10305         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
10306     }
10307   }
10308 
10309   if (!CompareWithSrc)
10310     return;
10311 
10312   // Determine if the argument to sizeof/strlen is equal to the source
10313   // argument.  In principle there's all kinds of things you could do
10314   // here, for instance creating an == expression and evaluating it with
10315   // EvaluateAsBooleanCondition, but this uses a more direct technique:
10316   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
10317   if (!SrcArgDRE)
10318     return;
10319 
10320   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
10321   if (!CompareWithSrcDRE ||
10322       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
10323     return;
10324 
10325   const Expr *OriginalSizeArg = Call->getArg(2);
10326   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
10327       << OriginalSizeArg->getSourceRange() << FnName;
10328 
10329   // Output a FIXIT hint if the destination is an array (rather than a
10330   // pointer to an array).  This could be enhanced to handle some
10331   // pointers if we know the actual size, like if DstArg is 'array+2'
10332   // we could say 'sizeof(array)-2'.
10333   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
10334   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
10335     return;
10336 
10337   SmallString<128> sizeString;
10338   llvm::raw_svector_ostream OS(sizeString);
10339   OS << "sizeof(";
10340   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10341   OS << ")";
10342 
10343   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
10344       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
10345                                       OS.str());
10346 }
10347 
10348 /// Check if two expressions refer to the same declaration.
10349 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
10350   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
10351     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
10352       return D1->getDecl() == D2->getDecl();
10353   return false;
10354 }
10355 
10356 static const Expr *getStrlenExprArg(const Expr *E) {
10357   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10358     const FunctionDecl *FD = CE->getDirectCallee();
10359     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
10360       return nullptr;
10361     return CE->getArg(0)->IgnoreParenCasts();
10362   }
10363   return nullptr;
10364 }
10365 
10366 // Warn on anti-patterns as the 'size' argument to strncat.
10367 // The correct size argument should look like following:
10368 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
10369 void Sema::CheckStrncatArguments(const CallExpr *CE,
10370                                  IdentifierInfo *FnName) {
10371   // Don't crash if the user has the wrong number of arguments.
10372   if (CE->getNumArgs() < 3)
10373     return;
10374   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
10375   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
10376   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
10377 
10378   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
10379                                      CE->getRParenLoc()))
10380     return;
10381 
10382   // Identify common expressions, which are wrongly used as the size argument
10383   // to strncat and may lead to buffer overflows.
10384   unsigned PatternType = 0;
10385   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
10386     // - sizeof(dst)
10387     if (referToTheSameDecl(SizeOfArg, DstArg))
10388       PatternType = 1;
10389     // - sizeof(src)
10390     else if (referToTheSameDecl(SizeOfArg, SrcArg))
10391       PatternType = 2;
10392   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
10393     if (BE->getOpcode() == BO_Sub) {
10394       const Expr *L = BE->getLHS()->IgnoreParenCasts();
10395       const Expr *R = BE->getRHS()->IgnoreParenCasts();
10396       // - sizeof(dst) - strlen(dst)
10397       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
10398           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
10399         PatternType = 1;
10400       // - sizeof(src) - (anything)
10401       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
10402         PatternType = 2;
10403     }
10404   }
10405 
10406   if (PatternType == 0)
10407     return;
10408 
10409   // Generate the diagnostic.
10410   SourceLocation SL = LenArg->getBeginLoc();
10411   SourceRange SR = LenArg->getSourceRange();
10412   SourceManager &SM = getSourceManager();
10413 
10414   // If the function is defined as a builtin macro, do not show macro expansion.
10415   if (SM.isMacroArgExpansion(SL)) {
10416     SL = SM.getSpellingLoc(SL);
10417     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
10418                      SM.getSpellingLoc(SR.getEnd()));
10419   }
10420 
10421   // Check if the destination is an array (rather than a pointer to an array).
10422   QualType DstTy = DstArg->getType();
10423   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
10424                                                                     Context);
10425   if (!isKnownSizeArray) {
10426     if (PatternType == 1)
10427       Diag(SL, diag::warn_strncat_wrong_size) << SR;
10428     else
10429       Diag(SL, diag::warn_strncat_src_size) << SR;
10430     return;
10431   }
10432 
10433   if (PatternType == 1)
10434     Diag(SL, diag::warn_strncat_large_size) << SR;
10435   else
10436     Diag(SL, diag::warn_strncat_src_size) << SR;
10437 
10438   SmallString<128> sizeString;
10439   llvm::raw_svector_ostream OS(sizeString);
10440   OS << "sizeof(";
10441   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10442   OS << ") - ";
10443   OS << "strlen(";
10444   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10445   OS << ") - 1";
10446 
10447   Diag(SL, diag::note_strncat_wrong_size)
10448     << FixItHint::CreateReplacement(SR, OS.str());
10449 }
10450 
10451 namespace {
10452 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
10453                                 const UnaryOperator *UnaryExpr, const Decl *D) {
10454   if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) {
10455     S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
10456         << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
10457     return;
10458   }
10459 }
10460 
10461 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
10462                                  const UnaryOperator *UnaryExpr) {
10463   if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
10464     const Decl *D = Lvalue->getDecl();
10465     if (isa<VarDecl, FunctionDecl>(D))
10466       return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
10467   }
10468 
10469   if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
10470     return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
10471                                       Lvalue->getMemberDecl());
10472 }
10473 
10474 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
10475                             const UnaryOperator *UnaryExpr) {
10476   const auto *Lambda = dyn_cast<LambdaExpr>(
10477       UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens());
10478   if (!Lambda)
10479     return;
10480 
10481   S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
10482       << CalleeName << 2 /*object: lambda expression*/;
10483 }
10484 
10485 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
10486                                   const DeclRefExpr *Lvalue) {
10487   const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
10488   if (Var == nullptr)
10489     return;
10490 
10491   S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
10492       << CalleeName << 0 /*object: */ << Var;
10493 }
10494 
10495 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
10496                             const CastExpr *Cast) {
10497   SmallString<128> SizeString;
10498   llvm::raw_svector_ostream OS(SizeString);
10499 
10500   clang::CastKind Kind = Cast->getCastKind();
10501   if (Kind == clang::CK_BitCast &&
10502       !Cast->getSubExpr()->getType()->isFunctionPointerType())
10503     return;
10504   if (Kind == clang::CK_IntegralToPointer &&
10505       !isa<IntegerLiteral>(
10506           Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
10507     return;
10508 
10509   switch (Cast->getCastKind()) {
10510   case clang::CK_BitCast:
10511   case clang::CK_IntegralToPointer:
10512   case clang::CK_FunctionToPointerDecay:
10513     OS << '\'';
10514     Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
10515     OS << '\'';
10516     break;
10517   default:
10518     return;
10519   }
10520 
10521   S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
10522       << CalleeName << 0 /*object: */ << OS.str();
10523 }
10524 } // namespace
10525 
10526 /// Alerts the user that they are attempting to free a non-malloc'd object.
10527 void Sema::CheckFreeArguments(const CallExpr *E) {
10528   const std::string CalleeName =
10529       dyn_cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
10530 
10531   { // Prefer something that doesn't involve a cast to make things simpler.
10532     const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
10533     if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
10534       switch (UnaryExpr->getOpcode()) {
10535       case UnaryOperator::Opcode::UO_AddrOf:
10536         return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
10537       case UnaryOperator::Opcode::UO_Plus:
10538         return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
10539       default:
10540         break;
10541       }
10542 
10543     if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
10544       if (Lvalue->getType()->isArrayType())
10545         return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
10546 
10547     if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
10548       Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
10549           << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
10550       return;
10551     }
10552 
10553     if (isa<BlockExpr>(Arg)) {
10554       Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
10555           << CalleeName << 1 /*object: block*/;
10556       return;
10557     }
10558   }
10559   // Maybe the cast was important, check after the other cases.
10560   if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
10561     return CheckFreeArgumentsCast(*this, CalleeName, Cast);
10562 }
10563 
10564 void
10565 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
10566                          SourceLocation ReturnLoc,
10567                          bool isObjCMethod,
10568                          const AttrVec *Attrs,
10569                          const FunctionDecl *FD) {
10570   // Check if the return value is null but should not be.
10571   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
10572        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
10573       CheckNonNullExpr(*this, RetValExp))
10574     Diag(ReturnLoc, diag::warn_null_ret)
10575       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
10576 
10577   // C++11 [basic.stc.dynamic.allocation]p4:
10578   //   If an allocation function declared with a non-throwing
10579   //   exception-specification fails to allocate storage, it shall return
10580   //   a null pointer. Any other allocation function that fails to allocate
10581   //   storage shall indicate failure only by throwing an exception [...]
10582   if (FD) {
10583     OverloadedOperatorKind Op = FD->getOverloadedOperator();
10584     if (Op == OO_New || Op == OO_Array_New) {
10585       const FunctionProtoType *Proto
10586         = FD->getType()->castAs<FunctionProtoType>();
10587       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
10588           CheckNonNullExpr(*this, RetValExp))
10589         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
10590           << FD << getLangOpts().CPlusPlus11;
10591     }
10592   }
10593 
10594   // PPC MMA non-pointer types are not allowed as return type. Checking the type
10595   // here prevent the user from using a PPC MMA type as trailing return type.
10596   if (Context.getTargetInfo().getTriple().isPPC64())
10597     CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
10598 }
10599 
10600 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
10601 
10602 /// Check for comparisons of floating point operands using != and ==.
10603 /// Issue a warning if these are no self-comparisons, as they are not likely
10604 /// to do what the programmer intended.
10605 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
10606   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
10607   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
10608 
10609   // Special case: check for x == x (which is OK).
10610   // Do not emit warnings for such cases.
10611   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
10612     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
10613       if (DRL->getDecl() == DRR->getDecl())
10614         return;
10615 
10616   // Special case: check for comparisons against literals that can be exactly
10617   //  represented by APFloat.  In such cases, do not emit a warning.  This
10618   //  is a heuristic: often comparison against such literals are used to
10619   //  detect if a value in a variable has not changed.  This clearly can
10620   //  lead to false negatives.
10621   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
10622     if (FLL->isExact())
10623       return;
10624   } else
10625     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
10626       if (FLR->isExact())
10627         return;
10628 
10629   // Check for comparisons with builtin types.
10630   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
10631     if (CL->getBuiltinCallee())
10632       return;
10633 
10634   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
10635     if (CR->getBuiltinCallee())
10636       return;
10637 
10638   // Emit the diagnostic.
10639   Diag(Loc, diag::warn_floatingpoint_eq)
10640     << LHS->getSourceRange() << RHS->getSourceRange();
10641 }
10642 
10643 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
10644 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
10645 
10646 namespace {
10647 
10648 /// Structure recording the 'active' range of an integer-valued
10649 /// expression.
10650 struct IntRange {
10651   /// The number of bits active in the int. Note that this includes exactly one
10652   /// sign bit if !NonNegative.
10653   unsigned Width;
10654 
10655   /// True if the int is known not to have negative values. If so, all leading
10656   /// bits before Width are known zero, otherwise they are known to be the
10657   /// same as the MSB within Width.
10658   bool NonNegative;
10659 
10660   IntRange(unsigned Width, bool NonNegative)
10661       : Width(Width), NonNegative(NonNegative) {}
10662 
10663   /// Number of bits excluding the sign bit.
10664   unsigned valueBits() const {
10665     return NonNegative ? Width : Width - 1;
10666   }
10667 
10668   /// Returns the range of the bool type.
10669   static IntRange forBoolType() {
10670     return IntRange(1, true);
10671   }
10672 
10673   /// Returns the range of an opaque value of the given integral type.
10674   static IntRange forValueOfType(ASTContext &C, QualType T) {
10675     return forValueOfCanonicalType(C,
10676                           T->getCanonicalTypeInternal().getTypePtr());
10677   }
10678 
10679   /// Returns the range of an opaque value of a canonical integral type.
10680   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
10681     assert(T->isCanonicalUnqualified());
10682 
10683     if (const VectorType *VT = dyn_cast<VectorType>(T))
10684       T = VT->getElementType().getTypePtr();
10685     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
10686       T = CT->getElementType().getTypePtr();
10687     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
10688       T = AT->getValueType().getTypePtr();
10689 
10690     if (!C.getLangOpts().CPlusPlus) {
10691       // For enum types in C code, use the underlying datatype.
10692       if (const EnumType *ET = dyn_cast<EnumType>(T))
10693         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
10694     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
10695       // For enum types in C++, use the known bit width of the enumerators.
10696       EnumDecl *Enum = ET->getDecl();
10697       // In C++11, enums can have a fixed underlying type. Use this type to
10698       // compute the range.
10699       if (Enum->isFixed()) {
10700         return IntRange(C.getIntWidth(QualType(T, 0)),
10701                         !ET->isSignedIntegerOrEnumerationType());
10702       }
10703 
10704       unsigned NumPositive = Enum->getNumPositiveBits();
10705       unsigned NumNegative = Enum->getNumNegativeBits();
10706 
10707       if (NumNegative == 0)
10708         return IntRange(NumPositive, true/*NonNegative*/);
10709       else
10710         return IntRange(std::max(NumPositive + 1, NumNegative),
10711                         false/*NonNegative*/);
10712     }
10713 
10714     if (const auto *EIT = dyn_cast<ExtIntType>(T))
10715       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
10716 
10717     const BuiltinType *BT = cast<BuiltinType>(T);
10718     assert(BT->isInteger());
10719 
10720     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10721   }
10722 
10723   /// Returns the "target" range of a canonical integral type, i.e.
10724   /// the range of values expressible in the type.
10725   ///
10726   /// This matches forValueOfCanonicalType except that enums have the
10727   /// full range of their type, not the range of their enumerators.
10728   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
10729     assert(T->isCanonicalUnqualified());
10730 
10731     if (const VectorType *VT = dyn_cast<VectorType>(T))
10732       T = VT->getElementType().getTypePtr();
10733     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
10734       T = CT->getElementType().getTypePtr();
10735     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
10736       T = AT->getValueType().getTypePtr();
10737     if (const EnumType *ET = dyn_cast<EnumType>(T))
10738       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
10739 
10740     if (const auto *EIT = dyn_cast<ExtIntType>(T))
10741       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
10742 
10743     const BuiltinType *BT = cast<BuiltinType>(T);
10744     assert(BT->isInteger());
10745 
10746     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10747   }
10748 
10749   /// Returns the supremum of two ranges: i.e. their conservative merge.
10750   static IntRange join(IntRange L, IntRange R) {
10751     bool Unsigned = L.NonNegative && R.NonNegative;
10752     return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
10753                     L.NonNegative && R.NonNegative);
10754   }
10755 
10756   /// Return the range of a bitwise-AND of the two ranges.
10757   static IntRange bit_and(IntRange L, IntRange R) {
10758     unsigned Bits = std::max(L.Width, R.Width);
10759     bool NonNegative = false;
10760     if (L.NonNegative) {
10761       Bits = std::min(Bits, L.Width);
10762       NonNegative = true;
10763     }
10764     if (R.NonNegative) {
10765       Bits = std::min(Bits, R.Width);
10766       NonNegative = true;
10767     }
10768     return IntRange(Bits, NonNegative);
10769   }
10770 
10771   /// Return the range of a sum of the two ranges.
10772   static IntRange sum(IntRange L, IntRange R) {
10773     bool Unsigned = L.NonNegative && R.NonNegative;
10774     return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
10775                     Unsigned);
10776   }
10777 
10778   /// Return the range of a difference of the two ranges.
10779   static IntRange difference(IntRange L, IntRange R) {
10780     // We need a 1-bit-wider range if:
10781     //   1) LHS can be negative: least value can be reduced.
10782     //   2) RHS can be negative: greatest value can be increased.
10783     bool CanWiden = !L.NonNegative || !R.NonNegative;
10784     bool Unsigned = L.NonNegative && R.Width == 0;
10785     return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
10786                         !Unsigned,
10787                     Unsigned);
10788   }
10789 
10790   /// Return the range of a product of the two ranges.
10791   static IntRange product(IntRange L, IntRange R) {
10792     // If both LHS and RHS can be negative, we can form
10793     //   -2^L * -2^R = 2^(L + R)
10794     // which requires L + R + 1 value bits to represent.
10795     bool CanWiden = !L.NonNegative && !R.NonNegative;
10796     bool Unsigned = L.NonNegative && R.NonNegative;
10797     return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
10798                     Unsigned);
10799   }
10800 
10801   /// Return the range of a remainder operation between the two ranges.
10802   static IntRange rem(IntRange L, IntRange R) {
10803     // The result of a remainder can't be larger than the result of
10804     // either side. The sign of the result is the sign of the LHS.
10805     bool Unsigned = L.NonNegative;
10806     return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
10807                     Unsigned);
10808   }
10809 };
10810 
10811 } // namespace
10812 
10813 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
10814                               unsigned MaxWidth) {
10815   if (value.isSigned() && value.isNegative())
10816     return IntRange(value.getMinSignedBits(), false);
10817 
10818   if (value.getBitWidth() > MaxWidth)
10819     value = value.trunc(MaxWidth);
10820 
10821   // isNonNegative() just checks the sign bit without considering
10822   // signedness.
10823   return IntRange(value.getActiveBits(), true);
10824 }
10825 
10826 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
10827                               unsigned MaxWidth) {
10828   if (result.isInt())
10829     return GetValueRange(C, result.getInt(), MaxWidth);
10830 
10831   if (result.isVector()) {
10832     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
10833     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
10834       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
10835       R = IntRange::join(R, El);
10836     }
10837     return R;
10838   }
10839 
10840   if (result.isComplexInt()) {
10841     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
10842     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
10843     return IntRange::join(R, I);
10844   }
10845 
10846   // This can happen with lossless casts to intptr_t of "based" lvalues.
10847   // Assume it might use arbitrary bits.
10848   // FIXME: The only reason we need to pass the type in here is to get
10849   // the sign right on this one case.  It would be nice if APValue
10850   // preserved this.
10851   assert(result.isLValue() || result.isAddrLabelDiff());
10852   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
10853 }
10854 
10855 static QualType GetExprType(const Expr *E) {
10856   QualType Ty = E->getType();
10857   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
10858     Ty = AtomicRHS->getValueType();
10859   return Ty;
10860 }
10861 
10862 /// Pseudo-evaluate the given integer expression, estimating the
10863 /// range of values it might take.
10864 ///
10865 /// \param MaxWidth The width to which the value will be truncated.
10866 /// \param Approximate If \c true, return a likely range for the result: in
10867 ///        particular, assume that aritmetic on narrower types doesn't leave
10868 ///        those types. If \c false, return a range including all possible
10869 ///        result values.
10870 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
10871                              bool InConstantContext, bool Approximate) {
10872   E = E->IgnoreParens();
10873 
10874   // Try a full evaluation first.
10875   Expr::EvalResult result;
10876   if (E->EvaluateAsRValue(result, C, InConstantContext))
10877     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
10878 
10879   // I think we only want to look through implicit casts here; if the
10880   // user has an explicit widening cast, we should treat the value as
10881   // being of the new, wider type.
10882   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
10883     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
10884       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
10885                           Approximate);
10886 
10887     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
10888 
10889     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
10890                          CE->getCastKind() == CK_BooleanToSignedIntegral;
10891 
10892     // Assume that non-integer casts can span the full range of the type.
10893     if (!isIntegerCast)
10894       return OutputTypeRange;
10895 
10896     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
10897                                      std::min(MaxWidth, OutputTypeRange.Width),
10898                                      InConstantContext, Approximate);
10899 
10900     // Bail out if the subexpr's range is as wide as the cast type.
10901     if (SubRange.Width >= OutputTypeRange.Width)
10902       return OutputTypeRange;
10903 
10904     // Otherwise, we take the smaller width, and we're non-negative if
10905     // either the output type or the subexpr is.
10906     return IntRange(SubRange.Width,
10907                     SubRange.NonNegative || OutputTypeRange.NonNegative);
10908   }
10909 
10910   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
10911     // If we can fold the condition, just take that operand.
10912     bool CondResult;
10913     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
10914       return GetExprRange(C,
10915                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
10916                           MaxWidth, InConstantContext, Approximate);
10917 
10918     // Otherwise, conservatively merge.
10919     // GetExprRange requires an integer expression, but a throw expression
10920     // results in a void type.
10921     Expr *E = CO->getTrueExpr();
10922     IntRange L = E->getType()->isVoidType()
10923                      ? IntRange{0, true}
10924                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
10925     E = CO->getFalseExpr();
10926     IntRange R = E->getType()->isVoidType()
10927                      ? IntRange{0, true}
10928                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
10929     return IntRange::join(L, R);
10930   }
10931 
10932   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
10933     IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
10934 
10935     switch (BO->getOpcode()) {
10936     case BO_Cmp:
10937       llvm_unreachable("builtin <=> should have class type");
10938 
10939     // Boolean-valued operations are single-bit and positive.
10940     case BO_LAnd:
10941     case BO_LOr:
10942     case BO_LT:
10943     case BO_GT:
10944     case BO_LE:
10945     case BO_GE:
10946     case BO_EQ:
10947     case BO_NE:
10948       return IntRange::forBoolType();
10949 
10950     // The type of the assignments is the type of the LHS, so the RHS
10951     // is not necessarily the same type.
10952     case BO_MulAssign:
10953     case BO_DivAssign:
10954     case BO_RemAssign:
10955     case BO_AddAssign:
10956     case BO_SubAssign:
10957     case BO_XorAssign:
10958     case BO_OrAssign:
10959       // TODO: bitfields?
10960       return IntRange::forValueOfType(C, GetExprType(E));
10961 
10962     // Simple assignments just pass through the RHS, which will have
10963     // been coerced to the LHS type.
10964     case BO_Assign:
10965       // TODO: bitfields?
10966       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
10967                           Approximate);
10968 
10969     // Operations with opaque sources are black-listed.
10970     case BO_PtrMemD:
10971     case BO_PtrMemI:
10972       return IntRange::forValueOfType(C, GetExprType(E));
10973 
10974     // Bitwise-and uses the *infinum* of the two source ranges.
10975     case BO_And:
10976     case BO_AndAssign:
10977       Combine = IntRange::bit_and;
10978       break;
10979 
10980     // Left shift gets black-listed based on a judgement call.
10981     case BO_Shl:
10982       // ...except that we want to treat '1 << (blah)' as logically
10983       // positive.  It's an important idiom.
10984       if (IntegerLiteral *I
10985             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
10986         if (I->getValue() == 1) {
10987           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
10988           return IntRange(R.Width, /*NonNegative*/ true);
10989         }
10990       }
10991       LLVM_FALLTHROUGH;
10992 
10993     case BO_ShlAssign:
10994       return IntRange::forValueOfType(C, GetExprType(E));
10995 
10996     // Right shift by a constant can narrow its left argument.
10997     case BO_Shr:
10998     case BO_ShrAssign: {
10999       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext,
11000                                 Approximate);
11001 
11002       // If the shift amount is a positive constant, drop the width by
11003       // that much.
11004       if (Optional<llvm::APSInt> shift =
11005               BO->getRHS()->getIntegerConstantExpr(C)) {
11006         if (shift->isNonNegative()) {
11007           unsigned zext = shift->getZExtValue();
11008           if (zext >= L.Width)
11009             L.Width = (L.NonNegative ? 0 : 1);
11010           else
11011             L.Width -= zext;
11012         }
11013       }
11014 
11015       return L;
11016     }
11017 
11018     // Comma acts as its right operand.
11019     case BO_Comma:
11020       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11021                           Approximate);
11022 
11023     case BO_Add:
11024       if (!Approximate)
11025         Combine = IntRange::sum;
11026       break;
11027 
11028     case BO_Sub:
11029       if (BO->getLHS()->getType()->isPointerType())
11030         return IntRange::forValueOfType(C, GetExprType(E));
11031       if (!Approximate)
11032         Combine = IntRange::difference;
11033       break;
11034 
11035     case BO_Mul:
11036       if (!Approximate)
11037         Combine = IntRange::product;
11038       break;
11039 
11040     // The width of a division result is mostly determined by the size
11041     // of the LHS.
11042     case BO_Div: {
11043       // Don't 'pre-truncate' the operands.
11044       unsigned opWidth = C.getIntWidth(GetExprType(E));
11045       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext,
11046                                 Approximate);
11047 
11048       // If the divisor is constant, use that.
11049       if (Optional<llvm::APSInt> divisor =
11050               BO->getRHS()->getIntegerConstantExpr(C)) {
11051         unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
11052         if (log2 >= L.Width)
11053           L.Width = (L.NonNegative ? 0 : 1);
11054         else
11055           L.Width = std::min(L.Width - log2, MaxWidth);
11056         return L;
11057       }
11058 
11059       // Otherwise, just use the LHS's width.
11060       // FIXME: This is wrong if the LHS could be its minimal value and the RHS
11061       // could be -1.
11062       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext,
11063                                 Approximate);
11064       return IntRange(L.Width, L.NonNegative && R.NonNegative);
11065     }
11066 
11067     case BO_Rem:
11068       Combine = IntRange::rem;
11069       break;
11070 
11071     // The default behavior is okay for these.
11072     case BO_Xor:
11073     case BO_Or:
11074       break;
11075     }
11076 
11077     // Combine the two ranges, but limit the result to the type in which we
11078     // performed the computation.
11079     QualType T = GetExprType(E);
11080     unsigned opWidth = C.getIntWidth(T);
11081     IntRange L =
11082         GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate);
11083     IntRange R =
11084         GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate);
11085     IntRange C = Combine(L, R);
11086     C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
11087     C.Width = std::min(C.Width, MaxWidth);
11088     return C;
11089   }
11090 
11091   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
11092     switch (UO->getOpcode()) {
11093     // Boolean-valued operations are white-listed.
11094     case UO_LNot:
11095       return IntRange::forBoolType();
11096 
11097     // Operations with opaque sources are black-listed.
11098     case UO_Deref:
11099     case UO_AddrOf: // should be impossible
11100       return IntRange::forValueOfType(C, GetExprType(E));
11101 
11102     default:
11103       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11104                           Approximate);
11105     }
11106   }
11107 
11108   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
11109     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
11110                         Approximate);
11111 
11112   if (const auto *BitField = E->getSourceBitField())
11113     return IntRange(BitField->getBitWidthValue(C),
11114                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
11115 
11116   return IntRange::forValueOfType(C, GetExprType(E));
11117 }
11118 
11119 static IntRange GetExprRange(ASTContext &C, const Expr *E,
11120                              bool InConstantContext, bool Approximate) {
11121   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
11122                       Approximate);
11123 }
11124 
11125 /// Checks whether the given value, which currently has the given
11126 /// source semantics, has the same value when coerced through the
11127 /// target semantics.
11128 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
11129                                  const llvm::fltSemantics &Src,
11130                                  const llvm::fltSemantics &Tgt) {
11131   llvm::APFloat truncated = value;
11132 
11133   bool ignored;
11134   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
11135   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
11136 
11137   return truncated.bitwiseIsEqual(value);
11138 }
11139 
11140 /// Checks whether the given value, which currently has the given
11141 /// source semantics, has the same value when coerced through the
11142 /// target semantics.
11143 ///
11144 /// The value might be a vector of floats (or a complex number).
11145 static bool IsSameFloatAfterCast(const APValue &value,
11146                                  const llvm::fltSemantics &Src,
11147                                  const llvm::fltSemantics &Tgt) {
11148   if (value.isFloat())
11149     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
11150 
11151   if (value.isVector()) {
11152     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
11153       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
11154         return false;
11155     return true;
11156   }
11157 
11158   assert(value.isComplexFloat());
11159   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
11160           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
11161 }
11162 
11163 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
11164                                        bool IsListInit = false);
11165 
11166 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
11167   // Suppress cases where we are comparing against an enum constant.
11168   if (const DeclRefExpr *DR =
11169       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
11170     if (isa<EnumConstantDecl>(DR->getDecl()))
11171       return true;
11172 
11173   // Suppress cases where the value is expanded from a macro, unless that macro
11174   // is how a language represents a boolean literal. This is the case in both C
11175   // and Objective-C.
11176   SourceLocation BeginLoc = E->getBeginLoc();
11177   if (BeginLoc.isMacroID()) {
11178     StringRef MacroName = Lexer::getImmediateMacroName(
11179         BeginLoc, S.getSourceManager(), S.getLangOpts());
11180     return MacroName != "YES" && MacroName != "NO" &&
11181            MacroName != "true" && MacroName != "false";
11182   }
11183 
11184   return false;
11185 }
11186 
11187 static bool isKnownToHaveUnsignedValue(Expr *E) {
11188   return E->getType()->isIntegerType() &&
11189          (!E->getType()->isSignedIntegerType() ||
11190           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
11191 }
11192 
11193 namespace {
11194 /// The promoted range of values of a type. In general this has the
11195 /// following structure:
11196 ///
11197 ///     |-----------| . . . |-----------|
11198 ///     ^           ^       ^           ^
11199 ///    Min       HoleMin  HoleMax      Max
11200 ///
11201 /// ... where there is only a hole if a signed type is promoted to unsigned
11202 /// (in which case Min and Max are the smallest and largest representable
11203 /// values).
11204 struct PromotedRange {
11205   // Min, or HoleMax if there is a hole.
11206   llvm::APSInt PromotedMin;
11207   // Max, or HoleMin if there is a hole.
11208   llvm::APSInt PromotedMax;
11209 
11210   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
11211     if (R.Width == 0)
11212       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
11213     else if (R.Width >= BitWidth && !Unsigned) {
11214       // Promotion made the type *narrower*. This happens when promoting
11215       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
11216       // Treat all values of 'signed int' as being in range for now.
11217       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
11218       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
11219     } else {
11220       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
11221                         .extOrTrunc(BitWidth);
11222       PromotedMin.setIsUnsigned(Unsigned);
11223 
11224       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
11225                         .extOrTrunc(BitWidth);
11226       PromotedMax.setIsUnsigned(Unsigned);
11227     }
11228   }
11229 
11230   // Determine whether this range is contiguous (has no hole).
11231   bool isContiguous() const { return PromotedMin <= PromotedMax; }
11232 
11233   // Where a constant value is within the range.
11234   enum ComparisonResult {
11235     LT = 0x1,
11236     LE = 0x2,
11237     GT = 0x4,
11238     GE = 0x8,
11239     EQ = 0x10,
11240     NE = 0x20,
11241     InRangeFlag = 0x40,
11242 
11243     Less = LE | LT | NE,
11244     Min = LE | InRangeFlag,
11245     InRange = InRangeFlag,
11246     Max = GE | InRangeFlag,
11247     Greater = GE | GT | NE,
11248 
11249     OnlyValue = LE | GE | EQ | InRangeFlag,
11250     InHole = NE
11251   };
11252 
11253   ComparisonResult compare(const llvm::APSInt &Value) const {
11254     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
11255            Value.isUnsigned() == PromotedMin.isUnsigned());
11256     if (!isContiguous()) {
11257       assert(Value.isUnsigned() && "discontiguous range for signed compare");
11258       if (Value.isMinValue()) return Min;
11259       if (Value.isMaxValue()) return Max;
11260       if (Value >= PromotedMin) return InRange;
11261       if (Value <= PromotedMax) return InRange;
11262       return InHole;
11263     }
11264 
11265     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
11266     case -1: return Less;
11267     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
11268     case 1:
11269       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
11270       case -1: return InRange;
11271       case 0: return Max;
11272       case 1: return Greater;
11273       }
11274     }
11275 
11276     llvm_unreachable("impossible compare result");
11277   }
11278 
11279   static llvm::Optional<StringRef>
11280   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
11281     if (Op == BO_Cmp) {
11282       ComparisonResult LTFlag = LT, GTFlag = GT;
11283       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
11284 
11285       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
11286       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
11287       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
11288       return llvm::None;
11289     }
11290 
11291     ComparisonResult TrueFlag, FalseFlag;
11292     if (Op == BO_EQ) {
11293       TrueFlag = EQ;
11294       FalseFlag = NE;
11295     } else if (Op == BO_NE) {
11296       TrueFlag = NE;
11297       FalseFlag = EQ;
11298     } else {
11299       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
11300         TrueFlag = LT;
11301         FalseFlag = GE;
11302       } else {
11303         TrueFlag = GT;
11304         FalseFlag = LE;
11305       }
11306       if (Op == BO_GE || Op == BO_LE)
11307         std::swap(TrueFlag, FalseFlag);
11308     }
11309     if (R & TrueFlag)
11310       return StringRef("true");
11311     if (R & FalseFlag)
11312       return StringRef("false");
11313     return llvm::None;
11314   }
11315 };
11316 }
11317 
11318 static bool HasEnumType(Expr *E) {
11319   // Strip off implicit integral promotions.
11320   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
11321     if (ICE->getCastKind() != CK_IntegralCast &&
11322         ICE->getCastKind() != CK_NoOp)
11323       break;
11324     E = ICE->getSubExpr();
11325   }
11326 
11327   return E->getType()->isEnumeralType();
11328 }
11329 
11330 static int classifyConstantValue(Expr *Constant) {
11331   // The values of this enumeration are used in the diagnostics
11332   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
11333   enum ConstantValueKind {
11334     Miscellaneous = 0,
11335     LiteralTrue,
11336     LiteralFalse
11337   };
11338   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
11339     return BL->getValue() ? ConstantValueKind::LiteralTrue
11340                           : ConstantValueKind::LiteralFalse;
11341   return ConstantValueKind::Miscellaneous;
11342 }
11343 
11344 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
11345                                         Expr *Constant, Expr *Other,
11346                                         const llvm::APSInt &Value,
11347                                         bool RhsConstant) {
11348   if (S.inTemplateInstantiation())
11349     return false;
11350 
11351   Expr *OriginalOther = Other;
11352 
11353   Constant = Constant->IgnoreParenImpCasts();
11354   Other = Other->IgnoreParenImpCasts();
11355 
11356   // Suppress warnings on tautological comparisons between values of the same
11357   // enumeration type. There are only two ways we could warn on this:
11358   //  - If the constant is outside the range of representable values of
11359   //    the enumeration. In such a case, we should warn about the cast
11360   //    to enumeration type, not about the comparison.
11361   //  - If the constant is the maximum / minimum in-range value. For an
11362   //    enumeratin type, such comparisons can be meaningful and useful.
11363   if (Constant->getType()->isEnumeralType() &&
11364       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
11365     return false;
11366 
11367   IntRange OtherValueRange = GetExprRange(
11368       S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false);
11369 
11370   QualType OtherT = Other->getType();
11371   if (const auto *AT = OtherT->getAs<AtomicType>())
11372     OtherT = AT->getValueType();
11373   IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
11374 
11375   // Special case for ObjC BOOL on targets where its a typedef for a signed char
11376   // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
11377   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
11378                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
11379                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
11380 
11381   // Whether we're treating Other as being a bool because of the form of
11382   // expression despite it having another type (typically 'int' in C).
11383   bool OtherIsBooleanDespiteType =
11384       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
11385   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
11386     OtherTypeRange = OtherValueRange = IntRange::forBoolType();
11387 
11388   // Check if all values in the range of possible values of this expression
11389   // lead to the same comparison outcome.
11390   PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(),
11391                                         Value.isUnsigned());
11392   auto Cmp = OtherPromotedValueRange.compare(Value);
11393   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
11394   if (!Result)
11395     return false;
11396 
11397   // Also consider the range determined by the type alone. This allows us to
11398   // classify the warning under the proper diagnostic group.
11399   bool TautologicalTypeCompare = false;
11400   {
11401     PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
11402                                          Value.isUnsigned());
11403     auto TypeCmp = OtherPromotedTypeRange.compare(Value);
11404     if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
11405                                                        RhsConstant)) {
11406       TautologicalTypeCompare = true;
11407       Cmp = TypeCmp;
11408       Result = TypeResult;
11409     }
11410   }
11411 
11412   // Don't warn if the non-constant operand actually always evaluates to the
11413   // same value.
11414   if (!TautologicalTypeCompare && OtherValueRange.Width == 0)
11415     return false;
11416 
11417   // Suppress the diagnostic for an in-range comparison if the constant comes
11418   // from a macro or enumerator. We don't want to diagnose
11419   //
11420   //   some_long_value <= INT_MAX
11421   //
11422   // when sizeof(int) == sizeof(long).
11423   bool InRange = Cmp & PromotedRange::InRangeFlag;
11424   if (InRange && IsEnumConstOrFromMacro(S, Constant))
11425     return false;
11426 
11427   // A comparison of an unsigned bit-field against 0 is really a type problem,
11428   // even though at the type level the bit-field might promote to 'signed int'.
11429   if (Other->refersToBitField() && InRange && Value == 0 &&
11430       Other->getType()->isUnsignedIntegerOrEnumerationType())
11431     TautologicalTypeCompare = true;
11432 
11433   // If this is a comparison to an enum constant, include that
11434   // constant in the diagnostic.
11435   const EnumConstantDecl *ED = nullptr;
11436   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
11437     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
11438 
11439   // Should be enough for uint128 (39 decimal digits)
11440   SmallString<64> PrettySourceValue;
11441   llvm::raw_svector_ostream OS(PrettySourceValue);
11442   if (ED) {
11443     OS << '\'' << *ED << "' (" << Value << ")";
11444   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
11445                Constant->IgnoreParenImpCasts())) {
11446     OS << (BL->getValue() ? "YES" : "NO");
11447   } else {
11448     OS << Value;
11449   }
11450 
11451   if (!TautologicalTypeCompare) {
11452     S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
11453         << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative
11454         << E->getOpcodeStr() << OS.str() << *Result
11455         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11456     return true;
11457   }
11458 
11459   if (IsObjCSignedCharBool) {
11460     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
11461                           S.PDiag(diag::warn_tautological_compare_objc_bool)
11462                               << OS.str() << *Result);
11463     return true;
11464   }
11465 
11466   // FIXME: We use a somewhat different formatting for the in-range cases and
11467   // cases involving boolean values for historical reasons. We should pick a
11468   // consistent way of presenting these diagnostics.
11469   if (!InRange || Other->isKnownToHaveBooleanValue()) {
11470 
11471     S.DiagRuntimeBehavior(
11472         E->getOperatorLoc(), E,
11473         S.PDiag(!InRange ? diag::warn_out_of_range_compare
11474                          : diag::warn_tautological_bool_compare)
11475             << OS.str() << classifyConstantValue(Constant) << OtherT
11476             << OtherIsBooleanDespiteType << *Result
11477             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
11478   } else {
11479     bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
11480     unsigned Diag =
11481         (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
11482             ? (HasEnumType(OriginalOther)
11483                    ? diag::warn_unsigned_enum_always_true_comparison
11484                    : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
11485                               : diag::warn_unsigned_always_true_comparison)
11486             : diag::warn_tautological_constant_compare;
11487 
11488     S.Diag(E->getOperatorLoc(), Diag)
11489         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
11490         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11491   }
11492 
11493   return true;
11494 }
11495 
11496 /// Analyze the operands of the given comparison.  Implements the
11497 /// fallback case from AnalyzeComparison.
11498 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
11499   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11500   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11501 }
11502 
11503 /// Implements -Wsign-compare.
11504 ///
11505 /// \param E the binary operator to check for warnings
11506 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
11507   // The type the comparison is being performed in.
11508   QualType T = E->getLHS()->getType();
11509 
11510   // Only analyze comparison operators where both sides have been converted to
11511   // the same type.
11512   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
11513     return AnalyzeImpConvsInComparison(S, E);
11514 
11515   // Don't analyze value-dependent comparisons directly.
11516   if (E->isValueDependent())
11517     return AnalyzeImpConvsInComparison(S, E);
11518 
11519   Expr *LHS = E->getLHS();
11520   Expr *RHS = E->getRHS();
11521 
11522   if (T->isIntegralType(S.Context)) {
11523     Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context);
11524     Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context);
11525 
11526     // We don't care about expressions whose result is a constant.
11527     if (RHSValue && LHSValue)
11528       return AnalyzeImpConvsInComparison(S, E);
11529 
11530     // We only care about expressions where just one side is literal
11531     if ((bool)RHSValue ^ (bool)LHSValue) {
11532       // Is the constant on the RHS or LHS?
11533       const bool RhsConstant = (bool)RHSValue;
11534       Expr *Const = RhsConstant ? RHS : LHS;
11535       Expr *Other = RhsConstant ? LHS : RHS;
11536       const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
11537 
11538       // Check whether an integer constant comparison results in a value
11539       // of 'true' or 'false'.
11540       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
11541         return AnalyzeImpConvsInComparison(S, E);
11542     }
11543   }
11544 
11545   if (!T->hasUnsignedIntegerRepresentation()) {
11546     // We don't do anything special if this isn't an unsigned integral
11547     // comparison:  we're only interested in integral comparisons, and
11548     // signed comparisons only happen in cases we don't care to warn about.
11549     return AnalyzeImpConvsInComparison(S, E);
11550   }
11551 
11552   LHS = LHS->IgnoreParenImpCasts();
11553   RHS = RHS->IgnoreParenImpCasts();
11554 
11555   if (!S.getLangOpts().CPlusPlus) {
11556     // Avoid warning about comparison of integers with different signs when
11557     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
11558     // the type of `E`.
11559     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
11560       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11561     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
11562       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11563   }
11564 
11565   // Check to see if one of the (unmodified) operands is of different
11566   // signedness.
11567   Expr *signedOperand, *unsignedOperand;
11568   if (LHS->getType()->hasSignedIntegerRepresentation()) {
11569     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
11570            "unsigned comparison between two signed integer expressions?");
11571     signedOperand = LHS;
11572     unsignedOperand = RHS;
11573   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
11574     signedOperand = RHS;
11575     unsignedOperand = LHS;
11576   } else {
11577     return AnalyzeImpConvsInComparison(S, E);
11578   }
11579 
11580   // Otherwise, calculate the effective range of the signed operand.
11581   IntRange signedRange = GetExprRange(
11582       S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true);
11583 
11584   // Go ahead and analyze implicit conversions in the operands.  Note
11585   // that we skip the implicit conversions on both sides.
11586   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
11587   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
11588 
11589   // If the signed range is non-negative, -Wsign-compare won't fire.
11590   if (signedRange.NonNegative)
11591     return;
11592 
11593   // For (in)equality comparisons, if the unsigned operand is a
11594   // constant which cannot collide with a overflowed signed operand,
11595   // then reinterpreting the signed operand as unsigned will not
11596   // change the result of the comparison.
11597   if (E->isEqualityOp()) {
11598     unsigned comparisonWidth = S.Context.getIntWidth(T);
11599     IntRange unsignedRange =
11600         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(),
11601                      /*Approximate*/ true);
11602 
11603     // We should never be unable to prove that the unsigned operand is
11604     // non-negative.
11605     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
11606 
11607     if (unsignedRange.Width < comparisonWidth)
11608       return;
11609   }
11610 
11611   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
11612                         S.PDiag(diag::warn_mixed_sign_comparison)
11613                             << LHS->getType() << RHS->getType()
11614                             << LHS->getSourceRange() << RHS->getSourceRange());
11615 }
11616 
11617 /// Analyzes an attempt to assign the given value to a bitfield.
11618 ///
11619 /// Returns true if there was something fishy about the attempt.
11620 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
11621                                       SourceLocation InitLoc) {
11622   assert(Bitfield->isBitField());
11623   if (Bitfield->isInvalidDecl())
11624     return false;
11625 
11626   // White-list bool bitfields.
11627   QualType BitfieldType = Bitfield->getType();
11628   if (BitfieldType->isBooleanType())
11629      return false;
11630 
11631   if (BitfieldType->isEnumeralType()) {
11632     EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
11633     // If the underlying enum type was not explicitly specified as an unsigned
11634     // type and the enum contain only positive values, MSVC++ will cause an
11635     // inconsistency by storing this as a signed type.
11636     if (S.getLangOpts().CPlusPlus11 &&
11637         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
11638         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
11639         BitfieldEnumDecl->getNumNegativeBits() == 0) {
11640       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
11641           << BitfieldEnumDecl;
11642     }
11643   }
11644 
11645   if (Bitfield->getType()->isBooleanType())
11646     return false;
11647 
11648   // Ignore value- or type-dependent expressions.
11649   if (Bitfield->getBitWidth()->isValueDependent() ||
11650       Bitfield->getBitWidth()->isTypeDependent() ||
11651       Init->isValueDependent() ||
11652       Init->isTypeDependent())
11653     return false;
11654 
11655   Expr *OriginalInit = Init->IgnoreParenImpCasts();
11656   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
11657 
11658   Expr::EvalResult Result;
11659   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
11660                                    Expr::SE_AllowSideEffects)) {
11661     // The RHS is not constant.  If the RHS has an enum type, make sure the
11662     // bitfield is wide enough to hold all the values of the enum without
11663     // truncation.
11664     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
11665       EnumDecl *ED = EnumTy->getDecl();
11666       bool SignedBitfield = BitfieldType->isSignedIntegerType();
11667 
11668       // Enum types are implicitly signed on Windows, so check if there are any
11669       // negative enumerators to see if the enum was intended to be signed or
11670       // not.
11671       bool SignedEnum = ED->getNumNegativeBits() > 0;
11672 
11673       // Check for surprising sign changes when assigning enum values to a
11674       // bitfield of different signedness.  If the bitfield is signed and we
11675       // have exactly the right number of bits to store this unsigned enum,
11676       // suggest changing the enum to an unsigned type. This typically happens
11677       // on Windows where unfixed enums always use an underlying type of 'int'.
11678       unsigned DiagID = 0;
11679       if (SignedEnum && !SignedBitfield) {
11680         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
11681       } else if (SignedBitfield && !SignedEnum &&
11682                  ED->getNumPositiveBits() == FieldWidth) {
11683         DiagID = diag::warn_signed_bitfield_enum_conversion;
11684       }
11685 
11686       if (DiagID) {
11687         S.Diag(InitLoc, DiagID) << Bitfield << ED;
11688         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
11689         SourceRange TypeRange =
11690             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
11691         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
11692             << SignedEnum << TypeRange;
11693       }
11694 
11695       // Compute the required bitwidth. If the enum has negative values, we need
11696       // one more bit than the normal number of positive bits to represent the
11697       // sign bit.
11698       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
11699                                                   ED->getNumNegativeBits())
11700                                        : ED->getNumPositiveBits();
11701 
11702       // Check the bitwidth.
11703       if (BitsNeeded > FieldWidth) {
11704         Expr *WidthExpr = Bitfield->getBitWidth();
11705         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
11706             << Bitfield << ED;
11707         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
11708             << BitsNeeded << ED << WidthExpr->getSourceRange();
11709       }
11710     }
11711 
11712     return false;
11713   }
11714 
11715   llvm::APSInt Value = Result.Val.getInt();
11716 
11717   unsigned OriginalWidth = Value.getBitWidth();
11718 
11719   if (!Value.isSigned() || Value.isNegative())
11720     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
11721       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
11722         OriginalWidth = Value.getMinSignedBits();
11723 
11724   if (OriginalWidth <= FieldWidth)
11725     return false;
11726 
11727   // Compute the value which the bitfield will contain.
11728   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
11729   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
11730 
11731   // Check whether the stored value is equal to the original value.
11732   TruncatedValue = TruncatedValue.extend(OriginalWidth);
11733   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
11734     return false;
11735 
11736   // Special-case bitfields of width 1: booleans are naturally 0/1, and
11737   // therefore don't strictly fit into a signed bitfield of width 1.
11738   if (FieldWidth == 1 && Value == 1)
11739     return false;
11740 
11741   std::string PrettyValue = Value.toString(10);
11742   std::string PrettyTrunc = TruncatedValue.toString(10);
11743 
11744   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
11745     << PrettyValue << PrettyTrunc << OriginalInit->getType()
11746     << Init->getSourceRange();
11747 
11748   return true;
11749 }
11750 
11751 /// Analyze the given simple or compound assignment for warning-worthy
11752 /// operations.
11753 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
11754   // Just recurse on the LHS.
11755   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11756 
11757   // We want to recurse on the RHS as normal unless we're assigning to
11758   // a bitfield.
11759   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
11760     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
11761                                   E->getOperatorLoc())) {
11762       // Recurse, ignoring any implicit conversions on the RHS.
11763       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
11764                                         E->getOperatorLoc());
11765     }
11766   }
11767 
11768   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11769 
11770   // Diagnose implicitly sequentially-consistent atomic assignment.
11771   if (E->getLHS()->getType()->isAtomicType())
11772     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
11773 }
11774 
11775 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
11776 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
11777                             SourceLocation CContext, unsigned diag,
11778                             bool pruneControlFlow = false) {
11779   if (pruneControlFlow) {
11780     S.DiagRuntimeBehavior(E->getExprLoc(), E,
11781                           S.PDiag(diag)
11782                               << SourceType << T << E->getSourceRange()
11783                               << SourceRange(CContext));
11784     return;
11785   }
11786   S.Diag(E->getExprLoc(), diag)
11787     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
11788 }
11789 
11790 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
11791 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
11792                             SourceLocation CContext,
11793                             unsigned diag, bool pruneControlFlow = false) {
11794   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
11795 }
11796 
11797 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
11798   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
11799       S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
11800 }
11801 
11802 static void adornObjCBoolConversionDiagWithTernaryFixit(
11803     Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
11804   Expr *Ignored = SourceExpr->IgnoreImplicit();
11805   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
11806     Ignored = OVE->getSourceExpr();
11807   bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
11808                      isa<BinaryOperator>(Ignored) ||
11809                      isa<CXXOperatorCallExpr>(Ignored);
11810   SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
11811   if (NeedsParens)
11812     Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
11813             << FixItHint::CreateInsertion(EndLoc, ")");
11814   Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
11815 }
11816 
11817 /// Diagnose an implicit cast from a floating point value to an integer value.
11818 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
11819                                     SourceLocation CContext) {
11820   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
11821   const bool PruneWarnings = S.inTemplateInstantiation();
11822 
11823   Expr *InnerE = E->IgnoreParenImpCasts();
11824   // We also want to warn on, e.g., "int i = -1.234"
11825   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
11826     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
11827       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
11828 
11829   const bool IsLiteral =
11830       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
11831 
11832   llvm::APFloat Value(0.0);
11833   bool IsConstant =
11834     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
11835   if (!IsConstant) {
11836     if (isObjCSignedCharBool(S, T)) {
11837       return adornObjCBoolConversionDiagWithTernaryFixit(
11838           S, E,
11839           S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
11840               << E->getType());
11841     }
11842 
11843     return DiagnoseImpCast(S, E, T, CContext,
11844                            diag::warn_impcast_float_integer, PruneWarnings);
11845   }
11846 
11847   bool isExact = false;
11848 
11849   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
11850                             T->hasUnsignedIntegerRepresentation());
11851   llvm::APFloat::opStatus Result = Value.convertToInteger(
11852       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
11853 
11854   // FIXME: Force the precision of the source value down so we don't print
11855   // digits which are usually useless (we don't really care here if we
11856   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
11857   // would automatically print the shortest representation, but it's a bit
11858   // tricky to implement.
11859   SmallString<16> PrettySourceValue;
11860   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
11861   precision = (precision * 59 + 195) / 196;
11862   Value.toString(PrettySourceValue, precision);
11863 
11864   if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
11865     return adornObjCBoolConversionDiagWithTernaryFixit(
11866         S, E,
11867         S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
11868             << PrettySourceValue);
11869   }
11870 
11871   if (Result == llvm::APFloat::opOK && isExact) {
11872     if (IsLiteral) return;
11873     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
11874                            PruneWarnings);
11875   }
11876 
11877   // Conversion of a floating-point value to a non-bool integer where the
11878   // integral part cannot be represented by the integer type is undefined.
11879   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
11880     return DiagnoseImpCast(
11881         S, E, T, CContext,
11882         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
11883                   : diag::warn_impcast_float_to_integer_out_of_range,
11884         PruneWarnings);
11885 
11886   unsigned DiagID = 0;
11887   if (IsLiteral) {
11888     // Warn on floating point literal to integer.
11889     DiagID = diag::warn_impcast_literal_float_to_integer;
11890   } else if (IntegerValue == 0) {
11891     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
11892       return DiagnoseImpCast(S, E, T, CContext,
11893                              diag::warn_impcast_float_integer, PruneWarnings);
11894     }
11895     // Warn on non-zero to zero conversion.
11896     DiagID = diag::warn_impcast_float_to_integer_zero;
11897   } else {
11898     if (IntegerValue.isUnsigned()) {
11899       if (!IntegerValue.isMaxValue()) {
11900         return DiagnoseImpCast(S, E, T, CContext,
11901                                diag::warn_impcast_float_integer, PruneWarnings);
11902       }
11903     } else {  // IntegerValue.isSigned()
11904       if (!IntegerValue.isMaxSignedValue() &&
11905           !IntegerValue.isMinSignedValue()) {
11906         return DiagnoseImpCast(S, E, T, CContext,
11907                                diag::warn_impcast_float_integer, PruneWarnings);
11908       }
11909     }
11910     // Warn on evaluatable floating point expression to integer conversion.
11911     DiagID = diag::warn_impcast_float_to_integer;
11912   }
11913 
11914   SmallString<16> PrettyTargetValue;
11915   if (IsBool)
11916     PrettyTargetValue = Value.isZero() ? "false" : "true";
11917   else
11918     IntegerValue.toString(PrettyTargetValue);
11919 
11920   if (PruneWarnings) {
11921     S.DiagRuntimeBehavior(E->getExprLoc(), E,
11922                           S.PDiag(DiagID)
11923                               << E->getType() << T.getUnqualifiedType()
11924                               << PrettySourceValue << PrettyTargetValue
11925                               << E->getSourceRange() << SourceRange(CContext));
11926   } else {
11927     S.Diag(E->getExprLoc(), DiagID)
11928         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
11929         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
11930   }
11931 }
11932 
11933 /// Analyze the given compound assignment for the possible losing of
11934 /// floating-point precision.
11935 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
11936   assert(isa<CompoundAssignOperator>(E) &&
11937          "Must be compound assignment operation");
11938   // Recurse on the LHS and RHS in here
11939   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11940   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11941 
11942   if (E->getLHS()->getType()->isAtomicType())
11943     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
11944 
11945   // Now check the outermost expression
11946   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
11947   const auto *RBT = cast<CompoundAssignOperator>(E)
11948                         ->getComputationResultType()
11949                         ->getAs<BuiltinType>();
11950 
11951   // The below checks assume source is floating point.
11952   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
11953 
11954   // If source is floating point but target is an integer.
11955   if (ResultBT->isInteger())
11956     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
11957                            E->getExprLoc(), diag::warn_impcast_float_integer);
11958 
11959   if (!ResultBT->isFloatingPoint())
11960     return;
11961 
11962   // If both source and target are floating points, warn about losing precision.
11963   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
11964       QualType(ResultBT, 0), QualType(RBT, 0));
11965   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
11966     // warn about dropping FP rank.
11967     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
11968                     diag::warn_impcast_float_result_precision);
11969 }
11970 
11971 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
11972                                       IntRange Range) {
11973   if (!Range.Width) return "0";
11974 
11975   llvm::APSInt ValueInRange = Value;
11976   ValueInRange.setIsSigned(!Range.NonNegative);
11977   ValueInRange = ValueInRange.trunc(Range.Width);
11978   return ValueInRange.toString(10);
11979 }
11980 
11981 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
11982   if (!isa<ImplicitCastExpr>(Ex))
11983     return false;
11984 
11985   Expr *InnerE = Ex->IgnoreParenImpCasts();
11986   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
11987   const Type *Source =
11988     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
11989   if (Target->isDependentType())
11990     return false;
11991 
11992   const BuiltinType *FloatCandidateBT =
11993     dyn_cast<BuiltinType>(ToBool ? Source : Target);
11994   const Type *BoolCandidateType = ToBool ? Target : Source;
11995 
11996   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
11997           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
11998 }
11999 
12000 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
12001                                              SourceLocation CC) {
12002   unsigned NumArgs = TheCall->getNumArgs();
12003   for (unsigned i = 0; i < NumArgs; ++i) {
12004     Expr *CurrA = TheCall->getArg(i);
12005     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
12006       continue;
12007 
12008     bool IsSwapped = ((i > 0) &&
12009         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
12010     IsSwapped |= ((i < (NumArgs - 1)) &&
12011         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
12012     if (IsSwapped) {
12013       // Warn on this floating-point to bool conversion.
12014       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
12015                       CurrA->getType(), CC,
12016                       diag::warn_impcast_floating_point_to_bool);
12017     }
12018   }
12019 }
12020 
12021 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
12022                                    SourceLocation CC) {
12023   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
12024                         E->getExprLoc()))
12025     return;
12026 
12027   // Don't warn on functions which have return type nullptr_t.
12028   if (isa<CallExpr>(E))
12029     return;
12030 
12031   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
12032   const Expr::NullPointerConstantKind NullKind =
12033       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
12034   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
12035     return;
12036 
12037   // Return if target type is a safe conversion.
12038   if (T->isAnyPointerType() || T->isBlockPointerType() ||
12039       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
12040     return;
12041 
12042   SourceLocation Loc = E->getSourceRange().getBegin();
12043 
12044   // Venture through the macro stacks to get to the source of macro arguments.
12045   // The new location is a better location than the complete location that was
12046   // passed in.
12047   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
12048   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
12049 
12050   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
12051   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
12052     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
12053         Loc, S.SourceMgr, S.getLangOpts());
12054     if (MacroName == "NULL")
12055       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
12056   }
12057 
12058   // Only warn if the null and context location are in the same macro expansion.
12059   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
12060     return;
12061 
12062   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
12063       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
12064       << FixItHint::CreateReplacement(Loc,
12065                                       S.getFixItZeroLiteralForType(T, Loc));
12066 }
12067 
12068 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12069                                   ObjCArrayLiteral *ArrayLiteral);
12070 
12071 static void
12072 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12073                            ObjCDictionaryLiteral *DictionaryLiteral);
12074 
12075 /// Check a single element within a collection literal against the
12076 /// target element type.
12077 static void checkObjCCollectionLiteralElement(Sema &S,
12078                                               QualType TargetElementType,
12079                                               Expr *Element,
12080                                               unsigned ElementKind) {
12081   // Skip a bitcast to 'id' or qualified 'id'.
12082   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
12083     if (ICE->getCastKind() == CK_BitCast &&
12084         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
12085       Element = ICE->getSubExpr();
12086   }
12087 
12088   QualType ElementType = Element->getType();
12089   ExprResult ElementResult(Element);
12090   if (ElementType->getAs<ObjCObjectPointerType>() &&
12091       S.CheckSingleAssignmentConstraints(TargetElementType,
12092                                          ElementResult,
12093                                          false, false)
12094         != Sema::Compatible) {
12095     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
12096         << ElementType << ElementKind << TargetElementType
12097         << Element->getSourceRange();
12098   }
12099 
12100   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
12101     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
12102   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
12103     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
12104 }
12105 
12106 /// Check an Objective-C array literal being converted to the given
12107 /// target type.
12108 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12109                                   ObjCArrayLiteral *ArrayLiteral) {
12110   if (!S.NSArrayDecl)
12111     return;
12112 
12113   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12114   if (!TargetObjCPtr)
12115     return;
12116 
12117   if (TargetObjCPtr->isUnspecialized() ||
12118       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12119         != S.NSArrayDecl->getCanonicalDecl())
12120     return;
12121 
12122   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12123   if (TypeArgs.size() != 1)
12124     return;
12125 
12126   QualType TargetElementType = TypeArgs[0];
12127   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
12128     checkObjCCollectionLiteralElement(S, TargetElementType,
12129                                       ArrayLiteral->getElement(I),
12130                                       0);
12131   }
12132 }
12133 
12134 /// Check an Objective-C dictionary literal being converted to the given
12135 /// target type.
12136 static void
12137 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12138                            ObjCDictionaryLiteral *DictionaryLiteral) {
12139   if (!S.NSDictionaryDecl)
12140     return;
12141 
12142   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12143   if (!TargetObjCPtr)
12144     return;
12145 
12146   if (TargetObjCPtr->isUnspecialized() ||
12147       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12148         != S.NSDictionaryDecl->getCanonicalDecl())
12149     return;
12150 
12151   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12152   if (TypeArgs.size() != 2)
12153     return;
12154 
12155   QualType TargetKeyType = TypeArgs[0];
12156   QualType TargetObjectType = TypeArgs[1];
12157   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
12158     auto Element = DictionaryLiteral->getKeyValueElement(I);
12159     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
12160     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
12161   }
12162 }
12163 
12164 // Helper function to filter out cases for constant width constant conversion.
12165 // Don't warn on char array initialization or for non-decimal values.
12166 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
12167                                           SourceLocation CC) {
12168   // If initializing from a constant, and the constant starts with '0',
12169   // then it is a binary, octal, or hexadecimal.  Allow these constants
12170   // to fill all the bits, even if there is a sign change.
12171   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
12172     const char FirstLiteralCharacter =
12173         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
12174     if (FirstLiteralCharacter == '0')
12175       return false;
12176   }
12177 
12178   // If the CC location points to a '{', and the type is char, then assume
12179   // assume it is an array initialization.
12180   if (CC.isValid() && T->isCharType()) {
12181     const char FirstContextCharacter =
12182         S.getSourceManager().getCharacterData(CC)[0];
12183     if (FirstContextCharacter == '{')
12184       return false;
12185   }
12186 
12187   return true;
12188 }
12189 
12190 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
12191   const auto *IL = dyn_cast<IntegerLiteral>(E);
12192   if (!IL) {
12193     if (auto *UO = dyn_cast<UnaryOperator>(E)) {
12194       if (UO->getOpcode() == UO_Minus)
12195         return dyn_cast<IntegerLiteral>(UO->getSubExpr());
12196     }
12197   }
12198 
12199   return IL;
12200 }
12201 
12202 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
12203   E = E->IgnoreParenImpCasts();
12204   SourceLocation ExprLoc = E->getExprLoc();
12205 
12206   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
12207     BinaryOperator::Opcode Opc = BO->getOpcode();
12208     Expr::EvalResult Result;
12209     // Do not diagnose unsigned shifts.
12210     if (Opc == BO_Shl) {
12211       const auto *LHS = getIntegerLiteral(BO->getLHS());
12212       const auto *RHS = getIntegerLiteral(BO->getRHS());
12213       if (LHS && LHS->getValue() == 0)
12214         S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
12215       else if (!E->isValueDependent() && LHS && RHS &&
12216                RHS->getValue().isNonNegative() &&
12217                E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
12218         S.Diag(ExprLoc, diag::warn_left_shift_always)
12219             << (Result.Val.getInt() != 0);
12220       else if (E->getType()->isSignedIntegerType())
12221         S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
12222     }
12223   }
12224 
12225   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
12226     const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
12227     const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
12228     if (!LHS || !RHS)
12229       return;
12230     if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
12231         (RHS->getValue() == 0 || RHS->getValue() == 1))
12232       // Do not diagnose common idioms.
12233       return;
12234     if (LHS->getValue() != 0 && RHS->getValue() != 0)
12235       S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
12236   }
12237 }
12238 
12239 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
12240                                     SourceLocation CC,
12241                                     bool *ICContext = nullptr,
12242                                     bool IsListInit = false) {
12243   if (E->isTypeDependent() || E->isValueDependent()) return;
12244 
12245   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
12246   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
12247   if (Source == Target) return;
12248   if (Target->isDependentType()) return;
12249 
12250   // If the conversion context location is invalid don't complain. We also
12251   // don't want to emit a warning if the issue occurs from the expansion of
12252   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
12253   // delay this check as long as possible. Once we detect we are in that
12254   // scenario, we just return.
12255   if (CC.isInvalid())
12256     return;
12257 
12258   if (Source->isAtomicType())
12259     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
12260 
12261   // Diagnose implicit casts to bool.
12262   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
12263     if (isa<StringLiteral>(E))
12264       // Warn on string literal to bool.  Checks for string literals in logical
12265       // and expressions, for instance, assert(0 && "error here"), are
12266       // prevented by a check in AnalyzeImplicitConversions().
12267       return DiagnoseImpCast(S, E, T, CC,
12268                              diag::warn_impcast_string_literal_to_bool);
12269     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
12270         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
12271       // This covers the literal expressions that evaluate to Objective-C
12272       // objects.
12273       return DiagnoseImpCast(S, E, T, CC,
12274                              diag::warn_impcast_objective_c_literal_to_bool);
12275     }
12276     if (Source->isPointerType() || Source->canDecayToPointerType()) {
12277       // Warn on pointer to bool conversion that is always true.
12278       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
12279                                      SourceRange(CC));
12280     }
12281   }
12282 
12283   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
12284   // is a typedef for signed char (macOS), then that constant value has to be 1
12285   // or 0.
12286   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
12287     Expr::EvalResult Result;
12288     if (E->EvaluateAsInt(Result, S.getASTContext(),
12289                          Expr::SE_AllowSideEffects)) {
12290       if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
12291         adornObjCBoolConversionDiagWithTernaryFixit(
12292             S, E,
12293             S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
12294                 << Result.Val.getInt().toString(10));
12295       }
12296       return;
12297     }
12298   }
12299 
12300   // Check implicit casts from Objective-C collection literals to specialized
12301   // collection types, e.g., NSArray<NSString *> *.
12302   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
12303     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
12304   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
12305     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
12306 
12307   // Strip vector types.
12308   if (const auto *SourceVT = dyn_cast<VectorType>(Source)) {
12309     if (Target->isVLSTBuiltinType()) {
12310       auto SourceVectorKind = SourceVT->getVectorKind();
12311       if (SourceVectorKind == VectorType::SveFixedLengthDataVector ||
12312           SourceVectorKind == VectorType::SveFixedLengthPredicateVector ||
12313           (SourceVectorKind == VectorType::GenericVector &&
12314            S.Context.getTypeSize(Source) == S.getLangOpts().ArmSveVectorBits))
12315         return;
12316     }
12317 
12318     if (!isa<VectorType>(Target)) {
12319       if (S.SourceMgr.isInSystemMacro(CC))
12320         return;
12321       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
12322     }
12323 
12324     // If the vector cast is cast between two vectors of the same size, it is
12325     // a bitcast, not a conversion.
12326     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
12327       return;
12328 
12329     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
12330     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
12331   }
12332   if (auto VecTy = dyn_cast<VectorType>(Target))
12333     Target = VecTy->getElementType().getTypePtr();
12334 
12335   // Strip complex types.
12336   if (isa<ComplexType>(Source)) {
12337     if (!isa<ComplexType>(Target)) {
12338       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
12339         return;
12340 
12341       return DiagnoseImpCast(S, E, T, CC,
12342                              S.getLangOpts().CPlusPlus
12343                                  ? diag::err_impcast_complex_scalar
12344                                  : diag::warn_impcast_complex_scalar);
12345     }
12346 
12347     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
12348     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
12349   }
12350 
12351   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
12352   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
12353 
12354   // If the source is floating point...
12355   if (SourceBT && SourceBT->isFloatingPoint()) {
12356     // ...and the target is floating point...
12357     if (TargetBT && TargetBT->isFloatingPoint()) {
12358       // ...then warn if we're dropping FP rank.
12359 
12360       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12361           QualType(SourceBT, 0), QualType(TargetBT, 0));
12362       if (Order > 0) {
12363         // Don't warn about float constants that are precisely
12364         // representable in the target type.
12365         Expr::EvalResult result;
12366         if (E->EvaluateAsRValue(result, S.Context)) {
12367           // Value might be a float, a float vector, or a float complex.
12368           if (IsSameFloatAfterCast(result.Val,
12369                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
12370                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
12371             return;
12372         }
12373 
12374         if (S.SourceMgr.isInSystemMacro(CC))
12375           return;
12376 
12377         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
12378       }
12379       // ... or possibly if we're increasing rank, too
12380       else if (Order < 0) {
12381         if (S.SourceMgr.isInSystemMacro(CC))
12382           return;
12383 
12384         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
12385       }
12386       return;
12387     }
12388 
12389     // If the target is integral, always warn.
12390     if (TargetBT && TargetBT->isInteger()) {
12391       if (S.SourceMgr.isInSystemMacro(CC))
12392         return;
12393 
12394       DiagnoseFloatingImpCast(S, E, T, CC);
12395     }
12396 
12397     // Detect the case where a call result is converted from floating-point to
12398     // to bool, and the final argument to the call is converted from bool, to
12399     // discover this typo:
12400     //
12401     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
12402     //
12403     // FIXME: This is an incredibly special case; is there some more general
12404     // way to detect this class of misplaced-parentheses bug?
12405     if (Target->isBooleanType() && isa<CallExpr>(E)) {
12406       // Check last argument of function call to see if it is an
12407       // implicit cast from a type matching the type the result
12408       // is being cast to.
12409       CallExpr *CEx = cast<CallExpr>(E);
12410       if (unsigned NumArgs = CEx->getNumArgs()) {
12411         Expr *LastA = CEx->getArg(NumArgs - 1);
12412         Expr *InnerE = LastA->IgnoreParenImpCasts();
12413         if (isa<ImplicitCastExpr>(LastA) &&
12414             InnerE->getType()->isBooleanType()) {
12415           // Warn on this floating-point to bool conversion
12416           DiagnoseImpCast(S, E, T, CC,
12417                           diag::warn_impcast_floating_point_to_bool);
12418         }
12419       }
12420     }
12421     return;
12422   }
12423 
12424   // Valid casts involving fixed point types should be accounted for here.
12425   if (Source->isFixedPointType()) {
12426     if (Target->isUnsaturatedFixedPointType()) {
12427       Expr::EvalResult Result;
12428       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
12429                                   S.isConstantEvaluated())) {
12430         llvm::APFixedPoint Value = Result.Val.getFixedPoint();
12431         llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
12432         llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T);
12433         if (Value > MaxVal || Value < MinVal) {
12434           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12435                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12436                                     << Value.toString() << T
12437                                     << E->getSourceRange()
12438                                     << clang::SourceRange(CC));
12439           return;
12440         }
12441       }
12442     } else if (Target->isIntegerType()) {
12443       Expr::EvalResult Result;
12444       if (!S.isConstantEvaluated() &&
12445           E->EvaluateAsFixedPoint(Result, S.Context,
12446                                   Expr::SE_AllowSideEffects)) {
12447         llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
12448 
12449         bool Overflowed;
12450         llvm::APSInt IntResult = FXResult.convertToInt(
12451             S.Context.getIntWidth(T),
12452             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
12453 
12454         if (Overflowed) {
12455           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12456                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12457                                     << FXResult.toString() << T
12458                                     << E->getSourceRange()
12459                                     << clang::SourceRange(CC));
12460           return;
12461         }
12462       }
12463     }
12464   } else if (Target->isUnsaturatedFixedPointType()) {
12465     if (Source->isIntegerType()) {
12466       Expr::EvalResult Result;
12467       if (!S.isConstantEvaluated() &&
12468           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
12469         llvm::APSInt Value = Result.Val.getInt();
12470 
12471         bool Overflowed;
12472         llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
12473             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
12474 
12475         if (Overflowed) {
12476           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12477                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12478                                     << Value.toString(/*Radix=*/10) << T
12479                                     << E->getSourceRange()
12480                                     << clang::SourceRange(CC));
12481           return;
12482         }
12483       }
12484     }
12485   }
12486 
12487   // If we are casting an integer type to a floating point type without
12488   // initialization-list syntax, we might lose accuracy if the floating
12489   // point type has a narrower significand than the integer type.
12490   if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
12491       TargetBT->isFloatingType() && !IsListInit) {
12492     // Determine the number of precision bits in the source integer type.
12493     IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(),
12494                                         /*Approximate*/ true);
12495     unsigned int SourcePrecision = SourceRange.Width;
12496 
12497     // Determine the number of precision bits in the
12498     // target floating point type.
12499     unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
12500         S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12501 
12502     if (SourcePrecision > 0 && TargetPrecision > 0 &&
12503         SourcePrecision > TargetPrecision) {
12504 
12505       if (Optional<llvm::APSInt> SourceInt =
12506               E->getIntegerConstantExpr(S.Context)) {
12507         // If the source integer is a constant, convert it to the target
12508         // floating point type. Issue a warning if the value changes
12509         // during the whole conversion.
12510         llvm::APFloat TargetFloatValue(
12511             S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12512         llvm::APFloat::opStatus ConversionStatus =
12513             TargetFloatValue.convertFromAPInt(
12514                 *SourceInt, SourceBT->isSignedInteger(),
12515                 llvm::APFloat::rmNearestTiesToEven);
12516 
12517         if (ConversionStatus != llvm::APFloat::opOK) {
12518           std::string PrettySourceValue = SourceInt->toString(10);
12519           SmallString<32> PrettyTargetValue;
12520           TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
12521 
12522           S.DiagRuntimeBehavior(
12523               E->getExprLoc(), E,
12524               S.PDiag(diag::warn_impcast_integer_float_precision_constant)
12525                   << PrettySourceValue << PrettyTargetValue << E->getType() << T
12526                   << E->getSourceRange() << clang::SourceRange(CC));
12527         }
12528       } else {
12529         // Otherwise, the implicit conversion may lose precision.
12530         DiagnoseImpCast(S, E, T, CC,
12531                         diag::warn_impcast_integer_float_precision);
12532       }
12533     }
12534   }
12535 
12536   DiagnoseNullConversion(S, E, T, CC);
12537 
12538   S.DiscardMisalignedMemberAddress(Target, E);
12539 
12540   if (Target->isBooleanType())
12541     DiagnoseIntInBoolContext(S, E);
12542 
12543   if (!Source->isIntegerType() || !Target->isIntegerType())
12544     return;
12545 
12546   // TODO: remove this early return once the false positives for constant->bool
12547   // in templates, macros, etc, are reduced or removed.
12548   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
12549     return;
12550 
12551   if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
12552       !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
12553     return adornObjCBoolConversionDiagWithTernaryFixit(
12554         S, E,
12555         S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
12556             << E->getType());
12557   }
12558 
12559   IntRange SourceTypeRange =
12560       IntRange::forTargetOfCanonicalType(S.Context, Source);
12561   IntRange LikelySourceRange =
12562       GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true);
12563   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
12564 
12565   if (LikelySourceRange.Width > TargetRange.Width) {
12566     // If the source is a constant, use a default-on diagnostic.
12567     // TODO: this should happen for bitfield stores, too.
12568     Expr::EvalResult Result;
12569     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
12570                          S.isConstantEvaluated())) {
12571       llvm::APSInt Value(32);
12572       Value = Result.Val.getInt();
12573 
12574       if (S.SourceMgr.isInSystemMacro(CC))
12575         return;
12576 
12577       std::string PrettySourceValue = Value.toString(10);
12578       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
12579 
12580       S.DiagRuntimeBehavior(
12581           E->getExprLoc(), E,
12582           S.PDiag(diag::warn_impcast_integer_precision_constant)
12583               << PrettySourceValue << PrettyTargetValue << E->getType() << T
12584               << E->getSourceRange() << SourceRange(CC));
12585       return;
12586     }
12587 
12588     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
12589     if (S.SourceMgr.isInSystemMacro(CC))
12590       return;
12591 
12592     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
12593       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
12594                              /* pruneControlFlow */ true);
12595     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
12596   }
12597 
12598   if (TargetRange.Width > SourceTypeRange.Width) {
12599     if (auto *UO = dyn_cast<UnaryOperator>(E))
12600       if (UO->getOpcode() == UO_Minus)
12601         if (Source->isUnsignedIntegerType()) {
12602           if (Target->isUnsignedIntegerType())
12603             return DiagnoseImpCast(S, E, T, CC,
12604                                    diag::warn_impcast_high_order_zero_bits);
12605           if (Target->isSignedIntegerType())
12606             return DiagnoseImpCast(S, E, T, CC,
12607                                    diag::warn_impcast_nonnegative_result);
12608         }
12609   }
12610 
12611   if (TargetRange.Width == LikelySourceRange.Width &&
12612       !TargetRange.NonNegative && LikelySourceRange.NonNegative &&
12613       Source->isSignedIntegerType()) {
12614     // Warn when doing a signed to signed conversion, warn if the positive
12615     // source value is exactly the width of the target type, which will
12616     // cause a negative value to be stored.
12617 
12618     Expr::EvalResult Result;
12619     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
12620         !S.SourceMgr.isInSystemMacro(CC)) {
12621       llvm::APSInt Value = Result.Val.getInt();
12622       if (isSameWidthConstantConversion(S, E, T, CC)) {
12623         std::string PrettySourceValue = Value.toString(10);
12624         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
12625 
12626         S.DiagRuntimeBehavior(
12627             E->getExprLoc(), E,
12628             S.PDiag(diag::warn_impcast_integer_precision_constant)
12629                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
12630                 << E->getSourceRange() << SourceRange(CC));
12631         return;
12632       }
12633     }
12634 
12635     // Fall through for non-constants to give a sign conversion warning.
12636   }
12637 
12638   if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) ||
12639       (!TargetRange.NonNegative && LikelySourceRange.NonNegative &&
12640        LikelySourceRange.Width == TargetRange.Width)) {
12641     if (S.SourceMgr.isInSystemMacro(CC))
12642       return;
12643 
12644     unsigned DiagID = diag::warn_impcast_integer_sign;
12645 
12646     // Traditionally, gcc has warned about this under -Wsign-compare.
12647     // We also want to warn about it in -Wconversion.
12648     // So if -Wconversion is off, use a completely identical diagnostic
12649     // in the sign-compare group.
12650     // The conditional-checking code will
12651     if (ICContext) {
12652       DiagID = diag::warn_impcast_integer_sign_conditional;
12653       *ICContext = true;
12654     }
12655 
12656     return DiagnoseImpCast(S, E, T, CC, DiagID);
12657   }
12658 
12659   // Diagnose conversions between different enumeration types.
12660   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
12661   // type, to give us better diagnostics.
12662   QualType SourceType = E->getType();
12663   if (!S.getLangOpts().CPlusPlus) {
12664     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12665       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
12666         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
12667         SourceType = S.Context.getTypeDeclType(Enum);
12668         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
12669       }
12670   }
12671 
12672   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
12673     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
12674       if (SourceEnum->getDecl()->hasNameForLinkage() &&
12675           TargetEnum->getDecl()->hasNameForLinkage() &&
12676           SourceEnum != TargetEnum) {
12677         if (S.SourceMgr.isInSystemMacro(CC))
12678           return;
12679 
12680         return DiagnoseImpCast(S, E, SourceType, T, CC,
12681                                diag::warn_impcast_different_enum_types);
12682       }
12683 }
12684 
12685 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
12686                                      SourceLocation CC, QualType T);
12687 
12688 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
12689                                     SourceLocation CC, bool &ICContext) {
12690   E = E->IgnoreParenImpCasts();
12691 
12692   if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
12693     return CheckConditionalOperator(S, CO, CC, T);
12694 
12695   AnalyzeImplicitConversions(S, E, CC);
12696   if (E->getType() != T)
12697     return CheckImplicitConversion(S, E, T, CC, &ICContext);
12698 }
12699 
12700 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
12701                                      SourceLocation CC, QualType T) {
12702   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
12703 
12704   Expr *TrueExpr = E->getTrueExpr();
12705   if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
12706     TrueExpr = BCO->getCommon();
12707 
12708   bool Suspicious = false;
12709   CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
12710   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
12711 
12712   if (T->isBooleanType())
12713     DiagnoseIntInBoolContext(S, E);
12714 
12715   // If -Wconversion would have warned about either of the candidates
12716   // for a signedness conversion to the context type...
12717   if (!Suspicious) return;
12718 
12719   // ...but it's currently ignored...
12720   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
12721     return;
12722 
12723   // ...then check whether it would have warned about either of the
12724   // candidates for a signedness conversion to the condition type.
12725   if (E->getType() == T) return;
12726 
12727   Suspicious = false;
12728   CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(),
12729                           E->getType(), CC, &Suspicious);
12730   if (!Suspicious)
12731     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
12732                             E->getType(), CC, &Suspicious);
12733 }
12734 
12735 /// Check conversion of given expression to boolean.
12736 /// Input argument E is a logical expression.
12737 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
12738   if (S.getLangOpts().Bool)
12739     return;
12740   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
12741     return;
12742   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
12743 }
12744 
12745 namespace {
12746 struct AnalyzeImplicitConversionsWorkItem {
12747   Expr *E;
12748   SourceLocation CC;
12749   bool IsListInit;
12750 };
12751 }
12752 
12753 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
12754 /// that should be visited are added to WorkList.
12755 static void AnalyzeImplicitConversions(
12756     Sema &S, AnalyzeImplicitConversionsWorkItem Item,
12757     llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
12758   Expr *OrigE = Item.E;
12759   SourceLocation CC = Item.CC;
12760 
12761   QualType T = OrigE->getType();
12762   Expr *E = OrigE->IgnoreParenImpCasts();
12763 
12764   // Propagate whether we are in a C++ list initialization expression.
12765   // If so, we do not issue warnings for implicit int-float conversion
12766   // precision loss, because C++11 narrowing already handles it.
12767   bool IsListInit = Item.IsListInit ||
12768                     (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
12769 
12770   if (E->isTypeDependent() || E->isValueDependent())
12771     return;
12772 
12773   Expr *SourceExpr = E;
12774   // Examine, but don't traverse into the source expression of an
12775   // OpaqueValueExpr, since it may have multiple parents and we don't want to
12776   // emit duplicate diagnostics. Its fine to examine the form or attempt to
12777   // evaluate it in the context of checking the specific conversion to T though.
12778   if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
12779     if (auto *Src = OVE->getSourceExpr())
12780       SourceExpr = Src;
12781 
12782   if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
12783     if (UO->getOpcode() == UO_Not &&
12784         UO->getSubExpr()->isKnownToHaveBooleanValue())
12785       S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
12786           << OrigE->getSourceRange() << T->isBooleanType()
12787           << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
12788 
12789   // For conditional operators, we analyze the arguments as if they
12790   // were being fed directly into the output.
12791   if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
12792     CheckConditionalOperator(S, CO, CC, T);
12793     return;
12794   }
12795 
12796   // Check implicit argument conversions for function calls.
12797   if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
12798     CheckImplicitArgumentConversions(S, Call, CC);
12799 
12800   // Go ahead and check any implicit conversions we might have skipped.
12801   // The non-canonical typecheck is just an optimization;
12802   // CheckImplicitConversion will filter out dead implicit conversions.
12803   if (SourceExpr->getType() != T)
12804     CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit);
12805 
12806   // Now continue drilling into this expression.
12807 
12808   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
12809     // The bound subexpressions in a PseudoObjectExpr are not reachable
12810     // as transitive children.
12811     // FIXME: Use a more uniform representation for this.
12812     for (auto *SE : POE->semantics())
12813       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
12814         WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
12815   }
12816 
12817   // Skip past explicit casts.
12818   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
12819     E = CE->getSubExpr()->IgnoreParenImpCasts();
12820     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
12821       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12822     WorkList.push_back({E, CC, IsListInit});
12823     return;
12824   }
12825 
12826   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12827     // Do a somewhat different check with comparison operators.
12828     if (BO->isComparisonOp())
12829       return AnalyzeComparison(S, BO);
12830 
12831     // And with simple assignments.
12832     if (BO->getOpcode() == BO_Assign)
12833       return AnalyzeAssignment(S, BO);
12834     // And with compound assignments.
12835     if (BO->isAssignmentOp())
12836       return AnalyzeCompoundAssignment(S, BO);
12837   }
12838 
12839   // These break the otherwise-useful invariant below.  Fortunately,
12840   // we don't really need to recurse into them, because any internal
12841   // expressions should have been analyzed already when they were
12842   // built into statements.
12843   if (isa<StmtExpr>(E)) return;
12844 
12845   // Don't descend into unevaluated contexts.
12846   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
12847 
12848   // Now just recurse over the expression's children.
12849   CC = E->getExprLoc();
12850   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
12851   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
12852   for (Stmt *SubStmt : E->children()) {
12853     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
12854     if (!ChildExpr)
12855       continue;
12856 
12857     if (IsLogicalAndOperator &&
12858         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
12859       // Ignore checking string literals that are in logical and operators.
12860       // This is a common pattern for asserts.
12861       continue;
12862     WorkList.push_back({ChildExpr, CC, IsListInit});
12863   }
12864 
12865   if (BO && BO->isLogicalOp()) {
12866     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
12867     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
12868       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
12869 
12870     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
12871     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
12872       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
12873   }
12874 
12875   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
12876     if (U->getOpcode() == UO_LNot) {
12877       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
12878     } else if (U->getOpcode() != UO_AddrOf) {
12879       if (U->getSubExpr()->getType()->isAtomicType())
12880         S.Diag(U->getSubExpr()->getBeginLoc(),
12881                diag::warn_atomic_implicit_seq_cst);
12882     }
12883   }
12884 }
12885 
12886 /// AnalyzeImplicitConversions - Find and report any interesting
12887 /// implicit conversions in the given expression.  There are a couple
12888 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
12889 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
12890                                        bool IsListInit/*= false*/) {
12891   llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
12892   WorkList.push_back({OrigE, CC, IsListInit});
12893   while (!WorkList.empty())
12894     AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
12895 }
12896 
12897 /// Diagnose integer type and any valid implicit conversion to it.
12898 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
12899   // Taking into account implicit conversions,
12900   // allow any integer.
12901   if (!E->getType()->isIntegerType()) {
12902     S.Diag(E->getBeginLoc(),
12903            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
12904     return true;
12905   }
12906   // Potentially emit standard warnings for implicit conversions if enabled
12907   // using -Wconversion.
12908   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
12909   return false;
12910 }
12911 
12912 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
12913 // Returns true when emitting a warning about taking the address of a reference.
12914 static bool CheckForReference(Sema &SemaRef, const Expr *E,
12915                               const PartialDiagnostic &PD) {
12916   E = E->IgnoreParenImpCasts();
12917 
12918   const FunctionDecl *FD = nullptr;
12919 
12920   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12921     if (!DRE->getDecl()->getType()->isReferenceType())
12922       return false;
12923   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
12924     if (!M->getMemberDecl()->getType()->isReferenceType())
12925       return false;
12926   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
12927     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
12928       return false;
12929     FD = Call->getDirectCallee();
12930   } else {
12931     return false;
12932   }
12933 
12934   SemaRef.Diag(E->getExprLoc(), PD);
12935 
12936   // If possible, point to location of function.
12937   if (FD) {
12938     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
12939   }
12940 
12941   return true;
12942 }
12943 
12944 // Returns true if the SourceLocation is expanded from any macro body.
12945 // Returns false if the SourceLocation is invalid, is from not in a macro
12946 // expansion, or is from expanded from a top-level macro argument.
12947 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
12948   if (Loc.isInvalid())
12949     return false;
12950 
12951   while (Loc.isMacroID()) {
12952     if (SM.isMacroBodyExpansion(Loc))
12953       return true;
12954     Loc = SM.getImmediateMacroCallerLoc(Loc);
12955   }
12956 
12957   return false;
12958 }
12959 
12960 /// Diagnose pointers that are always non-null.
12961 /// \param E the expression containing the pointer
12962 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
12963 /// compared to a null pointer
12964 /// \param IsEqual True when the comparison is equal to a null pointer
12965 /// \param Range Extra SourceRange to highlight in the diagnostic
12966 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
12967                                         Expr::NullPointerConstantKind NullKind,
12968                                         bool IsEqual, SourceRange Range) {
12969   if (!E)
12970     return;
12971 
12972   // Don't warn inside macros.
12973   if (E->getExprLoc().isMacroID()) {
12974     const SourceManager &SM = getSourceManager();
12975     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
12976         IsInAnyMacroBody(SM, Range.getBegin()))
12977       return;
12978   }
12979   E = E->IgnoreImpCasts();
12980 
12981   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
12982 
12983   if (isa<CXXThisExpr>(E)) {
12984     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
12985                                 : diag::warn_this_bool_conversion;
12986     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
12987     return;
12988   }
12989 
12990   bool IsAddressOf = false;
12991 
12992   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
12993     if (UO->getOpcode() != UO_AddrOf)
12994       return;
12995     IsAddressOf = true;
12996     E = UO->getSubExpr();
12997   }
12998 
12999   if (IsAddressOf) {
13000     unsigned DiagID = IsCompare
13001                           ? diag::warn_address_of_reference_null_compare
13002                           : diag::warn_address_of_reference_bool_conversion;
13003     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
13004                                          << IsEqual;
13005     if (CheckForReference(*this, E, PD)) {
13006       return;
13007     }
13008   }
13009 
13010   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
13011     bool IsParam = isa<NonNullAttr>(NonnullAttr);
13012     std::string Str;
13013     llvm::raw_string_ostream S(Str);
13014     E->printPretty(S, nullptr, getPrintingPolicy());
13015     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
13016                                 : diag::warn_cast_nonnull_to_bool;
13017     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
13018       << E->getSourceRange() << Range << IsEqual;
13019     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
13020   };
13021 
13022   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
13023   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
13024     if (auto *Callee = Call->getDirectCallee()) {
13025       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
13026         ComplainAboutNonnullParamOrCall(A);
13027         return;
13028       }
13029     }
13030   }
13031 
13032   // Expect to find a single Decl.  Skip anything more complicated.
13033   ValueDecl *D = nullptr;
13034   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
13035     D = R->getDecl();
13036   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13037     D = M->getMemberDecl();
13038   }
13039 
13040   // Weak Decls can be null.
13041   if (!D || D->isWeak())
13042     return;
13043 
13044   // Check for parameter decl with nonnull attribute
13045   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
13046     if (getCurFunction() &&
13047         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
13048       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
13049         ComplainAboutNonnullParamOrCall(A);
13050         return;
13051       }
13052 
13053       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
13054         // Skip function template not specialized yet.
13055         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
13056           return;
13057         auto ParamIter = llvm::find(FD->parameters(), PV);
13058         assert(ParamIter != FD->param_end());
13059         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
13060 
13061         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
13062           if (!NonNull->args_size()) {
13063               ComplainAboutNonnullParamOrCall(NonNull);
13064               return;
13065           }
13066 
13067           for (const ParamIdx &ArgNo : NonNull->args()) {
13068             if (ArgNo.getASTIndex() == ParamNo) {
13069               ComplainAboutNonnullParamOrCall(NonNull);
13070               return;
13071             }
13072           }
13073         }
13074       }
13075     }
13076   }
13077 
13078   QualType T = D->getType();
13079   const bool IsArray = T->isArrayType();
13080   const bool IsFunction = T->isFunctionType();
13081 
13082   // Address of function is used to silence the function warning.
13083   if (IsAddressOf && IsFunction) {
13084     return;
13085   }
13086 
13087   // Found nothing.
13088   if (!IsAddressOf && !IsFunction && !IsArray)
13089     return;
13090 
13091   // Pretty print the expression for the diagnostic.
13092   std::string Str;
13093   llvm::raw_string_ostream S(Str);
13094   E->printPretty(S, nullptr, getPrintingPolicy());
13095 
13096   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
13097                               : diag::warn_impcast_pointer_to_bool;
13098   enum {
13099     AddressOf,
13100     FunctionPointer,
13101     ArrayPointer
13102   } DiagType;
13103   if (IsAddressOf)
13104     DiagType = AddressOf;
13105   else if (IsFunction)
13106     DiagType = FunctionPointer;
13107   else if (IsArray)
13108     DiagType = ArrayPointer;
13109   else
13110     llvm_unreachable("Could not determine diagnostic.");
13111   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
13112                                 << Range << IsEqual;
13113 
13114   if (!IsFunction)
13115     return;
13116 
13117   // Suggest '&' to silence the function warning.
13118   Diag(E->getExprLoc(), diag::note_function_warning_silence)
13119       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
13120 
13121   // Check to see if '()' fixit should be emitted.
13122   QualType ReturnType;
13123   UnresolvedSet<4> NonTemplateOverloads;
13124   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
13125   if (ReturnType.isNull())
13126     return;
13127 
13128   if (IsCompare) {
13129     // There are two cases here.  If there is null constant, the only suggest
13130     // for a pointer return type.  If the null is 0, then suggest if the return
13131     // type is a pointer or an integer type.
13132     if (!ReturnType->isPointerType()) {
13133       if (NullKind == Expr::NPCK_ZeroExpression ||
13134           NullKind == Expr::NPCK_ZeroLiteral) {
13135         if (!ReturnType->isIntegerType())
13136           return;
13137       } else {
13138         return;
13139       }
13140     }
13141   } else { // !IsCompare
13142     // For function to bool, only suggest if the function pointer has bool
13143     // return type.
13144     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
13145       return;
13146   }
13147   Diag(E->getExprLoc(), diag::note_function_to_function_call)
13148       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
13149 }
13150 
13151 /// Diagnoses "dangerous" implicit conversions within the given
13152 /// expression (which is a full expression).  Implements -Wconversion
13153 /// and -Wsign-compare.
13154 ///
13155 /// \param CC the "context" location of the implicit conversion, i.e.
13156 ///   the most location of the syntactic entity requiring the implicit
13157 ///   conversion
13158 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
13159   // Don't diagnose in unevaluated contexts.
13160   if (isUnevaluatedContext())
13161     return;
13162 
13163   // Don't diagnose for value- or type-dependent expressions.
13164   if (E->isTypeDependent() || E->isValueDependent())
13165     return;
13166 
13167   // Check for array bounds violations in cases where the check isn't triggered
13168   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
13169   // ArraySubscriptExpr is on the RHS of a variable initialization.
13170   CheckArrayAccess(E);
13171 
13172   // This is not the right CC for (e.g.) a variable initialization.
13173   AnalyzeImplicitConversions(*this, E, CC);
13174 }
13175 
13176 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
13177 /// Input argument E is a logical expression.
13178 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
13179   ::CheckBoolLikeConversion(*this, E, CC);
13180 }
13181 
13182 /// Diagnose when expression is an integer constant expression and its evaluation
13183 /// results in integer overflow
13184 void Sema::CheckForIntOverflow (Expr *E) {
13185   // Use a work list to deal with nested struct initializers.
13186   SmallVector<Expr *, 2> Exprs(1, E);
13187 
13188   do {
13189     Expr *OriginalE = Exprs.pop_back_val();
13190     Expr *E = OriginalE->IgnoreParenCasts();
13191 
13192     if (isa<BinaryOperator>(E)) {
13193       E->EvaluateForOverflow(Context);
13194       continue;
13195     }
13196 
13197     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
13198       Exprs.append(InitList->inits().begin(), InitList->inits().end());
13199     else if (isa<ObjCBoxedExpr>(OriginalE))
13200       E->EvaluateForOverflow(Context);
13201     else if (auto Call = dyn_cast<CallExpr>(E))
13202       Exprs.append(Call->arg_begin(), Call->arg_end());
13203     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
13204       Exprs.append(Message->arg_begin(), Message->arg_end());
13205   } while (!Exprs.empty());
13206 }
13207 
13208 namespace {
13209 
13210 /// Visitor for expressions which looks for unsequenced operations on the
13211 /// same object.
13212 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
13213   using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
13214 
13215   /// A tree of sequenced regions within an expression. Two regions are
13216   /// unsequenced if one is an ancestor or a descendent of the other. When we
13217   /// finish processing an expression with sequencing, such as a comma
13218   /// expression, we fold its tree nodes into its parent, since they are
13219   /// unsequenced with respect to nodes we will visit later.
13220   class SequenceTree {
13221     struct Value {
13222       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
13223       unsigned Parent : 31;
13224       unsigned Merged : 1;
13225     };
13226     SmallVector<Value, 8> Values;
13227 
13228   public:
13229     /// A region within an expression which may be sequenced with respect
13230     /// to some other region.
13231     class Seq {
13232       friend class SequenceTree;
13233 
13234       unsigned Index;
13235 
13236       explicit Seq(unsigned N) : Index(N) {}
13237 
13238     public:
13239       Seq() : Index(0) {}
13240     };
13241 
13242     SequenceTree() { Values.push_back(Value(0)); }
13243     Seq root() const { return Seq(0); }
13244 
13245     /// Create a new sequence of operations, which is an unsequenced
13246     /// subset of \p Parent. This sequence of operations is sequenced with
13247     /// respect to other children of \p Parent.
13248     Seq allocate(Seq Parent) {
13249       Values.push_back(Value(Parent.Index));
13250       return Seq(Values.size() - 1);
13251     }
13252 
13253     /// Merge a sequence of operations into its parent.
13254     void merge(Seq S) {
13255       Values[S.Index].Merged = true;
13256     }
13257 
13258     /// Determine whether two operations are unsequenced. This operation
13259     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
13260     /// should have been merged into its parent as appropriate.
13261     bool isUnsequenced(Seq Cur, Seq Old) {
13262       unsigned C = representative(Cur.Index);
13263       unsigned Target = representative(Old.Index);
13264       while (C >= Target) {
13265         if (C == Target)
13266           return true;
13267         C = Values[C].Parent;
13268       }
13269       return false;
13270     }
13271 
13272   private:
13273     /// Pick a representative for a sequence.
13274     unsigned representative(unsigned K) {
13275       if (Values[K].Merged)
13276         // Perform path compression as we go.
13277         return Values[K].Parent = representative(Values[K].Parent);
13278       return K;
13279     }
13280   };
13281 
13282   /// An object for which we can track unsequenced uses.
13283   using Object = const NamedDecl *;
13284 
13285   /// Different flavors of object usage which we track. We only track the
13286   /// least-sequenced usage of each kind.
13287   enum UsageKind {
13288     /// A read of an object. Multiple unsequenced reads are OK.
13289     UK_Use,
13290 
13291     /// A modification of an object which is sequenced before the value
13292     /// computation of the expression, such as ++n in C++.
13293     UK_ModAsValue,
13294 
13295     /// A modification of an object which is not sequenced before the value
13296     /// computation of the expression, such as n++.
13297     UK_ModAsSideEffect,
13298 
13299     UK_Count = UK_ModAsSideEffect + 1
13300   };
13301 
13302   /// Bundle together a sequencing region and the expression corresponding
13303   /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
13304   struct Usage {
13305     const Expr *UsageExpr;
13306     SequenceTree::Seq Seq;
13307 
13308     Usage() : UsageExpr(nullptr), Seq() {}
13309   };
13310 
13311   struct UsageInfo {
13312     Usage Uses[UK_Count];
13313 
13314     /// Have we issued a diagnostic for this object already?
13315     bool Diagnosed;
13316 
13317     UsageInfo() : Uses(), Diagnosed(false) {}
13318   };
13319   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
13320 
13321   Sema &SemaRef;
13322 
13323   /// Sequenced regions within the expression.
13324   SequenceTree Tree;
13325 
13326   /// Declaration modifications and references which we have seen.
13327   UsageInfoMap UsageMap;
13328 
13329   /// The region we are currently within.
13330   SequenceTree::Seq Region;
13331 
13332   /// Filled in with declarations which were modified as a side-effect
13333   /// (that is, post-increment operations).
13334   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
13335 
13336   /// Expressions to check later. We defer checking these to reduce
13337   /// stack usage.
13338   SmallVectorImpl<const Expr *> &WorkList;
13339 
13340   /// RAII object wrapping the visitation of a sequenced subexpression of an
13341   /// expression. At the end of this process, the side-effects of the evaluation
13342   /// become sequenced with respect to the value computation of the result, so
13343   /// we downgrade any UK_ModAsSideEffect within the evaluation to
13344   /// UK_ModAsValue.
13345   struct SequencedSubexpression {
13346     SequencedSubexpression(SequenceChecker &Self)
13347       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
13348       Self.ModAsSideEffect = &ModAsSideEffect;
13349     }
13350 
13351     ~SequencedSubexpression() {
13352       for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
13353         // Add a new usage with usage kind UK_ModAsValue, and then restore
13354         // the previous usage with UK_ModAsSideEffect (thus clearing it if
13355         // the previous one was empty).
13356         UsageInfo &UI = Self.UsageMap[M.first];
13357         auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
13358         Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
13359         SideEffectUsage = M.second;
13360       }
13361       Self.ModAsSideEffect = OldModAsSideEffect;
13362     }
13363 
13364     SequenceChecker &Self;
13365     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
13366     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
13367   };
13368 
13369   /// RAII object wrapping the visitation of a subexpression which we might
13370   /// choose to evaluate as a constant. If any subexpression is evaluated and
13371   /// found to be non-constant, this allows us to suppress the evaluation of
13372   /// the outer expression.
13373   class EvaluationTracker {
13374   public:
13375     EvaluationTracker(SequenceChecker &Self)
13376         : Self(Self), Prev(Self.EvalTracker) {
13377       Self.EvalTracker = this;
13378     }
13379 
13380     ~EvaluationTracker() {
13381       Self.EvalTracker = Prev;
13382       if (Prev)
13383         Prev->EvalOK &= EvalOK;
13384     }
13385 
13386     bool evaluate(const Expr *E, bool &Result) {
13387       if (!EvalOK || E->isValueDependent())
13388         return false;
13389       EvalOK = E->EvaluateAsBooleanCondition(
13390           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
13391       return EvalOK;
13392     }
13393 
13394   private:
13395     SequenceChecker &Self;
13396     EvaluationTracker *Prev;
13397     bool EvalOK = true;
13398   } *EvalTracker = nullptr;
13399 
13400   /// Find the object which is produced by the specified expression,
13401   /// if any.
13402   Object getObject(const Expr *E, bool Mod) const {
13403     E = E->IgnoreParenCasts();
13404     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13405       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
13406         return getObject(UO->getSubExpr(), Mod);
13407     } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13408       if (BO->getOpcode() == BO_Comma)
13409         return getObject(BO->getRHS(), Mod);
13410       if (Mod && BO->isAssignmentOp())
13411         return getObject(BO->getLHS(), Mod);
13412     } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13413       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
13414       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
13415         return ME->getMemberDecl();
13416     } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13417       // FIXME: If this is a reference, map through to its value.
13418       return DRE->getDecl();
13419     return nullptr;
13420   }
13421 
13422   /// Note that an object \p O was modified or used by an expression
13423   /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
13424   /// the object \p O as obtained via the \p UsageMap.
13425   void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
13426     // Get the old usage for the given object and usage kind.
13427     Usage &U = UI.Uses[UK];
13428     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
13429       // If we have a modification as side effect and are in a sequenced
13430       // subexpression, save the old Usage so that we can restore it later
13431       // in SequencedSubexpression::~SequencedSubexpression.
13432       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
13433         ModAsSideEffect->push_back(std::make_pair(O, U));
13434       // Then record the new usage with the current sequencing region.
13435       U.UsageExpr = UsageExpr;
13436       U.Seq = Region;
13437     }
13438   }
13439 
13440   /// Check whether a modification or use of an object \p O in an expression
13441   /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
13442   /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
13443   /// \p IsModMod is true when we are checking for a mod-mod unsequenced
13444   /// usage and false we are checking for a mod-use unsequenced usage.
13445   void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
13446                   UsageKind OtherKind, bool IsModMod) {
13447     if (UI.Diagnosed)
13448       return;
13449 
13450     const Usage &U = UI.Uses[OtherKind];
13451     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
13452       return;
13453 
13454     const Expr *Mod = U.UsageExpr;
13455     const Expr *ModOrUse = UsageExpr;
13456     if (OtherKind == UK_Use)
13457       std::swap(Mod, ModOrUse);
13458 
13459     SemaRef.DiagRuntimeBehavior(
13460         Mod->getExprLoc(), {Mod, ModOrUse},
13461         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
13462                                : diag::warn_unsequenced_mod_use)
13463             << O << SourceRange(ModOrUse->getExprLoc()));
13464     UI.Diagnosed = true;
13465   }
13466 
13467   // A note on note{Pre, Post}{Use, Mod}:
13468   //
13469   // (It helps to follow the algorithm with an expression such as
13470   //  "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
13471   //  operations before C++17 and both are well-defined in C++17).
13472   //
13473   // When visiting a node which uses/modify an object we first call notePreUse
13474   // or notePreMod before visiting its sub-expression(s). At this point the
13475   // children of the current node have not yet been visited and so the eventual
13476   // uses/modifications resulting from the children of the current node have not
13477   // been recorded yet.
13478   //
13479   // We then visit the children of the current node. After that notePostUse or
13480   // notePostMod is called. These will 1) detect an unsequenced modification
13481   // as side effect (as in "k++ + k") and 2) add a new usage with the
13482   // appropriate usage kind.
13483   //
13484   // We also have to be careful that some operation sequences modification as
13485   // side effect as well (for example: || or ,). To account for this we wrap
13486   // the visitation of such a sub-expression (for example: the LHS of || or ,)
13487   // with SequencedSubexpression. SequencedSubexpression is an RAII object
13488   // which record usages which are modifications as side effect, and then
13489   // downgrade them (or more accurately restore the previous usage which was a
13490   // modification as side effect) when exiting the scope of the sequenced
13491   // subexpression.
13492 
13493   void notePreUse(Object O, const Expr *UseExpr) {
13494     UsageInfo &UI = UsageMap[O];
13495     // Uses conflict with other modifications.
13496     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
13497   }
13498 
13499   void notePostUse(Object O, const Expr *UseExpr) {
13500     UsageInfo &UI = UsageMap[O];
13501     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
13502                /*IsModMod=*/false);
13503     addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
13504   }
13505 
13506   void notePreMod(Object O, const Expr *ModExpr) {
13507     UsageInfo &UI = UsageMap[O];
13508     // Modifications conflict with other modifications and with uses.
13509     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
13510     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
13511   }
13512 
13513   void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
13514     UsageInfo &UI = UsageMap[O];
13515     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
13516                /*IsModMod=*/true);
13517     addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
13518   }
13519 
13520 public:
13521   SequenceChecker(Sema &S, const Expr *E,
13522                   SmallVectorImpl<const Expr *> &WorkList)
13523       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
13524     Visit(E);
13525     // Silence a -Wunused-private-field since WorkList is now unused.
13526     // TODO: Evaluate if it can be used, and if not remove it.
13527     (void)this->WorkList;
13528   }
13529 
13530   void VisitStmt(const Stmt *S) {
13531     // Skip all statements which aren't expressions for now.
13532   }
13533 
13534   void VisitExpr(const Expr *E) {
13535     // By default, just recurse to evaluated subexpressions.
13536     Base::VisitStmt(E);
13537   }
13538 
13539   void VisitCastExpr(const CastExpr *E) {
13540     Object O = Object();
13541     if (E->getCastKind() == CK_LValueToRValue)
13542       O = getObject(E->getSubExpr(), false);
13543 
13544     if (O)
13545       notePreUse(O, E);
13546     VisitExpr(E);
13547     if (O)
13548       notePostUse(O, E);
13549   }
13550 
13551   void VisitSequencedExpressions(const Expr *SequencedBefore,
13552                                  const Expr *SequencedAfter) {
13553     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
13554     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
13555     SequenceTree::Seq OldRegion = Region;
13556 
13557     {
13558       SequencedSubexpression SeqBefore(*this);
13559       Region = BeforeRegion;
13560       Visit(SequencedBefore);
13561     }
13562 
13563     Region = AfterRegion;
13564     Visit(SequencedAfter);
13565 
13566     Region = OldRegion;
13567 
13568     Tree.merge(BeforeRegion);
13569     Tree.merge(AfterRegion);
13570   }
13571 
13572   void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
13573     // C++17 [expr.sub]p1:
13574     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
13575     //   expression E1 is sequenced before the expression E2.
13576     if (SemaRef.getLangOpts().CPlusPlus17)
13577       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
13578     else {
13579       Visit(ASE->getLHS());
13580       Visit(ASE->getRHS());
13581     }
13582   }
13583 
13584   void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
13585   void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
13586   void VisitBinPtrMem(const BinaryOperator *BO) {
13587     // C++17 [expr.mptr.oper]p4:
13588     //  Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
13589     //  the expression E1 is sequenced before the expression E2.
13590     if (SemaRef.getLangOpts().CPlusPlus17)
13591       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13592     else {
13593       Visit(BO->getLHS());
13594       Visit(BO->getRHS());
13595     }
13596   }
13597 
13598   void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
13599   void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
13600   void VisitBinShlShr(const BinaryOperator *BO) {
13601     // C++17 [expr.shift]p4:
13602     //  The expression E1 is sequenced before the expression E2.
13603     if (SemaRef.getLangOpts().CPlusPlus17)
13604       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13605     else {
13606       Visit(BO->getLHS());
13607       Visit(BO->getRHS());
13608     }
13609   }
13610 
13611   void VisitBinComma(const BinaryOperator *BO) {
13612     // C++11 [expr.comma]p1:
13613     //   Every value computation and side effect associated with the left
13614     //   expression is sequenced before every value computation and side
13615     //   effect associated with the right expression.
13616     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13617   }
13618 
13619   void VisitBinAssign(const BinaryOperator *BO) {
13620     SequenceTree::Seq RHSRegion;
13621     SequenceTree::Seq LHSRegion;
13622     if (SemaRef.getLangOpts().CPlusPlus17) {
13623       RHSRegion = Tree.allocate(Region);
13624       LHSRegion = Tree.allocate(Region);
13625     } else {
13626       RHSRegion = Region;
13627       LHSRegion = Region;
13628     }
13629     SequenceTree::Seq OldRegion = Region;
13630 
13631     // C++11 [expr.ass]p1:
13632     //  [...] the assignment is sequenced after the value computation
13633     //  of the right and left operands, [...]
13634     //
13635     // so check it before inspecting the operands and update the
13636     // map afterwards.
13637     Object O = getObject(BO->getLHS(), /*Mod=*/true);
13638     if (O)
13639       notePreMod(O, BO);
13640 
13641     if (SemaRef.getLangOpts().CPlusPlus17) {
13642       // C++17 [expr.ass]p1:
13643       //  [...] The right operand is sequenced before the left operand. [...]
13644       {
13645         SequencedSubexpression SeqBefore(*this);
13646         Region = RHSRegion;
13647         Visit(BO->getRHS());
13648       }
13649 
13650       Region = LHSRegion;
13651       Visit(BO->getLHS());
13652 
13653       if (O && isa<CompoundAssignOperator>(BO))
13654         notePostUse(O, BO);
13655 
13656     } else {
13657       // C++11 does not specify any sequencing between the LHS and RHS.
13658       Region = LHSRegion;
13659       Visit(BO->getLHS());
13660 
13661       if (O && isa<CompoundAssignOperator>(BO))
13662         notePostUse(O, BO);
13663 
13664       Region = RHSRegion;
13665       Visit(BO->getRHS());
13666     }
13667 
13668     // C++11 [expr.ass]p1:
13669     //  the assignment is sequenced [...] before the value computation of the
13670     //  assignment expression.
13671     // C11 6.5.16/3 has no such rule.
13672     Region = OldRegion;
13673     if (O)
13674       notePostMod(O, BO,
13675                   SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
13676                                                   : UK_ModAsSideEffect);
13677     if (SemaRef.getLangOpts().CPlusPlus17) {
13678       Tree.merge(RHSRegion);
13679       Tree.merge(LHSRegion);
13680     }
13681   }
13682 
13683   void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
13684     VisitBinAssign(CAO);
13685   }
13686 
13687   void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
13688   void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
13689   void VisitUnaryPreIncDec(const UnaryOperator *UO) {
13690     Object O = getObject(UO->getSubExpr(), true);
13691     if (!O)
13692       return VisitExpr(UO);
13693 
13694     notePreMod(O, UO);
13695     Visit(UO->getSubExpr());
13696     // C++11 [expr.pre.incr]p1:
13697     //   the expression ++x is equivalent to x+=1
13698     notePostMod(O, UO,
13699                 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
13700                                                 : UK_ModAsSideEffect);
13701   }
13702 
13703   void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
13704   void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
13705   void VisitUnaryPostIncDec(const UnaryOperator *UO) {
13706     Object O = getObject(UO->getSubExpr(), true);
13707     if (!O)
13708       return VisitExpr(UO);
13709 
13710     notePreMod(O, UO);
13711     Visit(UO->getSubExpr());
13712     notePostMod(O, UO, UK_ModAsSideEffect);
13713   }
13714 
13715   void VisitBinLOr(const BinaryOperator *BO) {
13716     // C++11 [expr.log.or]p2:
13717     //  If the second expression is evaluated, every value computation and
13718     //  side effect associated with the first expression is sequenced before
13719     //  every value computation and side effect associated with the
13720     //  second expression.
13721     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
13722     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
13723     SequenceTree::Seq OldRegion = Region;
13724 
13725     EvaluationTracker Eval(*this);
13726     {
13727       SequencedSubexpression Sequenced(*this);
13728       Region = LHSRegion;
13729       Visit(BO->getLHS());
13730     }
13731 
13732     // C++11 [expr.log.or]p1:
13733     //  [...] the second operand is not evaluated if the first operand
13734     //  evaluates to true.
13735     bool EvalResult = false;
13736     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
13737     bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
13738     if (ShouldVisitRHS) {
13739       Region = RHSRegion;
13740       Visit(BO->getRHS());
13741     }
13742 
13743     Region = OldRegion;
13744     Tree.merge(LHSRegion);
13745     Tree.merge(RHSRegion);
13746   }
13747 
13748   void VisitBinLAnd(const BinaryOperator *BO) {
13749     // C++11 [expr.log.and]p2:
13750     //  If the second expression is evaluated, every value computation and
13751     //  side effect associated with the first expression is sequenced before
13752     //  every value computation and side effect associated with the
13753     //  second expression.
13754     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
13755     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
13756     SequenceTree::Seq OldRegion = Region;
13757 
13758     EvaluationTracker Eval(*this);
13759     {
13760       SequencedSubexpression Sequenced(*this);
13761       Region = LHSRegion;
13762       Visit(BO->getLHS());
13763     }
13764 
13765     // C++11 [expr.log.and]p1:
13766     //  [...] the second operand is not evaluated if the first operand is false.
13767     bool EvalResult = false;
13768     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
13769     bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
13770     if (ShouldVisitRHS) {
13771       Region = RHSRegion;
13772       Visit(BO->getRHS());
13773     }
13774 
13775     Region = OldRegion;
13776     Tree.merge(LHSRegion);
13777     Tree.merge(RHSRegion);
13778   }
13779 
13780   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
13781     // C++11 [expr.cond]p1:
13782     //  [...] Every value computation and side effect associated with the first
13783     //  expression is sequenced before every value computation and side effect
13784     //  associated with the second or third expression.
13785     SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
13786 
13787     // No sequencing is specified between the true and false expression.
13788     // However since exactly one of both is going to be evaluated we can
13789     // consider them to be sequenced. This is needed to avoid warning on
13790     // something like "x ? y+= 1 : y += 2;" in the case where we will visit
13791     // both the true and false expressions because we can't evaluate x.
13792     // This will still allow us to detect an expression like (pre C++17)
13793     // "(x ? y += 1 : y += 2) = y".
13794     //
13795     // We don't wrap the visitation of the true and false expression with
13796     // SequencedSubexpression because we don't want to downgrade modifications
13797     // as side effect in the true and false expressions after the visition
13798     // is done. (for example in the expression "(x ? y++ : y++) + y" we should
13799     // not warn between the two "y++", but we should warn between the "y++"
13800     // and the "y".
13801     SequenceTree::Seq TrueRegion = Tree.allocate(Region);
13802     SequenceTree::Seq FalseRegion = Tree.allocate(Region);
13803     SequenceTree::Seq OldRegion = Region;
13804 
13805     EvaluationTracker Eval(*this);
13806     {
13807       SequencedSubexpression Sequenced(*this);
13808       Region = ConditionRegion;
13809       Visit(CO->getCond());
13810     }
13811 
13812     // C++11 [expr.cond]p1:
13813     // [...] The first expression is contextually converted to bool (Clause 4).
13814     // It is evaluated and if it is true, the result of the conditional
13815     // expression is the value of the second expression, otherwise that of the
13816     // third expression. Only one of the second and third expressions is
13817     // evaluated. [...]
13818     bool EvalResult = false;
13819     bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
13820     bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
13821     bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
13822     if (ShouldVisitTrueExpr) {
13823       Region = TrueRegion;
13824       Visit(CO->getTrueExpr());
13825     }
13826     if (ShouldVisitFalseExpr) {
13827       Region = FalseRegion;
13828       Visit(CO->getFalseExpr());
13829     }
13830 
13831     Region = OldRegion;
13832     Tree.merge(ConditionRegion);
13833     Tree.merge(TrueRegion);
13834     Tree.merge(FalseRegion);
13835   }
13836 
13837   void VisitCallExpr(const CallExpr *CE) {
13838     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
13839 
13840     if (CE->isUnevaluatedBuiltinCall(Context))
13841       return;
13842 
13843     // C++11 [intro.execution]p15:
13844     //   When calling a function [...], every value computation and side effect
13845     //   associated with any argument expression, or with the postfix expression
13846     //   designating the called function, is sequenced before execution of every
13847     //   expression or statement in the body of the function [and thus before
13848     //   the value computation of its result].
13849     SequencedSubexpression Sequenced(*this);
13850     SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
13851       // C++17 [expr.call]p5
13852       //   The postfix-expression is sequenced before each expression in the
13853       //   expression-list and any default argument. [...]
13854       SequenceTree::Seq CalleeRegion;
13855       SequenceTree::Seq OtherRegion;
13856       if (SemaRef.getLangOpts().CPlusPlus17) {
13857         CalleeRegion = Tree.allocate(Region);
13858         OtherRegion = Tree.allocate(Region);
13859       } else {
13860         CalleeRegion = Region;
13861         OtherRegion = Region;
13862       }
13863       SequenceTree::Seq OldRegion = Region;
13864 
13865       // Visit the callee expression first.
13866       Region = CalleeRegion;
13867       if (SemaRef.getLangOpts().CPlusPlus17) {
13868         SequencedSubexpression Sequenced(*this);
13869         Visit(CE->getCallee());
13870       } else {
13871         Visit(CE->getCallee());
13872       }
13873 
13874       // Then visit the argument expressions.
13875       Region = OtherRegion;
13876       for (const Expr *Argument : CE->arguments())
13877         Visit(Argument);
13878 
13879       Region = OldRegion;
13880       if (SemaRef.getLangOpts().CPlusPlus17) {
13881         Tree.merge(CalleeRegion);
13882         Tree.merge(OtherRegion);
13883       }
13884     });
13885   }
13886 
13887   void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
13888     // C++17 [over.match.oper]p2:
13889     //   [...] the operator notation is first transformed to the equivalent
13890     //   function-call notation as summarized in Table 12 (where @ denotes one
13891     //   of the operators covered in the specified subclause). However, the
13892     //   operands are sequenced in the order prescribed for the built-in
13893     //   operator (Clause 8).
13894     //
13895     // From the above only overloaded binary operators and overloaded call
13896     // operators have sequencing rules in C++17 that we need to handle
13897     // separately.
13898     if (!SemaRef.getLangOpts().CPlusPlus17 ||
13899         (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
13900       return VisitCallExpr(CXXOCE);
13901 
13902     enum {
13903       NoSequencing,
13904       LHSBeforeRHS,
13905       RHSBeforeLHS,
13906       LHSBeforeRest
13907     } SequencingKind;
13908     switch (CXXOCE->getOperator()) {
13909     case OO_Equal:
13910     case OO_PlusEqual:
13911     case OO_MinusEqual:
13912     case OO_StarEqual:
13913     case OO_SlashEqual:
13914     case OO_PercentEqual:
13915     case OO_CaretEqual:
13916     case OO_AmpEqual:
13917     case OO_PipeEqual:
13918     case OO_LessLessEqual:
13919     case OO_GreaterGreaterEqual:
13920       SequencingKind = RHSBeforeLHS;
13921       break;
13922 
13923     case OO_LessLess:
13924     case OO_GreaterGreater:
13925     case OO_AmpAmp:
13926     case OO_PipePipe:
13927     case OO_Comma:
13928     case OO_ArrowStar:
13929     case OO_Subscript:
13930       SequencingKind = LHSBeforeRHS;
13931       break;
13932 
13933     case OO_Call:
13934       SequencingKind = LHSBeforeRest;
13935       break;
13936 
13937     default:
13938       SequencingKind = NoSequencing;
13939       break;
13940     }
13941 
13942     if (SequencingKind == NoSequencing)
13943       return VisitCallExpr(CXXOCE);
13944 
13945     // This is a call, so all subexpressions are sequenced before the result.
13946     SequencedSubexpression Sequenced(*this);
13947 
13948     SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
13949       assert(SemaRef.getLangOpts().CPlusPlus17 &&
13950              "Should only get there with C++17 and above!");
13951       assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
13952              "Should only get there with an overloaded binary operator"
13953              " or an overloaded call operator!");
13954 
13955       if (SequencingKind == LHSBeforeRest) {
13956         assert(CXXOCE->getOperator() == OO_Call &&
13957                "We should only have an overloaded call operator here!");
13958 
13959         // This is very similar to VisitCallExpr, except that we only have the
13960         // C++17 case. The postfix-expression is the first argument of the
13961         // CXXOperatorCallExpr. The expressions in the expression-list, if any,
13962         // are in the following arguments.
13963         //
13964         // Note that we intentionally do not visit the callee expression since
13965         // it is just a decayed reference to a function.
13966         SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
13967         SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
13968         SequenceTree::Seq OldRegion = Region;
13969 
13970         assert(CXXOCE->getNumArgs() >= 1 &&
13971                "An overloaded call operator must have at least one argument"
13972                " for the postfix-expression!");
13973         const Expr *PostfixExpr = CXXOCE->getArgs()[0];
13974         llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
13975                                           CXXOCE->getNumArgs() - 1);
13976 
13977         // Visit the postfix-expression first.
13978         {
13979           Region = PostfixExprRegion;
13980           SequencedSubexpression Sequenced(*this);
13981           Visit(PostfixExpr);
13982         }
13983 
13984         // Then visit the argument expressions.
13985         Region = ArgsRegion;
13986         for (const Expr *Arg : Args)
13987           Visit(Arg);
13988 
13989         Region = OldRegion;
13990         Tree.merge(PostfixExprRegion);
13991         Tree.merge(ArgsRegion);
13992       } else {
13993         assert(CXXOCE->getNumArgs() == 2 &&
13994                "Should only have two arguments here!");
13995         assert((SequencingKind == LHSBeforeRHS ||
13996                 SequencingKind == RHSBeforeLHS) &&
13997                "Unexpected sequencing kind!");
13998 
13999         // We do not visit the callee expression since it is just a decayed
14000         // reference to a function.
14001         const Expr *E1 = CXXOCE->getArg(0);
14002         const Expr *E2 = CXXOCE->getArg(1);
14003         if (SequencingKind == RHSBeforeLHS)
14004           std::swap(E1, E2);
14005 
14006         return VisitSequencedExpressions(E1, E2);
14007       }
14008     });
14009   }
14010 
14011   void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
14012     // This is a call, so all subexpressions are sequenced before the result.
14013     SequencedSubexpression Sequenced(*this);
14014 
14015     if (!CCE->isListInitialization())
14016       return VisitExpr(CCE);
14017 
14018     // In C++11, list initializations are sequenced.
14019     SmallVector<SequenceTree::Seq, 32> Elts;
14020     SequenceTree::Seq Parent = Region;
14021     for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
14022                                               E = CCE->arg_end();
14023          I != E; ++I) {
14024       Region = Tree.allocate(Parent);
14025       Elts.push_back(Region);
14026       Visit(*I);
14027     }
14028 
14029     // Forget that the initializers are sequenced.
14030     Region = Parent;
14031     for (unsigned I = 0; I < Elts.size(); ++I)
14032       Tree.merge(Elts[I]);
14033   }
14034 
14035   void VisitInitListExpr(const InitListExpr *ILE) {
14036     if (!SemaRef.getLangOpts().CPlusPlus11)
14037       return VisitExpr(ILE);
14038 
14039     // In C++11, list initializations are sequenced.
14040     SmallVector<SequenceTree::Seq, 32> Elts;
14041     SequenceTree::Seq Parent = Region;
14042     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
14043       const Expr *E = ILE->getInit(I);
14044       if (!E)
14045         continue;
14046       Region = Tree.allocate(Parent);
14047       Elts.push_back(Region);
14048       Visit(E);
14049     }
14050 
14051     // Forget that the initializers are sequenced.
14052     Region = Parent;
14053     for (unsigned I = 0; I < Elts.size(); ++I)
14054       Tree.merge(Elts[I]);
14055   }
14056 };
14057 
14058 } // namespace
14059 
14060 void Sema::CheckUnsequencedOperations(const Expr *E) {
14061   SmallVector<const Expr *, 8> WorkList;
14062   WorkList.push_back(E);
14063   while (!WorkList.empty()) {
14064     const Expr *Item = WorkList.pop_back_val();
14065     SequenceChecker(*this, Item, WorkList);
14066   }
14067 }
14068 
14069 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
14070                               bool IsConstexpr) {
14071   llvm::SaveAndRestore<bool> ConstantContext(
14072       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
14073   CheckImplicitConversions(E, CheckLoc);
14074   if (!E->isInstantiationDependent())
14075     CheckUnsequencedOperations(E);
14076   if (!IsConstexpr && !E->isValueDependent())
14077     CheckForIntOverflow(E);
14078   DiagnoseMisalignedMembers();
14079 }
14080 
14081 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
14082                                        FieldDecl *BitField,
14083                                        Expr *Init) {
14084   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
14085 }
14086 
14087 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
14088                                          SourceLocation Loc) {
14089   if (!PType->isVariablyModifiedType())
14090     return;
14091   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
14092     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
14093     return;
14094   }
14095   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
14096     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
14097     return;
14098   }
14099   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
14100     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
14101     return;
14102   }
14103 
14104   const ArrayType *AT = S.Context.getAsArrayType(PType);
14105   if (!AT)
14106     return;
14107 
14108   if (AT->getSizeModifier() != ArrayType::Star) {
14109     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
14110     return;
14111   }
14112 
14113   S.Diag(Loc, diag::err_array_star_in_function_definition);
14114 }
14115 
14116 /// CheckParmsForFunctionDef - Check that the parameters of the given
14117 /// function are appropriate for the definition of a function. This
14118 /// takes care of any checks that cannot be performed on the
14119 /// declaration itself, e.g., that the types of each of the function
14120 /// parameters are complete.
14121 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
14122                                     bool CheckParameterNames) {
14123   bool HasInvalidParm = false;
14124   for (ParmVarDecl *Param : Parameters) {
14125     // C99 6.7.5.3p4: the parameters in a parameter type list in a
14126     // function declarator that is part of a function definition of
14127     // that function shall not have incomplete type.
14128     //
14129     // This is also C++ [dcl.fct]p6.
14130     if (!Param->isInvalidDecl() &&
14131         RequireCompleteType(Param->getLocation(), Param->getType(),
14132                             diag::err_typecheck_decl_incomplete_type)) {
14133       Param->setInvalidDecl();
14134       HasInvalidParm = true;
14135     }
14136 
14137     // C99 6.9.1p5: If the declarator includes a parameter type list, the
14138     // declaration of each parameter shall include an identifier.
14139     if (CheckParameterNames && Param->getIdentifier() == nullptr &&
14140         !Param->isImplicit() && !getLangOpts().CPlusPlus) {
14141       // Diagnose this as an extension in C17 and earlier.
14142       if (!getLangOpts().C2x)
14143         Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
14144     }
14145 
14146     // C99 6.7.5.3p12:
14147     //   If the function declarator is not part of a definition of that
14148     //   function, parameters may have incomplete type and may use the [*]
14149     //   notation in their sequences of declarator specifiers to specify
14150     //   variable length array types.
14151     QualType PType = Param->getOriginalType();
14152     // FIXME: This diagnostic should point the '[*]' if source-location
14153     // information is added for it.
14154     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
14155 
14156     // If the parameter is a c++ class type and it has to be destructed in the
14157     // callee function, declare the destructor so that it can be called by the
14158     // callee function. Do not perform any direct access check on the dtor here.
14159     if (!Param->isInvalidDecl()) {
14160       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
14161         if (!ClassDecl->isInvalidDecl() &&
14162             !ClassDecl->hasIrrelevantDestructor() &&
14163             !ClassDecl->isDependentContext() &&
14164             ClassDecl->isParamDestroyedInCallee()) {
14165           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
14166           MarkFunctionReferenced(Param->getLocation(), Destructor);
14167           DiagnoseUseOfDecl(Destructor, Param->getLocation());
14168         }
14169       }
14170     }
14171 
14172     // Parameters with the pass_object_size attribute only need to be marked
14173     // constant at function definitions. Because we lack information about
14174     // whether we're on a declaration or definition when we're instantiating the
14175     // attribute, we need to check for constness here.
14176     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
14177       if (!Param->getType().isConstQualified())
14178         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
14179             << Attr->getSpelling() << 1;
14180 
14181     // Check for parameter names shadowing fields from the class.
14182     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
14183       // The owning context for the parameter should be the function, but we
14184       // want to see if this function's declaration context is a record.
14185       DeclContext *DC = Param->getDeclContext();
14186       if (DC && DC->isFunctionOrMethod()) {
14187         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
14188           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
14189                                      RD, /*DeclIsField*/ false);
14190       }
14191     }
14192   }
14193 
14194   return HasInvalidParm;
14195 }
14196 
14197 Optional<std::pair<CharUnits, CharUnits>>
14198 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx);
14199 
14200 /// Compute the alignment and offset of the base class object given the
14201 /// derived-to-base cast expression and the alignment and offset of the derived
14202 /// class object.
14203 static std::pair<CharUnits, CharUnits>
14204 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
14205                                    CharUnits BaseAlignment, CharUnits Offset,
14206                                    ASTContext &Ctx) {
14207   for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
14208        ++PathI) {
14209     const CXXBaseSpecifier *Base = *PathI;
14210     const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
14211     if (Base->isVirtual()) {
14212       // The complete object may have a lower alignment than the non-virtual
14213       // alignment of the base, in which case the base may be misaligned. Choose
14214       // the smaller of the non-virtual alignment and BaseAlignment, which is a
14215       // conservative lower bound of the complete object alignment.
14216       CharUnits NonVirtualAlignment =
14217           Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment();
14218       BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
14219       Offset = CharUnits::Zero();
14220     } else {
14221       const ASTRecordLayout &RL =
14222           Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
14223       Offset += RL.getBaseClassOffset(BaseDecl);
14224     }
14225     DerivedType = Base->getType();
14226   }
14227 
14228   return std::make_pair(BaseAlignment, Offset);
14229 }
14230 
14231 /// Compute the alignment and offset of a binary additive operator.
14232 static Optional<std::pair<CharUnits, CharUnits>>
14233 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
14234                                      bool IsSub, ASTContext &Ctx) {
14235   QualType PointeeType = PtrE->getType()->getPointeeType();
14236 
14237   if (!PointeeType->isConstantSizeType())
14238     return llvm::None;
14239 
14240   auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
14241 
14242   if (!P)
14243     return llvm::None;
14244 
14245   CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
14246   if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
14247     CharUnits Offset = EltSize * IdxRes->getExtValue();
14248     if (IsSub)
14249       Offset = -Offset;
14250     return std::make_pair(P->first, P->second + Offset);
14251   }
14252 
14253   // If the integer expression isn't a constant expression, compute the lower
14254   // bound of the alignment using the alignment and offset of the pointer
14255   // expression and the element size.
14256   return std::make_pair(
14257       P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
14258       CharUnits::Zero());
14259 }
14260 
14261 /// This helper function takes an lvalue expression and returns the alignment of
14262 /// a VarDecl and a constant offset from the VarDecl.
14263 Optional<std::pair<CharUnits, CharUnits>>
14264 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) {
14265   E = E->IgnoreParens();
14266   switch (E->getStmtClass()) {
14267   default:
14268     break;
14269   case Stmt::CStyleCastExprClass:
14270   case Stmt::CXXStaticCastExprClass:
14271   case Stmt::ImplicitCastExprClass: {
14272     auto *CE = cast<CastExpr>(E);
14273     const Expr *From = CE->getSubExpr();
14274     switch (CE->getCastKind()) {
14275     default:
14276       break;
14277     case CK_NoOp:
14278       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14279     case CK_UncheckedDerivedToBase:
14280     case CK_DerivedToBase: {
14281       auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14282       if (!P)
14283         break;
14284       return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
14285                                                 P->second, Ctx);
14286     }
14287     }
14288     break;
14289   }
14290   case Stmt::ArraySubscriptExprClass: {
14291     auto *ASE = cast<ArraySubscriptExpr>(E);
14292     return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(),
14293                                                 false, Ctx);
14294   }
14295   case Stmt::DeclRefExprClass: {
14296     if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
14297       // FIXME: If VD is captured by copy or is an escaping __block variable,
14298       // use the alignment of VD's type.
14299       if (!VD->getType()->isReferenceType())
14300         return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
14301       if (VD->hasInit())
14302         return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
14303     }
14304     break;
14305   }
14306   case Stmt::MemberExprClass: {
14307     auto *ME = cast<MemberExpr>(E);
14308     auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
14309     if (!FD || FD->getType()->isReferenceType())
14310       break;
14311     Optional<std::pair<CharUnits, CharUnits>> P;
14312     if (ME->isArrow())
14313       P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
14314     else
14315       P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
14316     if (!P)
14317       break;
14318     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
14319     uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
14320     return std::make_pair(P->first,
14321                           P->second + CharUnits::fromQuantity(Offset));
14322   }
14323   case Stmt::UnaryOperatorClass: {
14324     auto *UO = cast<UnaryOperator>(E);
14325     switch (UO->getOpcode()) {
14326     default:
14327       break;
14328     case UO_Deref:
14329       return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx);
14330     }
14331     break;
14332   }
14333   case Stmt::BinaryOperatorClass: {
14334     auto *BO = cast<BinaryOperator>(E);
14335     auto Opcode = BO->getOpcode();
14336     switch (Opcode) {
14337     default:
14338       break;
14339     case BO_Comma:
14340       return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx);
14341     }
14342     break;
14343   }
14344   }
14345   return llvm::None;
14346 }
14347 
14348 /// This helper function takes a pointer expression and returns the alignment of
14349 /// a VarDecl and a constant offset from the VarDecl.
14350 Optional<std::pair<CharUnits, CharUnits>>
14351 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) {
14352   E = E->IgnoreParens();
14353   switch (E->getStmtClass()) {
14354   default:
14355     break;
14356   case Stmt::CStyleCastExprClass:
14357   case Stmt::CXXStaticCastExprClass:
14358   case Stmt::ImplicitCastExprClass: {
14359     auto *CE = cast<CastExpr>(E);
14360     const Expr *From = CE->getSubExpr();
14361     switch (CE->getCastKind()) {
14362     default:
14363       break;
14364     case CK_NoOp:
14365       return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14366     case CK_ArrayToPointerDecay:
14367       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14368     case CK_UncheckedDerivedToBase:
14369     case CK_DerivedToBase: {
14370       auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14371       if (!P)
14372         break;
14373       return getDerivedToBaseAlignmentAndOffset(
14374           CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
14375     }
14376     }
14377     break;
14378   }
14379   case Stmt::CXXThisExprClass: {
14380     auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
14381     CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment();
14382     return std::make_pair(Alignment, CharUnits::Zero());
14383   }
14384   case Stmt::UnaryOperatorClass: {
14385     auto *UO = cast<UnaryOperator>(E);
14386     if (UO->getOpcode() == UO_AddrOf)
14387       return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx);
14388     break;
14389   }
14390   case Stmt::BinaryOperatorClass: {
14391     auto *BO = cast<BinaryOperator>(E);
14392     auto Opcode = BO->getOpcode();
14393     switch (Opcode) {
14394     default:
14395       break;
14396     case BO_Add:
14397     case BO_Sub: {
14398       const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
14399       if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
14400         std::swap(LHS, RHS);
14401       return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
14402                                                   Ctx);
14403     }
14404     case BO_Comma:
14405       return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
14406     }
14407     break;
14408   }
14409   }
14410   return llvm::None;
14411 }
14412 
14413 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
14414   // See if we can compute the alignment of a VarDecl and an offset from it.
14415   Optional<std::pair<CharUnits, CharUnits>> P =
14416       getBaseAlignmentAndOffsetFromPtr(E, S.Context);
14417 
14418   if (P)
14419     return P->first.alignmentAtOffset(P->second);
14420 
14421   // If that failed, return the type's alignment.
14422   return S.Context.getTypeAlignInChars(E->getType()->getPointeeType());
14423 }
14424 
14425 /// CheckCastAlign - Implements -Wcast-align, which warns when a
14426 /// pointer cast increases the alignment requirements.
14427 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
14428   // This is actually a lot of work to potentially be doing on every
14429   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
14430   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
14431     return;
14432 
14433   // Ignore dependent types.
14434   if (T->isDependentType() || Op->getType()->isDependentType())
14435     return;
14436 
14437   // Require that the destination be a pointer type.
14438   const PointerType *DestPtr = T->getAs<PointerType>();
14439   if (!DestPtr) return;
14440 
14441   // If the destination has alignment 1, we're done.
14442   QualType DestPointee = DestPtr->getPointeeType();
14443   if (DestPointee->isIncompleteType()) return;
14444   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
14445   if (DestAlign.isOne()) return;
14446 
14447   // Require that the source be a pointer type.
14448   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
14449   if (!SrcPtr) return;
14450   QualType SrcPointee = SrcPtr->getPointeeType();
14451 
14452   // Explicitly allow casts from cv void*.  We already implicitly
14453   // allowed casts to cv void*, since they have alignment 1.
14454   // Also allow casts involving incomplete types, which implicitly
14455   // includes 'void'.
14456   if (SrcPointee->isIncompleteType()) return;
14457 
14458   CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
14459 
14460   if (SrcAlign >= DestAlign) return;
14461 
14462   Diag(TRange.getBegin(), diag::warn_cast_align)
14463     << Op->getType() << T
14464     << static_cast<unsigned>(SrcAlign.getQuantity())
14465     << static_cast<unsigned>(DestAlign.getQuantity())
14466     << TRange << Op->getSourceRange();
14467 }
14468 
14469 /// Check whether this array fits the idiom of a size-one tail padded
14470 /// array member of a struct.
14471 ///
14472 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
14473 /// commonly used to emulate flexible arrays in C89 code.
14474 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
14475                                     const NamedDecl *ND) {
14476   if (Size != 1 || !ND) return false;
14477 
14478   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
14479   if (!FD) return false;
14480 
14481   // Don't consider sizes resulting from macro expansions or template argument
14482   // substitution to form C89 tail-padded arrays.
14483 
14484   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
14485   while (TInfo) {
14486     TypeLoc TL = TInfo->getTypeLoc();
14487     // Look through typedefs.
14488     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
14489       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
14490       TInfo = TDL->getTypeSourceInfo();
14491       continue;
14492     }
14493     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
14494       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
14495       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
14496         return false;
14497     }
14498     break;
14499   }
14500 
14501   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
14502   if (!RD) return false;
14503   if (RD->isUnion()) return false;
14504   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
14505     if (!CRD->isStandardLayout()) return false;
14506   }
14507 
14508   // See if this is the last field decl in the record.
14509   const Decl *D = FD;
14510   while ((D = D->getNextDeclInContext()))
14511     if (isa<FieldDecl>(D))
14512       return false;
14513   return true;
14514 }
14515 
14516 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
14517                             const ArraySubscriptExpr *ASE,
14518                             bool AllowOnePastEnd, bool IndexNegated) {
14519   // Already diagnosed by the constant evaluator.
14520   if (isConstantEvaluated())
14521     return;
14522 
14523   IndexExpr = IndexExpr->IgnoreParenImpCasts();
14524   if (IndexExpr->isValueDependent())
14525     return;
14526 
14527   const Type *EffectiveType =
14528       BaseExpr->getType()->getPointeeOrArrayElementType();
14529   BaseExpr = BaseExpr->IgnoreParenCasts();
14530   const ConstantArrayType *ArrayTy =
14531       Context.getAsConstantArrayType(BaseExpr->getType());
14532 
14533   if (!ArrayTy)
14534     return;
14535 
14536   const Type *BaseType = ArrayTy->getElementType().getTypePtr();
14537   if (EffectiveType->isDependentType() || BaseType->isDependentType())
14538     return;
14539 
14540   Expr::EvalResult Result;
14541   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
14542     return;
14543 
14544   llvm::APSInt index = Result.Val.getInt();
14545   if (IndexNegated)
14546     index = -index;
14547 
14548   const NamedDecl *ND = nullptr;
14549   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14550     ND = DRE->getDecl();
14551   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
14552     ND = ME->getMemberDecl();
14553 
14554   if (index.isUnsigned() || !index.isNegative()) {
14555     // It is possible that the type of the base expression after
14556     // IgnoreParenCasts is incomplete, even though the type of the base
14557     // expression before IgnoreParenCasts is complete (see PR39746 for an
14558     // example). In this case we have no information about whether the array
14559     // access exceeds the array bounds. However we can still diagnose an array
14560     // access which precedes the array bounds.
14561     if (BaseType->isIncompleteType())
14562       return;
14563 
14564     llvm::APInt size = ArrayTy->getSize();
14565     if (!size.isStrictlyPositive())
14566       return;
14567 
14568     if (BaseType != EffectiveType) {
14569       // Make sure we're comparing apples to apples when comparing index to size
14570       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
14571       uint64_t array_typesize = Context.getTypeSize(BaseType);
14572       // Handle ptrarith_typesize being zero, such as when casting to void*
14573       if (!ptrarith_typesize) ptrarith_typesize = 1;
14574       if (ptrarith_typesize != array_typesize) {
14575         // There's a cast to a different size type involved
14576         uint64_t ratio = array_typesize / ptrarith_typesize;
14577         // TODO: Be smarter about handling cases where array_typesize is not a
14578         // multiple of ptrarith_typesize
14579         if (ptrarith_typesize * ratio == array_typesize)
14580           size *= llvm::APInt(size.getBitWidth(), ratio);
14581       }
14582     }
14583 
14584     if (size.getBitWidth() > index.getBitWidth())
14585       index = index.zext(size.getBitWidth());
14586     else if (size.getBitWidth() < index.getBitWidth())
14587       size = size.zext(index.getBitWidth());
14588 
14589     // For array subscripting the index must be less than size, but for pointer
14590     // arithmetic also allow the index (offset) to be equal to size since
14591     // computing the next address after the end of the array is legal and
14592     // commonly done e.g. in C++ iterators and range-based for loops.
14593     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
14594       return;
14595 
14596     // Also don't warn for arrays of size 1 which are members of some
14597     // structure. These are often used to approximate flexible arrays in C89
14598     // code.
14599     if (IsTailPaddedMemberArray(*this, size, ND))
14600       return;
14601 
14602     // Suppress the warning if the subscript expression (as identified by the
14603     // ']' location) and the index expression are both from macro expansions
14604     // within a system header.
14605     if (ASE) {
14606       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
14607           ASE->getRBracketLoc());
14608       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
14609         SourceLocation IndexLoc =
14610             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
14611         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
14612           return;
14613       }
14614     }
14615 
14616     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
14617     if (ASE)
14618       DiagID = diag::warn_array_index_exceeds_bounds;
14619 
14620     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
14621                         PDiag(DiagID) << index.toString(10, true)
14622                                       << size.toString(10, true)
14623                                       << (unsigned)size.getLimitedValue(~0U)
14624                                       << IndexExpr->getSourceRange());
14625   } else {
14626     unsigned DiagID = diag::warn_array_index_precedes_bounds;
14627     if (!ASE) {
14628       DiagID = diag::warn_ptr_arith_precedes_bounds;
14629       if (index.isNegative()) index = -index;
14630     }
14631 
14632     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
14633                         PDiag(DiagID) << index.toString(10, true)
14634                                       << IndexExpr->getSourceRange());
14635   }
14636 
14637   if (!ND) {
14638     // Try harder to find a NamedDecl to point at in the note.
14639     while (const ArraySubscriptExpr *ASE =
14640            dyn_cast<ArraySubscriptExpr>(BaseExpr))
14641       BaseExpr = ASE->getBase()->IgnoreParenCasts();
14642     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14643       ND = DRE->getDecl();
14644     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
14645       ND = ME->getMemberDecl();
14646   }
14647 
14648   if (ND)
14649     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
14650                         PDiag(diag::note_array_declared_here) << ND);
14651 }
14652 
14653 void Sema::CheckArrayAccess(const Expr *expr) {
14654   int AllowOnePastEnd = 0;
14655   while (expr) {
14656     expr = expr->IgnoreParenImpCasts();
14657     switch (expr->getStmtClass()) {
14658       case Stmt::ArraySubscriptExprClass: {
14659         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
14660         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
14661                          AllowOnePastEnd > 0);
14662         expr = ASE->getBase();
14663         break;
14664       }
14665       case Stmt::MemberExprClass: {
14666         expr = cast<MemberExpr>(expr)->getBase();
14667         break;
14668       }
14669       case Stmt::OMPArraySectionExprClass: {
14670         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
14671         if (ASE->getLowerBound())
14672           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
14673                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
14674         return;
14675       }
14676       case Stmt::UnaryOperatorClass: {
14677         // Only unwrap the * and & unary operators
14678         const UnaryOperator *UO = cast<UnaryOperator>(expr);
14679         expr = UO->getSubExpr();
14680         switch (UO->getOpcode()) {
14681           case UO_AddrOf:
14682             AllowOnePastEnd++;
14683             break;
14684           case UO_Deref:
14685             AllowOnePastEnd--;
14686             break;
14687           default:
14688             return;
14689         }
14690         break;
14691       }
14692       case Stmt::ConditionalOperatorClass: {
14693         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
14694         if (const Expr *lhs = cond->getLHS())
14695           CheckArrayAccess(lhs);
14696         if (const Expr *rhs = cond->getRHS())
14697           CheckArrayAccess(rhs);
14698         return;
14699       }
14700       case Stmt::CXXOperatorCallExprClass: {
14701         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
14702         for (const auto *Arg : OCE->arguments())
14703           CheckArrayAccess(Arg);
14704         return;
14705       }
14706       default:
14707         return;
14708     }
14709   }
14710 }
14711 
14712 //===--- CHECK: Objective-C retain cycles ----------------------------------//
14713 
14714 namespace {
14715 
14716 struct RetainCycleOwner {
14717   VarDecl *Variable = nullptr;
14718   SourceRange Range;
14719   SourceLocation Loc;
14720   bool Indirect = false;
14721 
14722   RetainCycleOwner() = default;
14723 
14724   void setLocsFrom(Expr *e) {
14725     Loc = e->getExprLoc();
14726     Range = e->getSourceRange();
14727   }
14728 };
14729 
14730 } // namespace
14731 
14732 /// Consider whether capturing the given variable can possibly lead to
14733 /// a retain cycle.
14734 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
14735   // In ARC, it's captured strongly iff the variable has __strong
14736   // lifetime.  In MRR, it's captured strongly if the variable is
14737   // __block and has an appropriate type.
14738   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
14739     return false;
14740 
14741   owner.Variable = var;
14742   if (ref)
14743     owner.setLocsFrom(ref);
14744   return true;
14745 }
14746 
14747 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
14748   while (true) {
14749     e = e->IgnoreParens();
14750     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
14751       switch (cast->getCastKind()) {
14752       case CK_BitCast:
14753       case CK_LValueBitCast:
14754       case CK_LValueToRValue:
14755       case CK_ARCReclaimReturnedObject:
14756         e = cast->getSubExpr();
14757         continue;
14758 
14759       default:
14760         return false;
14761       }
14762     }
14763 
14764     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
14765       ObjCIvarDecl *ivar = ref->getDecl();
14766       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
14767         return false;
14768 
14769       // Try to find a retain cycle in the base.
14770       if (!findRetainCycleOwner(S, ref->getBase(), owner))
14771         return false;
14772 
14773       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
14774       owner.Indirect = true;
14775       return true;
14776     }
14777 
14778     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
14779       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
14780       if (!var) return false;
14781       return considerVariable(var, ref, owner);
14782     }
14783 
14784     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
14785       if (member->isArrow()) return false;
14786 
14787       // Don't count this as an indirect ownership.
14788       e = member->getBase();
14789       continue;
14790     }
14791 
14792     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
14793       // Only pay attention to pseudo-objects on property references.
14794       ObjCPropertyRefExpr *pre
14795         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
14796                                               ->IgnoreParens());
14797       if (!pre) return false;
14798       if (pre->isImplicitProperty()) return false;
14799       ObjCPropertyDecl *property = pre->getExplicitProperty();
14800       if (!property->isRetaining() &&
14801           !(property->getPropertyIvarDecl() &&
14802             property->getPropertyIvarDecl()->getType()
14803               .getObjCLifetime() == Qualifiers::OCL_Strong))
14804           return false;
14805 
14806       owner.Indirect = true;
14807       if (pre->isSuperReceiver()) {
14808         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
14809         if (!owner.Variable)
14810           return false;
14811         owner.Loc = pre->getLocation();
14812         owner.Range = pre->getSourceRange();
14813         return true;
14814       }
14815       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
14816                               ->getSourceExpr());
14817       continue;
14818     }
14819 
14820     // Array ivars?
14821 
14822     return false;
14823   }
14824 }
14825 
14826 namespace {
14827 
14828   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
14829     ASTContext &Context;
14830     VarDecl *Variable;
14831     Expr *Capturer = nullptr;
14832     bool VarWillBeReased = false;
14833 
14834     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
14835         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
14836           Context(Context), Variable(variable) {}
14837 
14838     void VisitDeclRefExpr(DeclRefExpr *ref) {
14839       if (ref->getDecl() == Variable && !Capturer)
14840         Capturer = ref;
14841     }
14842 
14843     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
14844       if (Capturer) return;
14845       Visit(ref->getBase());
14846       if (Capturer && ref->isFreeIvar())
14847         Capturer = ref;
14848     }
14849 
14850     void VisitBlockExpr(BlockExpr *block) {
14851       // Look inside nested blocks
14852       if (block->getBlockDecl()->capturesVariable(Variable))
14853         Visit(block->getBlockDecl()->getBody());
14854     }
14855 
14856     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
14857       if (Capturer) return;
14858       if (OVE->getSourceExpr())
14859         Visit(OVE->getSourceExpr());
14860     }
14861 
14862     void VisitBinaryOperator(BinaryOperator *BinOp) {
14863       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
14864         return;
14865       Expr *LHS = BinOp->getLHS();
14866       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
14867         if (DRE->getDecl() != Variable)
14868           return;
14869         if (Expr *RHS = BinOp->getRHS()) {
14870           RHS = RHS->IgnoreParenCasts();
14871           Optional<llvm::APSInt> Value;
14872           VarWillBeReased =
14873               (RHS && (Value = RHS->getIntegerConstantExpr(Context)) &&
14874                *Value == 0);
14875         }
14876       }
14877     }
14878   };
14879 
14880 } // namespace
14881 
14882 /// Check whether the given argument is a block which captures a
14883 /// variable.
14884 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
14885   assert(owner.Variable && owner.Loc.isValid());
14886 
14887   e = e->IgnoreParenCasts();
14888 
14889   // Look through [^{...} copy] and Block_copy(^{...}).
14890   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
14891     Selector Cmd = ME->getSelector();
14892     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
14893       e = ME->getInstanceReceiver();
14894       if (!e)
14895         return nullptr;
14896       e = e->IgnoreParenCasts();
14897     }
14898   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
14899     if (CE->getNumArgs() == 1) {
14900       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
14901       if (Fn) {
14902         const IdentifierInfo *FnI = Fn->getIdentifier();
14903         if (FnI && FnI->isStr("_Block_copy")) {
14904           e = CE->getArg(0)->IgnoreParenCasts();
14905         }
14906       }
14907     }
14908   }
14909 
14910   BlockExpr *block = dyn_cast<BlockExpr>(e);
14911   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
14912     return nullptr;
14913 
14914   FindCaptureVisitor visitor(S.Context, owner.Variable);
14915   visitor.Visit(block->getBlockDecl()->getBody());
14916   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
14917 }
14918 
14919 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
14920                                 RetainCycleOwner &owner) {
14921   assert(capturer);
14922   assert(owner.Variable && owner.Loc.isValid());
14923 
14924   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
14925     << owner.Variable << capturer->getSourceRange();
14926   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
14927     << owner.Indirect << owner.Range;
14928 }
14929 
14930 /// Check for a keyword selector that starts with the word 'add' or
14931 /// 'set'.
14932 static bool isSetterLikeSelector(Selector sel) {
14933   if (sel.isUnarySelector()) return false;
14934 
14935   StringRef str = sel.getNameForSlot(0);
14936   while (!str.empty() && str.front() == '_') str = str.substr(1);
14937   if (str.startswith("set"))
14938     str = str.substr(3);
14939   else if (str.startswith("add")) {
14940     // Specially allow 'addOperationWithBlock:'.
14941     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
14942       return false;
14943     str = str.substr(3);
14944   }
14945   else
14946     return false;
14947 
14948   if (str.empty()) return true;
14949   return !isLowercase(str.front());
14950 }
14951 
14952 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
14953                                                     ObjCMessageExpr *Message) {
14954   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
14955                                                 Message->getReceiverInterface(),
14956                                                 NSAPI::ClassId_NSMutableArray);
14957   if (!IsMutableArray) {
14958     return None;
14959   }
14960 
14961   Selector Sel = Message->getSelector();
14962 
14963   Optional<NSAPI::NSArrayMethodKind> MKOpt =
14964     S.NSAPIObj->getNSArrayMethodKind(Sel);
14965   if (!MKOpt) {
14966     return None;
14967   }
14968 
14969   NSAPI::NSArrayMethodKind MK = *MKOpt;
14970 
14971   switch (MK) {
14972     case NSAPI::NSMutableArr_addObject:
14973     case NSAPI::NSMutableArr_insertObjectAtIndex:
14974     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
14975       return 0;
14976     case NSAPI::NSMutableArr_replaceObjectAtIndex:
14977       return 1;
14978 
14979     default:
14980       return None;
14981   }
14982 
14983   return None;
14984 }
14985 
14986 static
14987 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
14988                                                   ObjCMessageExpr *Message) {
14989   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
14990                                             Message->getReceiverInterface(),
14991                                             NSAPI::ClassId_NSMutableDictionary);
14992   if (!IsMutableDictionary) {
14993     return None;
14994   }
14995 
14996   Selector Sel = Message->getSelector();
14997 
14998   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
14999     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
15000   if (!MKOpt) {
15001     return None;
15002   }
15003 
15004   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
15005 
15006   switch (MK) {
15007     case NSAPI::NSMutableDict_setObjectForKey:
15008     case NSAPI::NSMutableDict_setValueForKey:
15009     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
15010       return 0;
15011 
15012     default:
15013       return None;
15014   }
15015 
15016   return None;
15017 }
15018 
15019 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
15020   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
15021                                                 Message->getReceiverInterface(),
15022                                                 NSAPI::ClassId_NSMutableSet);
15023 
15024   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
15025                                             Message->getReceiverInterface(),
15026                                             NSAPI::ClassId_NSMutableOrderedSet);
15027   if (!IsMutableSet && !IsMutableOrderedSet) {
15028     return None;
15029   }
15030 
15031   Selector Sel = Message->getSelector();
15032 
15033   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
15034   if (!MKOpt) {
15035     return None;
15036   }
15037 
15038   NSAPI::NSSetMethodKind MK = *MKOpt;
15039 
15040   switch (MK) {
15041     case NSAPI::NSMutableSet_addObject:
15042     case NSAPI::NSOrderedSet_setObjectAtIndex:
15043     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
15044     case NSAPI::NSOrderedSet_insertObjectAtIndex:
15045       return 0;
15046     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
15047       return 1;
15048   }
15049 
15050   return None;
15051 }
15052 
15053 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
15054   if (!Message->isInstanceMessage()) {
15055     return;
15056   }
15057 
15058   Optional<int> ArgOpt;
15059 
15060   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
15061       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
15062       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
15063     return;
15064   }
15065 
15066   int ArgIndex = *ArgOpt;
15067 
15068   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
15069   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
15070     Arg = OE->getSourceExpr()->IgnoreImpCasts();
15071   }
15072 
15073   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
15074     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
15075       if (ArgRE->isObjCSelfExpr()) {
15076         Diag(Message->getSourceRange().getBegin(),
15077              diag::warn_objc_circular_container)
15078           << ArgRE->getDecl() << StringRef("'super'");
15079       }
15080     }
15081   } else {
15082     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
15083 
15084     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
15085       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
15086     }
15087 
15088     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
15089       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
15090         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
15091           ValueDecl *Decl = ReceiverRE->getDecl();
15092           Diag(Message->getSourceRange().getBegin(),
15093                diag::warn_objc_circular_container)
15094             << Decl << Decl;
15095           if (!ArgRE->isObjCSelfExpr()) {
15096             Diag(Decl->getLocation(),
15097                  diag::note_objc_circular_container_declared_here)
15098               << Decl;
15099           }
15100         }
15101       }
15102     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
15103       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
15104         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
15105           ObjCIvarDecl *Decl = IvarRE->getDecl();
15106           Diag(Message->getSourceRange().getBegin(),
15107                diag::warn_objc_circular_container)
15108             << Decl << Decl;
15109           Diag(Decl->getLocation(),
15110                diag::note_objc_circular_container_declared_here)
15111             << Decl;
15112         }
15113       }
15114     }
15115   }
15116 }
15117 
15118 /// Check a message send to see if it's likely to cause a retain cycle.
15119 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
15120   // Only check instance methods whose selector looks like a setter.
15121   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
15122     return;
15123 
15124   // Try to find a variable that the receiver is strongly owned by.
15125   RetainCycleOwner owner;
15126   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
15127     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
15128       return;
15129   } else {
15130     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
15131     owner.Variable = getCurMethodDecl()->getSelfDecl();
15132     owner.Loc = msg->getSuperLoc();
15133     owner.Range = msg->getSuperLoc();
15134   }
15135 
15136   // Check whether the receiver is captured by any of the arguments.
15137   const ObjCMethodDecl *MD = msg->getMethodDecl();
15138   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
15139     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
15140       // noescape blocks should not be retained by the method.
15141       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
15142         continue;
15143       return diagnoseRetainCycle(*this, capturer, owner);
15144     }
15145   }
15146 }
15147 
15148 /// Check a property assign to see if it's likely to cause a retain cycle.
15149 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
15150   RetainCycleOwner owner;
15151   if (!findRetainCycleOwner(*this, receiver, owner))
15152     return;
15153 
15154   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
15155     diagnoseRetainCycle(*this, capturer, owner);
15156 }
15157 
15158 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
15159   RetainCycleOwner Owner;
15160   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
15161     return;
15162 
15163   // Because we don't have an expression for the variable, we have to set the
15164   // location explicitly here.
15165   Owner.Loc = Var->getLocation();
15166   Owner.Range = Var->getSourceRange();
15167 
15168   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
15169     diagnoseRetainCycle(*this, Capturer, Owner);
15170 }
15171 
15172 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
15173                                      Expr *RHS, bool isProperty) {
15174   // Check if RHS is an Objective-C object literal, which also can get
15175   // immediately zapped in a weak reference.  Note that we explicitly
15176   // allow ObjCStringLiterals, since those are designed to never really die.
15177   RHS = RHS->IgnoreParenImpCasts();
15178 
15179   // This enum needs to match with the 'select' in
15180   // warn_objc_arc_literal_assign (off-by-1).
15181   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
15182   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
15183     return false;
15184 
15185   S.Diag(Loc, diag::warn_arc_literal_assign)
15186     << (unsigned) Kind
15187     << (isProperty ? 0 : 1)
15188     << RHS->getSourceRange();
15189 
15190   return true;
15191 }
15192 
15193 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
15194                                     Qualifiers::ObjCLifetime LT,
15195                                     Expr *RHS, bool isProperty) {
15196   // Strip off any implicit cast added to get to the one ARC-specific.
15197   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15198     if (cast->getCastKind() == CK_ARCConsumeObject) {
15199       S.Diag(Loc, diag::warn_arc_retained_assign)
15200         << (LT == Qualifiers::OCL_ExplicitNone)
15201         << (isProperty ? 0 : 1)
15202         << RHS->getSourceRange();
15203       return true;
15204     }
15205     RHS = cast->getSubExpr();
15206   }
15207 
15208   if (LT == Qualifiers::OCL_Weak &&
15209       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
15210     return true;
15211 
15212   return false;
15213 }
15214 
15215 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
15216                               QualType LHS, Expr *RHS) {
15217   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
15218 
15219   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
15220     return false;
15221 
15222   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
15223     return true;
15224 
15225   return false;
15226 }
15227 
15228 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
15229                               Expr *LHS, Expr *RHS) {
15230   QualType LHSType;
15231   // PropertyRef on LHS type need be directly obtained from
15232   // its declaration as it has a PseudoType.
15233   ObjCPropertyRefExpr *PRE
15234     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
15235   if (PRE && !PRE->isImplicitProperty()) {
15236     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15237     if (PD)
15238       LHSType = PD->getType();
15239   }
15240 
15241   if (LHSType.isNull())
15242     LHSType = LHS->getType();
15243 
15244   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
15245 
15246   if (LT == Qualifiers::OCL_Weak) {
15247     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
15248       getCurFunction()->markSafeWeakUse(LHS);
15249   }
15250 
15251   if (checkUnsafeAssigns(Loc, LHSType, RHS))
15252     return;
15253 
15254   // FIXME. Check for other life times.
15255   if (LT != Qualifiers::OCL_None)
15256     return;
15257 
15258   if (PRE) {
15259     if (PRE->isImplicitProperty())
15260       return;
15261     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15262     if (!PD)
15263       return;
15264 
15265     unsigned Attributes = PD->getPropertyAttributes();
15266     if (Attributes & ObjCPropertyAttribute::kind_assign) {
15267       // when 'assign' attribute was not explicitly specified
15268       // by user, ignore it and rely on property type itself
15269       // for lifetime info.
15270       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
15271       if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
15272           LHSType->isObjCRetainableType())
15273         return;
15274 
15275       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15276         if (cast->getCastKind() == CK_ARCConsumeObject) {
15277           Diag(Loc, diag::warn_arc_retained_property_assign)
15278           << RHS->getSourceRange();
15279           return;
15280         }
15281         RHS = cast->getSubExpr();
15282       }
15283     } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
15284       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
15285         return;
15286     }
15287   }
15288 }
15289 
15290 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
15291 
15292 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
15293                                         SourceLocation StmtLoc,
15294                                         const NullStmt *Body) {
15295   // Do not warn if the body is a macro that expands to nothing, e.g:
15296   //
15297   // #define CALL(x)
15298   // if (condition)
15299   //   CALL(0);
15300   if (Body->hasLeadingEmptyMacro())
15301     return false;
15302 
15303   // Get line numbers of statement and body.
15304   bool StmtLineInvalid;
15305   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
15306                                                       &StmtLineInvalid);
15307   if (StmtLineInvalid)
15308     return false;
15309 
15310   bool BodyLineInvalid;
15311   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
15312                                                       &BodyLineInvalid);
15313   if (BodyLineInvalid)
15314     return false;
15315 
15316   // Warn if null statement and body are on the same line.
15317   if (StmtLine != BodyLine)
15318     return false;
15319 
15320   return true;
15321 }
15322 
15323 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
15324                                  const Stmt *Body,
15325                                  unsigned DiagID) {
15326   // Since this is a syntactic check, don't emit diagnostic for template
15327   // instantiations, this just adds noise.
15328   if (CurrentInstantiationScope)
15329     return;
15330 
15331   // The body should be a null statement.
15332   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15333   if (!NBody)
15334     return;
15335 
15336   // Do the usual checks.
15337   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15338     return;
15339 
15340   Diag(NBody->getSemiLoc(), DiagID);
15341   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15342 }
15343 
15344 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
15345                                  const Stmt *PossibleBody) {
15346   assert(!CurrentInstantiationScope); // Ensured by caller
15347 
15348   SourceLocation StmtLoc;
15349   const Stmt *Body;
15350   unsigned DiagID;
15351   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
15352     StmtLoc = FS->getRParenLoc();
15353     Body = FS->getBody();
15354     DiagID = diag::warn_empty_for_body;
15355   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
15356     StmtLoc = WS->getCond()->getSourceRange().getEnd();
15357     Body = WS->getBody();
15358     DiagID = diag::warn_empty_while_body;
15359   } else
15360     return; // Neither `for' nor `while'.
15361 
15362   // The body should be a null statement.
15363   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15364   if (!NBody)
15365     return;
15366 
15367   // Skip expensive checks if diagnostic is disabled.
15368   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
15369     return;
15370 
15371   // Do the usual checks.
15372   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15373     return;
15374 
15375   // `for(...);' and `while(...);' are popular idioms, so in order to keep
15376   // noise level low, emit diagnostics only if for/while is followed by a
15377   // CompoundStmt, e.g.:
15378   //    for (int i = 0; i < n; i++);
15379   //    {
15380   //      a(i);
15381   //    }
15382   // or if for/while is followed by a statement with more indentation
15383   // than for/while itself:
15384   //    for (int i = 0; i < n; i++);
15385   //      a(i);
15386   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
15387   if (!ProbableTypo) {
15388     bool BodyColInvalid;
15389     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
15390         PossibleBody->getBeginLoc(), &BodyColInvalid);
15391     if (BodyColInvalid)
15392       return;
15393 
15394     bool StmtColInvalid;
15395     unsigned StmtCol =
15396         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
15397     if (StmtColInvalid)
15398       return;
15399 
15400     if (BodyCol > StmtCol)
15401       ProbableTypo = true;
15402   }
15403 
15404   if (ProbableTypo) {
15405     Diag(NBody->getSemiLoc(), DiagID);
15406     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15407   }
15408 }
15409 
15410 //===--- CHECK: Warn on self move with std::move. -------------------------===//
15411 
15412 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
15413 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
15414                              SourceLocation OpLoc) {
15415   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
15416     return;
15417 
15418   if (inTemplateInstantiation())
15419     return;
15420 
15421   // Strip parens and casts away.
15422   LHSExpr = LHSExpr->IgnoreParenImpCasts();
15423   RHSExpr = RHSExpr->IgnoreParenImpCasts();
15424 
15425   // Check for a call expression
15426   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
15427   if (!CE || CE->getNumArgs() != 1)
15428     return;
15429 
15430   // Check for a call to std::move
15431   if (!CE->isCallToStdMove())
15432     return;
15433 
15434   // Get argument from std::move
15435   RHSExpr = CE->getArg(0);
15436 
15437   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
15438   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
15439 
15440   // Two DeclRefExpr's, check that the decls are the same.
15441   if (LHSDeclRef && RHSDeclRef) {
15442     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15443       return;
15444     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15445         RHSDeclRef->getDecl()->getCanonicalDecl())
15446       return;
15447 
15448     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15449                                         << LHSExpr->getSourceRange()
15450                                         << RHSExpr->getSourceRange();
15451     return;
15452   }
15453 
15454   // Member variables require a different approach to check for self moves.
15455   // MemberExpr's are the same if every nested MemberExpr refers to the same
15456   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
15457   // the base Expr's are CXXThisExpr's.
15458   const Expr *LHSBase = LHSExpr;
15459   const Expr *RHSBase = RHSExpr;
15460   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
15461   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
15462   if (!LHSME || !RHSME)
15463     return;
15464 
15465   while (LHSME && RHSME) {
15466     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
15467         RHSME->getMemberDecl()->getCanonicalDecl())
15468       return;
15469 
15470     LHSBase = LHSME->getBase();
15471     RHSBase = RHSME->getBase();
15472     LHSME = dyn_cast<MemberExpr>(LHSBase);
15473     RHSME = dyn_cast<MemberExpr>(RHSBase);
15474   }
15475 
15476   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
15477   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
15478   if (LHSDeclRef && RHSDeclRef) {
15479     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15480       return;
15481     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15482         RHSDeclRef->getDecl()->getCanonicalDecl())
15483       return;
15484 
15485     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15486                                         << LHSExpr->getSourceRange()
15487                                         << RHSExpr->getSourceRange();
15488     return;
15489   }
15490 
15491   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
15492     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15493                                         << LHSExpr->getSourceRange()
15494                                         << RHSExpr->getSourceRange();
15495 }
15496 
15497 //===--- Layout compatibility ----------------------------------------------//
15498 
15499 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
15500 
15501 /// Check if two enumeration types are layout-compatible.
15502 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
15503   // C++11 [dcl.enum] p8:
15504   // Two enumeration types are layout-compatible if they have the same
15505   // underlying type.
15506   return ED1->isComplete() && ED2->isComplete() &&
15507          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
15508 }
15509 
15510 /// Check if two fields are layout-compatible.
15511 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
15512                                FieldDecl *Field2) {
15513   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
15514     return false;
15515 
15516   if (Field1->isBitField() != Field2->isBitField())
15517     return false;
15518 
15519   if (Field1->isBitField()) {
15520     // Make sure that the bit-fields are the same length.
15521     unsigned Bits1 = Field1->getBitWidthValue(C);
15522     unsigned Bits2 = Field2->getBitWidthValue(C);
15523 
15524     if (Bits1 != Bits2)
15525       return false;
15526   }
15527 
15528   return true;
15529 }
15530 
15531 /// Check if two standard-layout structs are layout-compatible.
15532 /// (C++11 [class.mem] p17)
15533 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
15534                                      RecordDecl *RD2) {
15535   // If both records are C++ classes, check that base classes match.
15536   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
15537     // If one of records is a CXXRecordDecl we are in C++ mode,
15538     // thus the other one is a CXXRecordDecl, too.
15539     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
15540     // Check number of base classes.
15541     if (D1CXX->getNumBases() != D2CXX->getNumBases())
15542       return false;
15543 
15544     // Check the base classes.
15545     for (CXXRecordDecl::base_class_const_iterator
15546                Base1 = D1CXX->bases_begin(),
15547            BaseEnd1 = D1CXX->bases_end(),
15548               Base2 = D2CXX->bases_begin();
15549          Base1 != BaseEnd1;
15550          ++Base1, ++Base2) {
15551       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
15552         return false;
15553     }
15554   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
15555     // If only RD2 is a C++ class, it should have zero base classes.
15556     if (D2CXX->getNumBases() > 0)
15557       return false;
15558   }
15559 
15560   // Check the fields.
15561   RecordDecl::field_iterator Field2 = RD2->field_begin(),
15562                              Field2End = RD2->field_end(),
15563                              Field1 = RD1->field_begin(),
15564                              Field1End = RD1->field_end();
15565   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
15566     if (!isLayoutCompatible(C, *Field1, *Field2))
15567       return false;
15568   }
15569   if (Field1 != Field1End || Field2 != Field2End)
15570     return false;
15571 
15572   return true;
15573 }
15574 
15575 /// Check if two standard-layout unions are layout-compatible.
15576 /// (C++11 [class.mem] p18)
15577 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
15578                                     RecordDecl *RD2) {
15579   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
15580   for (auto *Field2 : RD2->fields())
15581     UnmatchedFields.insert(Field2);
15582 
15583   for (auto *Field1 : RD1->fields()) {
15584     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
15585         I = UnmatchedFields.begin(),
15586         E = UnmatchedFields.end();
15587 
15588     for ( ; I != E; ++I) {
15589       if (isLayoutCompatible(C, Field1, *I)) {
15590         bool Result = UnmatchedFields.erase(*I);
15591         (void) Result;
15592         assert(Result);
15593         break;
15594       }
15595     }
15596     if (I == E)
15597       return false;
15598   }
15599 
15600   return UnmatchedFields.empty();
15601 }
15602 
15603 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
15604                                RecordDecl *RD2) {
15605   if (RD1->isUnion() != RD2->isUnion())
15606     return false;
15607 
15608   if (RD1->isUnion())
15609     return isLayoutCompatibleUnion(C, RD1, RD2);
15610   else
15611     return isLayoutCompatibleStruct(C, RD1, RD2);
15612 }
15613 
15614 /// Check if two types are layout-compatible in C++11 sense.
15615 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
15616   if (T1.isNull() || T2.isNull())
15617     return false;
15618 
15619   // C++11 [basic.types] p11:
15620   // If two types T1 and T2 are the same type, then T1 and T2 are
15621   // layout-compatible types.
15622   if (C.hasSameType(T1, T2))
15623     return true;
15624 
15625   T1 = T1.getCanonicalType().getUnqualifiedType();
15626   T2 = T2.getCanonicalType().getUnqualifiedType();
15627 
15628   const Type::TypeClass TC1 = T1->getTypeClass();
15629   const Type::TypeClass TC2 = T2->getTypeClass();
15630 
15631   if (TC1 != TC2)
15632     return false;
15633 
15634   if (TC1 == Type::Enum) {
15635     return isLayoutCompatible(C,
15636                               cast<EnumType>(T1)->getDecl(),
15637                               cast<EnumType>(T2)->getDecl());
15638   } else if (TC1 == Type::Record) {
15639     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
15640       return false;
15641 
15642     return isLayoutCompatible(C,
15643                               cast<RecordType>(T1)->getDecl(),
15644                               cast<RecordType>(T2)->getDecl());
15645   }
15646 
15647   return false;
15648 }
15649 
15650 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
15651 
15652 /// Given a type tag expression find the type tag itself.
15653 ///
15654 /// \param TypeExpr Type tag expression, as it appears in user's code.
15655 ///
15656 /// \param VD Declaration of an identifier that appears in a type tag.
15657 ///
15658 /// \param MagicValue Type tag magic value.
15659 ///
15660 /// \param isConstantEvaluated wether the evalaution should be performed in
15661 
15662 /// constant context.
15663 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
15664                             const ValueDecl **VD, uint64_t *MagicValue,
15665                             bool isConstantEvaluated) {
15666   while(true) {
15667     if (!TypeExpr)
15668       return false;
15669 
15670     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
15671 
15672     switch (TypeExpr->getStmtClass()) {
15673     case Stmt::UnaryOperatorClass: {
15674       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
15675       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
15676         TypeExpr = UO->getSubExpr();
15677         continue;
15678       }
15679       return false;
15680     }
15681 
15682     case Stmt::DeclRefExprClass: {
15683       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
15684       *VD = DRE->getDecl();
15685       return true;
15686     }
15687 
15688     case Stmt::IntegerLiteralClass: {
15689       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
15690       llvm::APInt MagicValueAPInt = IL->getValue();
15691       if (MagicValueAPInt.getActiveBits() <= 64) {
15692         *MagicValue = MagicValueAPInt.getZExtValue();
15693         return true;
15694       } else
15695         return false;
15696     }
15697 
15698     case Stmt::BinaryConditionalOperatorClass:
15699     case Stmt::ConditionalOperatorClass: {
15700       const AbstractConditionalOperator *ACO =
15701           cast<AbstractConditionalOperator>(TypeExpr);
15702       bool Result;
15703       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
15704                                                      isConstantEvaluated)) {
15705         if (Result)
15706           TypeExpr = ACO->getTrueExpr();
15707         else
15708           TypeExpr = ACO->getFalseExpr();
15709         continue;
15710       }
15711       return false;
15712     }
15713 
15714     case Stmt::BinaryOperatorClass: {
15715       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
15716       if (BO->getOpcode() == BO_Comma) {
15717         TypeExpr = BO->getRHS();
15718         continue;
15719       }
15720       return false;
15721     }
15722 
15723     default:
15724       return false;
15725     }
15726   }
15727 }
15728 
15729 /// Retrieve the C type corresponding to type tag TypeExpr.
15730 ///
15731 /// \param TypeExpr Expression that specifies a type tag.
15732 ///
15733 /// \param MagicValues Registered magic values.
15734 ///
15735 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
15736 ///        kind.
15737 ///
15738 /// \param TypeInfo Information about the corresponding C type.
15739 ///
15740 /// \param isConstantEvaluated wether the evalaution should be performed in
15741 /// constant context.
15742 ///
15743 /// \returns true if the corresponding C type was found.
15744 static bool GetMatchingCType(
15745     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
15746     const ASTContext &Ctx,
15747     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
15748         *MagicValues,
15749     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
15750     bool isConstantEvaluated) {
15751   FoundWrongKind = false;
15752 
15753   // Variable declaration that has type_tag_for_datatype attribute.
15754   const ValueDecl *VD = nullptr;
15755 
15756   uint64_t MagicValue;
15757 
15758   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
15759     return false;
15760 
15761   if (VD) {
15762     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
15763       if (I->getArgumentKind() != ArgumentKind) {
15764         FoundWrongKind = true;
15765         return false;
15766       }
15767       TypeInfo.Type = I->getMatchingCType();
15768       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
15769       TypeInfo.MustBeNull = I->getMustBeNull();
15770       return true;
15771     }
15772     return false;
15773   }
15774 
15775   if (!MagicValues)
15776     return false;
15777 
15778   llvm::DenseMap<Sema::TypeTagMagicValue,
15779                  Sema::TypeTagData>::const_iterator I =
15780       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
15781   if (I == MagicValues->end())
15782     return false;
15783 
15784   TypeInfo = I->second;
15785   return true;
15786 }
15787 
15788 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
15789                                       uint64_t MagicValue, QualType Type,
15790                                       bool LayoutCompatible,
15791                                       bool MustBeNull) {
15792   if (!TypeTagForDatatypeMagicValues)
15793     TypeTagForDatatypeMagicValues.reset(
15794         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
15795 
15796   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
15797   (*TypeTagForDatatypeMagicValues)[Magic] =
15798       TypeTagData(Type, LayoutCompatible, MustBeNull);
15799 }
15800 
15801 static bool IsSameCharType(QualType T1, QualType T2) {
15802   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
15803   if (!BT1)
15804     return false;
15805 
15806   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
15807   if (!BT2)
15808     return false;
15809 
15810   BuiltinType::Kind T1Kind = BT1->getKind();
15811   BuiltinType::Kind T2Kind = BT2->getKind();
15812 
15813   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
15814          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
15815          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
15816          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
15817 }
15818 
15819 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
15820                                     const ArrayRef<const Expr *> ExprArgs,
15821                                     SourceLocation CallSiteLoc) {
15822   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
15823   bool IsPointerAttr = Attr->getIsPointer();
15824 
15825   // Retrieve the argument representing the 'type_tag'.
15826   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
15827   if (TypeTagIdxAST >= ExprArgs.size()) {
15828     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
15829         << 0 << Attr->getTypeTagIdx().getSourceIndex();
15830     return;
15831   }
15832   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
15833   bool FoundWrongKind;
15834   TypeTagData TypeInfo;
15835   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
15836                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
15837                         TypeInfo, isConstantEvaluated())) {
15838     if (FoundWrongKind)
15839       Diag(TypeTagExpr->getExprLoc(),
15840            diag::warn_type_tag_for_datatype_wrong_kind)
15841         << TypeTagExpr->getSourceRange();
15842     return;
15843   }
15844 
15845   // Retrieve the argument representing the 'arg_idx'.
15846   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
15847   if (ArgumentIdxAST >= ExprArgs.size()) {
15848     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
15849         << 1 << Attr->getArgumentIdx().getSourceIndex();
15850     return;
15851   }
15852   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
15853   if (IsPointerAttr) {
15854     // Skip implicit cast of pointer to `void *' (as a function argument).
15855     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
15856       if (ICE->getType()->isVoidPointerType() &&
15857           ICE->getCastKind() == CK_BitCast)
15858         ArgumentExpr = ICE->getSubExpr();
15859   }
15860   QualType ArgumentType = ArgumentExpr->getType();
15861 
15862   // Passing a `void*' pointer shouldn't trigger a warning.
15863   if (IsPointerAttr && ArgumentType->isVoidPointerType())
15864     return;
15865 
15866   if (TypeInfo.MustBeNull) {
15867     // Type tag with matching void type requires a null pointer.
15868     if (!ArgumentExpr->isNullPointerConstant(Context,
15869                                              Expr::NPC_ValueDependentIsNotNull)) {
15870       Diag(ArgumentExpr->getExprLoc(),
15871            diag::warn_type_safety_null_pointer_required)
15872           << ArgumentKind->getName()
15873           << ArgumentExpr->getSourceRange()
15874           << TypeTagExpr->getSourceRange();
15875     }
15876     return;
15877   }
15878 
15879   QualType RequiredType = TypeInfo.Type;
15880   if (IsPointerAttr)
15881     RequiredType = Context.getPointerType(RequiredType);
15882 
15883   bool mismatch = false;
15884   if (!TypeInfo.LayoutCompatible) {
15885     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
15886 
15887     // C++11 [basic.fundamental] p1:
15888     // Plain char, signed char, and unsigned char are three distinct types.
15889     //
15890     // But we treat plain `char' as equivalent to `signed char' or `unsigned
15891     // char' depending on the current char signedness mode.
15892     if (mismatch)
15893       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
15894                                            RequiredType->getPointeeType())) ||
15895           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
15896         mismatch = false;
15897   } else
15898     if (IsPointerAttr)
15899       mismatch = !isLayoutCompatible(Context,
15900                                      ArgumentType->getPointeeType(),
15901                                      RequiredType->getPointeeType());
15902     else
15903       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
15904 
15905   if (mismatch)
15906     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
15907         << ArgumentType << ArgumentKind
15908         << TypeInfo.LayoutCompatible << RequiredType
15909         << ArgumentExpr->getSourceRange()
15910         << TypeTagExpr->getSourceRange();
15911 }
15912 
15913 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
15914                                          CharUnits Alignment) {
15915   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
15916 }
15917 
15918 void Sema::DiagnoseMisalignedMembers() {
15919   for (MisalignedMember &m : MisalignedMembers) {
15920     const NamedDecl *ND = m.RD;
15921     if (ND->getName().empty()) {
15922       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
15923         ND = TD;
15924     }
15925     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
15926         << m.MD << ND << m.E->getSourceRange();
15927   }
15928   MisalignedMembers.clear();
15929 }
15930 
15931 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
15932   E = E->IgnoreParens();
15933   if (!T->isPointerType() && !T->isIntegerType())
15934     return;
15935   if (isa<UnaryOperator>(E) &&
15936       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
15937     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
15938     if (isa<MemberExpr>(Op)) {
15939       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
15940       if (MA != MisalignedMembers.end() &&
15941           (T->isIntegerType() ||
15942            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
15943                                    Context.getTypeAlignInChars(
15944                                        T->getPointeeType()) <= MA->Alignment))))
15945         MisalignedMembers.erase(MA);
15946     }
15947   }
15948 }
15949 
15950 void Sema::RefersToMemberWithReducedAlignment(
15951     Expr *E,
15952     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
15953         Action) {
15954   const auto *ME = dyn_cast<MemberExpr>(E);
15955   if (!ME)
15956     return;
15957 
15958   // No need to check expressions with an __unaligned-qualified type.
15959   if (E->getType().getQualifiers().hasUnaligned())
15960     return;
15961 
15962   // For a chain of MemberExpr like "a.b.c.d" this list
15963   // will keep FieldDecl's like [d, c, b].
15964   SmallVector<FieldDecl *, 4> ReverseMemberChain;
15965   const MemberExpr *TopME = nullptr;
15966   bool AnyIsPacked = false;
15967   do {
15968     QualType BaseType = ME->getBase()->getType();
15969     if (BaseType->isDependentType())
15970       return;
15971     if (ME->isArrow())
15972       BaseType = BaseType->getPointeeType();
15973     RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
15974     if (RD->isInvalidDecl())
15975       return;
15976 
15977     ValueDecl *MD = ME->getMemberDecl();
15978     auto *FD = dyn_cast<FieldDecl>(MD);
15979     // We do not care about non-data members.
15980     if (!FD || FD->isInvalidDecl())
15981       return;
15982 
15983     AnyIsPacked =
15984         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
15985     ReverseMemberChain.push_back(FD);
15986 
15987     TopME = ME;
15988     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
15989   } while (ME);
15990   assert(TopME && "We did not compute a topmost MemberExpr!");
15991 
15992   // Not the scope of this diagnostic.
15993   if (!AnyIsPacked)
15994     return;
15995 
15996   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
15997   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
15998   // TODO: The innermost base of the member expression may be too complicated.
15999   // For now, just disregard these cases. This is left for future
16000   // improvement.
16001   if (!DRE && !isa<CXXThisExpr>(TopBase))
16002       return;
16003 
16004   // Alignment expected by the whole expression.
16005   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
16006 
16007   // No need to do anything else with this case.
16008   if (ExpectedAlignment.isOne())
16009     return;
16010 
16011   // Synthesize offset of the whole access.
16012   CharUnits Offset;
16013   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
16014        I++) {
16015     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
16016   }
16017 
16018   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
16019   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
16020       ReverseMemberChain.back()->getParent()->getTypeForDecl());
16021 
16022   // The base expression of the innermost MemberExpr may give
16023   // stronger guarantees than the class containing the member.
16024   if (DRE && !TopME->isArrow()) {
16025     const ValueDecl *VD = DRE->getDecl();
16026     if (!VD->getType()->isReferenceType())
16027       CompleteObjectAlignment =
16028           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
16029   }
16030 
16031   // Check if the synthesized offset fulfills the alignment.
16032   if (Offset % ExpectedAlignment != 0 ||
16033       // It may fulfill the offset it but the effective alignment may still be
16034       // lower than the expected expression alignment.
16035       CompleteObjectAlignment < ExpectedAlignment) {
16036     // If this happens, we want to determine a sensible culprit of this.
16037     // Intuitively, watching the chain of member expressions from right to
16038     // left, we start with the required alignment (as required by the field
16039     // type) but some packed attribute in that chain has reduced the alignment.
16040     // It may happen that another packed structure increases it again. But if
16041     // we are here such increase has not been enough. So pointing the first
16042     // FieldDecl that either is packed or else its RecordDecl is,
16043     // seems reasonable.
16044     FieldDecl *FD = nullptr;
16045     CharUnits Alignment;
16046     for (FieldDecl *FDI : ReverseMemberChain) {
16047       if (FDI->hasAttr<PackedAttr>() ||
16048           FDI->getParent()->hasAttr<PackedAttr>()) {
16049         FD = FDI;
16050         Alignment = std::min(
16051             Context.getTypeAlignInChars(FD->getType()),
16052             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
16053         break;
16054       }
16055     }
16056     assert(FD && "We did not find a packed FieldDecl!");
16057     Action(E, FD->getParent(), FD, Alignment);
16058   }
16059 }
16060 
16061 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
16062   using namespace std::placeholders;
16063 
16064   RefersToMemberWithReducedAlignment(
16065       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
16066                      _2, _3, _4));
16067 }
16068 
16069 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall,
16070                                             ExprResult CallResult) {
16071   if (checkArgCount(*this, TheCall, 1))
16072     return ExprError();
16073 
16074   ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
16075   if (MatrixArg.isInvalid())
16076     return MatrixArg;
16077   Expr *Matrix = MatrixArg.get();
16078 
16079   auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
16080   if (!MType) {
16081     Diag(Matrix->getBeginLoc(), diag::err_builtin_matrix_arg);
16082     return ExprError();
16083   }
16084 
16085   // Create returned matrix type by swapping rows and columns of the argument
16086   // matrix type.
16087   QualType ResultType = Context.getConstantMatrixType(
16088       MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
16089 
16090   // Change the return type to the type of the returned matrix.
16091   TheCall->setType(ResultType);
16092 
16093   // Update call argument to use the possibly converted matrix argument.
16094   TheCall->setArg(0, Matrix);
16095   return CallResult;
16096 }
16097 
16098 // Get and verify the matrix dimensions.
16099 static llvm::Optional<unsigned>
16100 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {
16101   SourceLocation ErrorPos;
16102   Optional<llvm::APSInt> Value =
16103       Expr->getIntegerConstantExpr(S.Context, &ErrorPos);
16104   if (!Value) {
16105     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
16106         << Name;
16107     return {};
16108   }
16109   uint64_t Dim = Value->getZExtValue();
16110   if (!ConstantMatrixType::isDimensionValid(Dim)) {
16111     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
16112         << Name << ConstantMatrixType::getMaxElementsPerDimension();
16113     return {};
16114   }
16115   return Dim;
16116 }
16117 
16118 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
16119                                                   ExprResult CallResult) {
16120   if (!getLangOpts().MatrixTypes) {
16121     Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
16122     return ExprError();
16123   }
16124 
16125   if (checkArgCount(*this, TheCall, 4))
16126     return ExprError();
16127 
16128   unsigned PtrArgIdx = 0;
16129   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16130   Expr *RowsExpr = TheCall->getArg(1);
16131   Expr *ColumnsExpr = TheCall->getArg(2);
16132   Expr *StrideExpr = TheCall->getArg(3);
16133 
16134   bool ArgError = false;
16135 
16136   // Check pointer argument.
16137   {
16138     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
16139     if (PtrConv.isInvalid())
16140       return PtrConv;
16141     PtrExpr = PtrConv.get();
16142     TheCall->setArg(0, PtrExpr);
16143     if (PtrExpr->isTypeDependent()) {
16144       TheCall->setType(Context.DependentTy);
16145       return TheCall;
16146     }
16147   }
16148 
16149   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16150   QualType ElementTy;
16151   if (!PtrTy) {
16152     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
16153         << PtrArgIdx + 1;
16154     ArgError = true;
16155   } else {
16156     ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
16157 
16158     if (!ConstantMatrixType::isValidElementType(ElementTy)) {
16159       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
16160           << PtrArgIdx + 1;
16161       ArgError = true;
16162     }
16163   }
16164 
16165   // Apply default Lvalue conversions and convert the expression to size_t.
16166   auto ApplyArgumentConversions = [this](Expr *E) {
16167     ExprResult Conv = DefaultLvalueConversion(E);
16168     if (Conv.isInvalid())
16169       return Conv;
16170 
16171     return tryConvertExprToType(Conv.get(), Context.getSizeType());
16172   };
16173 
16174   // Apply conversion to row and column expressions.
16175   ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
16176   if (!RowsConv.isInvalid()) {
16177     RowsExpr = RowsConv.get();
16178     TheCall->setArg(1, RowsExpr);
16179   } else
16180     RowsExpr = nullptr;
16181 
16182   ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
16183   if (!ColumnsConv.isInvalid()) {
16184     ColumnsExpr = ColumnsConv.get();
16185     TheCall->setArg(2, ColumnsExpr);
16186   } else
16187     ColumnsExpr = nullptr;
16188 
16189   // If any any part of the result matrix type is still pending, just use
16190   // Context.DependentTy, until all parts are resolved.
16191   if ((RowsExpr && RowsExpr->isTypeDependent()) ||
16192       (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
16193     TheCall->setType(Context.DependentTy);
16194     return CallResult;
16195   }
16196 
16197   // Check row and column dimenions.
16198   llvm::Optional<unsigned> MaybeRows;
16199   if (RowsExpr)
16200     MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
16201 
16202   llvm::Optional<unsigned> MaybeColumns;
16203   if (ColumnsExpr)
16204     MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
16205 
16206   // Check stride argument.
16207   ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
16208   if (StrideConv.isInvalid())
16209     return ExprError();
16210   StrideExpr = StrideConv.get();
16211   TheCall->setArg(3, StrideExpr);
16212 
16213   if (MaybeRows) {
16214     if (Optional<llvm::APSInt> Value =
16215             StrideExpr->getIntegerConstantExpr(Context)) {
16216       uint64_t Stride = Value->getZExtValue();
16217       if (Stride < *MaybeRows) {
16218         Diag(StrideExpr->getBeginLoc(),
16219              diag::err_builtin_matrix_stride_too_small);
16220         ArgError = true;
16221       }
16222     }
16223   }
16224 
16225   if (ArgError || !MaybeRows || !MaybeColumns)
16226     return ExprError();
16227 
16228   TheCall->setType(
16229       Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
16230   return CallResult;
16231 }
16232 
16233 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
16234                                                    ExprResult CallResult) {
16235   if (checkArgCount(*this, TheCall, 3))
16236     return ExprError();
16237 
16238   unsigned PtrArgIdx = 1;
16239   Expr *MatrixExpr = TheCall->getArg(0);
16240   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16241   Expr *StrideExpr = TheCall->getArg(2);
16242 
16243   bool ArgError = false;
16244 
16245   {
16246     ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
16247     if (MatrixConv.isInvalid())
16248       return MatrixConv;
16249     MatrixExpr = MatrixConv.get();
16250     TheCall->setArg(0, MatrixExpr);
16251   }
16252   if (MatrixExpr->isTypeDependent()) {
16253     TheCall->setType(Context.DependentTy);
16254     return TheCall;
16255   }
16256 
16257   auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
16258   if (!MatrixTy) {
16259     Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_matrix_arg) << 0;
16260     ArgError = true;
16261   }
16262 
16263   {
16264     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
16265     if (PtrConv.isInvalid())
16266       return PtrConv;
16267     PtrExpr = PtrConv.get();
16268     TheCall->setArg(1, PtrExpr);
16269     if (PtrExpr->isTypeDependent()) {
16270       TheCall->setType(Context.DependentTy);
16271       return TheCall;
16272     }
16273   }
16274 
16275   // Check pointer argument.
16276   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16277   if (!PtrTy) {
16278     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
16279         << PtrArgIdx + 1;
16280     ArgError = true;
16281   } else {
16282     QualType ElementTy = PtrTy->getPointeeType();
16283     if (ElementTy.isConstQualified()) {
16284       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
16285       ArgError = true;
16286     }
16287     ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
16288     if (MatrixTy &&
16289         !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
16290       Diag(PtrExpr->getBeginLoc(),
16291            diag::err_builtin_matrix_pointer_arg_mismatch)
16292           << ElementTy << MatrixTy->getElementType();
16293       ArgError = true;
16294     }
16295   }
16296 
16297   // Apply default Lvalue conversions and convert the stride expression to
16298   // size_t.
16299   {
16300     ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
16301     if (StrideConv.isInvalid())
16302       return StrideConv;
16303 
16304     StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
16305     if (StrideConv.isInvalid())
16306       return StrideConv;
16307     StrideExpr = StrideConv.get();
16308     TheCall->setArg(2, StrideExpr);
16309   }
16310 
16311   // Check stride argument.
16312   if (MatrixTy) {
16313     if (Optional<llvm::APSInt> Value =
16314             StrideExpr->getIntegerConstantExpr(Context)) {
16315       uint64_t Stride = Value->getZExtValue();
16316       if (Stride < MatrixTy->getNumRows()) {
16317         Diag(StrideExpr->getBeginLoc(),
16318              diag::err_builtin_matrix_stride_too_small);
16319         ArgError = true;
16320       }
16321     }
16322   }
16323 
16324   if (ArgError)
16325     return ExprError();
16326 
16327   return CallResult;
16328 }
16329 
16330 /// \brief Enforce the bounds of a TCB
16331 /// CheckTCBEnforcement - Enforces that every function in a named TCB only
16332 /// directly calls other functions in the same TCB as marked by the enforce_tcb
16333 /// and enforce_tcb_leaf attributes.
16334 void Sema::CheckTCBEnforcement(const CallExpr *TheCall,
16335                                const FunctionDecl *Callee) {
16336   const FunctionDecl *Caller = getCurFunctionDecl();
16337 
16338   // Calls to builtins are not enforced.
16339   if (!Caller || !Caller->hasAttr<EnforceTCBAttr>() ||
16340       Callee->getBuiltinID() != 0)
16341     return;
16342 
16343   // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
16344   // all TCBs the callee is a part of.
16345   llvm::StringSet<> CalleeTCBs;
16346   for_each(Callee->specific_attrs<EnforceTCBAttr>(),
16347            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
16348   for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(),
16349            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
16350 
16351   // Go through the TCBs the caller is a part of and emit warnings if Caller
16352   // is in a TCB that the Callee is not.
16353   for_each(
16354       Caller->specific_attrs<EnforceTCBAttr>(),
16355       [&](const auto *A) {
16356         StringRef CallerTCB = A->getTCBName();
16357         if (CalleeTCBs.count(CallerTCB) == 0) {
16358           this->Diag(TheCall->getExprLoc(),
16359                      diag::warn_tcb_enforcement_violation) << Callee
16360                                                            << CallerTCB;
16361         }
16362       });
16363 }
16364