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 that the argument to __builtin_function_start is a function.
199 static bool SemaBuiltinFunctionStart(Sema &S, CallExpr *TheCall) {
200   if (checkArgCount(S, TheCall, 1))
201     return true;
202 
203   ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
204   if (Arg.isInvalid())
205     return true;
206 
207   TheCall->setArg(0, Arg.get());
208   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(
209       Arg.get()->getAsBuiltinConstantDeclRef(S.getASTContext()));
210 
211   if (!FD) {
212     S.Diag(TheCall->getBeginLoc(), diag::err_function_start_invalid_type)
213         << TheCall->getSourceRange();
214     return true;
215   }
216 
217   return !S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
218                                               TheCall->getBeginLoc());
219 }
220 
221 /// Check the number of arguments and set the result type to
222 /// the argument type.
223 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
224   if (checkArgCount(S, TheCall, 1))
225     return true;
226 
227   TheCall->setType(TheCall->getArg(0)->getType());
228   return false;
229 }
230 
231 /// Check that the value argument for __builtin_is_aligned(value, alignment) and
232 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
233 /// type (but not a function pointer) and that the alignment is a power-of-two.
234 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
235   if (checkArgCount(S, TheCall, 2))
236     return true;
237 
238   clang::Expr *Source = TheCall->getArg(0);
239   bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
240 
241   auto IsValidIntegerType = [](QualType Ty) {
242     return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
243   };
244   QualType SrcTy = Source->getType();
245   // We should also be able to use it with arrays (but not functions!).
246   if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
247     SrcTy = S.Context.getDecayedType(SrcTy);
248   }
249   if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
250       SrcTy->isFunctionPointerType()) {
251     // FIXME: this is not quite the right error message since we don't allow
252     // floating point types, or member pointers.
253     S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand)
254         << SrcTy;
255     return true;
256   }
257 
258   clang::Expr *AlignOp = TheCall->getArg(1);
259   if (!IsValidIntegerType(AlignOp->getType())) {
260     S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int)
261         << AlignOp->getType();
262     return true;
263   }
264   Expr::EvalResult AlignResult;
265   unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1;
266   // We can't check validity of alignment if it is value dependent.
267   if (!AlignOp->isValueDependent() &&
268       AlignOp->EvaluateAsInt(AlignResult, S.Context,
269                              Expr::SE_AllowSideEffects)) {
270     llvm::APSInt AlignValue = AlignResult.Val.getInt();
271     llvm::APSInt MaxValue(
272         llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits));
273     if (AlignValue < 1) {
274       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1;
275       return true;
276     }
277     if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) {
278       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big)
279           << toString(MaxValue, 10);
280       return true;
281     }
282     if (!AlignValue.isPowerOf2()) {
283       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two);
284       return true;
285     }
286     if (AlignValue == 1) {
287       S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless)
288           << IsBooleanAlignBuiltin;
289     }
290   }
291 
292   ExprResult SrcArg = S.PerformCopyInitialization(
293       InitializedEntity::InitializeParameter(S.Context, SrcTy, false),
294       SourceLocation(), Source);
295   if (SrcArg.isInvalid())
296     return true;
297   TheCall->setArg(0, SrcArg.get());
298   ExprResult AlignArg =
299       S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
300                                       S.Context, AlignOp->getType(), false),
301                                   SourceLocation(), AlignOp);
302   if (AlignArg.isInvalid())
303     return true;
304   TheCall->setArg(1, AlignArg.get());
305   // For align_up/align_down, the return type is the same as the (potentially
306   // decayed) argument type including qualifiers. For is_aligned(), the result
307   // is always bool.
308   TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
309   return false;
310 }
311 
312 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall,
313                                 unsigned BuiltinID) {
314   if (checkArgCount(S, TheCall, 3))
315     return true;
316 
317   // First two arguments should be integers.
318   for (unsigned I = 0; I < 2; ++I) {
319     ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I));
320     if (Arg.isInvalid()) return true;
321     TheCall->setArg(I, Arg.get());
322 
323     QualType Ty = Arg.get()->getType();
324     if (!Ty->isIntegerType()) {
325       S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
326           << Ty << Arg.get()->getSourceRange();
327       return true;
328     }
329   }
330 
331   // Third argument should be a pointer to a non-const integer.
332   // IRGen correctly handles volatile, restrict, and address spaces, and
333   // the other qualifiers aren't possible.
334   {
335     ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(2));
336     if (Arg.isInvalid()) return true;
337     TheCall->setArg(2, Arg.get());
338 
339     QualType Ty = Arg.get()->getType();
340     const auto *PtrTy = Ty->getAs<PointerType>();
341     if (!PtrTy ||
342         !PtrTy->getPointeeType()->isIntegerType() ||
343         PtrTy->getPointeeType().isConstQualified()) {
344       S.Diag(Arg.get()->getBeginLoc(),
345              diag::err_overflow_builtin_must_be_ptr_int)
346         << Ty << Arg.get()->getSourceRange();
347       return true;
348     }
349   }
350 
351   // Disallow signed bit-precise integer args larger than 128 bits to mul
352   // function until we improve backend support.
353   if (BuiltinID == Builtin::BI__builtin_mul_overflow) {
354     for (unsigned I = 0; I < 3; ++I) {
355       const auto Arg = TheCall->getArg(I);
356       // Third argument will be a pointer.
357       auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType();
358       if (Ty->isBitIntType() && Ty->isSignedIntegerType() &&
359           S.getASTContext().getIntWidth(Ty) > 128)
360         return S.Diag(Arg->getBeginLoc(),
361                       diag::err_overflow_builtin_bit_int_max_size)
362                << 128;
363     }
364   }
365 
366   return false;
367 }
368 
369 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
370   if (checkArgCount(S, BuiltinCall, 2))
371     return true;
372 
373   SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
374   Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
375   Expr *Call = BuiltinCall->getArg(0);
376   Expr *Chain = BuiltinCall->getArg(1);
377 
378   if (Call->getStmtClass() != Stmt::CallExprClass) {
379     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
380         << Call->getSourceRange();
381     return true;
382   }
383 
384   auto CE = cast<CallExpr>(Call);
385   if (CE->getCallee()->getType()->isBlockPointerType()) {
386     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
387         << Call->getSourceRange();
388     return true;
389   }
390 
391   const Decl *TargetDecl = CE->getCalleeDecl();
392   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
393     if (FD->getBuiltinID()) {
394       S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
395           << Call->getSourceRange();
396       return true;
397     }
398 
399   if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
400     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
401         << Call->getSourceRange();
402     return true;
403   }
404 
405   ExprResult ChainResult = S.UsualUnaryConversions(Chain);
406   if (ChainResult.isInvalid())
407     return true;
408   if (!ChainResult.get()->getType()->isPointerType()) {
409     S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
410         << Chain->getSourceRange();
411     return true;
412   }
413 
414   QualType ReturnTy = CE->getCallReturnType(S.Context);
415   QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
416   QualType BuiltinTy = S.Context.getFunctionType(
417       ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
418   QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
419 
420   Builtin =
421       S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
422 
423   BuiltinCall->setType(CE->getType());
424   BuiltinCall->setValueKind(CE->getValueKind());
425   BuiltinCall->setObjectKind(CE->getObjectKind());
426   BuiltinCall->setCallee(Builtin);
427   BuiltinCall->setArg(1, ChainResult.get());
428 
429   return false;
430 }
431 
432 namespace {
433 
434 class ScanfDiagnosticFormatHandler
435     : public analyze_format_string::FormatStringHandler {
436   // Accepts the argument index (relative to the first destination index) of the
437   // argument whose size we want.
438   using ComputeSizeFunction =
439       llvm::function_ref<Optional<llvm::APSInt>(unsigned)>;
440 
441   // Accepts the argument index (relative to the first destination index), the
442   // destination size, and the source size).
443   using DiagnoseFunction =
444       llvm::function_ref<void(unsigned, unsigned, unsigned)>;
445 
446   ComputeSizeFunction ComputeSizeArgument;
447   DiagnoseFunction Diagnose;
448 
449 public:
450   ScanfDiagnosticFormatHandler(ComputeSizeFunction ComputeSizeArgument,
451                                DiagnoseFunction Diagnose)
452       : ComputeSizeArgument(ComputeSizeArgument), Diagnose(Diagnose) {}
453 
454   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
455                             const char *StartSpecifier,
456                             unsigned specifierLen) override {
457     if (!FS.consumesDataArgument())
458       return true;
459 
460     unsigned NulByte = 0;
461     switch ((FS.getConversionSpecifier().getKind())) {
462     default:
463       return true;
464     case analyze_format_string::ConversionSpecifier::sArg:
465     case analyze_format_string::ConversionSpecifier::ScanListArg:
466       NulByte = 1;
467       break;
468     case analyze_format_string::ConversionSpecifier::cArg:
469       break;
470     }
471 
472     analyze_format_string::OptionalAmount FW = FS.getFieldWidth();
473     if (FW.getHowSpecified() !=
474         analyze_format_string::OptionalAmount::HowSpecified::Constant)
475       return true;
476 
477     unsigned SourceSize = FW.getConstantAmount() + NulByte;
478 
479     Optional<llvm::APSInt> DestSizeAPS = ComputeSizeArgument(FS.getArgIndex());
480     if (!DestSizeAPS)
481       return true;
482 
483     unsigned DestSize = DestSizeAPS->getZExtValue();
484 
485     if (DestSize < SourceSize)
486       Diagnose(FS.getArgIndex(), DestSize, SourceSize);
487 
488     return true;
489   }
490 };
491 
492 class EstimateSizeFormatHandler
493     : public analyze_format_string::FormatStringHandler {
494   size_t Size;
495 
496 public:
497   EstimateSizeFormatHandler(StringRef Format)
498       : Size(std::min(Format.find(0), Format.size()) +
499              1 /* null byte always written by sprintf */) {}
500 
501   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
502                              const char *, unsigned SpecifierLen,
503                              const TargetInfo &) override {
504 
505     const size_t FieldWidth = computeFieldWidth(FS);
506     const size_t Precision = computePrecision(FS);
507 
508     // The actual format.
509     switch (FS.getConversionSpecifier().getKind()) {
510     // Just a char.
511     case analyze_format_string::ConversionSpecifier::cArg:
512     case analyze_format_string::ConversionSpecifier::CArg:
513       Size += std::max(FieldWidth, (size_t)1);
514       break;
515     // Just an integer.
516     case analyze_format_string::ConversionSpecifier::dArg:
517     case analyze_format_string::ConversionSpecifier::DArg:
518     case analyze_format_string::ConversionSpecifier::iArg:
519     case analyze_format_string::ConversionSpecifier::oArg:
520     case analyze_format_string::ConversionSpecifier::OArg:
521     case analyze_format_string::ConversionSpecifier::uArg:
522     case analyze_format_string::ConversionSpecifier::UArg:
523     case analyze_format_string::ConversionSpecifier::xArg:
524     case analyze_format_string::ConversionSpecifier::XArg:
525       Size += std::max(FieldWidth, Precision);
526       break;
527 
528     // %g style conversion switches between %f or %e style dynamically.
529     // %f always takes less space, so default to it.
530     case analyze_format_string::ConversionSpecifier::gArg:
531     case analyze_format_string::ConversionSpecifier::GArg:
532 
533     // Floating point number in the form '[+]ddd.ddd'.
534     case analyze_format_string::ConversionSpecifier::fArg:
535     case analyze_format_string::ConversionSpecifier::FArg:
536       Size += std::max(FieldWidth, 1 /* integer part */ +
537                                        (Precision ? 1 + Precision
538                                                   : 0) /* period + decimal */);
539       break;
540 
541     // Floating point number in the form '[-]d.ddde[+-]dd'.
542     case analyze_format_string::ConversionSpecifier::eArg:
543     case analyze_format_string::ConversionSpecifier::EArg:
544       Size +=
545           std::max(FieldWidth,
546                    1 /* integer part */ +
547                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
548                        1 /* e or E letter */ + 2 /* exponent */);
549       break;
550 
551     // Floating point number in the form '[-]0xh.hhhhp±dd'.
552     case analyze_format_string::ConversionSpecifier::aArg:
553     case analyze_format_string::ConversionSpecifier::AArg:
554       Size +=
555           std::max(FieldWidth,
556                    2 /* 0x */ + 1 /* integer part */ +
557                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
558                        1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
559       break;
560 
561     // Just a string.
562     case analyze_format_string::ConversionSpecifier::sArg:
563     case analyze_format_string::ConversionSpecifier::SArg:
564       Size += FieldWidth;
565       break;
566 
567     // Just a pointer in the form '0xddd'.
568     case analyze_format_string::ConversionSpecifier::pArg:
569       Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
570       break;
571 
572     // A plain percent.
573     case analyze_format_string::ConversionSpecifier::PercentArg:
574       Size += 1;
575       break;
576 
577     default:
578       break;
579     }
580 
581     Size += FS.hasPlusPrefix() || FS.hasSpacePrefix();
582 
583     if (FS.hasAlternativeForm()) {
584       switch (FS.getConversionSpecifier().getKind()) {
585       default:
586         break;
587       // Force a leading '0'.
588       case analyze_format_string::ConversionSpecifier::oArg:
589         Size += 1;
590         break;
591       // Force a leading '0x'.
592       case analyze_format_string::ConversionSpecifier::xArg:
593       case analyze_format_string::ConversionSpecifier::XArg:
594         Size += 2;
595         break;
596       // Force a period '.' before decimal, even if precision is 0.
597       case analyze_format_string::ConversionSpecifier::aArg:
598       case analyze_format_string::ConversionSpecifier::AArg:
599       case analyze_format_string::ConversionSpecifier::eArg:
600       case analyze_format_string::ConversionSpecifier::EArg:
601       case analyze_format_string::ConversionSpecifier::fArg:
602       case analyze_format_string::ConversionSpecifier::FArg:
603       case analyze_format_string::ConversionSpecifier::gArg:
604       case analyze_format_string::ConversionSpecifier::GArg:
605         Size += (Precision ? 0 : 1);
606         break;
607       }
608     }
609     assert(SpecifierLen <= Size && "no underflow");
610     Size -= SpecifierLen;
611     return true;
612   }
613 
614   size_t getSizeLowerBound() const { return Size; }
615 
616 private:
617   static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
618     const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
619     size_t FieldWidth = 0;
620     if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant)
621       FieldWidth = FW.getConstantAmount();
622     return FieldWidth;
623   }
624 
625   static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
626     const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
627     size_t Precision = 0;
628 
629     // See man 3 printf for default precision value based on the specifier.
630     switch (FW.getHowSpecified()) {
631     case analyze_format_string::OptionalAmount::NotSpecified:
632       switch (FS.getConversionSpecifier().getKind()) {
633       default:
634         break;
635       case analyze_format_string::ConversionSpecifier::dArg: // %d
636       case analyze_format_string::ConversionSpecifier::DArg: // %D
637       case analyze_format_string::ConversionSpecifier::iArg: // %i
638         Precision = 1;
639         break;
640       case analyze_format_string::ConversionSpecifier::oArg: // %d
641       case analyze_format_string::ConversionSpecifier::OArg: // %D
642       case analyze_format_string::ConversionSpecifier::uArg: // %d
643       case analyze_format_string::ConversionSpecifier::UArg: // %D
644       case analyze_format_string::ConversionSpecifier::xArg: // %d
645       case analyze_format_string::ConversionSpecifier::XArg: // %D
646         Precision = 1;
647         break;
648       case analyze_format_string::ConversionSpecifier::fArg: // %f
649       case analyze_format_string::ConversionSpecifier::FArg: // %F
650       case analyze_format_string::ConversionSpecifier::eArg: // %e
651       case analyze_format_string::ConversionSpecifier::EArg: // %E
652       case analyze_format_string::ConversionSpecifier::gArg: // %g
653       case analyze_format_string::ConversionSpecifier::GArg: // %G
654         Precision = 6;
655         break;
656       case analyze_format_string::ConversionSpecifier::pArg: // %d
657         Precision = 1;
658         break;
659       }
660       break;
661     case analyze_format_string::OptionalAmount::Constant:
662       Precision = FW.getConstantAmount();
663       break;
664     default:
665       break;
666     }
667     return Precision;
668   }
669 };
670 
671 } // namespace
672 
673 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
674                                                CallExpr *TheCall) {
675   if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
676       isConstantEvaluated())
677     return;
678 
679   bool UseDABAttr = false;
680   const FunctionDecl *UseDecl = FD;
681 
682   const auto *DABAttr = FD->getAttr<DiagnoseAsBuiltinAttr>();
683   if (DABAttr) {
684     UseDecl = DABAttr->getFunction();
685     assert(UseDecl && "Missing FunctionDecl in DiagnoseAsBuiltin attribute!");
686     UseDABAttr = true;
687   }
688 
689   unsigned BuiltinID = UseDecl->getBuiltinID(/*ConsiderWrappers=*/true);
690 
691   if (!BuiltinID)
692     return;
693 
694   const TargetInfo &TI = getASTContext().getTargetInfo();
695   unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
696 
697   auto TranslateIndex = [&](unsigned Index) -> Optional<unsigned> {
698     // If we refer to a diagnose_as_builtin attribute, we need to change the
699     // argument index to refer to the arguments of the called function. Unless
700     // the index is out of bounds, which presumably means it's a variadic
701     // function.
702     if (!UseDABAttr)
703       return Index;
704     unsigned DABIndices = DABAttr->argIndices_size();
705     unsigned NewIndex = Index < DABIndices
706                             ? DABAttr->argIndices_begin()[Index]
707                             : Index - DABIndices + FD->getNumParams();
708     if (NewIndex >= TheCall->getNumArgs())
709       return llvm::None;
710     return NewIndex;
711   };
712 
713   auto ComputeExplicitObjectSizeArgument =
714       [&](unsigned Index) -> Optional<llvm::APSInt> {
715     Optional<unsigned> IndexOptional = TranslateIndex(Index);
716     if (!IndexOptional)
717       return llvm::None;
718     unsigned NewIndex = IndexOptional.getValue();
719     Expr::EvalResult Result;
720     Expr *SizeArg = TheCall->getArg(NewIndex);
721     if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
722       return llvm::None;
723     llvm::APSInt Integer = Result.Val.getInt();
724     Integer.setIsUnsigned(true);
725     return Integer;
726   };
727 
728   auto ComputeSizeArgument = [&](unsigned Index) -> Optional<llvm::APSInt> {
729     // If the parameter has a pass_object_size attribute, then we should use its
730     // (potentially) more strict checking mode. Otherwise, conservatively assume
731     // type 0.
732     int BOSType = 0;
733     // This check can fail for variadic functions.
734     if (Index < FD->getNumParams()) {
735       if (const auto *POS =
736               FD->getParamDecl(Index)->getAttr<PassObjectSizeAttr>())
737         BOSType = POS->getType();
738     }
739 
740     Optional<unsigned> IndexOptional = TranslateIndex(Index);
741     if (!IndexOptional)
742       return llvm::None;
743     unsigned NewIndex = IndexOptional.getValue();
744 
745     const Expr *ObjArg = TheCall->getArg(NewIndex);
746     uint64_t Result;
747     if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
748       return llvm::None;
749 
750     // Get the object size in the target's size_t width.
751     return llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
752   };
753 
754   auto ComputeStrLenArgument = [&](unsigned Index) -> Optional<llvm::APSInt> {
755     Optional<unsigned> IndexOptional = TranslateIndex(Index);
756     if (!IndexOptional)
757       return llvm::None;
758     unsigned NewIndex = IndexOptional.getValue();
759 
760     const Expr *ObjArg = TheCall->getArg(NewIndex);
761     uint64_t Result;
762     if (!ObjArg->tryEvaluateStrLen(Result, getASTContext()))
763       return llvm::None;
764     // Add 1 for null byte.
765     return llvm::APSInt::getUnsigned(Result + 1).extOrTrunc(SizeTypeWidth);
766   };
767 
768   Optional<llvm::APSInt> SourceSize;
769   Optional<llvm::APSInt> DestinationSize;
770   unsigned DiagID = 0;
771   bool IsChkVariant = false;
772 
773   auto GetFunctionName = [&]() {
774     StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
775     // Skim off the details of whichever builtin was called to produce a better
776     // diagnostic, as it's unlikely that the user wrote the __builtin
777     // explicitly.
778     if (IsChkVariant) {
779       FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
780       FunctionName = FunctionName.drop_back(std::strlen("_chk"));
781     } else if (FunctionName.startswith("__builtin_")) {
782       FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
783     }
784     return FunctionName;
785   };
786 
787   switch (BuiltinID) {
788   default:
789     return;
790   case Builtin::BI__builtin_strcpy:
791   case Builtin::BIstrcpy: {
792     DiagID = diag::warn_fortify_strlen_overflow;
793     SourceSize = ComputeStrLenArgument(1);
794     DestinationSize = ComputeSizeArgument(0);
795     break;
796   }
797 
798   case Builtin::BI__builtin___strcpy_chk: {
799     DiagID = diag::warn_fortify_strlen_overflow;
800     SourceSize = ComputeStrLenArgument(1);
801     DestinationSize = ComputeExplicitObjectSizeArgument(2);
802     IsChkVariant = true;
803     break;
804   }
805 
806   case Builtin::BIscanf:
807   case Builtin::BIfscanf:
808   case Builtin::BIsscanf: {
809     unsigned FormatIndex = 1;
810     unsigned DataIndex = 2;
811     if (BuiltinID == Builtin::BIscanf) {
812       FormatIndex = 0;
813       DataIndex = 1;
814     }
815 
816     const auto *FormatExpr =
817         TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
818 
819     const auto *Format = dyn_cast<StringLiteral>(FormatExpr);
820     if (!Format)
821       return;
822 
823     if (!Format->isAscii() && !Format->isUTF8())
824       return;
825 
826     auto Diagnose = [&](unsigned ArgIndex, unsigned DestSize,
827                         unsigned SourceSize) {
828       DiagID = diag::warn_fortify_scanf_overflow;
829       unsigned Index = ArgIndex + DataIndex;
830       StringRef FunctionName = GetFunctionName();
831       DiagRuntimeBehavior(TheCall->getArg(Index)->getBeginLoc(), TheCall,
832                           PDiag(DiagID) << FunctionName << (Index + 1)
833                                         << DestSize << SourceSize);
834     };
835 
836     StringRef FormatStrRef = Format->getString();
837     auto ShiftedComputeSizeArgument = [&](unsigned Index) {
838       return ComputeSizeArgument(Index + DataIndex);
839     };
840     ScanfDiagnosticFormatHandler H(ShiftedComputeSizeArgument, Diagnose);
841     const char *FormatBytes = FormatStrRef.data();
842     const ConstantArrayType *T =
843         Context.getAsConstantArrayType(Format->getType());
844     assert(T && "String literal not of constant array type!");
845     size_t TypeSize = T->getSize().getZExtValue();
846 
847     // In case there's a null byte somewhere.
848     size_t StrLen =
849         std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
850 
851     analyze_format_string::ParseScanfString(H, FormatBytes,
852                                             FormatBytes + StrLen, getLangOpts(),
853                                             Context.getTargetInfo());
854 
855     // Unlike the other cases, in this one we have already issued the diagnostic
856     // here, so no need to continue (because unlike the other cases, here the
857     // diagnostic refers to the argument number).
858     return;
859   }
860 
861   case Builtin::BIsprintf:
862   case Builtin::BI__builtin___sprintf_chk: {
863     size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
864     auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
865 
866     if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) {
867 
868       if (!Format->isAscii() && !Format->isUTF8())
869         return;
870 
871       StringRef FormatStrRef = Format->getString();
872       EstimateSizeFormatHandler H(FormatStrRef);
873       const char *FormatBytes = FormatStrRef.data();
874       const ConstantArrayType *T =
875           Context.getAsConstantArrayType(Format->getType());
876       assert(T && "String literal not of constant array type!");
877       size_t TypeSize = T->getSize().getZExtValue();
878 
879       // In case there's a null byte somewhere.
880       size_t StrLen =
881           std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
882       if (!analyze_format_string::ParsePrintfString(
883               H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
884               Context.getTargetInfo(), false)) {
885         DiagID = diag::warn_fortify_source_format_overflow;
886         SourceSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
887                          .extOrTrunc(SizeTypeWidth);
888         if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
889           DestinationSize = ComputeExplicitObjectSizeArgument(2);
890           IsChkVariant = true;
891         } else {
892           DestinationSize = ComputeSizeArgument(0);
893         }
894         break;
895       }
896     }
897     return;
898   }
899   case Builtin::BI__builtin___memcpy_chk:
900   case Builtin::BI__builtin___memmove_chk:
901   case Builtin::BI__builtin___memset_chk:
902   case Builtin::BI__builtin___strlcat_chk:
903   case Builtin::BI__builtin___strlcpy_chk:
904   case Builtin::BI__builtin___strncat_chk:
905   case Builtin::BI__builtin___strncpy_chk:
906   case Builtin::BI__builtin___stpncpy_chk:
907   case Builtin::BI__builtin___memccpy_chk:
908   case Builtin::BI__builtin___mempcpy_chk: {
909     DiagID = diag::warn_builtin_chk_overflow;
910     SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 2);
911     DestinationSize =
912         ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
913     IsChkVariant = true;
914     break;
915   }
916 
917   case Builtin::BI__builtin___snprintf_chk:
918   case Builtin::BI__builtin___vsnprintf_chk: {
919     DiagID = diag::warn_builtin_chk_overflow;
920     SourceSize = ComputeExplicitObjectSizeArgument(1);
921     DestinationSize = ComputeExplicitObjectSizeArgument(3);
922     IsChkVariant = true;
923     break;
924   }
925 
926   case Builtin::BIstrncat:
927   case Builtin::BI__builtin_strncat:
928   case Builtin::BIstrncpy:
929   case Builtin::BI__builtin_strncpy:
930   case Builtin::BIstpncpy:
931   case Builtin::BI__builtin_stpncpy: {
932     // Whether these functions overflow depends on the runtime strlen of the
933     // string, not just the buffer size, so emitting the "always overflow"
934     // diagnostic isn't quite right. We should still diagnose passing a buffer
935     // size larger than the destination buffer though; this is a runtime abort
936     // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
937     DiagID = diag::warn_fortify_source_size_mismatch;
938     SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
939     DestinationSize = ComputeSizeArgument(0);
940     break;
941   }
942 
943   case Builtin::BImemcpy:
944   case Builtin::BI__builtin_memcpy:
945   case Builtin::BImemmove:
946   case Builtin::BI__builtin_memmove:
947   case Builtin::BImemset:
948   case Builtin::BI__builtin_memset:
949   case Builtin::BImempcpy:
950   case Builtin::BI__builtin_mempcpy: {
951     DiagID = diag::warn_fortify_source_overflow;
952     SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
953     DestinationSize = ComputeSizeArgument(0);
954     break;
955   }
956   case Builtin::BIsnprintf:
957   case Builtin::BI__builtin_snprintf:
958   case Builtin::BIvsnprintf:
959   case Builtin::BI__builtin_vsnprintf: {
960     DiagID = diag::warn_fortify_source_size_mismatch;
961     SourceSize = ComputeExplicitObjectSizeArgument(1);
962     DestinationSize = ComputeSizeArgument(0);
963     break;
964   }
965   }
966 
967   if (!SourceSize || !DestinationSize ||
968       llvm::APSInt::compareValues(SourceSize.getValue(),
969                                   DestinationSize.getValue()) <= 0)
970     return;
971 
972   StringRef FunctionName = GetFunctionName();
973 
974   SmallString<16> DestinationStr;
975   SmallString<16> SourceStr;
976   DestinationSize->toString(DestinationStr, /*Radix=*/10);
977   SourceSize->toString(SourceStr, /*Radix=*/10);
978   DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
979                       PDiag(DiagID)
980                           << FunctionName << DestinationStr << SourceStr);
981 }
982 
983 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
984                                      Scope::ScopeFlags NeededScopeFlags,
985                                      unsigned DiagID) {
986   // Scopes aren't available during instantiation. Fortunately, builtin
987   // functions cannot be template args so they cannot be formed through template
988   // instantiation. Therefore checking once during the parse is sufficient.
989   if (SemaRef.inTemplateInstantiation())
990     return false;
991 
992   Scope *S = SemaRef.getCurScope();
993   while (S && !S->isSEHExceptScope())
994     S = S->getParent();
995   if (!S || !(S->getFlags() & NeededScopeFlags)) {
996     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
997     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
998         << DRE->getDecl()->getIdentifier();
999     return true;
1000   }
1001 
1002   return false;
1003 }
1004 
1005 static inline bool isBlockPointer(Expr *Arg) {
1006   return Arg->getType()->isBlockPointerType();
1007 }
1008 
1009 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
1010 /// void*, which is a requirement of device side enqueue.
1011 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
1012   const BlockPointerType *BPT =
1013       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
1014   ArrayRef<QualType> Params =
1015       BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes();
1016   unsigned ArgCounter = 0;
1017   bool IllegalParams = false;
1018   // Iterate through the block parameters until either one is found that is not
1019   // a local void*, or the block is valid.
1020   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
1021        I != E; ++I, ++ArgCounter) {
1022     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
1023         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
1024             LangAS::opencl_local) {
1025       // Get the location of the error. If a block literal has been passed
1026       // (BlockExpr) then we can point straight to the offending argument,
1027       // else we just point to the variable reference.
1028       SourceLocation ErrorLoc;
1029       if (isa<BlockExpr>(BlockArg)) {
1030         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
1031         ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
1032       } else if (isa<DeclRefExpr>(BlockArg)) {
1033         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
1034       }
1035       S.Diag(ErrorLoc,
1036              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
1037       IllegalParams = true;
1038     }
1039   }
1040 
1041   return IllegalParams;
1042 }
1043 
1044 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
1045   // OpenCL device can support extension but not the feature as extension
1046   // requires subgroup independent forward progress, but subgroup independent
1047   // forward progress is optional in OpenCL C 3.0 __opencl_c_subgroups feature.
1048   if (!S.getOpenCLOptions().isSupported("cl_khr_subgroups", S.getLangOpts()) &&
1049       !S.getOpenCLOptions().isSupported("__opencl_c_subgroups",
1050                                         S.getLangOpts())) {
1051     S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
1052         << 1 << Call->getDirectCallee()
1053         << "cl_khr_subgroups or __opencl_c_subgroups";
1054     return true;
1055   }
1056   return false;
1057 }
1058 
1059 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
1060   if (checkArgCount(S, TheCall, 2))
1061     return true;
1062 
1063   if (checkOpenCLSubgroupExt(S, TheCall))
1064     return true;
1065 
1066   // First argument is an ndrange_t type.
1067   Expr *NDRangeArg = TheCall->getArg(0);
1068   if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
1069     S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1070         << TheCall->getDirectCallee() << "'ndrange_t'";
1071     return true;
1072   }
1073 
1074   Expr *BlockArg = TheCall->getArg(1);
1075   if (!isBlockPointer(BlockArg)) {
1076     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1077         << TheCall->getDirectCallee() << "block";
1078     return true;
1079   }
1080   return checkOpenCLBlockArgs(S, BlockArg);
1081 }
1082 
1083 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
1084 /// get_kernel_work_group_size
1085 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
1086 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
1087   if (checkArgCount(S, TheCall, 1))
1088     return true;
1089 
1090   Expr *BlockArg = TheCall->getArg(0);
1091   if (!isBlockPointer(BlockArg)) {
1092     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1093         << TheCall->getDirectCallee() << "block";
1094     return true;
1095   }
1096   return checkOpenCLBlockArgs(S, BlockArg);
1097 }
1098 
1099 /// Diagnose integer type and any valid implicit conversion to it.
1100 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
1101                                       const QualType &IntType);
1102 
1103 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
1104                                             unsigned Start, unsigned End) {
1105   bool IllegalParams = false;
1106   for (unsigned I = Start; I <= End; ++I)
1107     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
1108                                               S.Context.getSizeType());
1109   return IllegalParams;
1110 }
1111 
1112 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
1113 /// 'local void*' parameter of passed block.
1114 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
1115                                            Expr *BlockArg,
1116                                            unsigned NumNonVarArgs) {
1117   const BlockPointerType *BPT =
1118       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
1119   unsigned NumBlockParams =
1120       BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams();
1121   unsigned TotalNumArgs = TheCall->getNumArgs();
1122 
1123   // For each argument passed to the block, a corresponding uint needs to
1124   // be passed to describe the size of the local memory.
1125   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
1126     S.Diag(TheCall->getBeginLoc(),
1127            diag::err_opencl_enqueue_kernel_local_size_args);
1128     return true;
1129   }
1130 
1131   // Check that the sizes of the local memory are specified by integers.
1132   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
1133                                          TotalNumArgs - 1);
1134 }
1135 
1136 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
1137 /// overload formats specified in Table 6.13.17.1.
1138 /// int enqueue_kernel(queue_t queue,
1139 ///                    kernel_enqueue_flags_t flags,
1140 ///                    const ndrange_t ndrange,
1141 ///                    void (^block)(void))
1142 /// int enqueue_kernel(queue_t queue,
1143 ///                    kernel_enqueue_flags_t flags,
1144 ///                    const ndrange_t ndrange,
1145 ///                    uint num_events_in_wait_list,
1146 ///                    clk_event_t *event_wait_list,
1147 ///                    clk_event_t *event_ret,
1148 ///                    void (^block)(void))
1149 /// int enqueue_kernel(queue_t queue,
1150 ///                    kernel_enqueue_flags_t flags,
1151 ///                    const ndrange_t ndrange,
1152 ///                    void (^block)(local void*, ...),
1153 ///                    uint size0, ...)
1154 /// int enqueue_kernel(queue_t queue,
1155 ///                    kernel_enqueue_flags_t flags,
1156 ///                    const ndrange_t ndrange,
1157 ///                    uint num_events_in_wait_list,
1158 ///                    clk_event_t *event_wait_list,
1159 ///                    clk_event_t *event_ret,
1160 ///                    void (^block)(local void*, ...),
1161 ///                    uint size0, ...)
1162 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
1163   unsigned NumArgs = TheCall->getNumArgs();
1164 
1165   if (NumArgs < 4) {
1166     S.Diag(TheCall->getBeginLoc(),
1167            diag::err_typecheck_call_too_few_args_at_least)
1168         << 0 << 4 << NumArgs;
1169     return true;
1170   }
1171 
1172   Expr *Arg0 = TheCall->getArg(0);
1173   Expr *Arg1 = TheCall->getArg(1);
1174   Expr *Arg2 = TheCall->getArg(2);
1175   Expr *Arg3 = TheCall->getArg(3);
1176 
1177   // First argument always needs to be a queue_t type.
1178   if (!Arg0->getType()->isQueueT()) {
1179     S.Diag(TheCall->getArg(0)->getBeginLoc(),
1180            diag::err_opencl_builtin_expected_type)
1181         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
1182     return true;
1183   }
1184 
1185   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
1186   if (!Arg1->getType()->isIntegerType()) {
1187     S.Diag(TheCall->getArg(1)->getBeginLoc(),
1188            diag::err_opencl_builtin_expected_type)
1189         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
1190     return true;
1191   }
1192 
1193   // Third argument is always an ndrange_t type.
1194   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
1195     S.Diag(TheCall->getArg(2)->getBeginLoc(),
1196            diag::err_opencl_builtin_expected_type)
1197         << TheCall->getDirectCallee() << "'ndrange_t'";
1198     return true;
1199   }
1200 
1201   // With four arguments, there is only one form that the function could be
1202   // called in: no events and no variable arguments.
1203   if (NumArgs == 4) {
1204     // check that the last argument is the right block type.
1205     if (!isBlockPointer(Arg3)) {
1206       S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1207           << TheCall->getDirectCallee() << "block";
1208       return true;
1209     }
1210     // we have a block type, check the prototype
1211     const BlockPointerType *BPT =
1212         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
1213     if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) {
1214       S.Diag(Arg3->getBeginLoc(),
1215              diag::err_opencl_enqueue_kernel_blocks_no_args);
1216       return true;
1217     }
1218     return false;
1219   }
1220   // we can have block + varargs.
1221   if (isBlockPointer(Arg3))
1222     return (checkOpenCLBlockArgs(S, Arg3) ||
1223             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
1224   // last two cases with either exactly 7 args or 7 args and varargs.
1225   if (NumArgs >= 7) {
1226     // check common block argument.
1227     Expr *Arg6 = TheCall->getArg(6);
1228     if (!isBlockPointer(Arg6)) {
1229       S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1230           << TheCall->getDirectCallee() << "block";
1231       return true;
1232     }
1233     if (checkOpenCLBlockArgs(S, Arg6))
1234       return true;
1235 
1236     // Forth argument has to be any integer type.
1237     if (!Arg3->getType()->isIntegerType()) {
1238       S.Diag(TheCall->getArg(3)->getBeginLoc(),
1239              diag::err_opencl_builtin_expected_type)
1240           << TheCall->getDirectCallee() << "integer";
1241       return true;
1242     }
1243     // check remaining common arguments.
1244     Expr *Arg4 = TheCall->getArg(4);
1245     Expr *Arg5 = TheCall->getArg(5);
1246 
1247     // Fifth argument is always passed as a pointer to clk_event_t.
1248     if (!Arg4->isNullPointerConstant(S.Context,
1249                                      Expr::NPC_ValueDependentIsNotNull) &&
1250         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
1251       S.Diag(TheCall->getArg(4)->getBeginLoc(),
1252              diag::err_opencl_builtin_expected_type)
1253           << TheCall->getDirectCallee()
1254           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1255       return true;
1256     }
1257 
1258     // Sixth argument is always passed as a pointer to clk_event_t.
1259     if (!Arg5->isNullPointerConstant(S.Context,
1260                                      Expr::NPC_ValueDependentIsNotNull) &&
1261         !(Arg5->getType()->isPointerType() &&
1262           Arg5->getType()->getPointeeType()->isClkEventT())) {
1263       S.Diag(TheCall->getArg(5)->getBeginLoc(),
1264              diag::err_opencl_builtin_expected_type)
1265           << TheCall->getDirectCallee()
1266           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1267       return true;
1268     }
1269 
1270     if (NumArgs == 7)
1271       return false;
1272 
1273     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
1274   }
1275 
1276   // None of the specific case has been detected, give generic error
1277   S.Diag(TheCall->getBeginLoc(),
1278          diag::err_opencl_enqueue_kernel_incorrect_args);
1279   return true;
1280 }
1281 
1282 /// Returns OpenCL access qual.
1283 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
1284     return D->getAttr<OpenCLAccessAttr>();
1285 }
1286 
1287 /// Returns true if pipe element type is different from the pointer.
1288 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
1289   const Expr *Arg0 = Call->getArg(0);
1290   // First argument type should always be pipe.
1291   if (!Arg0->getType()->isPipeType()) {
1292     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1293         << Call->getDirectCallee() << Arg0->getSourceRange();
1294     return true;
1295   }
1296   OpenCLAccessAttr *AccessQual =
1297       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
1298   // Validates the access qualifier is compatible with the call.
1299   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
1300   // read_only and write_only, and assumed to be read_only if no qualifier is
1301   // specified.
1302   switch (Call->getDirectCallee()->getBuiltinID()) {
1303   case Builtin::BIread_pipe:
1304   case Builtin::BIreserve_read_pipe:
1305   case Builtin::BIcommit_read_pipe:
1306   case Builtin::BIwork_group_reserve_read_pipe:
1307   case Builtin::BIsub_group_reserve_read_pipe:
1308   case Builtin::BIwork_group_commit_read_pipe:
1309   case Builtin::BIsub_group_commit_read_pipe:
1310     if (!(!AccessQual || AccessQual->isReadOnly())) {
1311       S.Diag(Arg0->getBeginLoc(),
1312              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1313           << "read_only" << Arg0->getSourceRange();
1314       return true;
1315     }
1316     break;
1317   case Builtin::BIwrite_pipe:
1318   case Builtin::BIreserve_write_pipe:
1319   case Builtin::BIcommit_write_pipe:
1320   case Builtin::BIwork_group_reserve_write_pipe:
1321   case Builtin::BIsub_group_reserve_write_pipe:
1322   case Builtin::BIwork_group_commit_write_pipe:
1323   case Builtin::BIsub_group_commit_write_pipe:
1324     if (!(AccessQual && AccessQual->isWriteOnly())) {
1325       S.Diag(Arg0->getBeginLoc(),
1326              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1327           << "write_only" << Arg0->getSourceRange();
1328       return true;
1329     }
1330     break;
1331   default:
1332     break;
1333   }
1334   return false;
1335 }
1336 
1337 /// Returns true if pipe element type is different from the pointer.
1338 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
1339   const Expr *Arg0 = Call->getArg(0);
1340   const Expr *ArgIdx = Call->getArg(Idx);
1341   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
1342   const QualType EltTy = PipeTy->getElementType();
1343   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
1344   // The Idx argument should be a pointer and the type of the pointer and
1345   // the type of pipe element should also be the same.
1346   if (!ArgTy ||
1347       !S.Context.hasSameType(
1348           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
1349     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1350         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
1351         << ArgIdx->getType() << ArgIdx->getSourceRange();
1352     return true;
1353   }
1354   return false;
1355 }
1356 
1357 // Performs semantic analysis for the read/write_pipe call.
1358 // \param S Reference to the semantic analyzer.
1359 // \param Call A pointer to the builtin call.
1360 // \return True if a semantic error has been found, false otherwise.
1361 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
1362   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
1363   // functions have two forms.
1364   switch (Call->getNumArgs()) {
1365   case 2:
1366     if (checkOpenCLPipeArg(S, Call))
1367       return true;
1368     // The call with 2 arguments should be
1369     // read/write_pipe(pipe T, T*).
1370     // Check packet type T.
1371     if (checkOpenCLPipePacketType(S, Call, 1))
1372       return true;
1373     break;
1374 
1375   case 4: {
1376     if (checkOpenCLPipeArg(S, Call))
1377       return true;
1378     // The call with 4 arguments should be
1379     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
1380     // Check reserve_id_t.
1381     if (!Call->getArg(1)->getType()->isReserveIDT()) {
1382       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1383           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1384           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1385       return true;
1386     }
1387 
1388     // Check the index.
1389     const Expr *Arg2 = Call->getArg(2);
1390     if (!Arg2->getType()->isIntegerType() &&
1391         !Arg2->getType()->isUnsignedIntegerType()) {
1392       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1393           << Call->getDirectCallee() << S.Context.UnsignedIntTy
1394           << Arg2->getType() << Arg2->getSourceRange();
1395       return true;
1396     }
1397 
1398     // Check packet type T.
1399     if (checkOpenCLPipePacketType(S, Call, 3))
1400       return true;
1401   } break;
1402   default:
1403     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
1404         << Call->getDirectCallee() << Call->getSourceRange();
1405     return true;
1406   }
1407 
1408   return false;
1409 }
1410 
1411 // Performs a semantic analysis on the {work_group_/sub_group_
1412 //        /_}reserve_{read/write}_pipe
1413 // \param S Reference to the semantic analyzer.
1414 // \param Call The call to the builtin function to be analyzed.
1415 // \return True if a semantic error was found, false otherwise.
1416 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
1417   if (checkArgCount(S, Call, 2))
1418     return true;
1419 
1420   if (checkOpenCLPipeArg(S, Call))
1421     return true;
1422 
1423   // Check the reserve size.
1424   if (!Call->getArg(1)->getType()->isIntegerType() &&
1425       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
1426     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1427         << Call->getDirectCallee() << S.Context.UnsignedIntTy
1428         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1429     return true;
1430   }
1431 
1432   // Since return type of reserve_read/write_pipe built-in function is
1433   // reserve_id_t, which is not defined in the builtin def file , we used int
1434   // as return type and need to override the return type of these functions.
1435   Call->setType(S.Context.OCLReserveIDTy);
1436 
1437   return false;
1438 }
1439 
1440 // Performs a semantic analysis on {work_group_/sub_group_
1441 //        /_}commit_{read/write}_pipe
1442 // \param S Reference to the semantic analyzer.
1443 // \param Call The call to the builtin function to be analyzed.
1444 // \return True if a semantic error was found, false otherwise.
1445 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
1446   if (checkArgCount(S, Call, 2))
1447     return true;
1448 
1449   if (checkOpenCLPipeArg(S, Call))
1450     return true;
1451 
1452   // Check reserve_id_t.
1453   if (!Call->getArg(1)->getType()->isReserveIDT()) {
1454     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1455         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1456         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1457     return true;
1458   }
1459 
1460   return false;
1461 }
1462 
1463 // Performs a semantic analysis on the call to built-in Pipe
1464 //        Query Functions.
1465 // \param S Reference to the semantic analyzer.
1466 // \param Call The call to the builtin function to be analyzed.
1467 // \return True if a semantic error was found, false otherwise.
1468 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
1469   if (checkArgCount(S, Call, 1))
1470     return true;
1471 
1472   if (!Call->getArg(0)->getType()->isPipeType()) {
1473     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1474         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
1475     return true;
1476   }
1477 
1478   return false;
1479 }
1480 
1481 // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
1482 // Performs semantic analysis for the to_global/local/private call.
1483 // \param S Reference to the semantic analyzer.
1484 // \param BuiltinID ID of the builtin function.
1485 // \param Call A pointer to the builtin call.
1486 // \return True if a semantic error has been found, false otherwise.
1487 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
1488                                     CallExpr *Call) {
1489   if (checkArgCount(S, Call, 1))
1490     return true;
1491 
1492   auto RT = Call->getArg(0)->getType();
1493   if (!RT->isPointerType() || RT->getPointeeType()
1494       .getAddressSpace() == LangAS::opencl_constant) {
1495     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
1496         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
1497     return true;
1498   }
1499 
1500   if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
1501     S.Diag(Call->getArg(0)->getBeginLoc(),
1502            diag::warn_opencl_generic_address_space_arg)
1503         << Call->getDirectCallee()->getNameInfo().getAsString()
1504         << Call->getArg(0)->getSourceRange();
1505   }
1506 
1507   RT = RT->getPointeeType();
1508   auto Qual = RT.getQualifiers();
1509   switch (BuiltinID) {
1510   case Builtin::BIto_global:
1511     Qual.setAddressSpace(LangAS::opencl_global);
1512     break;
1513   case Builtin::BIto_local:
1514     Qual.setAddressSpace(LangAS::opencl_local);
1515     break;
1516   case Builtin::BIto_private:
1517     Qual.setAddressSpace(LangAS::opencl_private);
1518     break;
1519   default:
1520     llvm_unreachable("Invalid builtin function");
1521   }
1522   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
1523       RT.getUnqualifiedType(), Qual)));
1524 
1525   return false;
1526 }
1527 
1528 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
1529   if (checkArgCount(S, TheCall, 1))
1530     return ExprError();
1531 
1532   // Compute __builtin_launder's parameter type from the argument.
1533   // The parameter type is:
1534   //  * The type of the argument if it's not an array or function type,
1535   //  Otherwise,
1536   //  * The decayed argument type.
1537   QualType ParamTy = [&]() {
1538     QualType ArgTy = TheCall->getArg(0)->getType();
1539     if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1540       return S.Context.getPointerType(Ty->getElementType());
1541     if (ArgTy->isFunctionType()) {
1542       return S.Context.getPointerType(ArgTy);
1543     }
1544     return ArgTy;
1545   }();
1546 
1547   TheCall->setType(ParamTy);
1548 
1549   auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
1550     if (!ParamTy->isPointerType())
1551       return 0;
1552     if (ParamTy->isFunctionPointerType())
1553       return 1;
1554     if (ParamTy->isVoidPointerType())
1555       return 2;
1556     return llvm::Optional<unsigned>{};
1557   }();
1558   if (DiagSelect.hasValue()) {
1559     S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1560         << DiagSelect.getValue() << TheCall->getSourceRange();
1561     return ExprError();
1562   }
1563 
1564   // We either have an incomplete class type, or we have a class template
1565   // whose instantiation has not been forced. Example:
1566   //
1567   //   template <class T> struct Foo { T value; };
1568   //   Foo<int> *p = nullptr;
1569   //   auto *d = __builtin_launder(p);
1570   if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1571                             diag::err_incomplete_type))
1572     return ExprError();
1573 
1574   assert(ParamTy->getPointeeType()->isObjectType() &&
1575          "Unhandled non-object pointer case");
1576 
1577   InitializedEntity Entity =
1578       InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
1579   ExprResult Arg =
1580       S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1581   if (Arg.isInvalid())
1582     return ExprError();
1583   TheCall->setArg(0, Arg.get());
1584 
1585   return TheCall;
1586 }
1587 
1588 // Emit an error and return true if the current object format type is in the
1589 // list of unsupported types.
1590 static bool CheckBuiltinTargetNotInUnsupported(
1591     Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1592     ArrayRef<llvm::Triple::ObjectFormatType> UnsupportedObjectFormatTypes) {
1593   llvm::Triple::ObjectFormatType CurObjFormat =
1594       S.getASTContext().getTargetInfo().getTriple().getObjectFormat();
1595   if (llvm::is_contained(UnsupportedObjectFormatTypes, CurObjFormat)) {
1596     S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1597         << TheCall->getSourceRange();
1598     return true;
1599   }
1600   return false;
1601 }
1602 
1603 // Emit an error and return true if the current architecture is not in the list
1604 // of supported architectures.
1605 static bool
1606 CheckBuiltinTargetInSupported(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1607                               ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
1608   llvm::Triple::ArchType CurArch =
1609       S.getASTContext().getTargetInfo().getTriple().getArch();
1610   if (llvm::is_contained(SupportedArchs, CurArch))
1611     return false;
1612   S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1613       << TheCall->getSourceRange();
1614   return true;
1615 }
1616 
1617 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
1618                                  SourceLocation CallSiteLoc);
1619 
1620 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
1621                                       CallExpr *TheCall) {
1622   switch (TI.getTriple().getArch()) {
1623   default:
1624     // Some builtins don't require additional checking, so just consider these
1625     // acceptable.
1626     return false;
1627   case llvm::Triple::arm:
1628   case llvm::Triple::armeb:
1629   case llvm::Triple::thumb:
1630   case llvm::Triple::thumbeb:
1631     return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
1632   case llvm::Triple::aarch64:
1633   case llvm::Triple::aarch64_32:
1634   case llvm::Triple::aarch64_be:
1635     return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
1636   case llvm::Triple::bpfeb:
1637   case llvm::Triple::bpfel:
1638     return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
1639   case llvm::Triple::hexagon:
1640     return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
1641   case llvm::Triple::mips:
1642   case llvm::Triple::mipsel:
1643   case llvm::Triple::mips64:
1644   case llvm::Triple::mips64el:
1645     return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
1646   case llvm::Triple::systemz:
1647     return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
1648   case llvm::Triple::x86:
1649   case llvm::Triple::x86_64:
1650     return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall);
1651   case llvm::Triple::ppc:
1652   case llvm::Triple::ppcle:
1653   case llvm::Triple::ppc64:
1654   case llvm::Triple::ppc64le:
1655     return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
1656   case llvm::Triple::amdgcn:
1657     return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
1658   case llvm::Triple::riscv32:
1659   case llvm::Triple::riscv64:
1660     return CheckRISCVBuiltinFunctionCall(TI, BuiltinID, TheCall);
1661   }
1662 }
1663 
1664 ExprResult
1665 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
1666                                CallExpr *TheCall) {
1667   ExprResult TheCallResult(TheCall);
1668 
1669   // Find out if any arguments are required to be integer constant expressions.
1670   unsigned ICEArguments = 0;
1671   ASTContext::GetBuiltinTypeError Error;
1672   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
1673   if (Error != ASTContext::GE_None)
1674     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
1675 
1676   // If any arguments are required to be ICE's, check and diagnose.
1677   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
1678     // Skip arguments not required to be ICE's.
1679     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
1680 
1681     llvm::APSInt Result;
1682     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
1683       return true;
1684     ICEArguments &= ~(1 << ArgNo);
1685   }
1686 
1687   switch (BuiltinID) {
1688   case Builtin::BI__builtin___CFStringMakeConstantString:
1689     // CFStringMakeConstantString is currently not implemented for GOFF (i.e.,
1690     // on z/OS) and for XCOFF (i.e., on AIX). Emit unsupported
1691     if (CheckBuiltinTargetNotInUnsupported(
1692             *this, BuiltinID, TheCall,
1693             {llvm::Triple::GOFF, llvm::Triple::XCOFF}))
1694       return ExprError();
1695     assert(TheCall->getNumArgs() == 1 &&
1696            "Wrong # arguments to builtin CFStringMakeConstantString");
1697     if (CheckObjCString(TheCall->getArg(0)))
1698       return ExprError();
1699     break;
1700   case Builtin::BI__builtin_ms_va_start:
1701   case Builtin::BI__builtin_stdarg_start:
1702   case Builtin::BI__builtin_va_start:
1703     if (SemaBuiltinVAStart(BuiltinID, TheCall))
1704       return ExprError();
1705     break;
1706   case Builtin::BI__va_start: {
1707     switch (Context.getTargetInfo().getTriple().getArch()) {
1708     case llvm::Triple::aarch64:
1709     case llvm::Triple::arm:
1710     case llvm::Triple::thumb:
1711       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
1712         return ExprError();
1713       break;
1714     default:
1715       if (SemaBuiltinVAStart(BuiltinID, TheCall))
1716         return ExprError();
1717       break;
1718     }
1719     break;
1720   }
1721 
1722   // The acquire, release, and no fence variants are ARM and AArch64 only.
1723   case Builtin::BI_interlockedbittestandset_acq:
1724   case Builtin::BI_interlockedbittestandset_rel:
1725   case Builtin::BI_interlockedbittestandset_nf:
1726   case Builtin::BI_interlockedbittestandreset_acq:
1727   case Builtin::BI_interlockedbittestandreset_rel:
1728   case Builtin::BI_interlockedbittestandreset_nf:
1729     if (CheckBuiltinTargetInSupported(
1730             *this, BuiltinID, TheCall,
1731             {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
1732       return ExprError();
1733     break;
1734 
1735   // The 64-bit bittest variants are x64, ARM, and AArch64 only.
1736   case Builtin::BI_bittest64:
1737   case Builtin::BI_bittestandcomplement64:
1738   case Builtin::BI_bittestandreset64:
1739   case Builtin::BI_bittestandset64:
1740   case Builtin::BI_interlockedbittestandreset64:
1741   case Builtin::BI_interlockedbittestandset64:
1742     if (CheckBuiltinTargetInSupported(*this, BuiltinID, TheCall,
1743                                       {llvm::Triple::x86_64, llvm::Triple::arm,
1744                                        llvm::Triple::thumb,
1745                                        llvm::Triple::aarch64}))
1746       return ExprError();
1747     break;
1748 
1749   case Builtin::BI__builtin_isgreater:
1750   case Builtin::BI__builtin_isgreaterequal:
1751   case Builtin::BI__builtin_isless:
1752   case Builtin::BI__builtin_islessequal:
1753   case Builtin::BI__builtin_islessgreater:
1754   case Builtin::BI__builtin_isunordered:
1755     if (SemaBuiltinUnorderedCompare(TheCall))
1756       return ExprError();
1757     break;
1758   case Builtin::BI__builtin_fpclassify:
1759     if (SemaBuiltinFPClassification(TheCall, 6))
1760       return ExprError();
1761     break;
1762   case Builtin::BI__builtin_isfinite:
1763   case Builtin::BI__builtin_isinf:
1764   case Builtin::BI__builtin_isinf_sign:
1765   case Builtin::BI__builtin_isnan:
1766   case Builtin::BI__builtin_isnormal:
1767   case Builtin::BI__builtin_signbit:
1768   case Builtin::BI__builtin_signbitf:
1769   case Builtin::BI__builtin_signbitl:
1770     if (SemaBuiltinFPClassification(TheCall, 1))
1771       return ExprError();
1772     break;
1773   case Builtin::BI__builtin_shufflevector:
1774     return SemaBuiltinShuffleVector(TheCall);
1775     // TheCall will be freed by the smart pointer here, but that's fine, since
1776     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1777   case Builtin::BI__builtin_prefetch:
1778     if (SemaBuiltinPrefetch(TheCall))
1779       return ExprError();
1780     break;
1781   case Builtin::BI__builtin_alloca_with_align:
1782   case Builtin::BI__builtin_alloca_with_align_uninitialized:
1783     if (SemaBuiltinAllocaWithAlign(TheCall))
1784       return ExprError();
1785     LLVM_FALLTHROUGH;
1786   case Builtin::BI__builtin_alloca:
1787   case Builtin::BI__builtin_alloca_uninitialized:
1788     Diag(TheCall->getBeginLoc(), diag::warn_alloca)
1789         << TheCall->getDirectCallee();
1790     break;
1791   case Builtin::BI__arithmetic_fence:
1792     if (SemaBuiltinArithmeticFence(TheCall))
1793       return ExprError();
1794     break;
1795   case Builtin::BI__assume:
1796   case Builtin::BI__builtin_assume:
1797     if (SemaBuiltinAssume(TheCall))
1798       return ExprError();
1799     break;
1800   case Builtin::BI__builtin_assume_aligned:
1801     if (SemaBuiltinAssumeAligned(TheCall))
1802       return ExprError();
1803     break;
1804   case Builtin::BI__builtin_dynamic_object_size:
1805   case Builtin::BI__builtin_object_size:
1806     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1807       return ExprError();
1808     break;
1809   case Builtin::BI__builtin_longjmp:
1810     if (SemaBuiltinLongjmp(TheCall))
1811       return ExprError();
1812     break;
1813   case Builtin::BI__builtin_setjmp:
1814     if (SemaBuiltinSetjmp(TheCall))
1815       return ExprError();
1816     break;
1817   case Builtin::BI__builtin_classify_type:
1818     if (checkArgCount(*this, TheCall, 1)) return true;
1819     TheCall->setType(Context.IntTy);
1820     break;
1821   case Builtin::BI__builtin_complex:
1822     if (SemaBuiltinComplex(TheCall))
1823       return ExprError();
1824     break;
1825   case Builtin::BI__builtin_constant_p: {
1826     if (checkArgCount(*this, TheCall, 1)) return true;
1827     ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
1828     if (Arg.isInvalid()) return true;
1829     TheCall->setArg(0, Arg.get());
1830     TheCall->setType(Context.IntTy);
1831     break;
1832   }
1833   case Builtin::BI__builtin_launder:
1834     return SemaBuiltinLaunder(*this, TheCall);
1835   case Builtin::BI__sync_fetch_and_add:
1836   case Builtin::BI__sync_fetch_and_add_1:
1837   case Builtin::BI__sync_fetch_and_add_2:
1838   case Builtin::BI__sync_fetch_and_add_4:
1839   case Builtin::BI__sync_fetch_and_add_8:
1840   case Builtin::BI__sync_fetch_and_add_16:
1841   case Builtin::BI__sync_fetch_and_sub:
1842   case Builtin::BI__sync_fetch_and_sub_1:
1843   case Builtin::BI__sync_fetch_and_sub_2:
1844   case Builtin::BI__sync_fetch_and_sub_4:
1845   case Builtin::BI__sync_fetch_and_sub_8:
1846   case Builtin::BI__sync_fetch_and_sub_16:
1847   case Builtin::BI__sync_fetch_and_or:
1848   case Builtin::BI__sync_fetch_and_or_1:
1849   case Builtin::BI__sync_fetch_and_or_2:
1850   case Builtin::BI__sync_fetch_and_or_4:
1851   case Builtin::BI__sync_fetch_and_or_8:
1852   case Builtin::BI__sync_fetch_and_or_16:
1853   case Builtin::BI__sync_fetch_and_and:
1854   case Builtin::BI__sync_fetch_and_and_1:
1855   case Builtin::BI__sync_fetch_and_and_2:
1856   case Builtin::BI__sync_fetch_and_and_4:
1857   case Builtin::BI__sync_fetch_and_and_8:
1858   case Builtin::BI__sync_fetch_and_and_16:
1859   case Builtin::BI__sync_fetch_and_xor:
1860   case Builtin::BI__sync_fetch_and_xor_1:
1861   case Builtin::BI__sync_fetch_and_xor_2:
1862   case Builtin::BI__sync_fetch_and_xor_4:
1863   case Builtin::BI__sync_fetch_and_xor_8:
1864   case Builtin::BI__sync_fetch_and_xor_16:
1865   case Builtin::BI__sync_fetch_and_nand:
1866   case Builtin::BI__sync_fetch_and_nand_1:
1867   case Builtin::BI__sync_fetch_and_nand_2:
1868   case Builtin::BI__sync_fetch_and_nand_4:
1869   case Builtin::BI__sync_fetch_and_nand_8:
1870   case Builtin::BI__sync_fetch_and_nand_16:
1871   case Builtin::BI__sync_add_and_fetch:
1872   case Builtin::BI__sync_add_and_fetch_1:
1873   case Builtin::BI__sync_add_and_fetch_2:
1874   case Builtin::BI__sync_add_and_fetch_4:
1875   case Builtin::BI__sync_add_and_fetch_8:
1876   case Builtin::BI__sync_add_and_fetch_16:
1877   case Builtin::BI__sync_sub_and_fetch:
1878   case Builtin::BI__sync_sub_and_fetch_1:
1879   case Builtin::BI__sync_sub_and_fetch_2:
1880   case Builtin::BI__sync_sub_and_fetch_4:
1881   case Builtin::BI__sync_sub_and_fetch_8:
1882   case Builtin::BI__sync_sub_and_fetch_16:
1883   case Builtin::BI__sync_and_and_fetch:
1884   case Builtin::BI__sync_and_and_fetch_1:
1885   case Builtin::BI__sync_and_and_fetch_2:
1886   case Builtin::BI__sync_and_and_fetch_4:
1887   case Builtin::BI__sync_and_and_fetch_8:
1888   case Builtin::BI__sync_and_and_fetch_16:
1889   case Builtin::BI__sync_or_and_fetch:
1890   case Builtin::BI__sync_or_and_fetch_1:
1891   case Builtin::BI__sync_or_and_fetch_2:
1892   case Builtin::BI__sync_or_and_fetch_4:
1893   case Builtin::BI__sync_or_and_fetch_8:
1894   case Builtin::BI__sync_or_and_fetch_16:
1895   case Builtin::BI__sync_xor_and_fetch:
1896   case Builtin::BI__sync_xor_and_fetch_1:
1897   case Builtin::BI__sync_xor_and_fetch_2:
1898   case Builtin::BI__sync_xor_and_fetch_4:
1899   case Builtin::BI__sync_xor_and_fetch_8:
1900   case Builtin::BI__sync_xor_and_fetch_16:
1901   case Builtin::BI__sync_nand_and_fetch:
1902   case Builtin::BI__sync_nand_and_fetch_1:
1903   case Builtin::BI__sync_nand_and_fetch_2:
1904   case Builtin::BI__sync_nand_and_fetch_4:
1905   case Builtin::BI__sync_nand_and_fetch_8:
1906   case Builtin::BI__sync_nand_and_fetch_16:
1907   case Builtin::BI__sync_val_compare_and_swap:
1908   case Builtin::BI__sync_val_compare_and_swap_1:
1909   case Builtin::BI__sync_val_compare_and_swap_2:
1910   case Builtin::BI__sync_val_compare_and_swap_4:
1911   case Builtin::BI__sync_val_compare_and_swap_8:
1912   case Builtin::BI__sync_val_compare_and_swap_16:
1913   case Builtin::BI__sync_bool_compare_and_swap:
1914   case Builtin::BI__sync_bool_compare_and_swap_1:
1915   case Builtin::BI__sync_bool_compare_and_swap_2:
1916   case Builtin::BI__sync_bool_compare_and_swap_4:
1917   case Builtin::BI__sync_bool_compare_and_swap_8:
1918   case Builtin::BI__sync_bool_compare_and_swap_16:
1919   case Builtin::BI__sync_lock_test_and_set:
1920   case Builtin::BI__sync_lock_test_and_set_1:
1921   case Builtin::BI__sync_lock_test_and_set_2:
1922   case Builtin::BI__sync_lock_test_and_set_4:
1923   case Builtin::BI__sync_lock_test_and_set_8:
1924   case Builtin::BI__sync_lock_test_and_set_16:
1925   case Builtin::BI__sync_lock_release:
1926   case Builtin::BI__sync_lock_release_1:
1927   case Builtin::BI__sync_lock_release_2:
1928   case Builtin::BI__sync_lock_release_4:
1929   case Builtin::BI__sync_lock_release_8:
1930   case Builtin::BI__sync_lock_release_16:
1931   case Builtin::BI__sync_swap:
1932   case Builtin::BI__sync_swap_1:
1933   case Builtin::BI__sync_swap_2:
1934   case Builtin::BI__sync_swap_4:
1935   case Builtin::BI__sync_swap_8:
1936   case Builtin::BI__sync_swap_16:
1937     return SemaBuiltinAtomicOverloaded(TheCallResult);
1938   case Builtin::BI__sync_synchronize:
1939     Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1940         << TheCall->getCallee()->getSourceRange();
1941     break;
1942   case Builtin::BI__builtin_nontemporal_load:
1943   case Builtin::BI__builtin_nontemporal_store:
1944     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1945   case Builtin::BI__builtin_memcpy_inline: {
1946     clang::Expr *SizeOp = TheCall->getArg(2);
1947     // We warn about copying to or from `nullptr` pointers when `size` is
1948     // greater than 0. When `size` is value dependent we cannot evaluate its
1949     // value so we bail out.
1950     if (SizeOp->isValueDependent())
1951       break;
1952     if (!SizeOp->EvaluateKnownConstInt(Context).isZero()) {
1953       CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
1954       CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
1955     }
1956     break;
1957   }
1958 #define BUILTIN(ID, TYPE, ATTRS)
1959 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1960   case Builtin::BI##ID: \
1961     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1962 #include "clang/Basic/Builtins.def"
1963   case Builtin::BI__annotation:
1964     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1965       return ExprError();
1966     break;
1967   case Builtin::BI__builtin_annotation:
1968     if (SemaBuiltinAnnotation(*this, TheCall))
1969       return ExprError();
1970     break;
1971   case Builtin::BI__builtin_addressof:
1972     if (SemaBuiltinAddressof(*this, TheCall))
1973       return ExprError();
1974     break;
1975   case Builtin::BI__builtin_function_start:
1976     if (SemaBuiltinFunctionStart(*this, TheCall))
1977       return ExprError();
1978     break;
1979   case Builtin::BI__builtin_is_aligned:
1980   case Builtin::BI__builtin_align_up:
1981   case Builtin::BI__builtin_align_down:
1982     if (SemaBuiltinAlignment(*this, TheCall, BuiltinID))
1983       return ExprError();
1984     break;
1985   case Builtin::BI__builtin_add_overflow:
1986   case Builtin::BI__builtin_sub_overflow:
1987   case Builtin::BI__builtin_mul_overflow:
1988     if (SemaBuiltinOverflow(*this, TheCall, BuiltinID))
1989       return ExprError();
1990     break;
1991   case Builtin::BI__builtin_operator_new:
1992   case Builtin::BI__builtin_operator_delete: {
1993     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1994     ExprResult Res =
1995         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1996     if (Res.isInvalid())
1997       CorrectDelayedTyposInExpr(TheCallResult.get());
1998     return Res;
1999   }
2000   case Builtin::BI__builtin_dump_struct: {
2001     // We first want to ensure we are called with 2 arguments
2002     if (checkArgCount(*this, TheCall, 2))
2003       return ExprError();
2004     // Ensure that the first argument is of type 'struct XX *'
2005     const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
2006     const QualType PtrArgType = PtrArg->getType();
2007     if (!PtrArgType->isPointerType() ||
2008         !PtrArgType->getPointeeType()->isRecordType()) {
2009       Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
2010           << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
2011           << "structure pointer";
2012       return ExprError();
2013     }
2014 
2015     // Ensure that the second argument is of type 'FunctionType'
2016     const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
2017     const QualType FnPtrArgType = FnPtrArg->getType();
2018     if (!FnPtrArgType->isPointerType()) {
2019       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
2020           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
2021           << FnPtrArgType << "'int (*)(const char *, ...)'";
2022       return ExprError();
2023     }
2024 
2025     const auto *FuncType =
2026         FnPtrArgType->getPointeeType()->getAs<FunctionType>();
2027 
2028     if (!FuncType) {
2029       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
2030           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
2031           << FnPtrArgType << "'int (*)(const char *, ...)'";
2032       return ExprError();
2033     }
2034 
2035     if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
2036       if (!FT->getNumParams()) {
2037         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
2038             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
2039             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
2040         return ExprError();
2041       }
2042       QualType PT = FT->getParamType(0);
2043       if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
2044           !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
2045           !PT->getPointeeType().isConstQualified()) {
2046         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
2047             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
2048             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
2049         return ExprError();
2050       }
2051     }
2052 
2053     TheCall->setType(Context.IntTy);
2054     break;
2055   }
2056   case Builtin::BI__builtin_expect_with_probability: {
2057     // We first want to ensure we are called with 3 arguments
2058     if (checkArgCount(*this, TheCall, 3))
2059       return ExprError();
2060     // then check probability is constant float in range [0.0, 1.0]
2061     const Expr *ProbArg = TheCall->getArg(2);
2062     SmallVector<PartialDiagnosticAt, 8> Notes;
2063     Expr::EvalResult Eval;
2064     Eval.Diag = &Notes;
2065     if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
2066         !Eval.Val.isFloat()) {
2067       Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
2068           << ProbArg->getSourceRange();
2069       for (const PartialDiagnosticAt &PDiag : Notes)
2070         Diag(PDiag.first, PDiag.second);
2071       return ExprError();
2072     }
2073     llvm::APFloat Probability = Eval.Val.getFloat();
2074     bool LoseInfo = false;
2075     Probability.convert(llvm::APFloat::IEEEdouble(),
2076                         llvm::RoundingMode::Dynamic, &LoseInfo);
2077     if (!(Probability >= llvm::APFloat(0.0) &&
2078           Probability <= llvm::APFloat(1.0))) {
2079       Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
2080           << ProbArg->getSourceRange();
2081       return ExprError();
2082     }
2083     break;
2084   }
2085   case Builtin::BI__builtin_preserve_access_index:
2086     if (SemaBuiltinPreserveAI(*this, TheCall))
2087       return ExprError();
2088     break;
2089   case Builtin::BI__builtin_call_with_static_chain:
2090     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
2091       return ExprError();
2092     break;
2093   case Builtin::BI__exception_code:
2094   case Builtin::BI_exception_code:
2095     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
2096                                  diag::err_seh___except_block))
2097       return ExprError();
2098     break;
2099   case Builtin::BI__exception_info:
2100   case Builtin::BI_exception_info:
2101     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
2102                                  diag::err_seh___except_filter))
2103       return ExprError();
2104     break;
2105   case Builtin::BI__GetExceptionInfo:
2106     if (checkArgCount(*this, TheCall, 1))
2107       return ExprError();
2108 
2109     if (CheckCXXThrowOperand(
2110             TheCall->getBeginLoc(),
2111             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
2112             TheCall))
2113       return ExprError();
2114 
2115     TheCall->setType(Context.VoidPtrTy);
2116     break;
2117   // OpenCL v2.0, s6.13.16 - Pipe functions
2118   case Builtin::BIread_pipe:
2119   case Builtin::BIwrite_pipe:
2120     // Since those two functions are declared with var args, we need a semantic
2121     // check for the argument.
2122     if (SemaBuiltinRWPipe(*this, TheCall))
2123       return ExprError();
2124     break;
2125   case Builtin::BIreserve_read_pipe:
2126   case Builtin::BIreserve_write_pipe:
2127   case Builtin::BIwork_group_reserve_read_pipe:
2128   case Builtin::BIwork_group_reserve_write_pipe:
2129     if (SemaBuiltinReserveRWPipe(*this, TheCall))
2130       return ExprError();
2131     break;
2132   case Builtin::BIsub_group_reserve_read_pipe:
2133   case Builtin::BIsub_group_reserve_write_pipe:
2134     if (checkOpenCLSubgroupExt(*this, TheCall) ||
2135         SemaBuiltinReserveRWPipe(*this, TheCall))
2136       return ExprError();
2137     break;
2138   case Builtin::BIcommit_read_pipe:
2139   case Builtin::BIcommit_write_pipe:
2140   case Builtin::BIwork_group_commit_read_pipe:
2141   case Builtin::BIwork_group_commit_write_pipe:
2142     if (SemaBuiltinCommitRWPipe(*this, TheCall))
2143       return ExprError();
2144     break;
2145   case Builtin::BIsub_group_commit_read_pipe:
2146   case Builtin::BIsub_group_commit_write_pipe:
2147     if (checkOpenCLSubgroupExt(*this, TheCall) ||
2148         SemaBuiltinCommitRWPipe(*this, TheCall))
2149       return ExprError();
2150     break;
2151   case Builtin::BIget_pipe_num_packets:
2152   case Builtin::BIget_pipe_max_packets:
2153     if (SemaBuiltinPipePackets(*this, TheCall))
2154       return ExprError();
2155     break;
2156   case Builtin::BIto_global:
2157   case Builtin::BIto_local:
2158   case Builtin::BIto_private:
2159     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
2160       return ExprError();
2161     break;
2162   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
2163   case Builtin::BIenqueue_kernel:
2164     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
2165       return ExprError();
2166     break;
2167   case Builtin::BIget_kernel_work_group_size:
2168   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
2169     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
2170       return ExprError();
2171     break;
2172   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
2173   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
2174     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
2175       return ExprError();
2176     break;
2177   case Builtin::BI__builtin_os_log_format:
2178     Cleanup.setExprNeedsCleanups(true);
2179     LLVM_FALLTHROUGH;
2180   case Builtin::BI__builtin_os_log_format_buffer_size:
2181     if (SemaBuiltinOSLogFormat(TheCall))
2182       return ExprError();
2183     break;
2184   case Builtin::BI__builtin_frame_address:
2185   case Builtin::BI__builtin_return_address: {
2186     if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
2187       return ExprError();
2188 
2189     // -Wframe-address warning if non-zero passed to builtin
2190     // return/frame address.
2191     Expr::EvalResult Result;
2192     if (!TheCall->getArg(0)->isValueDependent() &&
2193         TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
2194         Result.Val.getInt() != 0)
2195       Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
2196           << ((BuiltinID == Builtin::BI__builtin_return_address)
2197                   ? "__builtin_return_address"
2198                   : "__builtin_frame_address")
2199           << TheCall->getSourceRange();
2200     break;
2201   }
2202 
2203   // __builtin_elementwise_abs restricts the element type to signed integers or
2204   // floating point types only.
2205   case Builtin::BI__builtin_elementwise_abs: {
2206     if (PrepareBuiltinElementwiseMathOneArgCall(TheCall))
2207       return ExprError();
2208 
2209     QualType ArgTy = TheCall->getArg(0)->getType();
2210     QualType EltTy = ArgTy;
2211 
2212     if (auto *VecTy = EltTy->getAs<VectorType>())
2213       EltTy = VecTy->getElementType();
2214     if (EltTy->isUnsignedIntegerType()) {
2215       Diag(TheCall->getArg(0)->getBeginLoc(),
2216            diag::err_builtin_invalid_arg_type)
2217           << 1 << /* signed integer or float ty*/ 3 << ArgTy;
2218       return ExprError();
2219     }
2220     break;
2221   }
2222 
2223   // These builtins restrict the element type to floating point
2224   // types only.
2225   case Builtin::BI__builtin_elementwise_ceil:
2226   case Builtin::BI__builtin_elementwise_floor:
2227   case Builtin::BI__builtin_elementwise_roundeven:
2228   case Builtin::BI__builtin_elementwise_trunc: {
2229     if (PrepareBuiltinElementwiseMathOneArgCall(TheCall))
2230       return ExprError();
2231 
2232     QualType ArgTy = TheCall->getArg(0)->getType();
2233     QualType EltTy = ArgTy;
2234 
2235     if (auto *VecTy = EltTy->getAs<VectorType>())
2236       EltTy = VecTy->getElementType();
2237     if (!EltTy->isFloatingType()) {
2238       Diag(TheCall->getArg(0)->getBeginLoc(),
2239            diag::err_builtin_invalid_arg_type)
2240           << 1 << /* float ty*/ 5 << ArgTy;
2241 
2242       return ExprError();
2243     }
2244     break;
2245   }
2246 
2247   // These builtins restrict the element type to integer
2248   // types only.
2249   case Builtin::BI__builtin_elementwise_add_sat:
2250   case Builtin::BI__builtin_elementwise_sub_sat: {
2251     if (SemaBuiltinElementwiseMath(TheCall))
2252       return ExprError();
2253 
2254     const Expr *Arg = TheCall->getArg(0);
2255     QualType ArgTy = Arg->getType();
2256     QualType EltTy = ArgTy;
2257 
2258     if (auto *VecTy = EltTy->getAs<VectorType>())
2259       EltTy = VecTy->getElementType();
2260 
2261     if (!EltTy->isIntegerType()) {
2262       Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2263           << 1 << /* integer ty */ 6 << ArgTy;
2264       return ExprError();
2265     }
2266     break;
2267   }
2268 
2269   case Builtin::BI__builtin_elementwise_min:
2270   case Builtin::BI__builtin_elementwise_max:
2271     if (SemaBuiltinElementwiseMath(TheCall))
2272       return ExprError();
2273     break;
2274   case Builtin::BI__builtin_reduce_max:
2275   case Builtin::BI__builtin_reduce_min: {
2276     if (PrepareBuiltinReduceMathOneArgCall(TheCall))
2277       return ExprError();
2278 
2279     const Expr *Arg = TheCall->getArg(0);
2280     const auto *TyA = Arg->getType()->getAs<VectorType>();
2281     if (!TyA) {
2282       Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2283           << 1 << /* vector ty*/ 4 << Arg->getType();
2284       return ExprError();
2285     }
2286 
2287     TheCall->setType(TyA->getElementType());
2288     break;
2289   }
2290 
2291   // These builtins support vectors of integers only.
2292   case Builtin::BI__builtin_reduce_xor:
2293   case Builtin::BI__builtin_reduce_or:
2294   case Builtin::BI__builtin_reduce_and: {
2295     if (PrepareBuiltinReduceMathOneArgCall(TheCall))
2296       return ExprError();
2297 
2298     const Expr *Arg = TheCall->getArg(0);
2299     const auto *TyA = Arg->getType()->getAs<VectorType>();
2300     if (!TyA || !TyA->getElementType()->isIntegerType()) {
2301       Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2302           << 1  << /* vector of integers */ 6 << Arg->getType();
2303       return ExprError();
2304     }
2305     TheCall->setType(TyA->getElementType());
2306     break;
2307   }
2308 
2309   case Builtin::BI__builtin_matrix_transpose:
2310     return SemaBuiltinMatrixTranspose(TheCall, TheCallResult);
2311 
2312   case Builtin::BI__builtin_matrix_column_major_load:
2313     return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
2314 
2315   case Builtin::BI__builtin_matrix_column_major_store:
2316     return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
2317 
2318   case Builtin::BI__builtin_get_device_side_mangled_name: {
2319     auto Check = [](CallExpr *TheCall) {
2320       if (TheCall->getNumArgs() != 1)
2321         return false;
2322       auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());
2323       if (!DRE)
2324         return false;
2325       auto *D = DRE->getDecl();
2326       if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D))
2327         return false;
2328       return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
2329              D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
2330     };
2331     if (!Check(TheCall)) {
2332       Diag(TheCall->getBeginLoc(),
2333            diag::err_hip_invalid_args_builtin_mangled_name);
2334       return ExprError();
2335     }
2336   }
2337   }
2338 
2339   // Since the target specific builtins for each arch overlap, only check those
2340   // of the arch we are compiling for.
2341   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
2342     if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
2343       assert(Context.getAuxTargetInfo() &&
2344              "Aux Target Builtin, but not an aux target?");
2345 
2346       if (CheckTSBuiltinFunctionCall(
2347               *Context.getAuxTargetInfo(),
2348               Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
2349         return ExprError();
2350     } else {
2351       if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
2352                                      TheCall))
2353         return ExprError();
2354     }
2355   }
2356 
2357   return TheCallResult;
2358 }
2359 
2360 // Get the valid immediate range for the specified NEON type code.
2361 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
2362   NeonTypeFlags Type(t);
2363   int IsQuad = ForceQuad ? true : Type.isQuad();
2364   switch (Type.getEltType()) {
2365   case NeonTypeFlags::Int8:
2366   case NeonTypeFlags::Poly8:
2367     return shift ? 7 : (8 << IsQuad) - 1;
2368   case NeonTypeFlags::Int16:
2369   case NeonTypeFlags::Poly16:
2370     return shift ? 15 : (4 << IsQuad) - 1;
2371   case NeonTypeFlags::Int32:
2372     return shift ? 31 : (2 << IsQuad) - 1;
2373   case NeonTypeFlags::Int64:
2374   case NeonTypeFlags::Poly64:
2375     return shift ? 63 : (1 << IsQuad) - 1;
2376   case NeonTypeFlags::Poly128:
2377     return shift ? 127 : (1 << IsQuad) - 1;
2378   case NeonTypeFlags::Float16:
2379     assert(!shift && "cannot shift float types!");
2380     return (4 << IsQuad) - 1;
2381   case NeonTypeFlags::Float32:
2382     assert(!shift && "cannot shift float types!");
2383     return (2 << IsQuad) - 1;
2384   case NeonTypeFlags::Float64:
2385     assert(!shift && "cannot shift float types!");
2386     return (1 << IsQuad) - 1;
2387   case NeonTypeFlags::BFloat16:
2388     assert(!shift && "cannot shift float types!");
2389     return (4 << IsQuad) - 1;
2390   }
2391   llvm_unreachable("Invalid NeonTypeFlag!");
2392 }
2393 
2394 /// getNeonEltType - Return the QualType corresponding to the elements of
2395 /// the vector type specified by the NeonTypeFlags.  This is used to check
2396 /// the pointer arguments for Neon load/store intrinsics.
2397 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
2398                                bool IsPolyUnsigned, bool IsInt64Long) {
2399   switch (Flags.getEltType()) {
2400   case NeonTypeFlags::Int8:
2401     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
2402   case NeonTypeFlags::Int16:
2403     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
2404   case NeonTypeFlags::Int32:
2405     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
2406   case NeonTypeFlags::Int64:
2407     if (IsInt64Long)
2408       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
2409     else
2410       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
2411                                 : Context.LongLongTy;
2412   case NeonTypeFlags::Poly8:
2413     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
2414   case NeonTypeFlags::Poly16:
2415     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
2416   case NeonTypeFlags::Poly64:
2417     if (IsInt64Long)
2418       return Context.UnsignedLongTy;
2419     else
2420       return Context.UnsignedLongLongTy;
2421   case NeonTypeFlags::Poly128:
2422     break;
2423   case NeonTypeFlags::Float16:
2424     return Context.HalfTy;
2425   case NeonTypeFlags::Float32:
2426     return Context.FloatTy;
2427   case NeonTypeFlags::Float64:
2428     return Context.DoubleTy;
2429   case NeonTypeFlags::BFloat16:
2430     return Context.BFloat16Ty;
2431   }
2432   llvm_unreachable("Invalid NeonTypeFlag!");
2433 }
2434 
2435 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2436   // Range check SVE intrinsics that take immediate values.
2437   SmallVector<std::tuple<int,int,int>, 3> ImmChecks;
2438 
2439   switch (BuiltinID) {
2440   default:
2441     return false;
2442 #define GET_SVE_IMMEDIATE_CHECK
2443 #include "clang/Basic/arm_sve_sema_rangechecks.inc"
2444 #undef GET_SVE_IMMEDIATE_CHECK
2445   }
2446 
2447   // Perform all the immediate checks for this builtin call.
2448   bool HasError = false;
2449   for (auto &I : ImmChecks) {
2450     int ArgNum, CheckTy, ElementSizeInBits;
2451     std::tie(ArgNum, CheckTy, ElementSizeInBits) = I;
2452 
2453     typedef bool(*OptionSetCheckFnTy)(int64_t Value);
2454 
2455     // Function that checks whether the operand (ArgNum) is an immediate
2456     // that is one of the predefined values.
2457     auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm,
2458                                    int ErrDiag) -> bool {
2459       // We can't check the value of a dependent argument.
2460       Expr *Arg = TheCall->getArg(ArgNum);
2461       if (Arg->isTypeDependent() || Arg->isValueDependent())
2462         return false;
2463 
2464       // Check constant-ness first.
2465       llvm::APSInt Imm;
2466       if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm))
2467         return true;
2468 
2469       if (!CheckImm(Imm.getSExtValue()))
2470         return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange();
2471       return false;
2472     };
2473 
2474     switch ((SVETypeFlags::ImmCheckType)CheckTy) {
2475     case SVETypeFlags::ImmCheck0_31:
2476       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31))
2477         HasError = true;
2478       break;
2479     case SVETypeFlags::ImmCheck0_13:
2480       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13))
2481         HasError = true;
2482       break;
2483     case SVETypeFlags::ImmCheck1_16:
2484       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16))
2485         HasError = true;
2486       break;
2487     case SVETypeFlags::ImmCheck0_7:
2488       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7))
2489         HasError = true;
2490       break;
2491     case SVETypeFlags::ImmCheckExtract:
2492       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2493                                       (2048 / ElementSizeInBits) - 1))
2494         HasError = true;
2495       break;
2496     case SVETypeFlags::ImmCheckShiftRight:
2497       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits))
2498         HasError = true;
2499       break;
2500     case SVETypeFlags::ImmCheckShiftRightNarrow:
2501       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1,
2502                                       ElementSizeInBits / 2))
2503         HasError = true;
2504       break;
2505     case SVETypeFlags::ImmCheckShiftLeft:
2506       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2507                                       ElementSizeInBits - 1))
2508         HasError = true;
2509       break;
2510     case SVETypeFlags::ImmCheckLaneIndex:
2511       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2512                                       (128 / (1 * ElementSizeInBits)) - 1))
2513         HasError = true;
2514       break;
2515     case SVETypeFlags::ImmCheckLaneIndexCompRotate:
2516       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2517                                       (128 / (2 * ElementSizeInBits)) - 1))
2518         HasError = true;
2519       break;
2520     case SVETypeFlags::ImmCheckLaneIndexDot:
2521       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2522                                       (128 / (4 * ElementSizeInBits)) - 1))
2523         HasError = true;
2524       break;
2525     case SVETypeFlags::ImmCheckComplexRot90_270:
2526       if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; },
2527                               diag::err_rotation_argument_to_cadd))
2528         HasError = true;
2529       break;
2530     case SVETypeFlags::ImmCheckComplexRotAll90:
2531       if (CheckImmediateInSet(
2532               [](int64_t V) {
2533                 return V == 0 || V == 90 || V == 180 || V == 270;
2534               },
2535               diag::err_rotation_argument_to_cmla))
2536         HasError = true;
2537       break;
2538     case SVETypeFlags::ImmCheck0_1:
2539       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1))
2540         HasError = true;
2541       break;
2542     case SVETypeFlags::ImmCheck0_2:
2543       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2))
2544         HasError = true;
2545       break;
2546     case SVETypeFlags::ImmCheck0_3:
2547       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3))
2548         HasError = true;
2549       break;
2550     }
2551   }
2552 
2553   return HasError;
2554 }
2555 
2556 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI,
2557                                         unsigned BuiltinID, CallExpr *TheCall) {
2558   llvm::APSInt Result;
2559   uint64_t mask = 0;
2560   unsigned TV = 0;
2561   int PtrArgNum = -1;
2562   bool HasConstPtr = false;
2563   switch (BuiltinID) {
2564 #define GET_NEON_OVERLOAD_CHECK
2565 #include "clang/Basic/arm_neon.inc"
2566 #include "clang/Basic/arm_fp16.inc"
2567 #undef GET_NEON_OVERLOAD_CHECK
2568   }
2569 
2570   // For NEON intrinsics which are overloaded on vector element type, validate
2571   // the immediate which specifies which variant to emit.
2572   unsigned ImmArg = TheCall->getNumArgs()-1;
2573   if (mask) {
2574     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
2575       return true;
2576 
2577     TV = Result.getLimitedValue(64);
2578     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
2579       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
2580              << TheCall->getArg(ImmArg)->getSourceRange();
2581   }
2582 
2583   if (PtrArgNum >= 0) {
2584     // Check that pointer arguments have the specified type.
2585     Expr *Arg = TheCall->getArg(PtrArgNum);
2586     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
2587       Arg = ICE->getSubExpr();
2588     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
2589     QualType RHSTy = RHS.get()->getType();
2590 
2591     llvm::Triple::ArchType Arch = TI.getTriple().getArch();
2592     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
2593                           Arch == llvm::Triple::aarch64_32 ||
2594                           Arch == llvm::Triple::aarch64_be;
2595     bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong;
2596     QualType EltTy =
2597         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
2598     if (HasConstPtr)
2599       EltTy = EltTy.withConst();
2600     QualType LHSTy = Context.getPointerType(EltTy);
2601     AssignConvertType ConvTy;
2602     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
2603     if (RHS.isInvalid())
2604       return true;
2605     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
2606                                  RHS.get(), AA_Assigning))
2607       return true;
2608   }
2609 
2610   // For NEON intrinsics which take an immediate value as part of the
2611   // instruction, range check them here.
2612   unsigned i = 0, l = 0, u = 0;
2613   switch (BuiltinID) {
2614   default:
2615     return false;
2616   #define GET_NEON_IMMEDIATE_CHECK
2617   #include "clang/Basic/arm_neon.inc"
2618   #include "clang/Basic/arm_fp16.inc"
2619   #undef GET_NEON_IMMEDIATE_CHECK
2620   }
2621 
2622   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2623 }
2624 
2625 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2626   switch (BuiltinID) {
2627   default:
2628     return false;
2629   #include "clang/Basic/arm_mve_builtin_sema.inc"
2630   }
2631 }
2632 
2633 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2634                                        CallExpr *TheCall) {
2635   bool Err = false;
2636   switch (BuiltinID) {
2637   default:
2638     return false;
2639 #include "clang/Basic/arm_cde_builtin_sema.inc"
2640   }
2641 
2642   if (Err)
2643     return true;
2644 
2645   return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true);
2646 }
2647 
2648 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI,
2649                                         const Expr *CoprocArg, bool WantCDE) {
2650   if (isConstantEvaluated())
2651     return false;
2652 
2653   // We can't check the value of a dependent argument.
2654   if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent())
2655     return false;
2656 
2657   llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context);
2658   int64_t CoprocNo = CoprocNoAP.getExtValue();
2659   assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative");
2660 
2661   uint32_t CDECoprocMask = TI.getARMCDECoprocMask();
2662   bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo));
2663 
2664   if (IsCDECoproc != WantCDE)
2665     return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc)
2666            << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange();
2667 
2668   return false;
2669 }
2670 
2671 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
2672                                         unsigned MaxWidth) {
2673   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
2674           BuiltinID == ARM::BI__builtin_arm_ldaex ||
2675           BuiltinID == ARM::BI__builtin_arm_strex ||
2676           BuiltinID == ARM::BI__builtin_arm_stlex ||
2677           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2678           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2679           BuiltinID == AArch64::BI__builtin_arm_strex ||
2680           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
2681          "unexpected ARM builtin");
2682   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
2683                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
2684                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2685                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
2686 
2687   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2688 
2689   // Ensure that we have the proper number of arguments.
2690   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
2691     return true;
2692 
2693   // Inspect the pointer argument of the atomic builtin.  This should always be
2694   // a pointer type, whose element is an integral scalar or pointer type.
2695   // Because it is a pointer type, we don't have to worry about any implicit
2696   // casts here.
2697   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
2698   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
2699   if (PointerArgRes.isInvalid())
2700     return true;
2701   PointerArg = PointerArgRes.get();
2702 
2703   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2704   if (!pointerType) {
2705     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
2706         << PointerArg->getType() << PointerArg->getSourceRange();
2707     return true;
2708   }
2709 
2710   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
2711   // task is to insert the appropriate casts into the AST. First work out just
2712   // what the appropriate type is.
2713   QualType ValType = pointerType->getPointeeType();
2714   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
2715   if (IsLdrex)
2716     AddrType.addConst();
2717 
2718   // Issue a warning if the cast is dodgy.
2719   CastKind CastNeeded = CK_NoOp;
2720   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
2721     CastNeeded = CK_BitCast;
2722     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
2723         << PointerArg->getType() << Context.getPointerType(AddrType)
2724         << AA_Passing << PointerArg->getSourceRange();
2725   }
2726 
2727   // Finally, do the cast and replace the argument with the corrected version.
2728   AddrType = Context.getPointerType(AddrType);
2729   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
2730   if (PointerArgRes.isInvalid())
2731     return true;
2732   PointerArg = PointerArgRes.get();
2733 
2734   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
2735 
2736   // In general, we allow ints, floats and pointers to be loaded and stored.
2737   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2738       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
2739     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
2740         << PointerArg->getType() << PointerArg->getSourceRange();
2741     return true;
2742   }
2743 
2744   // But ARM doesn't have instructions to deal with 128-bit versions.
2745   if (Context.getTypeSize(ValType) > MaxWidth) {
2746     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
2747     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
2748         << PointerArg->getType() << PointerArg->getSourceRange();
2749     return true;
2750   }
2751 
2752   switch (ValType.getObjCLifetime()) {
2753   case Qualifiers::OCL_None:
2754   case Qualifiers::OCL_ExplicitNone:
2755     // okay
2756     break;
2757 
2758   case Qualifiers::OCL_Weak:
2759   case Qualifiers::OCL_Strong:
2760   case Qualifiers::OCL_Autoreleasing:
2761     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
2762         << ValType << PointerArg->getSourceRange();
2763     return true;
2764   }
2765 
2766   if (IsLdrex) {
2767     TheCall->setType(ValType);
2768     return false;
2769   }
2770 
2771   // Initialize the argument to be stored.
2772   ExprResult ValArg = TheCall->getArg(0);
2773   InitializedEntity Entity = InitializedEntity::InitializeParameter(
2774       Context, ValType, /*consume*/ false);
2775   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2776   if (ValArg.isInvalid())
2777     return true;
2778   TheCall->setArg(0, ValArg.get());
2779 
2780   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
2781   // but the custom checker bypasses all default analysis.
2782   TheCall->setType(Context.IntTy);
2783   return false;
2784 }
2785 
2786 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2787                                        CallExpr *TheCall) {
2788   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
2789       BuiltinID == ARM::BI__builtin_arm_ldaex ||
2790       BuiltinID == ARM::BI__builtin_arm_strex ||
2791       BuiltinID == ARM::BI__builtin_arm_stlex) {
2792     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
2793   }
2794 
2795   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
2796     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2797       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
2798   }
2799 
2800   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2801       BuiltinID == ARM::BI__builtin_arm_wsr64)
2802     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
2803 
2804   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
2805       BuiltinID == ARM::BI__builtin_arm_rsrp ||
2806       BuiltinID == ARM::BI__builtin_arm_wsr ||
2807       BuiltinID == ARM::BI__builtin_arm_wsrp)
2808     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2809 
2810   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2811     return true;
2812   if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
2813     return true;
2814   if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall))
2815     return true;
2816 
2817   // For intrinsics which take an immediate value as part of the instruction,
2818   // range check them here.
2819   // FIXME: VFP Intrinsics should error if VFP not present.
2820   switch (BuiltinID) {
2821   default: return false;
2822   case ARM::BI__builtin_arm_ssat:
2823     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
2824   case ARM::BI__builtin_arm_usat:
2825     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
2826   case ARM::BI__builtin_arm_ssat16:
2827     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
2828   case ARM::BI__builtin_arm_usat16:
2829     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2830   case ARM::BI__builtin_arm_vcvtr_f:
2831   case ARM::BI__builtin_arm_vcvtr_d:
2832     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
2833   case ARM::BI__builtin_arm_dmb:
2834   case ARM::BI__builtin_arm_dsb:
2835   case ARM::BI__builtin_arm_isb:
2836   case ARM::BI__builtin_arm_dbg:
2837     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
2838   case ARM::BI__builtin_arm_cdp:
2839   case ARM::BI__builtin_arm_cdp2:
2840   case ARM::BI__builtin_arm_mcr:
2841   case ARM::BI__builtin_arm_mcr2:
2842   case ARM::BI__builtin_arm_mrc:
2843   case ARM::BI__builtin_arm_mrc2:
2844   case ARM::BI__builtin_arm_mcrr:
2845   case ARM::BI__builtin_arm_mcrr2:
2846   case ARM::BI__builtin_arm_mrrc:
2847   case ARM::BI__builtin_arm_mrrc2:
2848   case ARM::BI__builtin_arm_ldc:
2849   case ARM::BI__builtin_arm_ldcl:
2850   case ARM::BI__builtin_arm_ldc2:
2851   case ARM::BI__builtin_arm_ldc2l:
2852   case ARM::BI__builtin_arm_stc:
2853   case ARM::BI__builtin_arm_stcl:
2854   case ARM::BI__builtin_arm_stc2:
2855   case ARM::BI__builtin_arm_stc2l:
2856     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) ||
2857            CheckARMCoprocessorImmediate(TI, TheCall->getArg(0),
2858                                         /*WantCDE*/ false);
2859   }
2860 }
2861 
2862 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI,
2863                                            unsigned BuiltinID,
2864                                            CallExpr *TheCall) {
2865   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2866       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2867       BuiltinID == AArch64::BI__builtin_arm_strex ||
2868       BuiltinID == AArch64::BI__builtin_arm_stlex) {
2869     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
2870   }
2871 
2872   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
2873     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2874       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
2875       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
2876       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
2877   }
2878 
2879   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2880       BuiltinID == AArch64::BI__builtin_arm_wsr64)
2881     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2882 
2883   // Memory Tagging Extensions (MTE) Intrinsics
2884   if (BuiltinID == AArch64::BI__builtin_arm_irg ||
2885       BuiltinID == AArch64::BI__builtin_arm_addg ||
2886       BuiltinID == AArch64::BI__builtin_arm_gmi ||
2887       BuiltinID == AArch64::BI__builtin_arm_ldg ||
2888       BuiltinID == AArch64::BI__builtin_arm_stg ||
2889       BuiltinID == AArch64::BI__builtin_arm_subp) {
2890     return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
2891   }
2892 
2893   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
2894       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2895       BuiltinID == AArch64::BI__builtin_arm_wsr ||
2896       BuiltinID == AArch64::BI__builtin_arm_wsrp)
2897     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2898 
2899   // Only check the valid encoding range. Any constant in this range would be
2900   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
2901   // an exception for incorrect registers. This matches MSVC behavior.
2902   if (BuiltinID == AArch64::BI_ReadStatusReg ||
2903       BuiltinID == AArch64::BI_WriteStatusReg)
2904     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
2905 
2906   if (BuiltinID == AArch64::BI__getReg)
2907     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
2908 
2909   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2910     return true;
2911 
2912   if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall))
2913     return true;
2914 
2915   // For intrinsics which take an immediate value as part of the instruction,
2916   // range check them here.
2917   unsigned i = 0, l = 0, u = 0;
2918   switch (BuiltinID) {
2919   default: return false;
2920   case AArch64::BI__builtin_arm_dmb:
2921   case AArch64::BI__builtin_arm_dsb:
2922   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
2923   case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
2924   }
2925 
2926   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2927 }
2928 
2929 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) {
2930   if (Arg->getType()->getAsPlaceholderType())
2931     return false;
2932 
2933   // The first argument needs to be a record field access.
2934   // If it is an array element access, we delay decision
2935   // to BPF backend to check whether the access is a
2936   // field access or not.
2937   return (Arg->IgnoreParens()->getObjectKind() == OK_BitField ||
2938           isa<MemberExpr>(Arg->IgnoreParens()) ||
2939           isa<ArraySubscriptExpr>(Arg->IgnoreParens()));
2940 }
2941 
2942 static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S,
2943                             QualType VectorTy, QualType EltTy) {
2944   QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType();
2945   if (!Context.hasSameType(VectorEltTy, EltTy)) {
2946     S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types)
2947         << Call->getSourceRange() << VectorEltTy << EltTy;
2948     return false;
2949   }
2950   return true;
2951 }
2952 
2953 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) {
2954   QualType ArgType = Arg->getType();
2955   if (ArgType->getAsPlaceholderType())
2956     return false;
2957 
2958   // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type
2959   // format:
2960   //   1. __builtin_preserve_type_info(*(<type> *)0, flag);
2961   //   2. <type> var;
2962   //      __builtin_preserve_type_info(var, flag);
2963   if (!isa<DeclRefExpr>(Arg->IgnoreParens()) &&
2964       !isa<UnaryOperator>(Arg->IgnoreParens()))
2965     return false;
2966 
2967   // Typedef type.
2968   if (ArgType->getAs<TypedefType>())
2969     return true;
2970 
2971   // Record type or Enum type.
2972   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2973   if (const auto *RT = Ty->getAs<RecordType>()) {
2974     if (!RT->getDecl()->getDeclName().isEmpty())
2975       return true;
2976   } else if (const auto *ET = Ty->getAs<EnumType>()) {
2977     if (!ET->getDecl()->getDeclName().isEmpty())
2978       return true;
2979   }
2980 
2981   return false;
2982 }
2983 
2984 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) {
2985   QualType ArgType = Arg->getType();
2986   if (ArgType->getAsPlaceholderType())
2987     return false;
2988 
2989   // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type
2990   // format:
2991   //   __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>,
2992   //                                 flag);
2993   const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens());
2994   if (!UO)
2995     return false;
2996 
2997   const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr());
2998   if (!CE)
2999     return false;
3000   if (CE->getCastKind() != CK_IntegralToPointer &&
3001       CE->getCastKind() != CK_NullToPointer)
3002     return false;
3003 
3004   // The integer must be from an EnumConstantDecl.
3005   const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr());
3006   if (!DR)
3007     return false;
3008 
3009   const EnumConstantDecl *Enumerator =
3010       dyn_cast<EnumConstantDecl>(DR->getDecl());
3011   if (!Enumerator)
3012     return false;
3013 
3014   // The type must be EnumType.
3015   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
3016   const auto *ET = Ty->getAs<EnumType>();
3017   if (!ET)
3018     return false;
3019 
3020   // The enum value must be supported.
3021   return llvm::is_contained(ET->getDecl()->enumerators(), Enumerator);
3022 }
3023 
3024 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
3025                                        CallExpr *TheCall) {
3026   assert((BuiltinID == BPF::BI__builtin_preserve_field_info ||
3027           BuiltinID == BPF::BI__builtin_btf_type_id ||
3028           BuiltinID == BPF::BI__builtin_preserve_type_info ||
3029           BuiltinID == BPF::BI__builtin_preserve_enum_value) &&
3030          "unexpected BPF builtin");
3031 
3032   if (checkArgCount(*this, TheCall, 2))
3033     return true;
3034 
3035   // The second argument needs to be a constant int
3036   Expr *Arg = TheCall->getArg(1);
3037   Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context);
3038   diag::kind kind;
3039   if (!Value) {
3040     if (BuiltinID == BPF::BI__builtin_preserve_field_info)
3041       kind = diag::err_preserve_field_info_not_const;
3042     else if (BuiltinID == BPF::BI__builtin_btf_type_id)
3043       kind = diag::err_btf_type_id_not_const;
3044     else if (BuiltinID == BPF::BI__builtin_preserve_type_info)
3045       kind = diag::err_preserve_type_info_not_const;
3046     else
3047       kind = diag::err_preserve_enum_value_not_const;
3048     Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange();
3049     return true;
3050   }
3051 
3052   // The first argument
3053   Arg = TheCall->getArg(0);
3054   bool InvalidArg = false;
3055   bool ReturnUnsignedInt = true;
3056   if (BuiltinID == BPF::BI__builtin_preserve_field_info) {
3057     if (!isValidBPFPreserveFieldInfoArg(Arg)) {
3058       InvalidArg = true;
3059       kind = diag::err_preserve_field_info_not_field;
3060     }
3061   } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) {
3062     if (!isValidBPFPreserveTypeInfoArg(Arg)) {
3063       InvalidArg = true;
3064       kind = diag::err_preserve_type_info_invalid;
3065     }
3066   } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) {
3067     if (!isValidBPFPreserveEnumValueArg(Arg)) {
3068       InvalidArg = true;
3069       kind = diag::err_preserve_enum_value_invalid;
3070     }
3071     ReturnUnsignedInt = false;
3072   } else if (BuiltinID == BPF::BI__builtin_btf_type_id) {
3073     ReturnUnsignedInt = false;
3074   }
3075 
3076   if (InvalidArg) {
3077     Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange();
3078     return true;
3079   }
3080 
3081   if (ReturnUnsignedInt)
3082     TheCall->setType(Context.UnsignedIntTy);
3083   else
3084     TheCall->setType(Context.UnsignedLongTy);
3085   return false;
3086 }
3087 
3088 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
3089   struct ArgInfo {
3090     uint8_t OpNum;
3091     bool IsSigned;
3092     uint8_t BitWidth;
3093     uint8_t Align;
3094   };
3095   struct BuiltinInfo {
3096     unsigned BuiltinID;
3097     ArgInfo Infos[2];
3098   };
3099 
3100   static BuiltinInfo Infos[] = {
3101     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
3102     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
3103     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
3104     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  1 }} },
3105     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
3106     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
3107     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
3108     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
3109     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
3110     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
3111     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
3112 
3113     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
3114     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
3115     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
3116     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
3117     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
3118     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
3119     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
3120     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
3121     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
3122     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
3123     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
3124 
3125     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
3126     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
3127     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
3128     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
3129     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
3130     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
3131     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
3132     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
3133     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
3134     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
3135     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
3136     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
3137     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
3138     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
3139     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
3140     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
3141     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
3142     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
3143     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
3144     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
3145     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
3146     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
3147     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
3148     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
3149     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
3150     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
3151     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
3152     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
3153     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
3154     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
3155     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
3156     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
3157     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
3158     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
3159     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
3160     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
3161     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
3162     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
3163     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
3164     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
3165     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
3166     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
3167     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
3168     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
3169     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
3170     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
3171     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
3172     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
3173     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
3174     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
3175     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
3176     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
3177                                                       {{ 1, false, 6,  0 }} },
3178     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
3179     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
3180     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
3181     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
3182     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
3183     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
3184     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
3185                                                       {{ 1, false, 5,  0 }} },
3186     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
3187     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
3188     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
3189     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
3190     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
3191     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
3192                                                        { 2, false, 5,  0 }} },
3193     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
3194                                                        { 2, false, 6,  0 }} },
3195     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
3196                                                        { 3, false, 5,  0 }} },
3197     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
3198                                                        { 3, false, 6,  0 }} },
3199     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
3200     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
3201     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
3202     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
3203     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
3204     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
3205     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
3206     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
3207     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
3208     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
3209     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
3210     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
3211     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
3212     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
3213     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
3214     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
3215                                                       {{ 2, false, 4,  0 },
3216                                                        { 3, false, 5,  0 }} },
3217     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
3218                                                       {{ 2, false, 4,  0 },
3219                                                        { 3, false, 5,  0 }} },
3220     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
3221                                                       {{ 2, false, 4,  0 },
3222                                                        { 3, false, 5,  0 }} },
3223     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
3224                                                       {{ 2, false, 4,  0 },
3225                                                        { 3, false, 5,  0 }} },
3226     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
3227     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
3228     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
3229     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
3230     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
3231     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
3232     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
3233     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
3234     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
3235     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
3236     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
3237                                                        { 2, false, 5,  0 }} },
3238     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
3239                                                        { 2, false, 6,  0 }} },
3240     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
3241     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
3242     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
3243     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
3244     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
3245     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
3246     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
3247     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
3248     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
3249                                                       {{ 1, false, 4,  0 }} },
3250     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
3251     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
3252                                                       {{ 1, false, 4,  0 }} },
3253     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
3254     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
3255     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
3256     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
3257     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
3258     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
3259     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
3260     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
3261     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
3262     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
3263     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
3264     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
3265     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
3266     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
3267     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
3268     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
3269     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
3270     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
3271     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
3272     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
3273                                                       {{ 3, false, 1,  0 }} },
3274     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
3275     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
3276     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
3277     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
3278                                                       {{ 3, false, 1,  0 }} },
3279     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
3280     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
3281     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
3282     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
3283                                                       {{ 3, false, 1,  0 }} },
3284   };
3285 
3286   // Use a dynamically initialized static to sort the table exactly once on
3287   // first run.
3288   static const bool SortOnce =
3289       (llvm::sort(Infos,
3290                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
3291                    return LHS.BuiltinID < RHS.BuiltinID;
3292                  }),
3293        true);
3294   (void)SortOnce;
3295 
3296   const BuiltinInfo *F = llvm::partition_point(
3297       Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
3298   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
3299     return false;
3300 
3301   bool Error = false;
3302 
3303   for (const ArgInfo &A : F->Infos) {
3304     // Ignore empty ArgInfo elements.
3305     if (A.BitWidth == 0)
3306       continue;
3307 
3308     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
3309     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
3310     if (!A.Align) {
3311       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
3312     } else {
3313       unsigned M = 1 << A.Align;
3314       Min *= M;
3315       Max *= M;
3316       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
3317       Error |= SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
3318     }
3319   }
3320   return Error;
3321 }
3322 
3323 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
3324                                            CallExpr *TheCall) {
3325   return CheckHexagonBuiltinArgument(BuiltinID, TheCall);
3326 }
3327 
3328 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI,
3329                                         unsigned BuiltinID, CallExpr *TheCall) {
3330   return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) ||
3331          CheckMipsBuiltinArgument(BuiltinID, TheCall);
3332 }
3333 
3334 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
3335                                CallExpr *TheCall) {
3336 
3337   if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
3338       BuiltinID <= Mips::BI__builtin_mips_lwx) {
3339     if (!TI.hasFeature("dsp"))
3340       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
3341   }
3342 
3343   if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
3344       BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
3345     if (!TI.hasFeature("dspr2"))
3346       return Diag(TheCall->getBeginLoc(),
3347                   diag::err_mips_builtin_requires_dspr2);
3348   }
3349 
3350   if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
3351       BuiltinID <= Mips::BI__builtin_msa_xori_b) {
3352     if (!TI.hasFeature("msa"))
3353       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
3354   }
3355 
3356   return false;
3357 }
3358 
3359 // CheckMipsBuiltinArgument - Checks the constant value passed to the
3360 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
3361 // ordering for DSP is unspecified. MSA is ordered by the data format used
3362 // by the underlying instruction i.e., df/m, df/n and then by size.
3363 //
3364 // FIXME: The size tests here should instead be tablegen'd along with the
3365 //        definitions from include/clang/Basic/BuiltinsMips.def.
3366 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
3367 //        be too.
3368 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
3369   unsigned i = 0, l = 0, u = 0, m = 0;
3370   switch (BuiltinID) {
3371   default: return false;
3372   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
3373   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
3374   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
3375   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
3376   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
3377   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
3378   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
3379   // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
3380   // df/m field.
3381   // These intrinsics take an unsigned 3 bit immediate.
3382   case Mips::BI__builtin_msa_bclri_b:
3383   case Mips::BI__builtin_msa_bnegi_b:
3384   case Mips::BI__builtin_msa_bseti_b:
3385   case Mips::BI__builtin_msa_sat_s_b:
3386   case Mips::BI__builtin_msa_sat_u_b:
3387   case Mips::BI__builtin_msa_slli_b:
3388   case Mips::BI__builtin_msa_srai_b:
3389   case Mips::BI__builtin_msa_srari_b:
3390   case Mips::BI__builtin_msa_srli_b:
3391   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
3392   case Mips::BI__builtin_msa_binsli_b:
3393   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
3394   // These intrinsics take an unsigned 4 bit immediate.
3395   case Mips::BI__builtin_msa_bclri_h:
3396   case Mips::BI__builtin_msa_bnegi_h:
3397   case Mips::BI__builtin_msa_bseti_h:
3398   case Mips::BI__builtin_msa_sat_s_h:
3399   case Mips::BI__builtin_msa_sat_u_h:
3400   case Mips::BI__builtin_msa_slli_h:
3401   case Mips::BI__builtin_msa_srai_h:
3402   case Mips::BI__builtin_msa_srari_h:
3403   case Mips::BI__builtin_msa_srli_h:
3404   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
3405   case Mips::BI__builtin_msa_binsli_h:
3406   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
3407   // These intrinsics take an unsigned 5 bit immediate.
3408   // The first block of intrinsics actually have an unsigned 5 bit field,
3409   // not a df/n field.
3410   case Mips::BI__builtin_msa_cfcmsa:
3411   case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
3412   case Mips::BI__builtin_msa_clei_u_b:
3413   case Mips::BI__builtin_msa_clei_u_h:
3414   case Mips::BI__builtin_msa_clei_u_w:
3415   case Mips::BI__builtin_msa_clei_u_d:
3416   case Mips::BI__builtin_msa_clti_u_b:
3417   case Mips::BI__builtin_msa_clti_u_h:
3418   case Mips::BI__builtin_msa_clti_u_w:
3419   case Mips::BI__builtin_msa_clti_u_d:
3420   case Mips::BI__builtin_msa_maxi_u_b:
3421   case Mips::BI__builtin_msa_maxi_u_h:
3422   case Mips::BI__builtin_msa_maxi_u_w:
3423   case Mips::BI__builtin_msa_maxi_u_d:
3424   case Mips::BI__builtin_msa_mini_u_b:
3425   case Mips::BI__builtin_msa_mini_u_h:
3426   case Mips::BI__builtin_msa_mini_u_w:
3427   case Mips::BI__builtin_msa_mini_u_d:
3428   case Mips::BI__builtin_msa_addvi_b:
3429   case Mips::BI__builtin_msa_addvi_h:
3430   case Mips::BI__builtin_msa_addvi_w:
3431   case Mips::BI__builtin_msa_addvi_d:
3432   case Mips::BI__builtin_msa_bclri_w:
3433   case Mips::BI__builtin_msa_bnegi_w:
3434   case Mips::BI__builtin_msa_bseti_w:
3435   case Mips::BI__builtin_msa_sat_s_w:
3436   case Mips::BI__builtin_msa_sat_u_w:
3437   case Mips::BI__builtin_msa_slli_w:
3438   case Mips::BI__builtin_msa_srai_w:
3439   case Mips::BI__builtin_msa_srari_w:
3440   case Mips::BI__builtin_msa_srli_w:
3441   case Mips::BI__builtin_msa_srlri_w:
3442   case Mips::BI__builtin_msa_subvi_b:
3443   case Mips::BI__builtin_msa_subvi_h:
3444   case Mips::BI__builtin_msa_subvi_w:
3445   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
3446   case Mips::BI__builtin_msa_binsli_w:
3447   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
3448   // These intrinsics take an unsigned 6 bit immediate.
3449   case Mips::BI__builtin_msa_bclri_d:
3450   case Mips::BI__builtin_msa_bnegi_d:
3451   case Mips::BI__builtin_msa_bseti_d:
3452   case Mips::BI__builtin_msa_sat_s_d:
3453   case Mips::BI__builtin_msa_sat_u_d:
3454   case Mips::BI__builtin_msa_slli_d:
3455   case Mips::BI__builtin_msa_srai_d:
3456   case Mips::BI__builtin_msa_srari_d:
3457   case Mips::BI__builtin_msa_srli_d:
3458   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
3459   case Mips::BI__builtin_msa_binsli_d:
3460   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
3461   // These intrinsics take a signed 5 bit immediate.
3462   case Mips::BI__builtin_msa_ceqi_b:
3463   case Mips::BI__builtin_msa_ceqi_h:
3464   case Mips::BI__builtin_msa_ceqi_w:
3465   case Mips::BI__builtin_msa_ceqi_d:
3466   case Mips::BI__builtin_msa_clti_s_b:
3467   case Mips::BI__builtin_msa_clti_s_h:
3468   case Mips::BI__builtin_msa_clti_s_w:
3469   case Mips::BI__builtin_msa_clti_s_d:
3470   case Mips::BI__builtin_msa_clei_s_b:
3471   case Mips::BI__builtin_msa_clei_s_h:
3472   case Mips::BI__builtin_msa_clei_s_w:
3473   case Mips::BI__builtin_msa_clei_s_d:
3474   case Mips::BI__builtin_msa_maxi_s_b:
3475   case Mips::BI__builtin_msa_maxi_s_h:
3476   case Mips::BI__builtin_msa_maxi_s_w:
3477   case Mips::BI__builtin_msa_maxi_s_d:
3478   case Mips::BI__builtin_msa_mini_s_b:
3479   case Mips::BI__builtin_msa_mini_s_h:
3480   case Mips::BI__builtin_msa_mini_s_w:
3481   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
3482   // These intrinsics take an unsigned 8 bit immediate.
3483   case Mips::BI__builtin_msa_andi_b:
3484   case Mips::BI__builtin_msa_nori_b:
3485   case Mips::BI__builtin_msa_ori_b:
3486   case Mips::BI__builtin_msa_shf_b:
3487   case Mips::BI__builtin_msa_shf_h:
3488   case Mips::BI__builtin_msa_shf_w:
3489   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
3490   case Mips::BI__builtin_msa_bseli_b:
3491   case Mips::BI__builtin_msa_bmnzi_b:
3492   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
3493   // df/n format
3494   // These intrinsics take an unsigned 4 bit immediate.
3495   case Mips::BI__builtin_msa_copy_s_b:
3496   case Mips::BI__builtin_msa_copy_u_b:
3497   case Mips::BI__builtin_msa_insve_b:
3498   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
3499   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
3500   // These intrinsics take an unsigned 3 bit immediate.
3501   case Mips::BI__builtin_msa_copy_s_h:
3502   case Mips::BI__builtin_msa_copy_u_h:
3503   case Mips::BI__builtin_msa_insve_h:
3504   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
3505   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3506   // These intrinsics take an unsigned 2 bit immediate.
3507   case Mips::BI__builtin_msa_copy_s_w:
3508   case Mips::BI__builtin_msa_copy_u_w:
3509   case Mips::BI__builtin_msa_insve_w:
3510   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
3511   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3512   // These intrinsics take an unsigned 1 bit immediate.
3513   case Mips::BI__builtin_msa_copy_s_d:
3514   case Mips::BI__builtin_msa_copy_u_d:
3515   case Mips::BI__builtin_msa_insve_d:
3516   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
3517   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3518   // Memory offsets and immediate loads.
3519   // These intrinsics take a signed 10 bit immediate.
3520   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
3521   case Mips::BI__builtin_msa_ldi_h:
3522   case Mips::BI__builtin_msa_ldi_w:
3523   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
3524   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3525   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3526   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3527   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3528   case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break;
3529   case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break;
3530   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3531   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3532   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3533   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
3534   case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break;
3535   case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break;
3536   }
3537 
3538   if (!m)
3539     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3540 
3541   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3542          SemaBuiltinConstantArgMultiple(TheCall, i, m);
3543 }
3544 
3545 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str,
3546 /// advancing the pointer over the consumed characters. The decoded type is
3547 /// returned. If the decoded type represents a constant integer with a
3548 /// constraint on its value then Mask is set to that value. The type descriptors
3549 /// used in Str are specific to PPC MMA builtins and are documented in the file
3550 /// defining the PPC builtins.
3551 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str,
3552                                         unsigned &Mask) {
3553   bool RequireICE = false;
3554   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3555   switch (*Str++) {
3556   case 'V':
3557     return Context.getVectorType(Context.UnsignedCharTy, 16,
3558                                  VectorType::VectorKind::AltiVecVector);
3559   case 'i': {
3560     char *End;
3561     unsigned size = strtoul(Str, &End, 10);
3562     assert(End != Str && "Missing constant parameter constraint");
3563     Str = End;
3564     Mask = size;
3565     return Context.IntTy;
3566   }
3567   case 'W': {
3568     char *End;
3569     unsigned size = strtoul(Str, &End, 10);
3570     assert(End != Str && "Missing PowerPC MMA type size");
3571     Str = End;
3572     QualType Type;
3573     switch (size) {
3574   #define PPC_VECTOR_TYPE(typeName, Id, size) \
3575     case size: Type = Context.Id##Ty; break;
3576   #include "clang/Basic/PPCTypes.def"
3577     default: llvm_unreachable("Invalid PowerPC MMA vector type");
3578     }
3579     bool CheckVectorArgs = false;
3580     while (!CheckVectorArgs) {
3581       switch (*Str++) {
3582       case '*':
3583         Type = Context.getPointerType(Type);
3584         break;
3585       case 'C':
3586         Type = Type.withConst();
3587         break;
3588       default:
3589         CheckVectorArgs = true;
3590         --Str;
3591         break;
3592       }
3593     }
3594     return Type;
3595   }
3596   default:
3597     return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true);
3598   }
3599 }
3600 
3601 static bool isPPC_64Builtin(unsigned BuiltinID) {
3602   // These builtins only work on PPC 64bit targets.
3603   switch (BuiltinID) {
3604   case PPC::BI__builtin_divde:
3605   case PPC::BI__builtin_divdeu:
3606   case PPC::BI__builtin_bpermd:
3607   case PPC::BI__builtin_pdepd:
3608   case PPC::BI__builtin_pextd:
3609   case PPC::BI__builtin_ppc_ldarx:
3610   case PPC::BI__builtin_ppc_stdcx:
3611   case PPC::BI__builtin_ppc_tdw:
3612   case PPC::BI__builtin_ppc_trapd:
3613   case PPC::BI__builtin_ppc_cmpeqb:
3614   case PPC::BI__builtin_ppc_setb:
3615   case PPC::BI__builtin_ppc_mulhd:
3616   case PPC::BI__builtin_ppc_mulhdu:
3617   case PPC::BI__builtin_ppc_maddhd:
3618   case PPC::BI__builtin_ppc_maddhdu:
3619   case PPC::BI__builtin_ppc_maddld:
3620   case PPC::BI__builtin_ppc_load8r:
3621   case PPC::BI__builtin_ppc_store8r:
3622   case PPC::BI__builtin_ppc_insert_exp:
3623   case PPC::BI__builtin_ppc_extract_sig:
3624   case PPC::BI__builtin_ppc_addex:
3625   case PPC::BI__builtin_darn:
3626   case PPC::BI__builtin_darn_raw:
3627   case PPC::BI__builtin_ppc_compare_and_swaplp:
3628   case PPC::BI__builtin_ppc_fetch_and_addlp:
3629   case PPC::BI__builtin_ppc_fetch_and_andlp:
3630   case PPC::BI__builtin_ppc_fetch_and_orlp:
3631   case PPC::BI__builtin_ppc_fetch_and_swaplp:
3632     return true;
3633   }
3634   return false;
3635 }
3636 
3637 static bool SemaFeatureCheck(Sema &S, CallExpr *TheCall,
3638                              StringRef FeatureToCheck, unsigned DiagID,
3639                              StringRef DiagArg = "") {
3640   if (S.Context.getTargetInfo().hasFeature(FeatureToCheck))
3641     return false;
3642 
3643   if (DiagArg.empty())
3644     S.Diag(TheCall->getBeginLoc(), DiagID) << TheCall->getSourceRange();
3645   else
3646     S.Diag(TheCall->getBeginLoc(), DiagID)
3647         << DiagArg << TheCall->getSourceRange();
3648 
3649   return true;
3650 }
3651 
3652 /// Returns true if the argument consists of one contiguous run of 1s with any
3653 /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB, so
3654 /// 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not,
3655 /// since all 1s are not contiguous.
3656 bool Sema::SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
3657   llvm::APSInt Result;
3658   // We can't check the value of a dependent argument.
3659   Expr *Arg = TheCall->getArg(ArgNum);
3660   if (Arg->isTypeDependent() || Arg->isValueDependent())
3661     return false;
3662 
3663   // Check constant-ness first.
3664   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3665     return true;
3666 
3667   // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
3668   if (Result.isShiftedMask() || (~Result).isShiftedMask())
3669     return false;
3670 
3671   return Diag(TheCall->getBeginLoc(),
3672               diag::err_argument_not_contiguous_bit_field)
3673          << ArgNum << Arg->getSourceRange();
3674 }
3675 
3676 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3677                                        CallExpr *TheCall) {
3678   unsigned i = 0, l = 0, u = 0;
3679   bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64;
3680   llvm::APSInt Result;
3681 
3682   if (isPPC_64Builtin(BuiltinID) && !IsTarget64Bit)
3683     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3684            << TheCall->getSourceRange();
3685 
3686   switch (BuiltinID) {
3687   default: return false;
3688   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3689   case PPC::BI__builtin_altivec_crypto_vshasigmad:
3690     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3691            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3692   case PPC::BI__builtin_altivec_dss:
3693     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
3694   case PPC::BI__builtin_tbegin:
3695   case PPC::BI__builtin_tend:
3696     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 1) ||
3697            SemaFeatureCheck(*this, TheCall, "htm",
3698                             diag::err_ppc_builtin_requires_htm);
3699   case PPC::BI__builtin_tsr:
3700     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) ||
3701            SemaFeatureCheck(*this, TheCall, "htm",
3702                             diag::err_ppc_builtin_requires_htm);
3703   case PPC::BI__builtin_tabortwc:
3704   case PPC::BI__builtin_tabortdc:
3705     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3706            SemaFeatureCheck(*this, TheCall, "htm",
3707                             diag::err_ppc_builtin_requires_htm);
3708   case PPC::BI__builtin_tabortwci:
3709   case PPC::BI__builtin_tabortdci:
3710     return SemaFeatureCheck(*this, TheCall, "htm",
3711                             diag::err_ppc_builtin_requires_htm) ||
3712            (SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3713             SemaBuiltinConstantArgRange(TheCall, 2, 0, 31));
3714   case PPC::BI__builtin_tabort:
3715   case PPC::BI__builtin_tcheck:
3716   case PPC::BI__builtin_treclaim:
3717   case PPC::BI__builtin_trechkpt:
3718   case PPC::BI__builtin_tendall:
3719   case PPC::BI__builtin_tresume:
3720   case PPC::BI__builtin_tsuspend:
3721   case PPC::BI__builtin_get_texasr:
3722   case PPC::BI__builtin_get_texasru:
3723   case PPC::BI__builtin_get_tfhar:
3724   case PPC::BI__builtin_get_tfiar:
3725   case PPC::BI__builtin_set_texasr:
3726   case PPC::BI__builtin_set_texasru:
3727   case PPC::BI__builtin_set_tfhar:
3728   case PPC::BI__builtin_set_tfiar:
3729   case PPC::BI__builtin_ttest:
3730     return SemaFeatureCheck(*this, TheCall, "htm",
3731                             diag::err_ppc_builtin_requires_htm);
3732   // According to GCC 'Basic PowerPC Built-in Functions Available on ISA 2.05',
3733   // __builtin_(un)pack_longdouble are available only if long double uses IBM
3734   // extended double representation.
3735   case PPC::BI__builtin_unpack_longdouble:
3736     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 1))
3737       return true;
3738     LLVM_FALLTHROUGH;
3739   case PPC::BI__builtin_pack_longdouble:
3740     if (&TI.getLongDoubleFormat() != &llvm::APFloat::PPCDoubleDouble())
3741       return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_requires_abi)
3742              << "ibmlongdouble";
3743     return false;
3744   case PPC::BI__builtin_altivec_dst:
3745   case PPC::BI__builtin_altivec_dstt:
3746   case PPC::BI__builtin_altivec_dstst:
3747   case PPC::BI__builtin_altivec_dststt:
3748     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
3749   case PPC::BI__builtin_vsx_xxpermdi:
3750   case PPC::BI__builtin_vsx_xxsldwi:
3751     return SemaBuiltinVSX(TheCall);
3752   case PPC::BI__builtin_divwe:
3753   case PPC::BI__builtin_divweu:
3754   case PPC::BI__builtin_divde:
3755   case PPC::BI__builtin_divdeu:
3756     return SemaFeatureCheck(*this, TheCall, "extdiv",
3757                             diag::err_ppc_builtin_only_on_arch, "7");
3758   case PPC::BI__builtin_bpermd:
3759     return SemaFeatureCheck(*this, TheCall, "bpermd",
3760                             diag::err_ppc_builtin_only_on_arch, "7");
3761   case PPC::BI__builtin_unpack_vector_int128:
3762     return SemaFeatureCheck(*this, TheCall, "vsx",
3763                             diag::err_ppc_builtin_only_on_arch, "7") ||
3764            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3765   case PPC::BI__builtin_pack_vector_int128:
3766     return SemaFeatureCheck(*this, TheCall, "vsx",
3767                             diag::err_ppc_builtin_only_on_arch, "7");
3768   case PPC::BI__builtin_pdepd:
3769   case PPC::BI__builtin_pextd:
3770     return SemaFeatureCheck(*this, TheCall, "isa-v31-instructions",
3771                             diag::err_ppc_builtin_only_on_arch, "10");
3772   case PPC::BI__builtin_altivec_vgnb:
3773      return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7);
3774   case PPC::BI__builtin_altivec_vec_replace_elt:
3775   case PPC::BI__builtin_altivec_vec_replace_unaligned: {
3776     QualType VecTy = TheCall->getArg(0)->getType();
3777     QualType EltTy = TheCall->getArg(1)->getType();
3778     unsigned Width = Context.getIntWidth(EltTy);
3779     return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) ||
3780            !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy);
3781   }
3782   case PPC::BI__builtin_vsx_xxeval:
3783      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255);
3784   case PPC::BI__builtin_altivec_vsldbi:
3785      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3786   case PPC::BI__builtin_altivec_vsrdbi:
3787      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3788   case PPC::BI__builtin_vsx_xxpermx:
3789      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7);
3790   case PPC::BI__builtin_ppc_tw:
3791   case PPC::BI__builtin_ppc_tdw:
3792     return SemaBuiltinConstantArgRange(TheCall, 2, 1, 31);
3793   case PPC::BI__builtin_ppc_cmpeqb:
3794   case PPC::BI__builtin_ppc_setb:
3795   case PPC::BI__builtin_ppc_maddhd:
3796   case PPC::BI__builtin_ppc_maddhdu:
3797   case PPC::BI__builtin_ppc_maddld:
3798     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3799                             diag::err_ppc_builtin_only_on_arch, "9");
3800   case PPC::BI__builtin_ppc_cmprb:
3801     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3802                             diag::err_ppc_builtin_only_on_arch, "9") ||
3803            SemaBuiltinConstantArgRange(TheCall, 0, 0, 1);
3804   // For __rlwnm, __rlwimi and __rldimi, the last parameter mask must
3805   // be a constant that represents a contiguous bit field.
3806   case PPC::BI__builtin_ppc_rlwnm:
3807     return SemaValueIsRunOfOnes(TheCall, 2);
3808   case PPC::BI__builtin_ppc_rlwimi:
3809   case PPC::BI__builtin_ppc_rldimi:
3810     return SemaBuiltinConstantArg(TheCall, 2, Result) ||
3811            SemaValueIsRunOfOnes(TheCall, 3);
3812   case PPC::BI__builtin_ppc_extract_exp:
3813   case PPC::BI__builtin_ppc_extract_sig:
3814   case PPC::BI__builtin_ppc_insert_exp:
3815     return SemaFeatureCheck(*this, TheCall, "power9-vector",
3816                             diag::err_ppc_builtin_only_on_arch, "9");
3817   case PPC::BI__builtin_ppc_addex: {
3818     if (SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3819                          diag::err_ppc_builtin_only_on_arch, "9") ||
3820         SemaBuiltinConstantArgRange(TheCall, 2, 0, 3))
3821       return true;
3822     // Output warning for reserved values 1 to 3.
3823     int ArgValue =
3824         TheCall->getArg(2)->getIntegerConstantExpr(Context)->getSExtValue();
3825     if (ArgValue != 0)
3826       Diag(TheCall->getBeginLoc(), diag::warn_argument_undefined_behaviour)
3827           << ArgValue;
3828     return false;
3829   }
3830   case PPC::BI__builtin_ppc_mtfsb0:
3831   case PPC::BI__builtin_ppc_mtfsb1:
3832     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
3833   case PPC::BI__builtin_ppc_mtfsf:
3834     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 255);
3835   case PPC::BI__builtin_ppc_mtfsfi:
3836     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) ||
3837            SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
3838   case PPC::BI__builtin_ppc_alignx:
3839     return SemaBuiltinConstantArgPower2(TheCall, 0);
3840   case PPC::BI__builtin_ppc_rdlam:
3841     return SemaValueIsRunOfOnes(TheCall, 2);
3842   case PPC::BI__builtin_ppc_icbt:
3843   case PPC::BI__builtin_ppc_sthcx:
3844   case PPC::BI__builtin_ppc_stbcx:
3845   case PPC::BI__builtin_ppc_lharx:
3846   case PPC::BI__builtin_ppc_lbarx:
3847     return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions",
3848                             diag::err_ppc_builtin_only_on_arch, "8");
3849   case PPC::BI__builtin_vsx_ldrmb:
3850   case PPC::BI__builtin_vsx_strmb:
3851     return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions",
3852                             diag::err_ppc_builtin_only_on_arch, "8") ||
3853            SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
3854   case PPC::BI__builtin_altivec_vcntmbb:
3855   case PPC::BI__builtin_altivec_vcntmbh:
3856   case PPC::BI__builtin_altivec_vcntmbw:
3857   case PPC::BI__builtin_altivec_vcntmbd:
3858     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3859   case PPC::BI__builtin_darn:
3860   case PPC::BI__builtin_darn_raw:
3861   case PPC::BI__builtin_darn_32:
3862     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3863                             diag::err_ppc_builtin_only_on_arch, "9");
3864   case PPC::BI__builtin_vsx_xxgenpcvbm:
3865   case PPC::BI__builtin_vsx_xxgenpcvhm:
3866   case PPC::BI__builtin_vsx_xxgenpcvwm:
3867   case PPC::BI__builtin_vsx_xxgenpcvdm:
3868     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
3869   case PPC::BI__builtin_ppc_compare_exp_uo:
3870   case PPC::BI__builtin_ppc_compare_exp_lt:
3871   case PPC::BI__builtin_ppc_compare_exp_gt:
3872   case PPC::BI__builtin_ppc_compare_exp_eq:
3873     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3874                             diag::err_ppc_builtin_only_on_arch, "9") ||
3875            SemaFeatureCheck(*this, TheCall, "vsx",
3876                             diag::err_ppc_builtin_requires_vsx);
3877   case PPC::BI__builtin_ppc_test_data_class: {
3878     // Check if the first argument of the __builtin_ppc_test_data_class call is
3879     // valid. The argument must be either a 'float' or a 'double'.
3880     QualType ArgType = TheCall->getArg(0)->getType();
3881     if (ArgType != QualType(Context.FloatTy) &&
3882         ArgType != QualType(Context.DoubleTy))
3883       return Diag(TheCall->getBeginLoc(),
3884                   diag::err_ppc_invalid_test_data_class_type);
3885     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3886                             diag::err_ppc_builtin_only_on_arch, "9") ||
3887            SemaFeatureCheck(*this, TheCall, "vsx",
3888                             diag::err_ppc_builtin_requires_vsx) ||
3889            SemaBuiltinConstantArgRange(TheCall, 1, 0, 127);
3890   }
3891   case PPC::BI__builtin_ppc_load8r:
3892   case PPC::BI__builtin_ppc_store8r:
3893     return SemaFeatureCheck(*this, TheCall, "isa-v206-instructions",
3894                             diag::err_ppc_builtin_only_on_arch, "7");
3895 #define CUSTOM_BUILTIN(Name, Intr, Types, Acc)                                 \
3896   case PPC::BI__builtin_##Name:                                                \
3897     return SemaBuiltinPPCMMACall(TheCall, BuiltinID, Types);
3898 #include "clang/Basic/BuiltinsPPC.def"
3899   }
3900   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3901 }
3902 
3903 // Check if the given type is a non-pointer PPC MMA type. This function is used
3904 // in Sema to prevent invalid uses of restricted PPC MMA types.
3905 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) {
3906   if (Type->isPointerType() || Type->isArrayType())
3907     return false;
3908 
3909   QualType CoreType = Type.getCanonicalType().getUnqualifiedType();
3910 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty
3911   if (false
3912 #include "clang/Basic/PPCTypes.def"
3913      ) {
3914     Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type);
3915     return true;
3916   }
3917   return false;
3918 }
3919 
3920 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID,
3921                                           CallExpr *TheCall) {
3922   // position of memory order and scope arguments in the builtin
3923   unsigned OrderIndex, ScopeIndex;
3924   switch (BuiltinID) {
3925   case AMDGPU::BI__builtin_amdgcn_atomic_inc32:
3926   case AMDGPU::BI__builtin_amdgcn_atomic_inc64:
3927   case AMDGPU::BI__builtin_amdgcn_atomic_dec32:
3928   case AMDGPU::BI__builtin_amdgcn_atomic_dec64:
3929     OrderIndex = 2;
3930     ScopeIndex = 3;
3931     break;
3932   case AMDGPU::BI__builtin_amdgcn_fence:
3933     OrderIndex = 0;
3934     ScopeIndex = 1;
3935     break;
3936   default:
3937     return false;
3938   }
3939 
3940   ExprResult Arg = TheCall->getArg(OrderIndex);
3941   auto ArgExpr = Arg.get();
3942   Expr::EvalResult ArgResult;
3943 
3944   if (!ArgExpr->EvaluateAsInt(ArgResult, Context))
3945     return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int)
3946            << ArgExpr->getType();
3947   auto Ord = ArgResult.Val.getInt().getZExtValue();
3948 
3949   // Check validity of memory ordering as per C11 / C++11's memody model.
3950   // Only fence needs check. Atomic dec/inc allow all memory orders.
3951   if (!llvm::isValidAtomicOrderingCABI(Ord))
3952     return Diag(ArgExpr->getBeginLoc(),
3953                 diag::warn_atomic_op_has_invalid_memory_order)
3954            << ArgExpr->getSourceRange();
3955   switch (static_cast<llvm::AtomicOrderingCABI>(Ord)) {
3956   case llvm::AtomicOrderingCABI::relaxed:
3957   case llvm::AtomicOrderingCABI::consume:
3958     if (BuiltinID == AMDGPU::BI__builtin_amdgcn_fence)
3959       return Diag(ArgExpr->getBeginLoc(),
3960                   diag::warn_atomic_op_has_invalid_memory_order)
3961              << ArgExpr->getSourceRange();
3962     break;
3963   case llvm::AtomicOrderingCABI::acquire:
3964   case llvm::AtomicOrderingCABI::release:
3965   case llvm::AtomicOrderingCABI::acq_rel:
3966   case llvm::AtomicOrderingCABI::seq_cst:
3967     break;
3968   }
3969 
3970   Arg = TheCall->getArg(ScopeIndex);
3971   ArgExpr = Arg.get();
3972   Expr::EvalResult ArgResult1;
3973   // Check that sync scope is a constant literal
3974   if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context))
3975     return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal)
3976            << ArgExpr->getType();
3977 
3978   return false;
3979 }
3980 
3981 bool Sema::CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum) {
3982   llvm::APSInt Result;
3983 
3984   // We can't check the value of a dependent argument.
3985   Expr *Arg = TheCall->getArg(ArgNum);
3986   if (Arg->isTypeDependent() || Arg->isValueDependent())
3987     return false;
3988 
3989   // Check constant-ness first.
3990   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3991     return true;
3992 
3993   int64_t Val = Result.getSExtValue();
3994   if ((Val >= 0 && Val <= 3) || (Val >= 5 && Val <= 7))
3995     return false;
3996 
3997   return Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_invalid_lmul)
3998          << Arg->getSourceRange();
3999 }
4000 
4001 static bool isRISCV32Builtin(unsigned BuiltinID) {
4002   // These builtins only work on riscv32 targets.
4003   switch (BuiltinID) {
4004   case RISCV::BI__builtin_riscv_zip_32:
4005   case RISCV::BI__builtin_riscv_unzip_32:
4006   case RISCV::BI__builtin_riscv_aes32dsi_32:
4007   case RISCV::BI__builtin_riscv_aes32dsmi_32:
4008   case RISCV::BI__builtin_riscv_aes32esi_32:
4009   case RISCV::BI__builtin_riscv_aes32esmi_32:
4010   case RISCV::BI__builtin_riscv_sha512sig0h_32:
4011   case RISCV::BI__builtin_riscv_sha512sig0l_32:
4012   case RISCV::BI__builtin_riscv_sha512sig1h_32:
4013   case RISCV::BI__builtin_riscv_sha512sig1l_32:
4014   case RISCV::BI__builtin_riscv_sha512sum0r_32:
4015   case RISCV::BI__builtin_riscv_sha512sum1r_32:
4016     return true;
4017   }
4018 
4019   return false;
4020 }
4021 
4022 bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI,
4023                                          unsigned BuiltinID,
4024                                          CallExpr *TheCall) {
4025   // CodeGenFunction can also detect this, but this gives a better error
4026   // message.
4027   bool FeatureMissing = false;
4028   SmallVector<StringRef> ReqFeatures;
4029   StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID);
4030   Features.split(ReqFeatures, ',');
4031 
4032   // Check for 32-bit only builtins on a 64-bit target.
4033   const llvm::Triple &TT = TI.getTriple();
4034   if (TT.getArch() != llvm::Triple::riscv32 && isRISCV32Builtin(BuiltinID))
4035     return Diag(TheCall->getCallee()->getBeginLoc(),
4036                 diag::err_32_bit_builtin_64_bit_tgt);
4037 
4038   // Check if each required feature is included
4039   for (StringRef F : ReqFeatures) {
4040     SmallVector<StringRef> ReqOpFeatures;
4041     F.split(ReqOpFeatures, '|');
4042     bool HasFeature = false;
4043     for (StringRef OF : ReqOpFeatures) {
4044       if (TI.hasFeature(OF)) {
4045         HasFeature = true;
4046         continue;
4047       }
4048     }
4049 
4050     if (!HasFeature) {
4051       std::string FeatureStrs;
4052       for (StringRef OF : ReqOpFeatures) {
4053         // If the feature is 64bit, alter the string so it will print better in
4054         // the diagnostic.
4055         if (OF == "64bit")
4056           OF = "RV64";
4057 
4058         // Convert features like "zbr" and "experimental-zbr" to "Zbr".
4059         OF.consume_front("experimental-");
4060         std::string FeatureStr = OF.str();
4061         FeatureStr[0] = std::toupper(FeatureStr[0]);
4062         // Combine strings.
4063         FeatureStrs += FeatureStrs == "" ? "" : ", ";
4064         FeatureStrs += "'";
4065         FeatureStrs += FeatureStr;
4066         FeatureStrs += "'";
4067       }
4068       // Error message
4069       FeatureMissing = true;
4070       Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_requires_extension)
4071           << TheCall->getSourceRange() << StringRef(FeatureStrs);
4072     }
4073   }
4074 
4075   if (FeatureMissing)
4076     return true;
4077 
4078   switch (BuiltinID) {
4079   case RISCVVector::BI__builtin_rvv_vsetvli:
4080     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3) ||
4081            CheckRISCVLMUL(TheCall, 2);
4082   case RISCVVector::BI__builtin_rvv_vsetvlimax:
4083     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3) ||
4084            CheckRISCVLMUL(TheCall, 1);
4085   // Check if byteselect is in [0, 3]
4086   case RISCV::BI__builtin_riscv_aes32dsi_32:
4087   case RISCV::BI__builtin_riscv_aes32dsmi_32:
4088   case RISCV::BI__builtin_riscv_aes32esi_32:
4089   case RISCV::BI__builtin_riscv_aes32esmi_32:
4090   case RISCV::BI__builtin_riscv_sm4ks:
4091   case RISCV::BI__builtin_riscv_sm4ed:
4092     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
4093   // Check if rnum is in [0, 10]
4094   case RISCV::BI__builtin_riscv_aes64ks1i_64:
4095     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 10);
4096   }
4097 
4098   return false;
4099 }
4100 
4101 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
4102                                            CallExpr *TheCall) {
4103   if (BuiltinID == SystemZ::BI__builtin_tabort) {
4104     Expr *Arg = TheCall->getArg(0);
4105     if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context))
4106       if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256)
4107         return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
4108                << Arg->getSourceRange();
4109   }
4110 
4111   // For intrinsics which take an immediate value as part of the instruction,
4112   // range check them here.
4113   unsigned i = 0, l = 0, u = 0;
4114   switch (BuiltinID) {
4115   default: return false;
4116   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
4117   case SystemZ::BI__builtin_s390_verimb:
4118   case SystemZ::BI__builtin_s390_verimh:
4119   case SystemZ::BI__builtin_s390_verimf:
4120   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
4121   case SystemZ::BI__builtin_s390_vfaeb:
4122   case SystemZ::BI__builtin_s390_vfaeh:
4123   case SystemZ::BI__builtin_s390_vfaef:
4124   case SystemZ::BI__builtin_s390_vfaebs:
4125   case SystemZ::BI__builtin_s390_vfaehs:
4126   case SystemZ::BI__builtin_s390_vfaefs:
4127   case SystemZ::BI__builtin_s390_vfaezb:
4128   case SystemZ::BI__builtin_s390_vfaezh:
4129   case SystemZ::BI__builtin_s390_vfaezf:
4130   case SystemZ::BI__builtin_s390_vfaezbs:
4131   case SystemZ::BI__builtin_s390_vfaezhs:
4132   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
4133   case SystemZ::BI__builtin_s390_vfisb:
4134   case SystemZ::BI__builtin_s390_vfidb:
4135     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
4136            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
4137   case SystemZ::BI__builtin_s390_vftcisb:
4138   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
4139   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
4140   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
4141   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
4142   case SystemZ::BI__builtin_s390_vstrcb:
4143   case SystemZ::BI__builtin_s390_vstrch:
4144   case SystemZ::BI__builtin_s390_vstrcf:
4145   case SystemZ::BI__builtin_s390_vstrczb:
4146   case SystemZ::BI__builtin_s390_vstrczh:
4147   case SystemZ::BI__builtin_s390_vstrczf:
4148   case SystemZ::BI__builtin_s390_vstrcbs:
4149   case SystemZ::BI__builtin_s390_vstrchs:
4150   case SystemZ::BI__builtin_s390_vstrcfs:
4151   case SystemZ::BI__builtin_s390_vstrczbs:
4152   case SystemZ::BI__builtin_s390_vstrczhs:
4153   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
4154   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
4155   case SystemZ::BI__builtin_s390_vfminsb:
4156   case SystemZ::BI__builtin_s390_vfmaxsb:
4157   case SystemZ::BI__builtin_s390_vfmindb:
4158   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
4159   case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
4160   case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
4161   case SystemZ::BI__builtin_s390_vclfnhs:
4162   case SystemZ::BI__builtin_s390_vclfnls:
4163   case SystemZ::BI__builtin_s390_vcfn:
4164   case SystemZ::BI__builtin_s390_vcnf: i = 1; l = 0; u = 15; break;
4165   case SystemZ::BI__builtin_s390_vcrnfs: i = 2; l = 0; u = 15; break;
4166   }
4167   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
4168 }
4169 
4170 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
4171 /// This checks that the target supports __builtin_cpu_supports and
4172 /// that the string argument is constant and valid.
4173 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI,
4174                                    CallExpr *TheCall) {
4175   Expr *Arg = TheCall->getArg(0);
4176 
4177   // Check if the argument is a string literal.
4178   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4179     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
4180            << Arg->getSourceRange();
4181 
4182   // Check the contents of the string.
4183   StringRef Feature =
4184       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4185   if (!TI.validateCpuSupports(Feature))
4186     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
4187            << Arg->getSourceRange();
4188   return false;
4189 }
4190 
4191 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
4192 /// This checks that the target supports __builtin_cpu_is and
4193 /// that the string argument is constant and valid.
4194 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) {
4195   Expr *Arg = TheCall->getArg(0);
4196 
4197   // Check if the argument is a string literal.
4198   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4199     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
4200            << Arg->getSourceRange();
4201 
4202   // Check the contents of the string.
4203   StringRef Feature =
4204       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4205   if (!TI.validateCpuIs(Feature))
4206     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
4207            << Arg->getSourceRange();
4208   return false;
4209 }
4210 
4211 // Check if the rounding mode is legal.
4212 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
4213   // Indicates if this instruction has rounding control or just SAE.
4214   bool HasRC = false;
4215 
4216   unsigned ArgNum = 0;
4217   switch (BuiltinID) {
4218   default:
4219     return false;
4220   case X86::BI__builtin_ia32_vcvttsd2si32:
4221   case X86::BI__builtin_ia32_vcvttsd2si64:
4222   case X86::BI__builtin_ia32_vcvttsd2usi32:
4223   case X86::BI__builtin_ia32_vcvttsd2usi64:
4224   case X86::BI__builtin_ia32_vcvttss2si32:
4225   case X86::BI__builtin_ia32_vcvttss2si64:
4226   case X86::BI__builtin_ia32_vcvttss2usi32:
4227   case X86::BI__builtin_ia32_vcvttss2usi64:
4228   case X86::BI__builtin_ia32_vcvttsh2si32:
4229   case X86::BI__builtin_ia32_vcvttsh2si64:
4230   case X86::BI__builtin_ia32_vcvttsh2usi32:
4231   case X86::BI__builtin_ia32_vcvttsh2usi64:
4232     ArgNum = 1;
4233     break;
4234   case X86::BI__builtin_ia32_maxpd512:
4235   case X86::BI__builtin_ia32_maxps512:
4236   case X86::BI__builtin_ia32_minpd512:
4237   case X86::BI__builtin_ia32_minps512:
4238   case X86::BI__builtin_ia32_maxph512:
4239   case X86::BI__builtin_ia32_minph512:
4240     ArgNum = 2;
4241     break;
4242   case X86::BI__builtin_ia32_vcvtph2pd512_mask:
4243   case X86::BI__builtin_ia32_vcvtph2psx512_mask:
4244   case X86::BI__builtin_ia32_cvtps2pd512_mask:
4245   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
4246   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
4247   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
4248   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
4249   case X86::BI__builtin_ia32_cvttps2dq512_mask:
4250   case X86::BI__builtin_ia32_cvttps2qq512_mask:
4251   case X86::BI__builtin_ia32_cvttps2udq512_mask:
4252   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
4253   case X86::BI__builtin_ia32_vcvttph2w512_mask:
4254   case X86::BI__builtin_ia32_vcvttph2uw512_mask:
4255   case X86::BI__builtin_ia32_vcvttph2dq512_mask:
4256   case X86::BI__builtin_ia32_vcvttph2udq512_mask:
4257   case X86::BI__builtin_ia32_vcvttph2qq512_mask:
4258   case X86::BI__builtin_ia32_vcvttph2uqq512_mask:
4259   case X86::BI__builtin_ia32_exp2pd_mask:
4260   case X86::BI__builtin_ia32_exp2ps_mask:
4261   case X86::BI__builtin_ia32_getexppd512_mask:
4262   case X86::BI__builtin_ia32_getexpps512_mask:
4263   case X86::BI__builtin_ia32_getexpph512_mask:
4264   case X86::BI__builtin_ia32_rcp28pd_mask:
4265   case X86::BI__builtin_ia32_rcp28ps_mask:
4266   case X86::BI__builtin_ia32_rsqrt28pd_mask:
4267   case X86::BI__builtin_ia32_rsqrt28ps_mask:
4268   case X86::BI__builtin_ia32_vcomisd:
4269   case X86::BI__builtin_ia32_vcomiss:
4270   case X86::BI__builtin_ia32_vcomish:
4271   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
4272     ArgNum = 3;
4273     break;
4274   case X86::BI__builtin_ia32_cmppd512_mask:
4275   case X86::BI__builtin_ia32_cmpps512_mask:
4276   case X86::BI__builtin_ia32_cmpsd_mask:
4277   case X86::BI__builtin_ia32_cmpss_mask:
4278   case X86::BI__builtin_ia32_cmpsh_mask:
4279   case X86::BI__builtin_ia32_vcvtsh2sd_round_mask:
4280   case X86::BI__builtin_ia32_vcvtsh2ss_round_mask:
4281   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
4282   case X86::BI__builtin_ia32_getexpsd128_round_mask:
4283   case X86::BI__builtin_ia32_getexpss128_round_mask:
4284   case X86::BI__builtin_ia32_getexpsh128_round_mask:
4285   case X86::BI__builtin_ia32_getmantpd512_mask:
4286   case X86::BI__builtin_ia32_getmantps512_mask:
4287   case X86::BI__builtin_ia32_getmantph512_mask:
4288   case X86::BI__builtin_ia32_maxsd_round_mask:
4289   case X86::BI__builtin_ia32_maxss_round_mask:
4290   case X86::BI__builtin_ia32_maxsh_round_mask:
4291   case X86::BI__builtin_ia32_minsd_round_mask:
4292   case X86::BI__builtin_ia32_minss_round_mask:
4293   case X86::BI__builtin_ia32_minsh_round_mask:
4294   case X86::BI__builtin_ia32_rcp28sd_round_mask:
4295   case X86::BI__builtin_ia32_rcp28ss_round_mask:
4296   case X86::BI__builtin_ia32_reducepd512_mask:
4297   case X86::BI__builtin_ia32_reduceps512_mask:
4298   case X86::BI__builtin_ia32_reduceph512_mask:
4299   case X86::BI__builtin_ia32_rndscalepd_mask:
4300   case X86::BI__builtin_ia32_rndscaleps_mask:
4301   case X86::BI__builtin_ia32_rndscaleph_mask:
4302   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
4303   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
4304     ArgNum = 4;
4305     break;
4306   case X86::BI__builtin_ia32_fixupimmpd512_mask:
4307   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
4308   case X86::BI__builtin_ia32_fixupimmps512_mask:
4309   case X86::BI__builtin_ia32_fixupimmps512_maskz:
4310   case X86::BI__builtin_ia32_fixupimmsd_mask:
4311   case X86::BI__builtin_ia32_fixupimmsd_maskz:
4312   case X86::BI__builtin_ia32_fixupimmss_mask:
4313   case X86::BI__builtin_ia32_fixupimmss_maskz:
4314   case X86::BI__builtin_ia32_getmantsd_round_mask:
4315   case X86::BI__builtin_ia32_getmantss_round_mask:
4316   case X86::BI__builtin_ia32_getmantsh_round_mask:
4317   case X86::BI__builtin_ia32_rangepd512_mask:
4318   case X86::BI__builtin_ia32_rangeps512_mask:
4319   case X86::BI__builtin_ia32_rangesd128_round_mask:
4320   case X86::BI__builtin_ia32_rangess128_round_mask:
4321   case X86::BI__builtin_ia32_reducesd_mask:
4322   case X86::BI__builtin_ia32_reducess_mask:
4323   case X86::BI__builtin_ia32_reducesh_mask:
4324   case X86::BI__builtin_ia32_rndscalesd_round_mask:
4325   case X86::BI__builtin_ia32_rndscaless_round_mask:
4326   case X86::BI__builtin_ia32_rndscalesh_round_mask:
4327     ArgNum = 5;
4328     break;
4329   case X86::BI__builtin_ia32_vcvtsd2si64:
4330   case X86::BI__builtin_ia32_vcvtsd2si32:
4331   case X86::BI__builtin_ia32_vcvtsd2usi32:
4332   case X86::BI__builtin_ia32_vcvtsd2usi64:
4333   case X86::BI__builtin_ia32_vcvtss2si32:
4334   case X86::BI__builtin_ia32_vcvtss2si64:
4335   case X86::BI__builtin_ia32_vcvtss2usi32:
4336   case X86::BI__builtin_ia32_vcvtss2usi64:
4337   case X86::BI__builtin_ia32_vcvtsh2si32:
4338   case X86::BI__builtin_ia32_vcvtsh2si64:
4339   case X86::BI__builtin_ia32_vcvtsh2usi32:
4340   case X86::BI__builtin_ia32_vcvtsh2usi64:
4341   case X86::BI__builtin_ia32_sqrtpd512:
4342   case X86::BI__builtin_ia32_sqrtps512:
4343   case X86::BI__builtin_ia32_sqrtph512:
4344     ArgNum = 1;
4345     HasRC = true;
4346     break;
4347   case X86::BI__builtin_ia32_addph512:
4348   case X86::BI__builtin_ia32_divph512:
4349   case X86::BI__builtin_ia32_mulph512:
4350   case X86::BI__builtin_ia32_subph512:
4351   case X86::BI__builtin_ia32_addpd512:
4352   case X86::BI__builtin_ia32_addps512:
4353   case X86::BI__builtin_ia32_divpd512:
4354   case X86::BI__builtin_ia32_divps512:
4355   case X86::BI__builtin_ia32_mulpd512:
4356   case X86::BI__builtin_ia32_mulps512:
4357   case X86::BI__builtin_ia32_subpd512:
4358   case X86::BI__builtin_ia32_subps512:
4359   case X86::BI__builtin_ia32_cvtsi2sd64:
4360   case X86::BI__builtin_ia32_cvtsi2ss32:
4361   case X86::BI__builtin_ia32_cvtsi2ss64:
4362   case X86::BI__builtin_ia32_cvtusi2sd64:
4363   case X86::BI__builtin_ia32_cvtusi2ss32:
4364   case X86::BI__builtin_ia32_cvtusi2ss64:
4365   case X86::BI__builtin_ia32_vcvtusi2sh:
4366   case X86::BI__builtin_ia32_vcvtusi642sh:
4367   case X86::BI__builtin_ia32_vcvtsi2sh:
4368   case X86::BI__builtin_ia32_vcvtsi642sh:
4369     ArgNum = 2;
4370     HasRC = true;
4371     break;
4372   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
4373   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
4374   case X86::BI__builtin_ia32_vcvtpd2ph512_mask:
4375   case X86::BI__builtin_ia32_vcvtps2phx512_mask:
4376   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
4377   case X86::BI__builtin_ia32_cvtpd2dq512_mask:
4378   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
4379   case X86::BI__builtin_ia32_cvtpd2udq512_mask:
4380   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
4381   case X86::BI__builtin_ia32_cvtps2dq512_mask:
4382   case X86::BI__builtin_ia32_cvtps2qq512_mask:
4383   case X86::BI__builtin_ia32_cvtps2udq512_mask:
4384   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
4385   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
4386   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
4387   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
4388   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
4389   case X86::BI__builtin_ia32_vcvtdq2ph512_mask:
4390   case X86::BI__builtin_ia32_vcvtudq2ph512_mask:
4391   case X86::BI__builtin_ia32_vcvtw2ph512_mask:
4392   case X86::BI__builtin_ia32_vcvtuw2ph512_mask:
4393   case X86::BI__builtin_ia32_vcvtph2w512_mask:
4394   case X86::BI__builtin_ia32_vcvtph2uw512_mask:
4395   case X86::BI__builtin_ia32_vcvtph2dq512_mask:
4396   case X86::BI__builtin_ia32_vcvtph2udq512_mask:
4397   case X86::BI__builtin_ia32_vcvtph2qq512_mask:
4398   case X86::BI__builtin_ia32_vcvtph2uqq512_mask:
4399   case X86::BI__builtin_ia32_vcvtqq2ph512_mask:
4400   case X86::BI__builtin_ia32_vcvtuqq2ph512_mask:
4401     ArgNum = 3;
4402     HasRC = true;
4403     break;
4404   case X86::BI__builtin_ia32_addsh_round_mask:
4405   case X86::BI__builtin_ia32_addss_round_mask:
4406   case X86::BI__builtin_ia32_addsd_round_mask:
4407   case X86::BI__builtin_ia32_divsh_round_mask:
4408   case X86::BI__builtin_ia32_divss_round_mask:
4409   case X86::BI__builtin_ia32_divsd_round_mask:
4410   case X86::BI__builtin_ia32_mulsh_round_mask:
4411   case X86::BI__builtin_ia32_mulss_round_mask:
4412   case X86::BI__builtin_ia32_mulsd_round_mask:
4413   case X86::BI__builtin_ia32_subsh_round_mask:
4414   case X86::BI__builtin_ia32_subss_round_mask:
4415   case X86::BI__builtin_ia32_subsd_round_mask:
4416   case X86::BI__builtin_ia32_scalefph512_mask:
4417   case X86::BI__builtin_ia32_scalefpd512_mask:
4418   case X86::BI__builtin_ia32_scalefps512_mask:
4419   case X86::BI__builtin_ia32_scalefsd_round_mask:
4420   case X86::BI__builtin_ia32_scalefss_round_mask:
4421   case X86::BI__builtin_ia32_scalefsh_round_mask:
4422   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
4423   case X86::BI__builtin_ia32_vcvtss2sh_round_mask:
4424   case X86::BI__builtin_ia32_vcvtsd2sh_round_mask:
4425   case X86::BI__builtin_ia32_sqrtsd_round_mask:
4426   case X86::BI__builtin_ia32_sqrtss_round_mask:
4427   case X86::BI__builtin_ia32_sqrtsh_round_mask:
4428   case X86::BI__builtin_ia32_vfmaddsd3_mask:
4429   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
4430   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
4431   case X86::BI__builtin_ia32_vfmaddss3_mask:
4432   case X86::BI__builtin_ia32_vfmaddss3_maskz:
4433   case X86::BI__builtin_ia32_vfmaddss3_mask3:
4434   case X86::BI__builtin_ia32_vfmaddsh3_mask:
4435   case X86::BI__builtin_ia32_vfmaddsh3_maskz:
4436   case X86::BI__builtin_ia32_vfmaddsh3_mask3:
4437   case X86::BI__builtin_ia32_vfmaddpd512_mask:
4438   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
4439   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
4440   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
4441   case X86::BI__builtin_ia32_vfmaddps512_mask:
4442   case X86::BI__builtin_ia32_vfmaddps512_maskz:
4443   case X86::BI__builtin_ia32_vfmaddps512_mask3:
4444   case X86::BI__builtin_ia32_vfmsubps512_mask3:
4445   case X86::BI__builtin_ia32_vfmaddph512_mask:
4446   case X86::BI__builtin_ia32_vfmaddph512_maskz:
4447   case X86::BI__builtin_ia32_vfmaddph512_mask3:
4448   case X86::BI__builtin_ia32_vfmsubph512_mask3:
4449   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
4450   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
4451   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
4452   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
4453   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
4454   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
4455   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
4456   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
4457   case X86::BI__builtin_ia32_vfmaddsubph512_mask:
4458   case X86::BI__builtin_ia32_vfmaddsubph512_maskz:
4459   case X86::BI__builtin_ia32_vfmaddsubph512_mask3:
4460   case X86::BI__builtin_ia32_vfmsubaddph512_mask3:
4461   case X86::BI__builtin_ia32_vfmaddcsh_mask:
4462   case X86::BI__builtin_ia32_vfmaddcsh_round_mask:
4463   case X86::BI__builtin_ia32_vfmaddcsh_round_mask3:
4464   case X86::BI__builtin_ia32_vfmaddcph512_mask:
4465   case X86::BI__builtin_ia32_vfmaddcph512_maskz:
4466   case X86::BI__builtin_ia32_vfmaddcph512_mask3:
4467   case X86::BI__builtin_ia32_vfcmaddcsh_mask:
4468   case X86::BI__builtin_ia32_vfcmaddcsh_round_mask:
4469   case X86::BI__builtin_ia32_vfcmaddcsh_round_mask3:
4470   case X86::BI__builtin_ia32_vfcmaddcph512_mask:
4471   case X86::BI__builtin_ia32_vfcmaddcph512_maskz:
4472   case X86::BI__builtin_ia32_vfcmaddcph512_mask3:
4473   case X86::BI__builtin_ia32_vfmulcsh_mask:
4474   case X86::BI__builtin_ia32_vfmulcph512_mask:
4475   case X86::BI__builtin_ia32_vfcmulcsh_mask:
4476   case X86::BI__builtin_ia32_vfcmulcph512_mask:
4477     ArgNum = 4;
4478     HasRC = true;
4479     break;
4480   }
4481 
4482   llvm::APSInt Result;
4483 
4484   // We can't check the value of a dependent argument.
4485   Expr *Arg = TheCall->getArg(ArgNum);
4486   if (Arg->isTypeDependent() || Arg->isValueDependent())
4487     return false;
4488 
4489   // Check constant-ness first.
4490   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4491     return true;
4492 
4493   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
4494   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
4495   // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
4496   // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
4497   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
4498       Result == 8/*ROUND_NO_EXC*/ ||
4499       (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
4500       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
4501     return false;
4502 
4503   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
4504          << Arg->getSourceRange();
4505 }
4506 
4507 // Check if the gather/scatter scale is legal.
4508 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
4509                                              CallExpr *TheCall) {
4510   unsigned ArgNum = 0;
4511   switch (BuiltinID) {
4512   default:
4513     return false;
4514   case X86::BI__builtin_ia32_gatherpfdpd:
4515   case X86::BI__builtin_ia32_gatherpfdps:
4516   case X86::BI__builtin_ia32_gatherpfqpd:
4517   case X86::BI__builtin_ia32_gatherpfqps:
4518   case X86::BI__builtin_ia32_scatterpfdpd:
4519   case X86::BI__builtin_ia32_scatterpfdps:
4520   case X86::BI__builtin_ia32_scatterpfqpd:
4521   case X86::BI__builtin_ia32_scatterpfqps:
4522     ArgNum = 3;
4523     break;
4524   case X86::BI__builtin_ia32_gatherd_pd:
4525   case X86::BI__builtin_ia32_gatherd_pd256:
4526   case X86::BI__builtin_ia32_gatherq_pd:
4527   case X86::BI__builtin_ia32_gatherq_pd256:
4528   case X86::BI__builtin_ia32_gatherd_ps:
4529   case X86::BI__builtin_ia32_gatherd_ps256:
4530   case X86::BI__builtin_ia32_gatherq_ps:
4531   case X86::BI__builtin_ia32_gatherq_ps256:
4532   case X86::BI__builtin_ia32_gatherd_q:
4533   case X86::BI__builtin_ia32_gatherd_q256:
4534   case X86::BI__builtin_ia32_gatherq_q:
4535   case X86::BI__builtin_ia32_gatherq_q256:
4536   case X86::BI__builtin_ia32_gatherd_d:
4537   case X86::BI__builtin_ia32_gatherd_d256:
4538   case X86::BI__builtin_ia32_gatherq_d:
4539   case X86::BI__builtin_ia32_gatherq_d256:
4540   case X86::BI__builtin_ia32_gather3div2df:
4541   case X86::BI__builtin_ia32_gather3div2di:
4542   case X86::BI__builtin_ia32_gather3div4df:
4543   case X86::BI__builtin_ia32_gather3div4di:
4544   case X86::BI__builtin_ia32_gather3div4sf:
4545   case X86::BI__builtin_ia32_gather3div4si:
4546   case X86::BI__builtin_ia32_gather3div8sf:
4547   case X86::BI__builtin_ia32_gather3div8si:
4548   case X86::BI__builtin_ia32_gather3siv2df:
4549   case X86::BI__builtin_ia32_gather3siv2di:
4550   case X86::BI__builtin_ia32_gather3siv4df:
4551   case X86::BI__builtin_ia32_gather3siv4di:
4552   case X86::BI__builtin_ia32_gather3siv4sf:
4553   case X86::BI__builtin_ia32_gather3siv4si:
4554   case X86::BI__builtin_ia32_gather3siv8sf:
4555   case X86::BI__builtin_ia32_gather3siv8si:
4556   case X86::BI__builtin_ia32_gathersiv8df:
4557   case X86::BI__builtin_ia32_gathersiv16sf:
4558   case X86::BI__builtin_ia32_gatherdiv8df:
4559   case X86::BI__builtin_ia32_gatherdiv16sf:
4560   case X86::BI__builtin_ia32_gathersiv8di:
4561   case X86::BI__builtin_ia32_gathersiv16si:
4562   case X86::BI__builtin_ia32_gatherdiv8di:
4563   case X86::BI__builtin_ia32_gatherdiv16si:
4564   case X86::BI__builtin_ia32_scatterdiv2df:
4565   case X86::BI__builtin_ia32_scatterdiv2di:
4566   case X86::BI__builtin_ia32_scatterdiv4df:
4567   case X86::BI__builtin_ia32_scatterdiv4di:
4568   case X86::BI__builtin_ia32_scatterdiv4sf:
4569   case X86::BI__builtin_ia32_scatterdiv4si:
4570   case X86::BI__builtin_ia32_scatterdiv8sf:
4571   case X86::BI__builtin_ia32_scatterdiv8si:
4572   case X86::BI__builtin_ia32_scattersiv2df:
4573   case X86::BI__builtin_ia32_scattersiv2di:
4574   case X86::BI__builtin_ia32_scattersiv4df:
4575   case X86::BI__builtin_ia32_scattersiv4di:
4576   case X86::BI__builtin_ia32_scattersiv4sf:
4577   case X86::BI__builtin_ia32_scattersiv4si:
4578   case X86::BI__builtin_ia32_scattersiv8sf:
4579   case X86::BI__builtin_ia32_scattersiv8si:
4580   case X86::BI__builtin_ia32_scattersiv8df:
4581   case X86::BI__builtin_ia32_scattersiv16sf:
4582   case X86::BI__builtin_ia32_scatterdiv8df:
4583   case X86::BI__builtin_ia32_scatterdiv16sf:
4584   case X86::BI__builtin_ia32_scattersiv8di:
4585   case X86::BI__builtin_ia32_scattersiv16si:
4586   case X86::BI__builtin_ia32_scatterdiv8di:
4587   case X86::BI__builtin_ia32_scatterdiv16si:
4588     ArgNum = 4;
4589     break;
4590   }
4591 
4592   llvm::APSInt Result;
4593 
4594   // We can't check the value of a dependent argument.
4595   Expr *Arg = TheCall->getArg(ArgNum);
4596   if (Arg->isTypeDependent() || Arg->isValueDependent())
4597     return false;
4598 
4599   // Check constant-ness first.
4600   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4601     return true;
4602 
4603   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
4604     return false;
4605 
4606   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
4607          << Arg->getSourceRange();
4608 }
4609 
4610 enum { TileRegLow = 0, TileRegHigh = 7 };
4611 
4612 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
4613                                              ArrayRef<int> ArgNums) {
4614   for (int ArgNum : ArgNums) {
4615     if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh))
4616       return true;
4617   }
4618   return false;
4619 }
4620 
4621 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall,
4622                                         ArrayRef<int> ArgNums) {
4623   // Because the max number of tile register is TileRegHigh + 1, so here we use
4624   // each bit to represent the usage of them in bitset.
4625   std::bitset<TileRegHigh + 1> ArgValues;
4626   for (int ArgNum : ArgNums) {
4627     Expr *Arg = TheCall->getArg(ArgNum);
4628     if (Arg->isTypeDependent() || Arg->isValueDependent())
4629       continue;
4630 
4631     llvm::APSInt Result;
4632     if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4633       return true;
4634     int ArgExtValue = Result.getExtValue();
4635     assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) &&
4636            "Incorrect tile register num.");
4637     if (ArgValues.test(ArgExtValue))
4638       return Diag(TheCall->getBeginLoc(),
4639                   diag::err_x86_builtin_tile_arg_duplicate)
4640              << TheCall->getArg(ArgNum)->getSourceRange();
4641     ArgValues.set(ArgExtValue);
4642   }
4643   return false;
4644 }
4645 
4646 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
4647                                                 ArrayRef<int> ArgNums) {
4648   return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) ||
4649          CheckX86BuiltinTileDuplicate(TheCall, ArgNums);
4650 }
4651 
4652 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) {
4653   switch (BuiltinID) {
4654   default:
4655     return false;
4656   case X86::BI__builtin_ia32_tileloadd64:
4657   case X86::BI__builtin_ia32_tileloaddt164:
4658   case X86::BI__builtin_ia32_tilestored64:
4659   case X86::BI__builtin_ia32_tilezero:
4660     return CheckX86BuiltinTileArgumentsRange(TheCall, 0);
4661   case X86::BI__builtin_ia32_tdpbssd:
4662   case X86::BI__builtin_ia32_tdpbsud:
4663   case X86::BI__builtin_ia32_tdpbusd:
4664   case X86::BI__builtin_ia32_tdpbuud:
4665   case X86::BI__builtin_ia32_tdpbf16ps:
4666     return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2});
4667   }
4668 }
4669 static bool isX86_32Builtin(unsigned BuiltinID) {
4670   // These builtins only work on x86-32 targets.
4671   switch (BuiltinID) {
4672   case X86::BI__builtin_ia32_readeflags_u32:
4673   case X86::BI__builtin_ia32_writeeflags_u32:
4674     return true;
4675   }
4676 
4677   return false;
4678 }
4679 
4680 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
4681                                        CallExpr *TheCall) {
4682   if (BuiltinID == X86::BI__builtin_cpu_supports)
4683     return SemaBuiltinCpuSupports(*this, TI, TheCall);
4684 
4685   if (BuiltinID == X86::BI__builtin_cpu_is)
4686     return SemaBuiltinCpuIs(*this, TI, TheCall);
4687 
4688   // Check for 32-bit only builtins on a 64-bit target.
4689   const llvm::Triple &TT = TI.getTriple();
4690   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
4691     return Diag(TheCall->getCallee()->getBeginLoc(),
4692                 diag::err_32_bit_builtin_64_bit_tgt);
4693 
4694   // If the intrinsic has rounding or SAE make sure its valid.
4695   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
4696     return true;
4697 
4698   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
4699   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
4700     return true;
4701 
4702   // If the intrinsic has a tile arguments, make sure they are valid.
4703   if (CheckX86BuiltinTileArguments(BuiltinID, TheCall))
4704     return true;
4705 
4706   // For intrinsics which take an immediate value as part of the instruction,
4707   // range check them here.
4708   int i = 0, l = 0, u = 0;
4709   switch (BuiltinID) {
4710   default:
4711     return false;
4712   case X86::BI__builtin_ia32_vec_ext_v2si:
4713   case X86::BI__builtin_ia32_vec_ext_v2di:
4714   case X86::BI__builtin_ia32_vextractf128_pd256:
4715   case X86::BI__builtin_ia32_vextractf128_ps256:
4716   case X86::BI__builtin_ia32_vextractf128_si256:
4717   case X86::BI__builtin_ia32_extract128i256:
4718   case X86::BI__builtin_ia32_extractf64x4_mask:
4719   case X86::BI__builtin_ia32_extracti64x4_mask:
4720   case X86::BI__builtin_ia32_extractf32x8_mask:
4721   case X86::BI__builtin_ia32_extracti32x8_mask:
4722   case X86::BI__builtin_ia32_extractf64x2_256_mask:
4723   case X86::BI__builtin_ia32_extracti64x2_256_mask:
4724   case X86::BI__builtin_ia32_extractf32x4_256_mask:
4725   case X86::BI__builtin_ia32_extracti32x4_256_mask:
4726     i = 1; l = 0; u = 1;
4727     break;
4728   case X86::BI__builtin_ia32_vec_set_v2di:
4729   case X86::BI__builtin_ia32_vinsertf128_pd256:
4730   case X86::BI__builtin_ia32_vinsertf128_ps256:
4731   case X86::BI__builtin_ia32_vinsertf128_si256:
4732   case X86::BI__builtin_ia32_insert128i256:
4733   case X86::BI__builtin_ia32_insertf32x8:
4734   case X86::BI__builtin_ia32_inserti32x8:
4735   case X86::BI__builtin_ia32_insertf64x4:
4736   case X86::BI__builtin_ia32_inserti64x4:
4737   case X86::BI__builtin_ia32_insertf64x2_256:
4738   case X86::BI__builtin_ia32_inserti64x2_256:
4739   case X86::BI__builtin_ia32_insertf32x4_256:
4740   case X86::BI__builtin_ia32_inserti32x4_256:
4741     i = 2; l = 0; u = 1;
4742     break;
4743   case X86::BI__builtin_ia32_vpermilpd:
4744   case X86::BI__builtin_ia32_vec_ext_v4hi:
4745   case X86::BI__builtin_ia32_vec_ext_v4si:
4746   case X86::BI__builtin_ia32_vec_ext_v4sf:
4747   case X86::BI__builtin_ia32_vec_ext_v4di:
4748   case X86::BI__builtin_ia32_extractf32x4_mask:
4749   case X86::BI__builtin_ia32_extracti32x4_mask:
4750   case X86::BI__builtin_ia32_extractf64x2_512_mask:
4751   case X86::BI__builtin_ia32_extracti64x2_512_mask:
4752     i = 1; l = 0; u = 3;
4753     break;
4754   case X86::BI_mm_prefetch:
4755   case X86::BI__builtin_ia32_vec_ext_v8hi:
4756   case X86::BI__builtin_ia32_vec_ext_v8si:
4757     i = 1; l = 0; u = 7;
4758     break;
4759   case X86::BI__builtin_ia32_sha1rnds4:
4760   case X86::BI__builtin_ia32_blendpd:
4761   case X86::BI__builtin_ia32_shufpd:
4762   case X86::BI__builtin_ia32_vec_set_v4hi:
4763   case X86::BI__builtin_ia32_vec_set_v4si:
4764   case X86::BI__builtin_ia32_vec_set_v4di:
4765   case X86::BI__builtin_ia32_shuf_f32x4_256:
4766   case X86::BI__builtin_ia32_shuf_f64x2_256:
4767   case X86::BI__builtin_ia32_shuf_i32x4_256:
4768   case X86::BI__builtin_ia32_shuf_i64x2_256:
4769   case X86::BI__builtin_ia32_insertf64x2_512:
4770   case X86::BI__builtin_ia32_inserti64x2_512:
4771   case X86::BI__builtin_ia32_insertf32x4:
4772   case X86::BI__builtin_ia32_inserti32x4:
4773     i = 2; l = 0; u = 3;
4774     break;
4775   case X86::BI__builtin_ia32_vpermil2pd:
4776   case X86::BI__builtin_ia32_vpermil2pd256:
4777   case X86::BI__builtin_ia32_vpermil2ps:
4778   case X86::BI__builtin_ia32_vpermil2ps256:
4779     i = 3; l = 0; u = 3;
4780     break;
4781   case X86::BI__builtin_ia32_cmpb128_mask:
4782   case X86::BI__builtin_ia32_cmpw128_mask:
4783   case X86::BI__builtin_ia32_cmpd128_mask:
4784   case X86::BI__builtin_ia32_cmpq128_mask:
4785   case X86::BI__builtin_ia32_cmpb256_mask:
4786   case X86::BI__builtin_ia32_cmpw256_mask:
4787   case X86::BI__builtin_ia32_cmpd256_mask:
4788   case X86::BI__builtin_ia32_cmpq256_mask:
4789   case X86::BI__builtin_ia32_cmpb512_mask:
4790   case X86::BI__builtin_ia32_cmpw512_mask:
4791   case X86::BI__builtin_ia32_cmpd512_mask:
4792   case X86::BI__builtin_ia32_cmpq512_mask:
4793   case X86::BI__builtin_ia32_ucmpb128_mask:
4794   case X86::BI__builtin_ia32_ucmpw128_mask:
4795   case X86::BI__builtin_ia32_ucmpd128_mask:
4796   case X86::BI__builtin_ia32_ucmpq128_mask:
4797   case X86::BI__builtin_ia32_ucmpb256_mask:
4798   case X86::BI__builtin_ia32_ucmpw256_mask:
4799   case X86::BI__builtin_ia32_ucmpd256_mask:
4800   case X86::BI__builtin_ia32_ucmpq256_mask:
4801   case X86::BI__builtin_ia32_ucmpb512_mask:
4802   case X86::BI__builtin_ia32_ucmpw512_mask:
4803   case X86::BI__builtin_ia32_ucmpd512_mask:
4804   case X86::BI__builtin_ia32_ucmpq512_mask:
4805   case X86::BI__builtin_ia32_vpcomub:
4806   case X86::BI__builtin_ia32_vpcomuw:
4807   case X86::BI__builtin_ia32_vpcomud:
4808   case X86::BI__builtin_ia32_vpcomuq:
4809   case X86::BI__builtin_ia32_vpcomb:
4810   case X86::BI__builtin_ia32_vpcomw:
4811   case X86::BI__builtin_ia32_vpcomd:
4812   case X86::BI__builtin_ia32_vpcomq:
4813   case X86::BI__builtin_ia32_vec_set_v8hi:
4814   case X86::BI__builtin_ia32_vec_set_v8si:
4815     i = 2; l = 0; u = 7;
4816     break;
4817   case X86::BI__builtin_ia32_vpermilpd256:
4818   case X86::BI__builtin_ia32_roundps:
4819   case X86::BI__builtin_ia32_roundpd:
4820   case X86::BI__builtin_ia32_roundps256:
4821   case X86::BI__builtin_ia32_roundpd256:
4822   case X86::BI__builtin_ia32_getmantpd128_mask:
4823   case X86::BI__builtin_ia32_getmantpd256_mask:
4824   case X86::BI__builtin_ia32_getmantps128_mask:
4825   case X86::BI__builtin_ia32_getmantps256_mask:
4826   case X86::BI__builtin_ia32_getmantpd512_mask:
4827   case X86::BI__builtin_ia32_getmantps512_mask:
4828   case X86::BI__builtin_ia32_getmantph128_mask:
4829   case X86::BI__builtin_ia32_getmantph256_mask:
4830   case X86::BI__builtin_ia32_getmantph512_mask:
4831   case X86::BI__builtin_ia32_vec_ext_v16qi:
4832   case X86::BI__builtin_ia32_vec_ext_v16hi:
4833     i = 1; l = 0; u = 15;
4834     break;
4835   case X86::BI__builtin_ia32_pblendd128:
4836   case X86::BI__builtin_ia32_blendps:
4837   case X86::BI__builtin_ia32_blendpd256:
4838   case X86::BI__builtin_ia32_shufpd256:
4839   case X86::BI__builtin_ia32_roundss:
4840   case X86::BI__builtin_ia32_roundsd:
4841   case X86::BI__builtin_ia32_rangepd128_mask:
4842   case X86::BI__builtin_ia32_rangepd256_mask:
4843   case X86::BI__builtin_ia32_rangepd512_mask:
4844   case X86::BI__builtin_ia32_rangeps128_mask:
4845   case X86::BI__builtin_ia32_rangeps256_mask:
4846   case X86::BI__builtin_ia32_rangeps512_mask:
4847   case X86::BI__builtin_ia32_getmantsd_round_mask:
4848   case X86::BI__builtin_ia32_getmantss_round_mask:
4849   case X86::BI__builtin_ia32_getmantsh_round_mask:
4850   case X86::BI__builtin_ia32_vec_set_v16qi:
4851   case X86::BI__builtin_ia32_vec_set_v16hi:
4852     i = 2; l = 0; u = 15;
4853     break;
4854   case X86::BI__builtin_ia32_vec_ext_v32qi:
4855     i = 1; l = 0; u = 31;
4856     break;
4857   case X86::BI__builtin_ia32_cmpps:
4858   case X86::BI__builtin_ia32_cmpss:
4859   case X86::BI__builtin_ia32_cmppd:
4860   case X86::BI__builtin_ia32_cmpsd:
4861   case X86::BI__builtin_ia32_cmpps256:
4862   case X86::BI__builtin_ia32_cmppd256:
4863   case X86::BI__builtin_ia32_cmpps128_mask:
4864   case X86::BI__builtin_ia32_cmppd128_mask:
4865   case X86::BI__builtin_ia32_cmpps256_mask:
4866   case X86::BI__builtin_ia32_cmppd256_mask:
4867   case X86::BI__builtin_ia32_cmpps512_mask:
4868   case X86::BI__builtin_ia32_cmppd512_mask:
4869   case X86::BI__builtin_ia32_cmpsd_mask:
4870   case X86::BI__builtin_ia32_cmpss_mask:
4871   case X86::BI__builtin_ia32_vec_set_v32qi:
4872     i = 2; l = 0; u = 31;
4873     break;
4874   case X86::BI__builtin_ia32_permdf256:
4875   case X86::BI__builtin_ia32_permdi256:
4876   case X86::BI__builtin_ia32_permdf512:
4877   case X86::BI__builtin_ia32_permdi512:
4878   case X86::BI__builtin_ia32_vpermilps:
4879   case X86::BI__builtin_ia32_vpermilps256:
4880   case X86::BI__builtin_ia32_vpermilpd512:
4881   case X86::BI__builtin_ia32_vpermilps512:
4882   case X86::BI__builtin_ia32_pshufd:
4883   case X86::BI__builtin_ia32_pshufd256:
4884   case X86::BI__builtin_ia32_pshufd512:
4885   case X86::BI__builtin_ia32_pshufhw:
4886   case X86::BI__builtin_ia32_pshufhw256:
4887   case X86::BI__builtin_ia32_pshufhw512:
4888   case X86::BI__builtin_ia32_pshuflw:
4889   case X86::BI__builtin_ia32_pshuflw256:
4890   case X86::BI__builtin_ia32_pshuflw512:
4891   case X86::BI__builtin_ia32_vcvtps2ph:
4892   case X86::BI__builtin_ia32_vcvtps2ph_mask:
4893   case X86::BI__builtin_ia32_vcvtps2ph256:
4894   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
4895   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
4896   case X86::BI__builtin_ia32_rndscaleps_128_mask:
4897   case X86::BI__builtin_ia32_rndscalepd_128_mask:
4898   case X86::BI__builtin_ia32_rndscaleps_256_mask:
4899   case X86::BI__builtin_ia32_rndscalepd_256_mask:
4900   case X86::BI__builtin_ia32_rndscaleps_mask:
4901   case X86::BI__builtin_ia32_rndscalepd_mask:
4902   case X86::BI__builtin_ia32_rndscaleph_mask:
4903   case X86::BI__builtin_ia32_reducepd128_mask:
4904   case X86::BI__builtin_ia32_reducepd256_mask:
4905   case X86::BI__builtin_ia32_reducepd512_mask:
4906   case X86::BI__builtin_ia32_reduceps128_mask:
4907   case X86::BI__builtin_ia32_reduceps256_mask:
4908   case X86::BI__builtin_ia32_reduceps512_mask:
4909   case X86::BI__builtin_ia32_reduceph128_mask:
4910   case X86::BI__builtin_ia32_reduceph256_mask:
4911   case X86::BI__builtin_ia32_reduceph512_mask:
4912   case X86::BI__builtin_ia32_prold512:
4913   case X86::BI__builtin_ia32_prolq512:
4914   case X86::BI__builtin_ia32_prold128:
4915   case X86::BI__builtin_ia32_prold256:
4916   case X86::BI__builtin_ia32_prolq128:
4917   case X86::BI__builtin_ia32_prolq256:
4918   case X86::BI__builtin_ia32_prord512:
4919   case X86::BI__builtin_ia32_prorq512:
4920   case X86::BI__builtin_ia32_prord128:
4921   case X86::BI__builtin_ia32_prord256:
4922   case X86::BI__builtin_ia32_prorq128:
4923   case X86::BI__builtin_ia32_prorq256:
4924   case X86::BI__builtin_ia32_fpclasspd128_mask:
4925   case X86::BI__builtin_ia32_fpclasspd256_mask:
4926   case X86::BI__builtin_ia32_fpclassps128_mask:
4927   case X86::BI__builtin_ia32_fpclassps256_mask:
4928   case X86::BI__builtin_ia32_fpclassps512_mask:
4929   case X86::BI__builtin_ia32_fpclasspd512_mask:
4930   case X86::BI__builtin_ia32_fpclassph128_mask:
4931   case X86::BI__builtin_ia32_fpclassph256_mask:
4932   case X86::BI__builtin_ia32_fpclassph512_mask:
4933   case X86::BI__builtin_ia32_fpclasssd_mask:
4934   case X86::BI__builtin_ia32_fpclassss_mask:
4935   case X86::BI__builtin_ia32_fpclasssh_mask:
4936   case X86::BI__builtin_ia32_pslldqi128_byteshift:
4937   case X86::BI__builtin_ia32_pslldqi256_byteshift:
4938   case X86::BI__builtin_ia32_pslldqi512_byteshift:
4939   case X86::BI__builtin_ia32_psrldqi128_byteshift:
4940   case X86::BI__builtin_ia32_psrldqi256_byteshift:
4941   case X86::BI__builtin_ia32_psrldqi512_byteshift:
4942   case X86::BI__builtin_ia32_kshiftliqi:
4943   case X86::BI__builtin_ia32_kshiftlihi:
4944   case X86::BI__builtin_ia32_kshiftlisi:
4945   case X86::BI__builtin_ia32_kshiftlidi:
4946   case X86::BI__builtin_ia32_kshiftriqi:
4947   case X86::BI__builtin_ia32_kshiftrihi:
4948   case X86::BI__builtin_ia32_kshiftrisi:
4949   case X86::BI__builtin_ia32_kshiftridi:
4950     i = 1; l = 0; u = 255;
4951     break;
4952   case X86::BI__builtin_ia32_vperm2f128_pd256:
4953   case X86::BI__builtin_ia32_vperm2f128_ps256:
4954   case X86::BI__builtin_ia32_vperm2f128_si256:
4955   case X86::BI__builtin_ia32_permti256:
4956   case X86::BI__builtin_ia32_pblendw128:
4957   case X86::BI__builtin_ia32_pblendw256:
4958   case X86::BI__builtin_ia32_blendps256:
4959   case X86::BI__builtin_ia32_pblendd256:
4960   case X86::BI__builtin_ia32_palignr128:
4961   case X86::BI__builtin_ia32_palignr256:
4962   case X86::BI__builtin_ia32_palignr512:
4963   case X86::BI__builtin_ia32_alignq512:
4964   case X86::BI__builtin_ia32_alignd512:
4965   case X86::BI__builtin_ia32_alignd128:
4966   case X86::BI__builtin_ia32_alignd256:
4967   case X86::BI__builtin_ia32_alignq128:
4968   case X86::BI__builtin_ia32_alignq256:
4969   case X86::BI__builtin_ia32_vcomisd:
4970   case X86::BI__builtin_ia32_vcomiss:
4971   case X86::BI__builtin_ia32_shuf_f32x4:
4972   case X86::BI__builtin_ia32_shuf_f64x2:
4973   case X86::BI__builtin_ia32_shuf_i32x4:
4974   case X86::BI__builtin_ia32_shuf_i64x2:
4975   case X86::BI__builtin_ia32_shufpd512:
4976   case X86::BI__builtin_ia32_shufps:
4977   case X86::BI__builtin_ia32_shufps256:
4978   case X86::BI__builtin_ia32_shufps512:
4979   case X86::BI__builtin_ia32_dbpsadbw128:
4980   case X86::BI__builtin_ia32_dbpsadbw256:
4981   case X86::BI__builtin_ia32_dbpsadbw512:
4982   case X86::BI__builtin_ia32_vpshldd128:
4983   case X86::BI__builtin_ia32_vpshldd256:
4984   case X86::BI__builtin_ia32_vpshldd512:
4985   case X86::BI__builtin_ia32_vpshldq128:
4986   case X86::BI__builtin_ia32_vpshldq256:
4987   case X86::BI__builtin_ia32_vpshldq512:
4988   case X86::BI__builtin_ia32_vpshldw128:
4989   case X86::BI__builtin_ia32_vpshldw256:
4990   case X86::BI__builtin_ia32_vpshldw512:
4991   case X86::BI__builtin_ia32_vpshrdd128:
4992   case X86::BI__builtin_ia32_vpshrdd256:
4993   case X86::BI__builtin_ia32_vpshrdd512:
4994   case X86::BI__builtin_ia32_vpshrdq128:
4995   case X86::BI__builtin_ia32_vpshrdq256:
4996   case X86::BI__builtin_ia32_vpshrdq512:
4997   case X86::BI__builtin_ia32_vpshrdw128:
4998   case X86::BI__builtin_ia32_vpshrdw256:
4999   case X86::BI__builtin_ia32_vpshrdw512:
5000     i = 2; l = 0; u = 255;
5001     break;
5002   case X86::BI__builtin_ia32_fixupimmpd512_mask:
5003   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
5004   case X86::BI__builtin_ia32_fixupimmps512_mask:
5005   case X86::BI__builtin_ia32_fixupimmps512_maskz:
5006   case X86::BI__builtin_ia32_fixupimmsd_mask:
5007   case X86::BI__builtin_ia32_fixupimmsd_maskz:
5008   case X86::BI__builtin_ia32_fixupimmss_mask:
5009   case X86::BI__builtin_ia32_fixupimmss_maskz:
5010   case X86::BI__builtin_ia32_fixupimmpd128_mask:
5011   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
5012   case X86::BI__builtin_ia32_fixupimmpd256_mask:
5013   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
5014   case X86::BI__builtin_ia32_fixupimmps128_mask:
5015   case X86::BI__builtin_ia32_fixupimmps128_maskz:
5016   case X86::BI__builtin_ia32_fixupimmps256_mask:
5017   case X86::BI__builtin_ia32_fixupimmps256_maskz:
5018   case X86::BI__builtin_ia32_pternlogd512_mask:
5019   case X86::BI__builtin_ia32_pternlogd512_maskz:
5020   case X86::BI__builtin_ia32_pternlogq512_mask:
5021   case X86::BI__builtin_ia32_pternlogq512_maskz:
5022   case X86::BI__builtin_ia32_pternlogd128_mask:
5023   case X86::BI__builtin_ia32_pternlogd128_maskz:
5024   case X86::BI__builtin_ia32_pternlogd256_mask:
5025   case X86::BI__builtin_ia32_pternlogd256_maskz:
5026   case X86::BI__builtin_ia32_pternlogq128_mask:
5027   case X86::BI__builtin_ia32_pternlogq128_maskz:
5028   case X86::BI__builtin_ia32_pternlogq256_mask:
5029   case X86::BI__builtin_ia32_pternlogq256_maskz:
5030     i = 3; l = 0; u = 255;
5031     break;
5032   case X86::BI__builtin_ia32_gatherpfdpd:
5033   case X86::BI__builtin_ia32_gatherpfdps:
5034   case X86::BI__builtin_ia32_gatherpfqpd:
5035   case X86::BI__builtin_ia32_gatherpfqps:
5036   case X86::BI__builtin_ia32_scatterpfdpd:
5037   case X86::BI__builtin_ia32_scatterpfdps:
5038   case X86::BI__builtin_ia32_scatterpfqpd:
5039   case X86::BI__builtin_ia32_scatterpfqps:
5040     i = 4; l = 2; u = 3;
5041     break;
5042   case X86::BI__builtin_ia32_reducesd_mask:
5043   case X86::BI__builtin_ia32_reducess_mask:
5044   case X86::BI__builtin_ia32_rndscalesd_round_mask:
5045   case X86::BI__builtin_ia32_rndscaless_round_mask:
5046   case X86::BI__builtin_ia32_rndscalesh_round_mask:
5047   case X86::BI__builtin_ia32_reducesh_mask:
5048     i = 4; l = 0; u = 255;
5049     break;
5050   }
5051 
5052   // Note that we don't force a hard error on the range check here, allowing
5053   // template-generated or macro-generated dead code to potentially have out-of-
5054   // range values. These need to code generate, but don't need to necessarily
5055   // make any sense. We use a warning that defaults to an error.
5056   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
5057 }
5058 
5059 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
5060 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
5061 /// Returns true when the format fits the function and the FormatStringInfo has
5062 /// been populated.
5063 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
5064                                FormatStringInfo *FSI) {
5065   FSI->HasVAListArg = Format->getFirstArg() == 0;
5066   FSI->FormatIdx = Format->getFormatIdx() - 1;
5067   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
5068 
5069   // The way the format attribute works in GCC, the implicit this argument
5070   // of member functions is counted. However, it doesn't appear in our own
5071   // lists, so decrement format_idx in that case.
5072   if (IsCXXMember) {
5073     if(FSI->FormatIdx == 0)
5074       return false;
5075     --FSI->FormatIdx;
5076     if (FSI->FirstDataArg != 0)
5077       --FSI->FirstDataArg;
5078   }
5079   return true;
5080 }
5081 
5082 /// Checks if a the given expression evaluates to null.
5083 ///
5084 /// Returns true if the value evaluates to null.
5085 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
5086   // If the expression has non-null type, it doesn't evaluate to null.
5087   if (auto nullability
5088         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
5089     if (*nullability == NullabilityKind::NonNull)
5090       return false;
5091   }
5092 
5093   // As a special case, transparent unions initialized with zero are
5094   // considered null for the purposes of the nonnull attribute.
5095   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
5096     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
5097       if (const CompoundLiteralExpr *CLE =
5098           dyn_cast<CompoundLiteralExpr>(Expr))
5099         if (const InitListExpr *ILE =
5100             dyn_cast<InitListExpr>(CLE->getInitializer()))
5101           Expr = ILE->getInit(0);
5102   }
5103 
5104   bool Result;
5105   return (!Expr->isValueDependent() &&
5106           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
5107           !Result);
5108 }
5109 
5110 static void CheckNonNullArgument(Sema &S,
5111                                  const Expr *ArgExpr,
5112                                  SourceLocation CallSiteLoc) {
5113   if (CheckNonNullExpr(S, ArgExpr))
5114     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
5115                           S.PDiag(diag::warn_null_arg)
5116                               << ArgExpr->getSourceRange());
5117 }
5118 
5119 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
5120   FormatStringInfo FSI;
5121   if ((GetFormatStringType(Format) == FST_NSString) &&
5122       getFormatStringInfo(Format, false, &FSI)) {
5123     Idx = FSI.FormatIdx;
5124     return true;
5125   }
5126   return false;
5127 }
5128 
5129 /// Diagnose use of %s directive in an NSString which is being passed
5130 /// as formatting string to formatting method.
5131 static void
5132 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
5133                                         const NamedDecl *FDecl,
5134                                         Expr **Args,
5135                                         unsigned NumArgs) {
5136   unsigned Idx = 0;
5137   bool Format = false;
5138   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
5139   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
5140     Idx = 2;
5141     Format = true;
5142   }
5143   else
5144     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
5145       if (S.GetFormatNSStringIdx(I, Idx)) {
5146         Format = true;
5147         break;
5148       }
5149     }
5150   if (!Format || NumArgs <= Idx)
5151     return;
5152   const Expr *FormatExpr = Args[Idx];
5153   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
5154     FormatExpr = CSCE->getSubExpr();
5155   const StringLiteral *FormatString;
5156   if (const ObjCStringLiteral *OSL =
5157       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
5158     FormatString = OSL->getString();
5159   else
5160     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
5161   if (!FormatString)
5162     return;
5163   if (S.FormatStringHasSArg(FormatString)) {
5164     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
5165       << "%s" << 1 << 1;
5166     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
5167       << FDecl->getDeclName();
5168   }
5169 }
5170 
5171 /// Determine whether the given type has a non-null nullability annotation.
5172 static bool isNonNullType(ASTContext &ctx, QualType type) {
5173   if (auto nullability = type->getNullability(ctx))
5174     return *nullability == NullabilityKind::NonNull;
5175 
5176   return false;
5177 }
5178 
5179 static void CheckNonNullArguments(Sema &S,
5180                                   const NamedDecl *FDecl,
5181                                   const FunctionProtoType *Proto,
5182                                   ArrayRef<const Expr *> Args,
5183                                   SourceLocation CallSiteLoc) {
5184   assert((FDecl || Proto) && "Need a function declaration or prototype");
5185 
5186   // Already checked by by constant evaluator.
5187   if (S.isConstantEvaluated())
5188     return;
5189   // Check the attributes attached to the method/function itself.
5190   llvm::SmallBitVector NonNullArgs;
5191   if (FDecl) {
5192     // Handle the nonnull attribute on the function/method declaration itself.
5193     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
5194       if (!NonNull->args_size()) {
5195         // Easy case: all pointer arguments are nonnull.
5196         for (const auto *Arg : Args)
5197           if (S.isValidPointerAttrType(Arg->getType()))
5198             CheckNonNullArgument(S, Arg, CallSiteLoc);
5199         return;
5200       }
5201 
5202       for (const ParamIdx &Idx : NonNull->args()) {
5203         unsigned IdxAST = Idx.getASTIndex();
5204         if (IdxAST >= Args.size())
5205           continue;
5206         if (NonNullArgs.empty())
5207           NonNullArgs.resize(Args.size());
5208         NonNullArgs.set(IdxAST);
5209       }
5210     }
5211   }
5212 
5213   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
5214     // Handle the nonnull attribute on the parameters of the
5215     // function/method.
5216     ArrayRef<ParmVarDecl*> parms;
5217     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
5218       parms = FD->parameters();
5219     else
5220       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
5221 
5222     unsigned ParamIndex = 0;
5223     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
5224          I != E; ++I, ++ParamIndex) {
5225       const ParmVarDecl *PVD = *I;
5226       if (PVD->hasAttr<NonNullAttr>() ||
5227           isNonNullType(S.Context, PVD->getType())) {
5228         if (NonNullArgs.empty())
5229           NonNullArgs.resize(Args.size());
5230 
5231         NonNullArgs.set(ParamIndex);
5232       }
5233     }
5234   } else {
5235     // If we have a non-function, non-method declaration but no
5236     // function prototype, try to dig out the function prototype.
5237     if (!Proto) {
5238       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
5239         QualType type = VD->getType().getNonReferenceType();
5240         if (auto pointerType = type->getAs<PointerType>())
5241           type = pointerType->getPointeeType();
5242         else if (auto blockType = type->getAs<BlockPointerType>())
5243           type = blockType->getPointeeType();
5244         // FIXME: data member pointers?
5245 
5246         // Dig out the function prototype, if there is one.
5247         Proto = type->getAs<FunctionProtoType>();
5248       }
5249     }
5250 
5251     // Fill in non-null argument information from the nullability
5252     // information on the parameter types (if we have them).
5253     if (Proto) {
5254       unsigned Index = 0;
5255       for (auto paramType : Proto->getParamTypes()) {
5256         if (isNonNullType(S.Context, paramType)) {
5257           if (NonNullArgs.empty())
5258             NonNullArgs.resize(Args.size());
5259 
5260           NonNullArgs.set(Index);
5261         }
5262 
5263         ++Index;
5264       }
5265     }
5266   }
5267 
5268   // Check for non-null arguments.
5269   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
5270        ArgIndex != ArgIndexEnd; ++ArgIndex) {
5271     if (NonNullArgs[ArgIndex])
5272       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
5273   }
5274 }
5275 
5276 /// Warn if a pointer or reference argument passed to a function points to an
5277 /// object that is less aligned than the parameter. This can happen when
5278 /// creating a typedef with a lower alignment than the original type and then
5279 /// calling functions defined in terms of the original type.
5280 void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
5281                              StringRef ParamName, QualType ArgTy,
5282                              QualType ParamTy) {
5283 
5284   // If a function accepts a pointer or reference type
5285   if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
5286     return;
5287 
5288   // If the parameter is a pointer type, get the pointee type for the
5289   // argument too. If the parameter is a reference type, don't try to get
5290   // the pointee type for the argument.
5291   if (ParamTy->isPointerType())
5292     ArgTy = ArgTy->getPointeeType();
5293 
5294   // Remove reference or pointer
5295   ParamTy = ParamTy->getPointeeType();
5296 
5297   // Find expected alignment, and the actual alignment of the passed object.
5298   // getTypeAlignInChars requires complete types
5299   if (ArgTy.isNull() || ParamTy->isIncompleteType() ||
5300       ArgTy->isIncompleteType() || ParamTy->isUndeducedType() ||
5301       ArgTy->isUndeducedType())
5302     return;
5303 
5304   CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
5305   CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
5306 
5307   // If the argument is less aligned than the parameter, there is a
5308   // potential alignment issue.
5309   if (ArgAlign < ParamAlign)
5310     Diag(Loc, diag::warn_param_mismatched_alignment)
5311         << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
5312         << ParamName << (FDecl != nullptr) << FDecl;
5313 }
5314 
5315 /// Handles the checks for format strings, non-POD arguments to vararg
5316 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
5317 /// attributes.
5318 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
5319                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
5320                      bool IsMemberFunction, SourceLocation Loc,
5321                      SourceRange Range, VariadicCallType CallType) {
5322   // FIXME: We should check as much as we can in the template definition.
5323   if (CurContext->isDependentContext())
5324     return;
5325 
5326   // Printf and scanf checking.
5327   llvm::SmallBitVector CheckedVarArgs;
5328   if (FDecl) {
5329     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
5330       // Only create vector if there are format attributes.
5331       CheckedVarArgs.resize(Args.size());
5332 
5333       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
5334                            CheckedVarArgs);
5335     }
5336   }
5337 
5338   // Refuse POD arguments that weren't caught by the format string
5339   // checks above.
5340   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
5341   if (CallType != VariadicDoesNotApply &&
5342       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
5343     unsigned NumParams = Proto ? Proto->getNumParams()
5344                        : FDecl && isa<FunctionDecl>(FDecl)
5345                            ? cast<FunctionDecl>(FDecl)->getNumParams()
5346                        : FDecl && isa<ObjCMethodDecl>(FDecl)
5347                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
5348                        : 0;
5349 
5350     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
5351       // Args[ArgIdx] can be null in malformed code.
5352       if (const Expr *Arg = Args[ArgIdx]) {
5353         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
5354           checkVariadicArgument(Arg, CallType);
5355       }
5356     }
5357   }
5358 
5359   if (FDecl || Proto) {
5360     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
5361 
5362     // Type safety checking.
5363     if (FDecl) {
5364       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
5365         CheckArgumentWithTypeTag(I, Args, Loc);
5366     }
5367   }
5368 
5369   // Check that passed arguments match the alignment of original arguments.
5370   // Try to get the missing prototype from the declaration.
5371   if (!Proto && FDecl) {
5372     const auto *FT = FDecl->getFunctionType();
5373     if (isa_and_nonnull<FunctionProtoType>(FT))
5374       Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
5375   }
5376   if (Proto) {
5377     // For variadic functions, we may have more args than parameters.
5378     // For some K&R functions, we may have less args than parameters.
5379     const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
5380     for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
5381       // Args[ArgIdx] can be null in malformed code.
5382       if (const Expr *Arg = Args[ArgIdx]) {
5383         if (Arg->containsErrors())
5384           continue;
5385 
5386         QualType ParamTy = Proto->getParamType(ArgIdx);
5387         QualType ArgTy = Arg->getType();
5388         CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
5389                           ArgTy, ParamTy);
5390       }
5391     }
5392   }
5393 
5394   if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
5395     auto *AA = FDecl->getAttr<AllocAlignAttr>();
5396     const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
5397     if (!Arg->isValueDependent()) {
5398       Expr::EvalResult Align;
5399       if (Arg->EvaluateAsInt(Align, Context)) {
5400         const llvm::APSInt &I = Align.Val.getInt();
5401         if (!I.isPowerOf2())
5402           Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
5403               << Arg->getSourceRange();
5404 
5405         if (I > Sema::MaximumAlignment)
5406           Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
5407               << Arg->getSourceRange() << Sema::MaximumAlignment;
5408       }
5409     }
5410   }
5411 
5412   if (FD)
5413     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
5414 }
5415 
5416 /// CheckConstructorCall - Check a constructor call for correctness and safety
5417 /// properties not enforced by the C type system.
5418 void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
5419                                 ArrayRef<const Expr *> Args,
5420                                 const FunctionProtoType *Proto,
5421                                 SourceLocation Loc) {
5422   VariadicCallType CallType =
5423       Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
5424 
5425   auto *Ctor = cast<CXXConstructorDecl>(FDecl);
5426   CheckArgAlignment(Loc, FDecl, "'this'", Context.getPointerType(ThisType),
5427                     Context.getPointerType(Ctor->getThisObjectType()));
5428 
5429   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
5430             Loc, SourceRange(), CallType);
5431 }
5432 
5433 /// CheckFunctionCall - Check a direct function call for various correctness
5434 /// and safety properties not strictly enforced by the C type system.
5435 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
5436                              const FunctionProtoType *Proto) {
5437   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
5438                               isa<CXXMethodDecl>(FDecl);
5439   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
5440                           IsMemberOperatorCall;
5441   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
5442                                                   TheCall->getCallee());
5443   Expr** Args = TheCall->getArgs();
5444   unsigned NumArgs = TheCall->getNumArgs();
5445 
5446   Expr *ImplicitThis = nullptr;
5447   if (IsMemberOperatorCall) {
5448     // If this is a call to a member operator, hide the first argument
5449     // from checkCall.
5450     // FIXME: Our choice of AST representation here is less than ideal.
5451     ImplicitThis = Args[0];
5452     ++Args;
5453     --NumArgs;
5454   } else if (IsMemberFunction)
5455     ImplicitThis =
5456         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
5457 
5458   if (ImplicitThis) {
5459     // ImplicitThis may or may not be a pointer, depending on whether . or -> is
5460     // used.
5461     QualType ThisType = ImplicitThis->getType();
5462     if (!ThisType->isPointerType()) {
5463       assert(!ThisType->isReferenceType());
5464       ThisType = Context.getPointerType(ThisType);
5465     }
5466 
5467     QualType ThisTypeFromDecl =
5468         Context.getPointerType(cast<CXXMethodDecl>(FDecl)->getThisObjectType());
5469 
5470     CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
5471                       ThisTypeFromDecl);
5472   }
5473 
5474   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
5475             IsMemberFunction, TheCall->getRParenLoc(),
5476             TheCall->getCallee()->getSourceRange(), CallType);
5477 
5478   IdentifierInfo *FnInfo = FDecl->getIdentifier();
5479   // None of the checks below are needed for functions that don't have
5480   // simple names (e.g., C++ conversion functions).
5481   if (!FnInfo)
5482     return false;
5483 
5484   CheckTCBEnforcement(TheCall, FDecl);
5485 
5486   CheckAbsoluteValueFunction(TheCall, FDecl);
5487   CheckMaxUnsignedZero(TheCall, FDecl);
5488 
5489   if (getLangOpts().ObjC)
5490     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
5491 
5492   unsigned CMId = FDecl->getMemoryFunctionKind();
5493 
5494   // Handle memory setting and copying functions.
5495   switch (CMId) {
5496   case 0:
5497     return false;
5498   case Builtin::BIstrlcpy: // fallthrough
5499   case Builtin::BIstrlcat:
5500     CheckStrlcpycatArguments(TheCall, FnInfo);
5501     break;
5502   case Builtin::BIstrncat:
5503     CheckStrncatArguments(TheCall, FnInfo);
5504     break;
5505   case Builtin::BIfree:
5506     CheckFreeArguments(TheCall);
5507     break;
5508   default:
5509     CheckMemaccessArguments(TheCall, CMId, FnInfo);
5510   }
5511 
5512   return false;
5513 }
5514 
5515 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
5516                                ArrayRef<const Expr *> Args) {
5517   VariadicCallType CallType =
5518       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
5519 
5520   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
5521             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
5522             CallType);
5523 
5524   return false;
5525 }
5526 
5527 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
5528                             const FunctionProtoType *Proto) {
5529   QualType Ty;
5530   if (const auto *V = dyn_cast<VarDecl>(NDecl))
5531     Ty = V->getType().getNonReferenceType();
5532   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
5533     Ty = F->getType().getNonReferenceType();
5534   else
5535     return false;
5536 
5537   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
5538       !Ty->isFunctionProtoType())
5539     return false;
5540 
5541   VariadicCallType CallType;
5542   if (!Proto || !Proto->isVariadic()) {
5543     CallType = VariadicDoesNotApply;
5544   } else if (Ty->isBlockPointerType()) {
5545     CallType = VariadicBlock;
5546   } else { // Ty->isFunctionPointerType()
5547     CallType = VariadicFunction;
5548   }
5549 
5550   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
5551             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5552             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
5553             TheCall->getCallee()->getSourceRange(), CallType);
5554 
5555   return false;
5556 }
5557 
5558 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
5559 /// such as function pointers returned from functions.
5560 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
5561   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
5562                                                   TheCall->getCallee());
5563   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
5564             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5565             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
5566             TheCall->getCallee()->getSourceRange(), CallType);
5567 
5568   return false;
5569 }
5570 
5571 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
5572   if (!llvm::isValidAtomicOrderingCABI(Ordering))
5573     return false;
5574 
5575   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
5576   switch (Op) {
5577   case AtomicExpr::AO__c11_atomic_init:
5578   case AtomicExpr::AO__opencl_atomic_init:
5579     llvm_unreachable("There is no ordering argument for an init");
5580 
5581   case AtomicExpr::AO__c11_atomic_load:
5582   case AtomicExpr::AO__opencl_atomic_load:
5583   case AtomicExpr::AO__hip_atomic_load:
5584   case AtomicExpr::AO__atomic_load_n:
5585   case AtomicExpr::AO__atomic_load:
5586     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
5587            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5588 
5589   case AtomicExpr::AO__c11_atomic_store:
5590   case AtomicExpr::AO__opencl_atomic_store:
5591   case AtomicExpr::AO__hip_atomic_store:
5592   case AtomicExpr::AO__atomic_store:
5593   case AtomicExpr::AO__atomic_store_n:
5594     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
5595            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
5596            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5597 
5598   default:
5599     return true;
5600   }
5601 }
5602 
5603 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
5604                                          AtomicExpr::AtomicOp Op) {
5605   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
5606   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5607   MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
5608   return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
5609                          DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
5610                          Op);
5611 }
5612 
5613 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
5614                                  SourceLocation RParenLoc, MultiExprArg Args,
5615                                  AtomicExpr::AtomicOp Op,
5616                                  AtomicArgumentOrder ArgOrder) {
5617   // All the non-OpenCL operations take one of the following forms.
5618   // The OpenCL operations take the __c11 forms with one extra argument for
5619   // synchronization scope.
5620   enum {
5621     // C    __c11_atomic_init(A *, C)
5622     Init,
5623 
5624     // C    __c11_atomic_load(A *, int)
5625     Load,
5626 
5627     // void __atomic_load(A *, CP, int)
5628     LoadCopy,
5629 
5630     // void __atomic_store(A *, CP, int)
5631     Copy,
5632 
5633     // C    __c11_atomic_add(A *, M, int)
5634     Arithmetic,
5635 
5636     // C    __atomic_exchange_n(A *, CP, int)
5637     Xchg,
5638 
5639     // void __atomic_exchange(A *, C *, CP, int)
5640     GNUXchg,
5641 
5642     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
5643     C11CmpXchg,
5644 
5645     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
5646     GNUCmpXchg
5647   } Form = Init;
5648 
5649   const unsigned NumForm = GNUCmpXchg + 1;
5650   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
5651   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
5652   // where:
5653   //   C is an appropriate type,
5654   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
5655   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
5656   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
5657   //   the int parameters are for orderings.
5658 
5659   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
5660       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
5661       "need to update code for modified forms");
5662   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
5663                     AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
5664                         AtomicExpr::AO__atomic_load,
5665                 "need to update code for modified C11 atomics");
5666   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
5667                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
5668   bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_load &&
5669                Op <= AtomicExpr::AO__hip_atomic_fetch_max;
5670   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
5671                Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
5672                IsOpenCL;
5673   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
5674              Op == AtomicExpr::AO__atomic_store_n ||
5675              Op == AtomicExpr::AO__atomic_exchange_n ||
5676              Op == AtomicExpr::AO__atomic_compare_exchange_n;
5677   bool IsAddSub = false;
5678 
5679   switch (Op) {
5680   case AtomicExpr::AO__c11_atomic_init:
5681   case AtomicExpr::AO__opencl_atomic_init:
5682     Form = Init;
5683     break;
5684 
5685   case AtomicExpr::AO__c11_atomic_load:
5686   case AtomicExpr::AO__opencl_atomic_load:
5687   case AtomicExpr::AO__hip_atomic_load:
5688   case AtomicExpr::AO__atomic_load_n:
5689     Form = Load;
5690     break;
5691 
5692   case AtomicExpr::AO__atomic_load:
5693     Form = LoadCopy;
5694     break;
5695 
5696   case AtomicExpr::AO__c11_atomic_store:
5697   case AtomicExpr::AO__opencl_atomic_store:
5698   case AtomicExpr::AO__hip_atomic_store:
5699   case AtomicExpr::AO__atomic_store:
5700   case AtomicExpr::AO__atomic_store_n:
5701     Form = Copy;
5702     break;
5703   case AtomicExpr::AO__hip_atomic_fetch_add:
5704   case AtomicExpr::AO__hip_atomic_fetch_min:
5705   case AtomicExpr::AO__hip_atomic_fetch_max:
5706   case AtomicExpr::AO__c11_atomic_fetch_add:
5707   case AtomicExpr::AO__c11_atomic_fetch_sub:
5708   case AtomicExpr::AO__opencl_atomic_fetch_add:
5709   case AtomicExpr::AO__opencl_atomic_fetch_sub:
5710   case AtomicExpr::AO__atomic_fetch_add:
5711   case AtomicExpr::AO__atomic_fetch_sub:
5712   case AtomicExpr::AO__atomic_add_fetch:
5713   case AtomicExpr::AO__atomic_sub_fetch:
5714     IsAddSub = true;
5715     Form = Arithmetic;
5716     break;
5717   case AtomicExpr::AO__c11_atomic_fetch_and:
5718   case AtomicExpr::AO__c11_atomic_fetch_or:
5719   case AtomicExpr::AO__c11_atomic_fetch_xor:
5720   case AtomicExpr::AO__hip_atomic_fetch_and:
5721   case AtomicExpr::AO__hip_atomic_fetch_or:
5722   case AtomicExpr::AO__hip_atomic_fetch_xor:
5723   case AtomicExpr::AO__c11_atomic_fetch_nand:
5724   case AtomicExpr::AO__opencl_atomic_fetch_and:
5725   case AtomicExpr::AO__opencl_atomic_fetch_or:
5726   case AtomicExpr::AO__opencl_atomic_fetch_xor:
5727   case AtomicExpr::AO__atomic_fetch_and:
5728   case AtomicExpr::AO__atomic_fetch_or:
5729   case AtomicExpr::AO__atomic_fetch_xor:
5730   case AtomicExpr::AO__atomic_fetch_nand:
5731   case AtomicExpr::AO__atomic_and_fetch:
5732   case AtomicExpr::AO__atomic_or_fetch:
5733   case AtomicExpr::AO__atomic_xor_fetch:
5734   case AtomicExpr::AO__atomic_nand_fetch:
5735     Form = Arithmetic;
5736     break;
5737   case AtomicExpr::AO__c11_atomic_fetch_min:
5738   case AtomicExpr::AO__c11_atomic_fetch_max:
5739   case AtomicExpr::AO__opencl_atomic_fetch_min:
5740   case AtomicExpr::AO__opencl_atomic_fetch_max:
5741   case AtomicExpr::AO__atomic_min_fetch:
5742   case AtomicExpr::AO__atomic_max_fetch:
5743   case AtomicExpr::AO__atomic_fetch_min:
5744   case AtomicExpr::AO__atomic_fetch_max:
5745     Form = Arithmetic;
5746     break;
5747 
5748   case AtomicExpr::AO__c11_atomic_exchange:
5749   case AtomicExpr::AO__hip_atomic_exchange:
5750   case AtomicExpr::AO__opencl_atomic_exchange:
5751   case AtomicExpr::AO__atomic_exchange_n:
5752     Form = Xchg;
5753     break;
5754 
5755   case AtomicExpr::AO__atomic_exchange:
5756     Form = GNUXchg;
5757     break;
5758 
5759   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
5760   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
5761   case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
5762   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
5763   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
5764   case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
5765     Form = C11CmpXchg;
5766     break;
5767 
5768   case AtomicExpr::AO__atomic_compare_exchange:
5769   case AtomicExpr::AO__atomic_compare_exchange_n:
5770     Form = GNUCmpXchg;
5771     break;
5772   }
5773 
5774   unsigned AdjustedNumArgs = NumArgs[Form];
5775   if ((IsOpenCL || IsHIP) && Op != AtomicExpr::AO__opencl_atomic_init)
5776     ++AdjustedNumArgs;
5777   // Check we have the right number of arguments.
5778   if (Args.size() < AdjustedNumArgs) {
5779     Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
5780         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5781         << ExprRange;
5782     return ExprError();
5783   } else if (Args.size() > AdjustedNumArgs) {
5784     Diag(Args[AdjustedNumArgs]->getBeginLoc(),
5785          diag::err_typecheck_call_too_many_args)
5786         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5787         << ExprRange;
5788     return ExprError();
5789   }
5790 
5791   // Inspect the first argument of the atomic operation.
5792   Expr *Ptr = Args[0];
5793   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
5794   if (ConvertedPtr.isInvalid())
5795     return ExprError();
5796 
5797   Ptr = ConvertedPtr.get();
5798   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
5799   if (!pointerType) {
5800     Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
5801         << Ptr->getType() << Ptr->getSourceRange();
5802     return ExprError();
5803   }
5804 
5805   // For a __c11 builtin, this should be a pointer to an _Atomic type.
5806   QualType AtomTy = pointerType->getPointeeType(); // 'A'
5807   QualType ValType = AtomTy; // 'C'
5808   if (IsC11) {
5809     if (!AtomTy->isAtomicType()) {
5810       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
5811           << Ptr->getType() << Ptr->getSourceRange();
5812       return ExprError();
5813     }
5814     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
5815         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
5816       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
5817           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
5818           << Ptr->getSourceRange();
5819       return ExprError();
5820     }
5821     ValType = AtomTy->castAs<AtomicType>()->getValueType();
5822   } else if (Form != Load && Form != LoadCopy) {
5823     if (ValType.isConstQualified()) {
5824       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
5825           << Ptr->getType() << Ptr->getSourceRange();
5826       return ExprError();
5827     }
5828   }
5829 
5830   // For an arithmetic operation, the implied arithmetic must be well-formed.
5831   if (Form == Arithmetic) {
5832     // GCC does not enforce these rules for GNU atomics, but we do to help catch
5833     // trivial type errors.
5834     auto IsAllowedValueType = [&](QualType ValType) {
5835       if (ValType->isIntegerType())
5836         return true;
5837       if (ValType->isPointerType())
5838         return true;
5839       if (!ValType->isFloatingType())
5840         return false;
5841       // LLVM Parser does not allow atomicrmw with x86_fp80 type.
5842       if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
5843           &Context.getTargetInfo().getLongDoubleFormat() ==
5844               &llvm::APFloat::x87DoubleExtended())
5845         return false;
5846       return true;
5847     };
5848     if (IsAddSub && !IsAllowedValueType(ValType)) {
5849       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_ptr_or_fp)
5850           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5851       return ExprError();
5852     }
5853     if (!IsAddSub && !ValType->isIntegerType()) {
5854       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
5855           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5856       return ExprError();
5857     }
5858     if (IsC11 && ValType->isPointerType() &&
5859         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
5860                             diag::err_incomplete_type)) {
5861       return ExprError();
5862     }
5863   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
5864     // For __atomic_*_n operations, the value type must be a scalar integral or
5865     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
5866     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
5867         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5868     return ExprError();
5869   }
5870 
5871   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
5872       !AtomTy->isScalarType()) {
5873     // For GNU atomics, require a trivially-copyable type. This is not part of
5874     // the GNU atomics specification but we enforce it for consistency with
5875     // other atomics which generally all require a trivially-copyable type. This
5876     // is because atomics just copy bits.
5877     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
5878         << Ptr->getType() << Ptr->getSourceRange();
5879     return ExprError();
5880   }
5881 
5882   switch (ValType.getObjCLifetime()) {
5883   case Qualifiers::OCL_None:
5884   case Qualifiers::OCL_ExplicitNone:
5885     // okay
5886     break;
5887 
5888   case Qualifiers::OCL_Weak:
5889   case Qualifiers::OCL_Strong:
5890   case Qualifiers::OCL_Autoreleasing:
5891     // FIXME: Can this happen? By this point, ValType should be known
5892     // to be trivially copyable.
5893     Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
5894         << ValType << Ptr->getSourceRange();
5895     return ExprError();
5896   }
5897 
5898   // All atomic operations have an overload which takes a pointer to a volatile
5899   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
5900   // into the result or the other operands. Similarly atomic_load takes a
5901   // pointer to a const 'A'.
5902   ValType.removeLocalVolatile();
5903   ValType.removeLocalConst();
5904   QualType ResultType = ValType;
5905   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
5906       Form == Init)
5907     ResultType = Context.VoidTy;
5908   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
5909     ResultType = Context.BoolTy;
5910 
5911   // The type of a parameter passed 'by value'. In the GNU atomics, such
5912   // arguments are actually passed as pointers.
5913   QualType ByValType = ValType; // 'CP'
5914   bool IsPassedByAddress = false;
5915   if (!IsC11 && !IsHIP && !IsN) {
5916     ByValType = Ptr->getType();
5917     IsPassedByAddress = true;
5918   }
5919 
5920   SmallVector<Expr *, 5> APIOrderedArgs;
5921   if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
5922     APIOrderedArgs.push_back(Args[0]);
5923     switch (Form) {
5924     case Init:
5925     case Load:
5926       APIOrderedArgs.push_back(Args[1]); // Val1/Order
5927       break;
5928     case LoadCopy:
5929     case Copy:
5930     case Arithmetic:
5931     case Xchg:
5932       APIOrderedArgs.push_back(Args[2]); // Val1
5933       APIOrderedArgs.push_back(Args[1]); // Order
5934       break;
5935     case GNUXchg:
5936       APIOrderedArgs.push_back(Args[2]); // Val1
5937       APIOrderedArgs.push_back(Args[3]); // Val2
5938       APIOrderedArgs.push_back(Args[1]); // Order
5939       break;
5940     case C11CmpXchg:
5941       APIOrderedArgs.push_back(Args[2]); // Val1
5942       APIOrderedArgs.push_back(Args[4]); // Val2
5943       APIOrderedArgs.push_back(Args[1]); // Order
5944       APIOrderedArgs.push_back(Args[3]); // OrderFail
5945       break;
5946     case GNUCmpXchg:
5947       APIOrderedArgs.push_back(Args[2]); // Val1
5948       APIOrderedArgs.push_back(Args[4]); // Val2
5949       APIOrderedArgs.push_back(Args[5]); // Weak
5950       APIOrderedArgs.push_back(Args[1]); // Order
5951       APIOrderedArgs.push_back(Args[3]); // OrderFail
5952       break;
5953     }
5954   } else
5955     APIOrderedArgs.append(Args.begin(), Args.end());
5956 
5957   // The first argument's non-CV pointer type is used to deduce the type of
5958   // subsequent arguments, except for:
5959   //  - weak flag (always converted to bool)
5960   //  - memory order (always converted to int)
5961   //  - scope  (always converted to int)
5962   for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
5963     QualType Ty;
5964     if (i < NumVals[Form] + 1) {
5965       switch (i) {
5966       case 0:
5967         // The first argument is always a pointer. It has a fixed type.
5968         // It is always dereferenced, a nullptr is undefined.
5969         CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5970         // Nothing else to do: we already know all we want about this pointer.
5971         continue;
5972       case 1:
5973         // The second argument is the non-atomic operand. For arithmetic, this
5974         // is always passed by value, and for a compare_exchange it is always
5975         // passed by address. For the rest, GNU uses by-address and C11 uses
5976         // by-value.
5977         assert(Form != Load);
5978         if (Form == Arithmetic && ValType->isPointerType())
5979           Ty = Context.getPointerDiffType();
5980         else if (Form == Init || Form == Arithmetic)
5981           Ty = ValType;
5982         else if (Form == Copy || Form == Xchg) {
5983           if (IsPassedByAddress) {
5984             // The value pointer is always dereferenced, a nullptr is undefined.
5985             CheckNonNullArgument(*this, APIOrderedArgs[i],
5986                                  ExprRange.getBegin());
5987           }
5988           Ty = ByValType;
5989         } else {
5990           Expr *ValArg = APIOrderedArgs[i];
5991           // The value pointer is always dereferenced, a nullptr is undefined.
5992           CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
5993           LangAS AS = LangAS::Default;
5994           // Keep address space of non-atomic pointer type.
5995           if (const PointerType *PtrTy =
5996                   ValArg->getType()->getAs<PointerType>()) {
5997             AS = PtrTy->getPointeeType().getAddressSpace();
5998           }
5999           Ty = Context.getPointerType(
6000               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
6001         }
6002         break;
6003       case 2:
6004         // The third argument to compare_exchange / GNU exchange is the desired
6005         // value, either by-value (for the C11 and *_n variant) or as a pointer.
6006         if (IsPassedByAddress)
6007           CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
6008         Ty = ByValType;
6009         break;
6010       case 3:
6011         // The fourth argument to GNU compare_exchange is a 'weak' flag.
6012         Ty = Context.BoolTy;
6013         break;
6014       }
6015     } else {
6016       // The order(s) and scope are always converted to int.
6017       Ty = Context.IntTy;
6018     }
6019 
6020     InitializedEntity Entity =
6021         InitializedEntity::InitializeParameter(Context, Ty, false);
6022     ExprResult Arg = APIOrderedArgs[i];
6023     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6024     if (Arg.isInvalid())
6025       return true;
6026     APIOrderedArgs[i] = Arg.get();
6027   }
6028 
6029   // Permute the arguments into a 'consistent' order.
6030   SmallVector<Expr*, 5> SubExprs;
6031   SubExprs.push_back(Ptr);
6032   switch (Form) {
6033   case Init:
6034     // Note, AtomicExpr::getVal1() has a special case for this atomic.
6035     SubExprs.push_back(APIOrderedArgs[1]); // Val1
6036     break;
6037   case Load:
6038     SubExprs.push_back(APIOrderedArgs[1]); // Order
6039     break;
6040   case LoadCopy:
6041   case Copy:
6042   case Arithmetic:
6043   case Xchg:
6044     SubExprs.push_back(APIOrderedArgs[2]); // Order
6045     SubExprs.push_back(APIOrderedArgs[1]); // Val1
6046     break;
6047   case GNUXchg:
6048     // Note, AtomicExpr::getVal2() has a special case for this atomic.
6049     SubExprs.push_back(APIOrderedArgs[3]); // Order
6050     SubExprs.push_back(APIOrderedArgs[1]); // Val1
6051     SubExprs.push_back(APIOrderedArgs[2]); // Val2
6052     break;
6053   case C11CmpXchg:
6054     SubExprs.push_back(APIOrderedArgs[3]); // Order
6055     SubExprs.push_back(APIOrderedArgs[1]); // Val1
6056     SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
6057     SubExprs.push_back(APIOrderedArgs[2]); // Val2
6058     break;
6059   case GNUCmpXchg:
6060     SubExprs.push_back(APIOrderedArgs[4]); // Order
6061     SubExprs.push_back(APIOrderedArgs[1]); // Val1
6062     SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
6063     SubExprs.push_back(APIOrderedArgs[2]); // Val2
6064     SubExprs.push_back(APIOrderedArgs[3]); // Weak
6065     break;
6066   }
6067 
6068   if (SubExprs.size() >= 2 && Form != Init) {
6069     if (Optional<llvm::APSInt> Result =
6070             SubExprs[1]->getIntegerConstantExpr(Context))
6071       if (!isValidOrderingForOp(Result->getSExtValue(), Op))
6072         Diag(SubExprs[1]->getBeginLoc(),
6073              diag::warn_atomic_op_has_invalid_memory_order)
6074             << SubExprs[1]->getSourceRange();
6075   }
6076 
6077   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
6078     auto *Scope = Args[Args.size() - 1];
6079     if (Optional<llvm::APSInt> Result =
6080             Scope->getIntegerConstantExpr(Context)) {
6081       if (!ScopeModel->isValid(Result->getZExtValue()))
6082         Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
6083             << Scope->getSourceRange();
6084     }
6085     SubExprs.push_back(Scope);
6086   }
6087 
6088   AtomicExpr *AE = new (Context)
6089       AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
6090 
6091   if ((Op == AtomicExpr::AO__c11_atomic_load ||
6092        Op == AtomicExpr::AO__c11_atomic_store ||
6093        Op == AtomicExpr::AO__opencl_atomic_load ||
6094        Op == AtomicExpr::AO__hip_atomic_load ||
6095        Op == AtomicExpr::AO__opencl_atomic_store ||
6096        Op == AtomicExpr::AO__hip_atomic_store) &&
6097       Context.AtomicUsesUnsupportedLibcall(AE))
6098     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
6099         << ((Op == AtomicExpr::AO__c11_atomic_load ||
6100              Op == AtomicExpr::AO__opencl_atomic_load ||
6101              Op == AtomicExpr::AO__hip_atomic_load)
6102                 ? 0
6103                 : 1);
6104 
6105   if (ValType->isBitIntType()) {
6106     Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_bit_int_prohibit);
6107     return ExprError();
6108   }
6109 
6110   return AE;
6111 }
6112 
6113 /// checkBuiltinArgument - Given a call to a builtin function, perform
6114 /// normal type-checking on the given argument, updating the call in
6115 /// place.  This is useful when a builtin function requires custom
6116 /// type-checking for some of its arguments but not necessarily all of
6117 /// them.
6118 ///
6119 /// Returns true on error.
6120 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
6121   FunctionDecl *Fn = E->getDirectCallee();
6122   assert(Fn && "builtin call without direct callee!");
6123 
6124   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
6125   InitializedEntity Entity =
6126     InitializedEntity::InitializeParameter(S.Context, Param);
6127 
6128   ExprResult Arg = E->getArg(0);
6129   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
6130   if (Arg.isInvalid())
6131     return true;
6132 
6133   E->setArg(ArgIndex, Arg.get());
6134   return false;
6135 }
6136 
6137 /// We have a call to a function like __sync_fetch_and_add, which is an
6138 /// overloaded function based on the pointer type of its first argument.
6139 /// The main BuildCallExpr routines have already promoted the types of
6140 /// arguments because all of these calls are prototyped as void(...).
6141 ///
6142 /// This function goes through and does final semantic checking for these
6143 /// builtins, as well as generating any warnings.
6144 ExprResult
6145 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
6146   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
6147   Expr *Callee = TheCall->getCallee();
6148   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
6149   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6150 
6151   // Ensure that we have at least one argument to do type inference from.
6152   if (TheCall->getNumArgs() < 1) {
6153     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
6154         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
6155     return ExprError();
6156   }
6157 
6158   // Inspect the first argument of the atomic builtin.  This should always be
6159   // a pointer type, whose element is an integral scalar or pointer type.
6160   // Because it is a pointer type, we don't have to worry about any implicit
6161   // casts here.
6162   // FIXME: We don't allow floating point scalars as input.
6163   Expr *FirstArg = TheCall->getArg(0);
6164   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
6165   if (FirstArgResult.isInvalid())
6166     return ExprError();
6167   FirstArg = FirstArgResult.get();
6168   TheCall->setArg(0, FirstArg);
6169 
6170   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
6171   if (!pointerType) {
6172     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
6173         << FirstArg->getType() << FirstArg->getSourceRange();
6174     return ExprError();
6175   }
6176 
6177   QualType ValType = pointerType->getPointeeType();
6178   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
6179       !ValType->isBlockPointerType()) {
6180     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
6181         << FirstArg->getType() << FirstArg->getSourceRange();
6182     return ExprError();
6183   }
6184 
6185   if (ValType.isConstQualified()) {
6186     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
6187         << FirstArg->getType() << FirstArg->getSourceRange();
6188     return ExprError();
6189   }
6190 
6191   switch (ValType.getObjCLifetime()) {
6192   case Qualifiers::OCL_None:
6193   case Qualifiers::OCL_ExplicitNone:
6194     // okay
6195     break;
6196 
6197   case Qualifiers::OCL_Weak:
6198   case Qualifiers::OCL_Strong:
6199   case Qualifiers::OCL_Autoreleasing:
6200     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
6201         << ValType << FirstArg->getSourceRange();
6202     return ExprError();
6203   }
6204 
6205   // Strip any qualifiers off ValType.
6206   ValType = ValType.getUnqualifiedType();
6207 
6208   // The majority of builtins return a value, but a few have special return
6209   // types, so allow them to override appropriately below.
6210   QualType ResultType = ValType;
6211 
6212   // We need to figure out which concrete builtin this maps onto.  For example,
6213   // __sync_fetch_and_add with a 2 byte object turns into
6214   // __sync_fetch_and_add_2.
6215 #define BUILTIN_ROW(x) \
6216   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
6217     Builtin::BI##x##_8, Builtin::BI##x##_16 }
6218 
6219   static const unsigned BuiltinIndices[][5] = {
6220     BUILTIN_ROW(__sync_fetch_and_add),
6221     BUILTIN_ROW(__sync_fetch_and_sub),
6222     BUILTIN_ROW(__sync_fetch_and_or),
6223     BUILTIN_ROW(__sync_fetch_and_and),
6224     BUILTIN_ROW(__sync_fetch_and_xor),
6225     BUILTIN_ROW(__sync_fetch_and_nand),
6226 
6227     BUILTIN_ROW(__sync_add_and_fetch),
6228     BUILTIN_ROW(__sync_sub_and_fetch),
6229     BUILTIN_ROW(__sync_and_and_fetch),
6230     BUILTIN_ROW(__sync_or_and_fetch),
6231     BUILTIN_ROW(__sync_xor_and_fetch),
6232     BUILTIN_ROW(__sync_nand_and_fetch),
6233 
6234     BUILTIN_ROW(__sync_val_compare_and_swap),
6235     BUILTIN_ROW(__sync_bool_compare_and_swap),
6236     BUILTIN_ROW(__sync_lock_test_and_set),
6237     BUILTIN_ROW(__sync_lock_release),
6238     BUILTIN_ROW(__sync_swap)
6239   };
6240 #undef BUILTIN_ROW
6241 
6242   // Determine the index of the size.
6243   unsigned SizeIndex;
6244   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
6245   case 1: SizeIndex = 0; break;
6246   case 2: SizeIndex = 1; break;
6247   case 4: SizeIndex = 2; break;
6248   case 8: SizeIndex = 3; break;
6249   case 16: SizeIndex = 4; break;
6250   default:
6251     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
6252         << FirstArg->getType() << FirstArg->getSourceRange();
6253     return ExprError();
6254   }
6255 
6256   // Each of these builtins has one pointer argument, followed by some number of
6257   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
6258   // that we ignore.  Find out which row of BuiltinIndices to read from as well
6259   // as the number of fixed args.
6260   unsigned BuiltinID = FDecl->getBuiltinID();
6261   unsigned BuiltinIndex, NumFixed = 1;
6262   bool WarnAboutSemanticsChange = false;
6263   switch (BuiltinID) {
6264   default: llvm_unreachable("Unknown overloaded atomic builtin!");
6265   case Builtin::BI__sync_fetch_and_add:
6266   case Builtin::BI__sync_fetch_and_add_1:
6267   case Builtin::BI__sync_fetch_and_add_2:
6268   case Builtin::BI__sync_fetch_and_add_4:
6269   case Builtin::BI__sync_fetch_and_add_8:
6270   case Builtin::BI__sync_fetch_and_add_16:
6271     BuiltinIndex = 0;
6272     break;
6273 
6274   case Builtin::BI__sync_fetch_and_sub:
6275   case Builtin::BI__sync_fetch_and_sub_1:
6276   case Builtin::BI__sync_fetch_and_sub_2:
6277   case Builtin::BI__sync_fetch_and_sub_4:
6278   case Builtin::BI__sync_fetch_and_sub_8:
6279   case Builtin::BI__sync_fetch_and_sub_16:
6280     BuiltinIndex = 1;
6281     break;
6282 
6283   case Builtin::BI__sync_fetch_and_or:
6284   case Builtin::BI__sync_fetch_and_or_1:
6285   case Builtin::BI__sync_fetch_and_or_2:
6286   case Builtin::BI__sync_fetch_and_or_4:
6287   case Builtin::BI__sync_fetch_and_or_8:
6288   case Builtin::BI__sync_fetch_and_or_16:
6289     BuiltinIndex = 2;
6290     break;
6291 
6292   case Builtin::BI__sync_fetch_and_and:
6293   case Builtin::BI__sync_fetch_and_and_1:
6294   case Builtin::BI__sync_fetch_and_and_2:
6295   case Builtin::BI__sync_fetch_and_and_4:
6296   case Builtin::BI__sync_fetch_and_and_8:
6297   case Builtin::BI__sync_fetch_and_and_16:
6298     BuiltinIndex = 3;
6299     break;
6300 
6301   case Builtin::BI__sync_fetch_and_xor:
6302   case Builtin::BI__sync_fetch_and_xor_1:
6303   case Builtin::BI__sync_fetch_and_xor_2:
6304   case Builtin::BI__sync_fetch_and_xor_4:
6305   case Builtin::BI__sync_fetch_and_xor_8:
6306   case Builtin::BI__sync_fetch_and_xor_16:
6307     BuiltinIndex = 4;
6308     break;
6309 
6310   case Builtin::BI__sync_fetch_and_nand:
6311   case Builtin::BI__sync_fetch_and_nand_1:
6312   case Builtin::BI__sync_fetch_and_nand_2:
6313   case Builtin::BI__sync_fetch_and_nand_4:
6314   case Builtin::BI__sync_fetch_and_nand_8:
6315   case Builtin::BI__sync_fetch_and_nand_16:
6316     BuiltinIndex = 5;
6317     WarnAboutSemanticsChange = true;
6318     break;
6319 
6320   case Builtin::BI__sync_add_and_fetch:
6321   case Builtin::BI__sync_add_and_fetch_1:
6322   case Builtin::BI__sync_add_and_fetch_2:
6323   case Builtin::BI__sync_add_and_fetch_4:
6324   case Builtin::BI__sync_add_and_fetch_8:
6325   case Builtin::BI__sync_add_and_fetch_16:
6326     BuiltinIndex = 6;
6327     break;
6328 
6329   case Builtin::BI__sync_sub_and_fetch:
6330   case Builtin::BI__sync_sub_and_fetch_1:
6331   case Builtin::BI__sync_sub_and_fetch_2:
6332   case Builtin::BI__sync_sub_and_fetch_4:
6333   case Builtin::BI__sync_sub_and_fetch_8:
6334   case Builtin::BI__sync_sub_and_fetch_16:
6335     BuiltinIndex = 7;
6336     break;
6337 
6338   case Builtin::BI__sync_and_and_fetch:
6339   case Builtin::BI__sync_and_and_fetch_1:
6340   case Builtin::BI__sync_and_and_fetch_2:
6341   case Builtin::BI__sync_and_and_fetch_4:
6342   case Builtin::BI__sync_and_and_fetch_8:
6343   case Builtin::BI__sync_and_and_fetch_16:
6344     BuiltinIndex = 8;
6345     break;
6346 
6347   case Builtin::BI__sync_or_and_fetch:
6348   case Builtin::BI__sync_or_and_fetch_1:
6349   case Builtin::BI__sync_or_and_fetch_2:
6350   case Builtin::BI__sync_or_and_fetch_4:
6351   case Builtin::BI__sync_or_and_fetch_8:
6352   case Builtin::BI__sync_or_and_fetch_16:
6353     BuiltinIndex = 9;
6354     break;
6355 
6356   case Builtin::BI__sync_xor_and_fetch:
6357   case Builtin::BI__sync_xor_and_fetch_1:
6358   case Builtin::BI__sync_xor_and_fetch_2:
6359   case Builtin::BI__sync_xor_and_fetch_4:
6360   case Builtin::BI__sync_xor_and_fetch_8:
6361   case Builtin::BI__sync_xor_and_fetch_16:
6362     BuiltinIndex = 10;
6363     break;
6364 
6365   case Builtin::BI__sync_nand_and_fetch:
6366   case Builtin::BI__sync_nand_and_fetch_1:
6367   case Builtin::BI__sync_nand_and_fetch_2:
6368   case Builtin::BI__sync_nand_and_fetch_4:
6369   case Builtin::BI__sync_nand_and_fetch_8:
6370   case Builtin::BI__sync_nand_and_fetch_16:
6371     BuiltinIndex = 11;
6372     WarnAboutSemanticsChange = true;
6373     break;
6374 
6375   case Builtin::BI__sync_val_compare_and_swap:
6376   case Builtin::BI__sync_val_compare_and_swap_1:
6377   case Builtin::BI__sync_val_compare_and_swap_2:
6378   case Builtin::BI__sync_val_compare_and_swap_4:
6379   case Builtin::BI__sync_val_compare_and_swap_8:
6380   case Builtin::BI__sync_val_compare_and_swap_16:
6381     BuiltinIndex = 12;
6382     NumFixed = 2;
6383     break;
6384 
6385   case Builtin::BI__sync_bool_compare_and_swap:
6386   case Builtin::BI__sync_bool_compare_and_swap_1:
6387   case Builtin::BI__sync_bool_compare_and_swap_2:
6388   case Builtin::BI__sync_bool_compare_and_swap_4:
6389   case Builtin::BI__sync_bool_compare_and_swap_8:
6390   case Builtin::BI__sync_bool_compare_and_swap_16:
6391     BuiltinIndex = 13;
6392     NumFixed = 2;
6393     ResultType = Context.BoolTy;
6394     break;
6395 
6396   case Builtin::BI__sync_lock_test_and_set:
6397   case Builtin::BI__sync_lock_test_and_set_1:
6398   case Builtin::BI__sync_lock_test_and_set_2:
6399   case Builtin::BI__sync_lock_test_and_set_4:
6400   case Builtin::BI__sync_lock_test_and_set_8:
6401   case Builtin::BI__sync_lock_test_and_set_16:
6402     BuiltinIndex = 14;
6403     break;
6404 
6405   case Builtin::BI__sync_lock_release:
6406   case Builtin::BI__sync_lock_release_1:
6407   case Builtin::BI__sync_lock_release_2:
6408   case Builtin::BI__sync_lock_release_4:
6409   case Builtin::BI__sync_lock_release_8:
6410   case Builtin::BI__sync_lock_release_16:
6411     BuiltinIndex = 15;
6412     NumFixed = 0;
6413     ResultType = Context.VoidTy;
6414     break;
6415 
6416   case Builtin::BI__sync_swap:
6417   case Builtin::BI__sync_swap_1:
6418   case Builtin::BI__sync_swap_2:
6419   case Builtin::BI__sync_swap_4:
6420   case Builtin::BI__sync_swap_8:
6421   case Builtin::BI__sync_swap_16:
6422     BuiltinIndex = 16;
6423     break;
6424   }
6425 
6426   // Now that we know how many fixed arguments we expect, first check that we
6427   // have at least that many.
6428   if (TheCall->getNumArgs() < 1+NumFixed) {
6429     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
6430         << 0 << 1 + NumFixed << TheCall->getNumArgs()
6431         << Callee->getSourceRange();
6432     return ExprError();
6433   }
6434 
6435   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
6436       << Callee->getSourceRange();
6437 
6438   if (WarnAboutSemanticsChange) {
6439     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
6440         << Callee->getSourceRange();
6441   }
6442 
6443   // Get the decl for the concrete builtin from this, we can tell what the
6444   // concrete integer type we should convert to is.
6445   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
6446   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
6447   FunctionDecl *NewBuiltinDecl;
6448   if (NewBuiltinID == BuiltinID)
6449     NewBuiltinDecl = FDecl;
6450   else {
6451     // Perform builtin lookup to avoid redeclaring it.
6452     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
6453     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
6454     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
6455     assert(Res.getFoundDecl());
6456     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
6457     if (!NewBuiltinDecl)
6458       return ExprError();
6459   }
6460 
6461   // The first argument --- the pointer --- has a fixed type; we
6462   // deduce the types of the rest of the arguments accordingly.  Walk
6463   // the remaining arguments, converting them to the deduced value type.
6464   for (unsigned i = 0; i != NumFixed; ++i) {
6465     ExprResult Arg = TheCall->getArg(i+1);
6466 
6467     // GCC does an implicit conversion to the pointer or integer ValType.  This
6468     // can fail in some cases (1i -> int**), check for this error case now.
6469     // Initialize the argument.
6470     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6471                                                    ValType, /*consume*/ false);
6472     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6473     if (Arg.isInvalid())
6474       return ExprError();
6475 
6476     // Okay, we have something that *can* be converted to the right type.  Check
6477     // to see if there is a potentially weird extension going on here.  This can
6478     // happen when you do an atomic operation on something like an char* and
6479     // pass in 42.  The 42 gets converted to char.  This is even more strange
6480     // for things like 45.123 -> char, etc.
6481     // FIXME: Do this check.
6482     TheCall->setArg(i+1, Arg.get());
6483   }
6484 
6485   // Create a new DeclRefExpr to refer to the new decl.
6486   DeclRefExpr *NewDRE = DeclRefExpr::Create(
6487       Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
6488       /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
6489       DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
6490 
6491   // Set the callee in the CallExpr.
6492   // FIXME: This loses syntactic information.
6493   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
6494   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
6495                                               CK_BuiltinFnToFnPtr);
6496   TheCall->setCallee(PromotedCall.get());
6497 
6498   // Change the result type of the call to match the original value type. This
6499   // is arbitrary, but the codegen for these builtins ins design to handle it
6500   // gracefully.
6501   TheCall->setType(ResultType);
6502 
6503   // Prohibit problematic uses of bit-precise integer types with atomic
6504   // builtins. The arguments would have already been converted to the first
6505   // argument's type, so only need to check the first argument.
6506   const auto *BitIntValType = ValType->getAs<BitIntType>();
6507   if (BitIntValType && !llvm::isPowerOf2_64(BitIntValType->getNumBits())) {
6508     Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
6509     return ExprError();
6510   }
6511 
6512   return TheCallResult;
6513 }
6514 
6515 /// SemaBuiltinNontemporalOverloaded - We have a call to
6516 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
6517 /// overloaded function based on the pointer type of its last argument.
6518 ///
6519 /// This function goes through and does final semantic checking for these
6520 /// builtins.
6521 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
6522   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
6523   DeclRefExpr *DRE =
6524       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6525   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6526   unsigned BuiltinID = FDecl->getBuiltinID();
6527   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
6528           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
6529          "Unexpected nontemporal load/store builtin!");
6530   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
6531   unsigned numArgs = isStore ? 2 : 1;
6532 
6533   // Ensure that we have the proper number of arguments.
6534   if (checkArgCount(*this, TheCall, numArgs))
6535     return ExprError();
6536 
6537   // Inspect the last argument of the nontemporal builtin.  This should always
6538   // be a pointer type, from which we imply the type of the memory access.
6539   // Because it is a pointer type, we don't have to worry about any implicit
6540   // casts here.
6541   Expr *PointerArg = TheCall->getArg(numArgs - 1);
6542   ExprResult PointerArgResult =
6543       DefaultFunctionArrayLvalueConversion(PointerArg);
6544 
6545   if (PointerArgResult.isInvalid())
6546     return ExprError();
6547   PointerArg = PointerArgResult.get();
6548   TheCall->setArg(numArgs - 1, PointerArg);
6549 
6550   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
6551   if (!pointerType) {
6552     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
6553         << PointerArg->getType() << PointerArg->getSourceRange();
6554     return ExprError();
6555   }
6556 
6557   QualType ValType = pointerType->getPointeeType();
6558 
6559   // Strip any qualifiers off ValType.
6560   ValType = ValType.getUnqualifiedType();
6561   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
6562       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
6563       !ValType->isVectorType()) {
6564     Diag(DRE->getBeginLoc(),
6565          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
6566         << PointerArg->getType() << PointerArg->getSourceRange();
6567     return ExprError();
6568   }
6569 
6570   if (!isStore) {
6571     TheCall->setType(ValType);
6572     return TheCallResult;
6573   }
6574 
6575   ExprResult ValArg = TheCall->getArg(0);
6576   InitializedEntity Entity = InitializedEntity::InitializeParameter(
6577       Context, ValType, /*consume*/ false);
6578   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
6579   if (ValArg.isInvalid())
6580     return ExprError();
6581 
6582   TheCall->setArg(0, ValArg.get());
6583   TheCall->setType(Context.VoidTy);
6584   return TheCallResult;
6585 }
6586 
6587 /// CheckObjCString - Checks that the argument to the builtin
6588 /// CFString constructor is correct
6589 /// Note: It might also make sense to do the UTF-16 conversion here (would
6590 /// simplify the backend).
6591 bool Sema::CheckObjCString(Expr *Arg) {
6592   Arg = Arg->IgnoreParenCasts();
6593   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
6594 
6595   if (!Literal || !Literal->isAscii()) {
6596     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
6597         << Arg->getSourceRange();
6598     return true;
6599   }
6600 
6601   if (Literal->containsNonAsciiOrNull()) {
6602     StringRef String = Literal->getString();
6603     unsigned NumBytes = String.size();
6604     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
6605     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
6606     llvm::UTF16 *ToPtr = &ToBuf[0];
6607 
6608     llvm::ConversionResult Result =
6609         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
6610                                  ToPtr + NumBytes, llvm::strictConversion);
6611     // Check for conversion failure.
6612     if (Result != llvm::conversionOK)
6613       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
6614           << Arg->getSourceRange();
6615   }
6616   return false;
6617 }
6618 
6619 /// CheckObjCString - Checks that the format string argument to the os_log()
6620 /// and os_trace() functions is correct, and converts it to const char *.
6621 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
6622   Arg = Arg->IgnoreParenCasts();
6623   auto *Literal = dyn_cast<StringLiteral>(Arg);
6624   if (!Literal) {
6625     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
6626       Literal = ObjcLiteral->getString();
6627     }
6628   }
6629 
6630   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
6631     return ExprError(
6632         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
6633         << Arg->getSourceRange());
6634   }
6635 
6636   ExprResult Result(Literal);
6637   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
6638   InitializedEntity Entity =
6639       InitializedEntity::InitializeParameter(Context, ResultTy, false);
6640   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
6641   return Result;
6642 }
6643 
6644 /// Check that the user is calling the appropriate va_start builtin for the
6645 /// target and calling convention.
6646 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
6647   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
6648   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
6649   bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
6650                     TT.getArch() == llvm::Triple::aarch64_32);
6651   bool IsWindows = TT.isOSWindows();
6652   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
6653   if (IsX64 || IsAArch64) {
6654     CallingConv CC = CC_C;
6655     if (const FunctionDecl *FD = S.getCurFunctionDecl())
6656       CC = FD->getType()->castAs<FunctionType>()->getCallConv();
6657     if (IsMSVAStart) {
6658       // Don't allow this in System V ABI functions.
6659       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
6660         return S.Diag(Fn->getBeginLoc(),
6661                       diag::err_ms_va_start_used_in_sysv_function);
6662     } else {
6663       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
6664       // On x64 Windows, don't allow this in System V ABI functions.
6665       // (Yes, that means there's no corresponding way to support variadic
6666       // System V ABI functions on Windows.)
6667       if ((IsWindows && CC == CC_X86_64SysV) ||
6668           (!IsWindows && CC == CC_Win64))
6669         return S.Diag(Fn->getBeginLoc(),
6670                       diag::err_va_start_used_in_wrong_abi_function)
6671                << !IsWindows;
6672     }
6673     return false;
6674   }
6675 
6676   if (IsMSVAStart)
6677     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
6678   return false;
6679 }
6680 
6681 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
6682                                              ParmVarDecl **LastParam = nullptr) {
6683   // Determine whether the current function, block, or obj-c method is variadic
6684   // and get its parameter list.
6685   bool IsVariadic = false;
6686   ArrayRef<ParmVarDecl *> Params;
6687   DeclContext *Caller = S.CurContext;
6688   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
6689     IsVariadic = Block->isVariadic();
6690     Params = Block->parameters();
6691   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
6692     IsVariadic = FD->isVariadic();
6693     Params = FD->parameters();
6694   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
6695     IsVariadic = MD->isVariadic();
6696     // FIXME: This isn't correct for methods (results in bogus warning).
6697     Params = MD->parameters();
6698   } else if (isa<CapturedDecl>(Caller)) {
6699     // We don't support va_start in a CapturedDecl.
6700     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
6701     return true;
6702   } else {
6703     // This must be some other declcontext that parses exprs.
6704     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
6705     return true;
6706   }
6707 
6708   if (!IsVariadic) {
6709     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
6710     return true;
6711   }
6712 
6713   if (LastParam)
6714     *LastParam = Params.empty() ? nullptr : Params.back();
6715 
6716   return false;
6717 }
6718 
6719 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
6720 /// for validity.  Emit an error and return true on failure; return false
6721 /// on success.
6722 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
6723   Expr *Fn = TheCall->getCallee();
6724 
6725   if (checkVAStartABI(*this, BuiltinID, Fn))
6726     return true;
6727 
6728   if (checkArgCount(*this, TheCall, 2))
6729     return true;
6730 
6731   // Type-check the first argument normally.
6732   if (checkBuiltinArgument(*this, TheCall, 0))
6733     return true;
6734 
6735   // Check that the current function is variadic, and get its last parameter.
6736   ParmVarDecl *LastParam;
6737   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
6738     return true;
6739 
6740   // Verify that the second argument to the builtin is the last argument of the
6741   // current function or method.
6742   bool SecondArgIsLastNamedArgument = false;
6743   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
6744 
6745   // These are valid if SecondArgIsLastNamedArgument is false after the next
6746   // block.
6747   QualType Type;
6748   SourceLocation ParamLoc;
6749   bool IsCRegister = false;
6750 
6751   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
6752     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
6753       SecondArgIsLastNamedArgument = PV == LastParam;
6754 
6755       Type = PV->getType();
6756       ParamLoc = PV->getLocation();
6757       IsCRegister =
6758           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
6759     }
6760   }
6761 
6762   if (!SecondArgIsLastNamedArgument)
6763     Diag(TheCall->getArg(1)->getBeginLoc(),
6764          diag::warn_second_arg_of_va_start_not_last_named_param);
6765   else if (IsCRegister || Type->isReferenceType() ||
6766            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
6767              // Promotable integers are UB, but enumerations need a bit of
6768              // extra checking to see what their promotable type actually is.
6769              if (!Type->isPromotableIntegerType())
6770                return false;
6771              if (!Type->isEnumeralType())
6772                return true;
6773              const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
6774              return !(ED &&
6775                       Context.typesAreCompatible(ED->getPromotionType(), Type));
6776            }()) {
6777     unsigned Reason = 0;
6778     if (Type->isReferenceType())  Reason = 1;
6779     else if (IsCRegister)         Reason = 2;
6780     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
6781     Diag(ParamLoc, diag::note_parameter_type) << Type;
6782   }
6783 
6784   TheCall->setType(Context.VoidTy);
6785   return false;
6786 }
6787 
6788 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
6789   auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {
6790     const LangOptions &LO = getLangOpts();
6791 
6792     if (LO.CPlusPlus)
6793       return Arg->getType()
6794                  .getCanonicalType()
6795                  .getTypePtr()
6796                  ->getPointeeType()
6797                  .withoutLocalFastQualifiers() == Context.CharTy;
6798 
6799     // In C, allow aliasing through `char *`, this is required for AArch64 at
6800     // least.
6801     return true;
6802   };
6803 
6804   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
6805   //                 const char *named_addr);
6806 
6807   Expr *Func = Call->getCallee();
6808 
6809   if (Call->getNumArgs() < 3)
6810     return Diag(Call->getEndLoc(),
6811                 diag::err_typecheck_call_too_few_args_at_least)
6812            << 0 /*function call*/ << 3 << Call->getNumArgs();
6813 
6814   // Type-check the first argument normally.
6815   if (checkBuiltinArgument(*this, Call, 0))
6816     return true;
6817 
6818   // Check that the current function is variadic.
6819   if (checkVAStartIsInVariadicFunction(*this, Func))
6820     return true;
6821 
6822   // __va_start on Windows does not validate the parameter qualifiers
6823 
6824   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
6825   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
6826 
6827   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
6828   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
6829 
6830   const QualType &ConstCharPtrTy =
6831       Context.getPointerType(Context.CharTy.withConst());
6832   if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
6833     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6834         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
6835         << 0                                      /* qualifier difference */
6836         << 3                                      /* parameter mismatch */
6837         << 2 << Arg1->getType() << ConstCharPtrTy;
6838 
6839   const QualType SizeTy = Context.getSizeType();
6840   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
6841     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6842         << Arg2->getType() << SizeTy << 1 /* different class */
6843         << 0                              /* qualifier difference */
6844         << 3                              /* parameter mismatch */
6845         << 3 << Arg2->getType() << SizeTy;
6846 
6847   return false;
6848 }
6849 
6850 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
6851 /// friends.  This is declared to take (...), so we have to check everything.
6852 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
6853   if (checkArgCount(*this, TheCall, 2))
6854     return true;
6855 
6856   ExprResult OrigArg0 = TheCall->getArg(0);
6857   ExprResult OrigArg1 = TheCall->getArg(1);
6858 
6859   // Do standard promotions between the two arguments, returning their common
6860   // type.
6861   QualType Res = UsualArithmeticConversions(
6862       OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
6863   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
6864     return true;
6865 
6866   // Make sure any conversions are pushed back into the call; this is
6867   // type safe since unordered compare builtins are declared as "_Bool
6868   // foo(...)".
6869   TheCall->setArg(0, OrigArg0.get());
6870   TheCall->setArg(1, OrigArg1.get());
6871 
6872   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
6873     return false;
6874 
6875   // If the common type isn't a real floating type, then the arguments were
6876   // invalid for this operation.
6877   if (Res.isNull() || !Res->isRealFloatingType())
6878     return Diag(OrigArg0.get()->getBeginLoc(),
6879                 diag::err_typecheck_call_invalid_ordered_compare)
6880            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
6881            << SourceRange(OrigArg0.get()->getBeginLoc(),
6882                           OrigArg1.get()->getEndLoc());
6883 
6884   return false;
6885 }
6886 
6887 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
6888 /// __builtin_isnan and friends.  This is declared to take (...), so we have
6889 /// to check everything. We expect the last argument to be a floating point
6890 /// value.
6891 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
6892   if (checkArgCount(*this, TheCall, NumArgs))
6893     return true;
6894 
6895   // __builtin_fpclassify is the only case where NumArgs != 1, so we can count
6896   // on all preceding parameters just being int.  Try all of those.
6897   for (unsigned i = 0; i < NumArgs - 1; ++i) {
6898     Expr *Arg = TheCall->getArg(i);
6899 
6900     if (Arg->isTypeDependent())
6901       return false;
6902 
6903     ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);
6904 
6905     if (Res.isInvalid())
6906       return true;
6907     TheCall->setArg(i, Res.get());
6908   }
6909 
6910   Expr *OrigArg = TheCall->getArg(NumArgs-1);
6911 
6912   if (OrigArg->isTypeDependent())
6913     return false;
6914 
6915   // Usual Unary Conversions will convert half to float, which we want for
6916   // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
6917   // type how it is, but do normal L->Rvalue conversions.
6918   if (Context.getTargetInfo().useFP16ConversionIntrinsics())
6919     OrigArg = UsualUnaryConversions(OrigArg).get();
6920   else
6921     OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
6922   TheCall->setArg(NumArgs - 1, OrigArg);
6923 
6924   // This operation requires a non-_Complex floating-point number.
6925   if (!OrigArg->getType()->isRealFloatingType())
6926     return Diag(OrigArg->getBeginLoc(),
6927                 diag::err_typecheck_call_invalid_unary_fp)
6928            << OrigArg->getType() << OrigArg->getSourceRange();
6929 
6930   return false;
6931 }
6932 
6933 /// Perform semantic analysis for a call to __builtin_complex.
6934 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) {
6935   if (checkArgCount(*this, TheCall, 2))
6936     return true;
6937 
6938   bool Dependent = false;
6939   for (unsigned I = 0; I != 2; ++I) {
6940     Expr *Arg = TheCall->getArg(I);
6941     QualType T = Arg->getType();
6942     if (T->isDependentType()) {
6943       Dependent = true;
6944       continue;
6945     }
6946 
6947     // Despite supporting _Complex int, GCC requires a real floating point type
6948     // for the operands of __builtin_complex.
6949     if (!T->isRealFloatingType()) {
6950       return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
6951              << Arg->getType() << Arg->getSourceRange();
6952     }
6953 
6954     ExprResult Converted = DefaultLvalueConversion(Arg);
6955     if (Converted.isInvalid())
6956       return true;
6957     TheCall->setArg(I, Converted.get());
6958   }
6959 
6960   if (Dependent) {
6961     TheCall->setType(Context.DependentTy);
6962     return false;
6963   }
6964 
6965   Expr *Real = TheCall->getArg(0);
6966   Expr *Imag = TheCall->getArg(1);
6967   if (!Context.hasSameType(Real->getType(), Imag->getType())) {
6968     return Diag(Real->getBeginLoc(),
6969                 diag::err_typecheck_call_different_arg_types)
6970            << Real->getType() << Imag->getType()
6971            << Real->getSourceRange() << Imag->getSourceRange();
6972   }
6973 
6974   // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers;
6975   // don't allow this builtin to form those types either.
6976   // FIXME: Should we allow these types?
6977   if (Real->getType()->isFloat16Type())
6978     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6979            << "_Float16";
6980   if (Real->getType()->isHalfType())
6981     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6982            << "half";
6983 
6984   TheCall->setType(Context.getComplexType(Real->getType()));
6985   return false;
6986 }
6987 
6988 // Customized Sema Checking for VSX builtins that have the following signature:
6989 // vector [...] builtinName(vector [...], vector [...], const int);
6990 // Which takes the same type of vectors (any legal vector type) for the first
6991 // two arguments and takes compile time constant for the third argument.
6992 // Example builtins are :
6993 // vector double vec_xxpermdi(vector double, vector double, int);
6994 // vector short vec_xxsldwi(vector short, vector short, int);
6995 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
6996   unsigned ExpectedNumArgs = 3;
6997   if (checkArgCount(*this, TheCall, ExpectedNumArgs))
6998     return true;
6999 
7000   // Check the third argument is a compile time constant
7001   if (!TheCall->getArg(2)->isIntegerConstantExpr(Context))
7002     return Diag(TheCall->getBeginLoc(),
7003                 diag::err_vsx_builtin_nonconstant_argument)
7004            << 3 /* argument index */ << TheCall->getDirectCallee()
7005            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
7006                           TheCall->getArg(2)->getEndLoc());
7007 
7008   QualType Arg1Ty = TheCall->getArg(0)->getType();
7009   QualType Arg2Ty = TheCall->getArg(1)->getType();
7010 
7011   // Check the type of argument 1 and argument 2 are vectors.
7012   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
7013   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
7014       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
7015     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
7016            << TheCall->getDirectCallee()
7017            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
7018                           TheCall->getArg(1)->getEndLoc());
7019   }
7020 
7021   // Check the first two arguments are the same type.
7022   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
7023     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
7024            << TheCall->getDirectCallee()
7025            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
7026                           TheCall->getArg(1)->getEndLoc());
7027   }
7028 
7029   // When default clang type checking is turned off and the customized type
7030   // checking is used, the returning type of the function must be explicitly
7031   // set. Otherwise it is _Bool by default.
7032   TheCall->setType(Arg1Ty);
7033 
7034   return false;
7035 }
7036 
7037 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
7038 // This is declared to take (...), so we have to check everything.
7039 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
7040   if (TheCall->getNumArgs() < 2)
7041     return ExprError(Diag(TheCall->getEndLoc(),
7042                           diag::err_typecheck_call_too_few_args_at_least)
7043                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
7044                      << TheCall->getSourceRange());
7045 
7046   // Determine which of the following types of shufflevector we're checking:
7047   // 1) unary, vector mask: (lhs, mask)
7048   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
7049   QualType resType = TheCall->getArg(0)->getType();
7050   unsigned numElements = 0;
7051 
7052   if (!TheCall->getArg(0)->isTypeDependent() &&
7053       !TheCall->getArg(1)->isTypeDependent()) {
7054     QualType LHSType = TheCall->getArg(0)->getType();
7055     QualType RHSType = TheCall->getArg(1)->getType();
7056 
7057     if (!LHSType->isVectorType() || !RHSType->isVectorType())
7058       return ExprError(
7059           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
7060           << TheCall->getDirectCallee()
7061           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
7062                          TheCall->getArg(1)->getEndLoc()));
7063 
7064     numElements = LHSType->castAs<VectorType>()->getNumElements();
7065     unsigned numResElements = TheCall->getNumArgs() - 2;
7066 
7067     // Check to see if we have a call with 2 vector arguments, the unary shuffle
7068     // with mask.  If so, verify that RHS is an integer vector type with the
7069     // same number of elts as lhs.
7070     if (TheCall->getNumArgs() == 2) {
7071       if (!RHSType->hasIntegerRepresentation() ||
7072           RHSType->castAs<VectorType>()->getNumElements() != numElements)
7073         return ExprError(Diag(TheCall->getBeginLoc(),
7074                               diag::err_vec_builtin_incompatible_vector)
7075                          << TheCall->getDirectCallee()
7076                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
7077                                         TheCall->getArg(1)->getEndLoc()));
7078     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
7079       return ExprError(Diag(TheCall->getBeginLoc(),
7080                             diag::err_vec_builtin_incompatible_vector)
7081                        << TheCall->getDirectCallee()
7082                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
7083                                       TheCall->getArg(1)->getEndLoc()));
7084     } else if (numElements != numResElements) {
7085       QualType eltType = LHSType->castAs<VectorType>()->getElementType();
7086       resType = Context.getVectorType(eltType, numResElements,
7087                                       VectorType::GenericVector);
7088     }
7089   }
7090 
7091   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
7092     if (TheCall->getArg(i)->isTypeDependent() ||
7093         TheCall->getArg(i)->isValueDependent())
7094       continue;
7095 
7096     Optional<llvm::APSInt> Result;
7097     if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context)))
7098       return ExprError(Diag(TheCall->getBeginLoc(),
7099                             diag::err_shufflevector_nonconstant_argument)
7100                        << TheCall->getArg(i)->getSourceRange());
7101 
7102     // Allow -1 which will be translated to undef in the IR.
7103     if (Result->isSigned() && Result->isAllOnes())
7104       continue;
7105 
7106     if (Result->getActiveBits() > 64 ||
7107         Result->getZExtValue() >= numElements * 2)
7108       return ExprError(Diag(TheCall->getBeginLoc(),
7109                             diag::err_shufflevector_argument_too_large)
7110                        << TheCall->getArg(i)->getSourceRange());
7111   }
7112 
7113   SmallVector<Expr*, 32> exprs;
7114 
7115   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
7116     exprs.push_back(TheCall->getArg(i));
7117     TheCall->setArg(i, nullptr);
7118   }
7119 
7120   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
7121                                          TheCall->getCallee()->getBeginLoc(),
7122                                          TheCall->getRParenLoc());
7123 }
7124 
7125 /// SemaConvertVectorExpr - Handle __builtin_convertvector
7126 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
7127                                        SourceLocation BuiltinLoc,
7128                                        SourceLocation RParenLoc) {
7129   ExprValueKind VK = VK_PRValue;
7130   ExprObjectKind OK = OK_Ordinary;
7131   QualType DstTy = TInfo->getType();
7132   QualType SrcTy = E->getType();
7133 
7134   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
7135     return ExprError(Diag(BuiltinLoc,
7136                           diag::err_convertvector_non_vector)
7137                      << E->getSourceRange());
7138   if (!DstTy->isVectorType() && !DstTy->isDependentType())
7139     return ExprError(Diag(BuiltinLoc,
7140                           diag::err_convertvector_non_vector_type));
7141 
7142   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
7143     unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
7144     unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
7145     if (SrcElts != DstElts)
7146       return ExprError(Diag(BuiltinLoc,
7147                             diag::err_convertvector_incompatible_vector)
7148                        << E->getSourceRange());
7149   }
7150 
7151   return new (Context)
7152       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
7153 }
7154 
7155 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
7156 // This is declared to take (const void*, ...) and can take two
7157 // optional constant int args.
7158 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
7159   unsigned NumArgs = TheCall->getNumArgs();
7160 
7161   if (NumArgs > 3)
7162     return Diag(TheCall->getEndLoc(),
7163                 diag::err_typecheck_call_too_many_args_at_most)
7164            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
7165 
7166   // Argument 0 is checked for us and the remaining arguments must be
7167   // constant integers.
7168   for (unsigned i = 1; i != NumArgs; ++i)
7169     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
7170       return true;
7171 
7172   return false;
7173 }
7174 
7175 /// SemaBuiltinArithmeticFence - Handle __arithmetic_fence.
7176 bool Sema::SemaBuiltinArithmeticFence(CallExpr *TheCall) {
7177   if (!Context.getTargetInfo().checkArithmeticFenceSupported())
7178     return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
7179            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7180   if (checkArgCount(*this, TheCall, 1))
7181     return true;
7182   Expr *Arg = TheCall->getArg(0);
7183   if (Arg->isInstantiationDependent())
7184     return false;
7185 
7186   QualType ArgTy = Arg->getType();
7187   if (!ArgTy->hasFloatingRepresentation())
7188     return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector)
7189            << ArgTy;
7190   if (Arg->isLValue()) {
7191     ExprResult FirstArg = DefaultLvalueConversion(Arg);
7192     TheCall->setArg(0, FirstArg.get());
7193   }
7194   TheCall->setType(TheCall->getArg(0)->getType());
7195   return false;
7196 }
7197 
7198 /// SemaBuiltinAssume - Handle __assume (MS Extension).
7199 // __assume does not evaluate its arguments, and should warn if its argument
7200 // has side effects.
7201 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
7202   Expr *Arg = TheCall->getArg(0);
7203   if (Arg->isInstantiationDependent()) return false;
7204 
7205   if (Arg->HasSideEffects(Context))
7206     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
7207         << Arg->getSourceRange()
7208         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
7209 
7210   return false;
7211 }
7212 
7213 /// Handle __builtin_alloca_with_align. This is declared
7214 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
7215 /// than 8.
7216 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
7217   // The alignment must be a constant integer.
7218   Expr *Arg = TheCall->getArg(1);
7219 
7220   // We can't check the value of a dependent argument.
7221   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
7222     if (const auto *UE =
7223             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
7224       if (UE->getKind() == UETT_AlignOf ||
7225           UE->getKind() == UETT_PreferredAlignOf)
7226         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
7227             << Arg->getSourceRange();
7228 
7229     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
7230 
7231     if (!Result.isPowerOf2())
7232       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
7233              << Arg->getSourceRange();
7234 
7235     if (Result < Context.getCharWidth())
7236       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
7237              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
7238 
7239     if (Result > std::numeric_limits<int32_t>::max())
7240       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
7241              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
7242   }
7243 
7244   return false;
7245 }
7246 
7247 /// Handle __builtin_assume_aligned. This is declared
7248 /// as (const void*, size_t, ...) and can take one optional constant int arg.
7249 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
7250   unsigned NumArgs = TheCall->getNumArgs();
7251 
7252   if (NumArgs > 3)
7253     return Diag(TheCall->getEndLoc(),
7254                 diag::err_typecheck_call_too_many_args_at_most)
7255            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
7256 
7257   // The alignment must be a constant integer.
7258   Expr *Arg = TheCall->getArg(1);
7259 
7260   // We can't check the value of a dependent argument.
7261   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
7262     llvm::APSInt Result;
7263     if (SemaBuiltinConstantArg(TheCall, 1, Result))
7264       return true;
7265 
7266     if (!Result.isPowerOf2())
7267       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
7268              << Arg->getSourceRange();
7269 
7270     if (Result > Sema::MaximumAlignment)
7271       Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
7272           << Arg->getSourceRange() << Sema::MaximumAlignment;
7273   }
7274 
7275   if (NumArgs > 2) {
7276     ExprResult Arg(TheCall->getArg(2));
7277     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
7278       Context.getSizeType(), false);
7279     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
7280     if (Arg.isInvalid()) return true;
7281     TheCall->setArg(2, Arg.get());
7282   }
7283 
7284   return false;
7285 }
7286 
7287 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
7288   unsigned BuiltinID =
7289       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
7290   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
7291 
7292   unsigned NumArgs = TheCall->getNumArgs();
7293   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
7294   if (NumArgs < NumRequiredArgs) {
7295     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
7296            << 0 /* function call */ << NumRequiredArgs << NumArgs
7297            << TheCall->getSourceRange();
7298   }
7299   if (NumArgs >= NumRequiredArgs + 0x100) {
7300     return Diag(TheCall->getEndLoc(),
7301                 diag::err_typecheck_call_too_many_args_at_most)
7302            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
7303            << TheCall->getSourceRange();
7304   }
7305   unsigned i = 0;
7306 
7307   // For formatting call, check buffer arg.
7308   if (!IsSizeCall) {
7309     ExprResult Arg(TheCall->getArg(i));
7310     InitializedEntity Entity = InitializedEntity::InitializeParameter(
7311         Context, Context.VoidPtrTy, false);
7312     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
7313     if (Arg.isInvalid())
7314       return true;
7315     TheCall->setArg(i, Arg.get());
7316     i++;
7317   }
7318 
7319   // Check string literal arg.
7320   unsigned FormatIdx = i;
7321   {
7322     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
7323     if (Arg.isInvalid())
7324       return true;
7325     TheCall->setArg(i, Arg.get());
7326     i++;
7327   }
7328 
7329   // Make sure variadic args are scalar.
7330   unsigned FirstDataArg = i;
7331   while (i < NumArgs) {
7332     ExprResult Arg = DefaultVariadicArgumentPromotion(
7333         TheCall->getArg(i), VariadicFunction, nullptr);
7334     if (Arg.isInvalid())
7335       return true;
7336     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
7337     if (ArgSize.getQuantity() >= 0x100) {
7338       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
7339              << i << (int)ArgSize.getQuantity() << 0xff
7340              << TheCall->getSourceRange();
7341     }
7342     TheCall->setArg(i, Arg.get());
7343     i++;
7344   }
7345 
7346   // Check formatting specifiers. NOTE: We're only doing this for the non-size
7347   // call to avoid duplicate diagnostics.
7348   if (!IsSizeCall) {
7349     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
7350     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
7351     bool Success = CheckFormatArguments(
7352         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
7353         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
7354         CheckedVarArgs);
7355     if (!Success)
7356       return true;
7357   }
7358 
7359   if (IsSizeCall) {
7360     TheCall->setType(Context.getSizeType());
7361   } else {
7362     TheCall->setType(Context.VoidPtrTy);
7363   }
7364   return false;
7365 }
7366 
7367 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
7368 /// TheCall is a constant expression.
7369 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
7370                                   llvm::APSInt &Result) {
7371   Expr *Arg = TheCall->getArg(ArgNum);
7372   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
7373   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
7374 
7375   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
7376 
7377   Optional<llvm::APSInt> R;
7378   if (!(R = Arg->getIntegerConstantExpr(Context)))
7379     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
7380            << FDecl->getDeclName() << Arg->getSourceRange();
7381   Result = *R;
7382   return false;
7383 }
7384 
7385 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
7386 /// TheCall is a constant expression in the range [Low, High].
7387 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
7388                                        int Low, int High, bool RangeIsError) {
7389   if (isConstantEvaluated())
7390     return false;
7391   llvm::APSInt Result;
7392 
7393   // We can't check the value of a dependent argument.
7394   Expr *Arg = TheCall->getArg(ArgNum);
7395   if (Arg->isTypeDependent() || Arg->isValueDependent())
7396     return false;
7397 
7398   // Check constant-ness first.
7399   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7400     return true;
7401 
7402   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
7403     if (RangeIsError)
7404       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
7405              << toString(Result, 10) << Low << High << Arg->getSourceRange();
7406     else
7407       // Defer the warning until we know if the code will be emitted so that
7408       // dead code can ignore this.
7409       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
7410                           PDiag(diag::warn_argument_invalid_range)
7411                               << toString(Result, 10) << Low << High
7412                               << Arg->getSourceRange());
7413   }
7414 
7415   return false;
7416 }
7417 
7418 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
7419 /// TheCall is a constant expression is a multiple of Num..
7420 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
7421                                           unsigned Num) {
7422   llvm::APSInt Result;
7423 
7424   // We can't check the value of a dependent argument.
7425   Expr *Arg = TheCall->getArg(ArgNum);
7426   if (Arg->isTypeDependent() || Arg->isValueDependent())
7427     return false;
7428 
7429   // Check constant-ness first.
7430   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7431     return true;
7432 
7433   if (Result.getSExtValue() % Num != 0)
7434     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
7435            << Num << Arg->getSourceRange();
7436 
7437   return false;
7438 }
7439 
7440 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
7441 /// constant expression representing a power of 2.
7442 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
7443   llvm::APSInt Result;
7444 
7445   // We can't check the value of a dependent argument.
7446   Expr *Arg = TheCall->getArg(ArgNum);
7447   if (Arg->isTypeDependent() || Arg->isValueDependent())
7448     return false;
7449 
7450   // Check constant-ness first.
7451   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7452     return true;
7453 
7454   // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
7455   // and only if x is a power of 2.
7456   if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
7457     return false;
7458 
7459   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
7460          << Arg->getSourceRange();
7461 }
7462 
7463 static bool IsShiftedByte(llvm::APSInt Value) {
7464   if (Value.isNegative())
7465     return false;
7466 
7467   // Check if it's a shifted byte, by shifting it down
7468   while (true) {
7469     // If the value fits in the bottom byte, the check passes.
7470     if (Value < 0x100)
7471       return true;
7472 
7473     // Otherwise, if the value has _any_ bits in the bottom byte, the check
7474     // fails.
7475     if ((Value & 0xFF) != 0)
7476       return false;
7477 
7478     // If the bottom 8 bits are all 0, but something above that is nonzero,
7479     // then shifting the value right by 8 bits won't affect whether it's a
7480     // shifted byte or not. So do that, and go round again.
7481     Value >>= 8;
7482   }
7483 }
7484 
7485 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
7486 /// a constant expression representing an arbitrary byte value shifted left by
7487 /// a multiple of 8 bits.
7488 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
7489                                              unsigned ArgBits) {
7490   llvm::APSInt Result;
7491 
7492   // We can't check the value of a dependent argument.
7493   Expr *Arg = TheCall->getArg(ArgNum);
7494   if (Arg->isTypeDependent() || Arg->isValueDependent())
7495     return false;
7496 
7497   // Check constant-ness first.
7498   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7499     return true;
7500 
7501   // Truncate to the given size.
7502   Result = Result.getLoBits(ArgBits);
7503   Result.setIsUnsigned(true);
7504 
7505   if (IsShiftedByte(Result))
7506     return false;
7507 
7508   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
7509          << Arg->getSourceRange();
7510 }
7511 
7512 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
7513 /// TheCall is a constant expression representing either a shifted byte value,
7514 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
7515 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
7516 /// Arm MVE intrinsics.
7517 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
7518                                                    int ArgNum,
7519                                                    unsigned ArgBits) {
7520   llvm::APSInt Result;
7521 
7522   // We can't check the value of a dependent argument.
7523   Expr *Arg = TheCall->getArg(ArgNum);
7524   if (Arg->isTypeDependent() || Arg->isValueDependent())
7525     return false;
7526 
7527   // Check constant-ness first.
7528   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7529     return true;
7530 
7531   // Truncate to the given size.
7532   Result = Result.getLoBits(ArgBits);
7533   Result.setIsUnsigned(true);
7534 
7535   // Check to see if it's in either of the required forms.
7536   if (IsShiftedByte(Result) ||
7537       (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
7538     return false;
7539 
7540   return Diag(TheCall->getBeginLoc(),
7541               diag::err_argument_not_shifted_byte_or_xxff)
7542          << Arg->getSourceRange();
7543 }
7544 
7545 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
7546 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
7547   if (BuiltinID == AArch64::BI__builtin_arm_irg) {
7548     if (checkArgCount(*this, TheCall, 2))
7549       return true;
7550     Expr *Arg0 = TheCall->getArg(0);
7551     Expr *Arg1 = TheCall->getArg(1);
7552 
7553     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7554     if (FirstArg.isInvalid())
7555       return true;
7556     QualType FirstArgType = FirstArg.get()->getType();
7557     if (!FirstArgType->isAnyPointerType())
7558       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7559                << "first" << FirstArgType << Arg0->getSourceRange();
7560     TheCall->setArg(0, FirstArg.get());
7561 
7562     ExprResult SecArg = DefaultLvalueConversion(Arg1);
7563     if (SecArg.isInvalid())
7564       return true;
7565     QualType SecArgType = SecArg.get()->getType();
7566     if (!SecArgType->isIntegerType())
7567       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
7568                << "second" << SecArgType << Arg1->getSourceRange();
7569 
7570     // Derive the return type from the pointer argument.
7571     TheCall->setType(FirstArgType);
7572     return false;
7573   }
7574 
7575   if (BuiltinID == AArch64::BI__builtin_arm_addg) {
7576     if (checkArgCount(*this, TheCall, 2))
7577       return true;
7578 
7579     Expr *Arg0 = TheCall->getArg(0);
7580     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7581     if (FirstArg.isInvalid())
7582       return true;
7583     QualType FirstArgType = FirstArg.get()->getType();
7584     if (!FirstArgType->isAnyPointerType())
7585       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7586                << "first" << FirstArgType << Arg0->getSourceRange();
7587     TheCall->setArg(0, FirstArg.get());
7588 
7589     // Derive the return type from the pointer argument.
7590     TheCall->setType(FirstArgType);
7591 
7592     // Second arg must be an constant in range [0,15]
7593     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
7594   }
7595 
7596   if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
7597     if (checkArgCount(*this, TheCall, 2))
7598       return true;
7599     Expr *Arg0 = TheCall->getArg(0);
7600     Expr *Arg1 = TheCall->getArg(1);
7601 
7602     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7603     if (FirstArg.isInvalid())
7604       return true;
7605     QualType FirstArgType = FirstArg.get()->getType();
7606     if (!FirstArgType->isAnyPointerType())
7607       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7608                << "first" << FirstArgType << Arg0->getSourceRange();
7609 
7610     QualType SecArgType = Arg1->getType();
7611     if (!SecArgType->isIntegerType())
7612       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
7613                << "second" << SecArgType << Arg1->getSourceRange();
7614     TheCall->setType(Context.IntTy);
7615     return false;
7616   }
7617 
7618   if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
7619       BuiltinID == AArch64::BI__builtin_arm_stg) {
7620     if (checkArgCount(*this, TheCall, 1))
7621       return true;
7622     Expr *Arg0 = TheCall->getArg(0);
7623     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7624     if (FirstArg.isInvalid())
7625       return true;
7626 
7627     QualType FirstArgType = FirstArg.get()->getType();
7628     if (!FirstArgType->isAnyPointerType())
7629       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7630                << "first" << FirstArgType << Arg0->getSourceRange();
7631     TheCall->setArg(0, FirstArg.get());
7632 
7633     // Derive the return type from the pointer argument.
7634     if (BuiltinID == AArch64::BI__builtin_arm_ldg)
7635       TheCall->setType(FirstArgType);
7636     return false;
7637   }
7638 
7639   if (BuiltinID == AArch64::BI__builtin_arm_subp) {
7640     Expr *ArgA = TheCall->getArg(0);
7641     Expr *ArgB = TheCall->getArg(1);
7642 
7643     ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
7644     ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
7645 
7646     if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
7647       return true;
7648 
7649     QualType ArgTypeA = ArgExprA.get()->getType();
7650     QualType ArgTypeB = ArgExprB.get()->getType();
7651 
7652     auto isNull = [&] (Expr *E) -> bool {
7653       return E->isNullPointerConstant(
7654                         Context, Expr::NPC_ValueDependentIsNotNull); };
7655 
7656     // argument should be either a pointer or null
7657     if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
7658       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
7659         << "first" << ArgTypeA << ArgA->getSourceRange();
7660 
7661     if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
7662       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
7663         << "second" << ArgTypeB << ArgB->getSourceRange();
7664 
7665     // Ensure Pointee types are compatible
7666     if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
7667         ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
7668       QualType pointeeA = ArgTypeA->getPointeeType();
7669       QualType pointeeB = ArgTypeB->getPointeeType();
7670       if (!Context.typesAreCompatible(
7671              Context.getCanonicalType(pointeeA).getUnqualifiedType(),
7672              Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
7673         return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
7674           << ArgTypeA <<  ArgTypeB << ArgA->getSourceRange()
7675           << ArgB->getSourceRange();
7676       }
7677     }
7678 
7679     // at least one argument should be pointer type
7680     if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
7681       return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
7682         <<  ArgTypeA << ArgTypeB << ArgA->getSourceRange();
7683 
7684     if (isNull(ArgA)) // adopt type of the other pointer
7685       ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
7686 
7687     if (isNull(ArgB))
7688       ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
7689 
7690     TheCall->setArg(0, ArgExprA.get());
7691     TheCall->setArg(1, ArgExprB.get());
7692     TheCall->setType(Context.LongLongTy);
7693     return false;
7694   }
7695   assert(false && "Unhandled ARM MTE intrinsic");
7696   return true;
7697 }
7698 
7699 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
7700 /// TheCall is an ARM/AArch64 special register string literal.
7701 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
7702                                     int ArgNum, unsigned ExpectedFieldNum,
7703                                     bool AllowName) {
7704   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
7705                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
7706                       BuiltinID == ARM::BI__builtin_arm_rsr ||
7707                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
7708                       BuiltinID == ARM::BI__builtin_arm_wsr ||
7709                       BuiltinID == ARM::BI__builtin_arm_wsrp;
7710   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
7711                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
7712                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
7713                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
7714                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
7715                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
7716   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
7717 
7718   // We can't check the value of a dependent argument.
7719   Expr *Arg = TheCall->getArg(ArgNum);
7720   if (Arg->isTypeDependent() || Arg->isValueDependent())
7721     return false;
7722 
7723   // Check if the argument is a string literal.
7724   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
7725     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
7726            << Arg->getSourceRange();
7727 
7728   // Check the type of special register given.
7729   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
7730   SmallVector<StringRef, 6> Fields;
7731   Reg.split(Fields, ":");
7732 
7733   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
7734     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
7735            << Arg->getSourceRange();
7736 
7737   // If the string is the name of a register then we cannot check that it is
7738   // valid here but if the string is of one the forms described in ACLE then we
7739   // can check that the supplied fields are integers and within the valid
7740   // ranges.
7741   if (Fields.size() > 1) {
7742     bool FiveFields = Fields.size() == 5;
7743 
7744     bool ValidString = true;
7745     if (IsARMBuiltin) {
7746       ValidString &= Fields[0].startswith_insensitive("cp") ||
7747                      Fields[0].startswith_insensitive("p");
7748       if (ValidString)
7749         Fields[0] = Fields[0].drop_front(
7750             Fields[0].startswith_insensitive("cp") ? 2 : 1);
7751 
7752       ValidString &= Fields[2].startswith_insensitive("c");
7753       if (ValidString)
7754         Fields[2] = Fields[2].drop_front(1);
7755 
7756       if (FiveFields) {
7757         ValidString &= Fields[3].startswith_insensitive("c");
7758         if (ValidString)
7759           Fields[3] = Fields[3].drop_front(1);
7760       }
7761     }
7762 
7763     SmallVector<int, 5> Ranges;
7764     if (FiveFields)
7765       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
7766     else
7767       Ranges.append({15, 7, 15});
7768 
7769     for (unsigned i=0; i<Fields.size(); ++i) {
7770       int IntField;
7771       ValidString &= !Fields[i].getAsInteger(10, IntField);
7772       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
7773     }
7774 
7775     if (!ValidString)
7776       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
7777              << Arg->getSourceRange();
7778   } else if (IsAArch64Builtin && Fields.size() == 1) {
7779     // If the register name is one of those that appear in the condition below
7780     // and the special register builtin being used is one of the write builtins,
7781     // then we require that the argument provided for writing to the register
7782     // is an integer constant expression. This is because it will be lowered to
7783     // an MSR (immediate) instruction, so we need to know the immediate at
7784     // compile time.
7785     if (TheCall->getNumArgs() != 2)
7786       return false;
7787 
7788     std::string RegLower = Reg.lower();
7789     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
7790         RegLower != "pan" && RegLower != "uao")
7791       return false;
7792 
7793     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
7794   }
7795 
7796   return false;
7797 }
7798 
7799 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity.
7800 /// Emit an error and return true on failure; return false on success.
7801 /// TypeStr is a string containing the type descriptor of the value returned by
7802 /// the builtin and the descriptors of the expected type of the arguments.
7803 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, unsigned BuiltinID,
7804                                  const char *TypeStr) {
7805 
7806   assert((TypeStr[0] != '\0') &&
7807          "Invalid types in PPC MMA builtin declaration");
7808 
7809   switch (BuiltinID) {
7810   default:
7811     // This function is called in CheckPPCBuiltinFunctionCall where the
7812     // BuiltinID is guaranteed to be an MMA or pair vector memop builtin, here
7813     // we are isolating the pair vector memop builtins that can be used with mma
7814     // off so the default case is every builtin that requires mma and paired
7815     // vector memops.
7816     if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops",
7817                          diag::err_ppc_builtin_only_on_arch, "10") ||
7818         SemaFeatureCheck(*this, TheCall, "mma",
7819                          diag::err_ppc_builtin_only_on_arch, "10"))
7820       return true;
7821     break;
7822   case PPC::BI__builtin_vsx_lxvp:
7823   case PPC::BI__builtin_vsx_stxvp:
7824   case PPC::BI__builtin_vsx_assemble_pair:
7825   case PPC::BI__builtin_vsx_disassemble_pair:
7826     if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops",
7827                          diag::err_ppc_builtin_only_on_arch, "10"))
7828       return true;
7829     break;
7830   }
7831 
7832   unsigned Mask = 0;
7833   unsigned ArgNum = 0;
7834 
7835   // The first type in TypeStr is the type of the value returned by the
7836   // builtin. So we first read that type and change the type of TheCall.
7837   QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7838   TheCall->setType(type);
7839 
7840   while (*TypeStr != '\0') {
7841     Mask = 0;
7842     QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7843     if (ArgNum >= TheCall->getNumArgs()) {
7844       ArgNum++;
7845       break;
7846     }
7847 
7848     Expr *Arg = TheCall->getArg(ArgNum);
7849     QualType PassedType = Arg->getType();
7850     QualType StrippedRVType = PassedType.getCanonicalType();
7851 
7852     // Strip Restrict/Volatile qualifiers.
7853     if (StrippedRVType.isRestrictQualified() ||
7854         StrippedRVType.isVolatileQualified())
7855       StrippedRVType = StrippedRVType.getCanonicalType().getUnqualifiedType();
7856 
7857     // The only case where the argument type and expected type are allowed to
7858     // mismatch is if the argument type is a non-void pointer (or array) and
7859     // expected type is a void pointer.
7860     if (StrippedRVType != ExpectedType)
7861       if (!(ExpectedType->isVoidPointerType() &&
7862             (StrippedRVType->isPointerType() || StrippedRVType->isArrayType())))
7863         return Diag(Arg->getBeginLoc(),
7864                     diag::err_typecheck_convert_incompatible)
7865                << PassedType << ExpectedType << 1 << 0 << 0;
7866 
7867     // If the value of the Mask is not 0, we have a constraint in the size of
7868     // the integer argument so here we ensure the argument is a constant that
7869     // is in the valid range.
7870     if (Mask != 0 &&
7871         SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true))
7872       return true;
7873 
7874     ArgNum++;
7875   }
7876 
7877   // In case we exited early from the previous loop, there are other types to
7878   // read from TypeStr. So we need to read them all to ensure we have the right
7879   // number of arguments in TheCall and if it is not the case, to display a
7880   // better error message.
7881   while (*TypeStr != '\0') {
7882     (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7883     ArgNum++;
7884   }
7885   if (checkArgCount(*this, TheCall, ArgNum))
7886     return true;
7887 
7888   return false;
7889 }
7890 
7891 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
7892 /// This checks that the target supports __builtin_longjmp and
7893 /// that val is a constant 1.
7894 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
7895   if (!Context.getTargetInfo().hasSjLjLowering())
7896     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
7897            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7898 
7899   Expr *Arg = TheCall->getArg(1);
7900   llvm::APSInt Result;
7901 
7902   // TODO: This is less than ideal. Overload this to take a value.
7903   if (SemaBuiltinConstantArg(TheCall, 1, Result))
7904     return true;
7905 
7906   if (Result != 1)
7907     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
7908            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
7909 
7910   return false;
7911 }
7912 
7913 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
7914 /// This checks that the target supports __builtin_setjmp.
7915 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
7916   if (!Context.getTargetInfo().hasSjLjLowering())
7917     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
7918            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7919   return false;
7920 }
7921 
7922 namespace {
7923 
7924 class UncoveredArgHandler {
7925   enum { Unknown = -1, AllCovered = -2 };
7926 
7927   signed FirstUncoveredArg = Unknown;
7928   SmallVector<const Expr *, 4> DiagnosticExprs;
7929 
7930 public:
7931   UncoveredArgHandler() = default;
7932 
7933   bool hasUncoveredArg() const {
7934     return (FirstUncoveredArg >= 0);
7935   }
7936 
7937   unsigned getUncoveredArg() const {
7938     assert(hasUncoveredArg() && "no uncovered argument");
7939     return FirstUncoveredArg;
7940   }
7941 
7942   void setAllCovered() {
7943     // A string has been found with all arguments covered, so clear out
7944     // the diagnostics.
7945     DiagnosticExprs.clear();
7946     FirstUncoveredArg = AllCovered;
7947   }
7948 
7949   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
7950     assert(NewFirstUncoveredArg >= 0 && "Outside range");
7951 
7952     // Don't update if a previous string covers all arguments.
7953     if (FirstUncoveredArg == AllCovered)
7954       return;
7955 
7956     // UncoveredArgHandler tracks the highest uncovered argument index
7957     // and with it all the strings that match this index.
7958     if (NewFirstUncoveredArg == FirstUncoveredArg)
7959       DiagnosticExprs.push_back(StrExpr);
7960     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
7961       DiagnosticExprs.clear();
7962       DiagnosticExprs.push_back(StrExpr);
7963       FirstUncoveredArg = NewFirstUncoveredArg;
7964     }
7965   }
7966 
7967   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
7968 };
7969 
7970 enum StringLiteralCheckType {
7971   SLCT_NotALiteral,
7972   SLCT_UncheckedLiteral,
7973   SLCT_CheckedLiteral
7974 };
7975 
7976 } // namespace
7977 
7978 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
7979                                      BinaryOperatorKind BinOpKind,
7980                                      bool AddendIsRight) {
7981   unsigned BitWidth = Offset.getBitWidth();
7982   unsigned AddendBitWidth = Addend.getBitWidth();
7983   // There might be negative interim results.
7984   if (Addend.isUnsigned()) {
7985     Addend = Addend.zext(++AddendBitWidth);
7986     Addend.setIsSigned(true);
7987   }
7988   // Adjust the bit width of the APSInts.
7989   if (AddendBitWidth > BitWidth) {
7990     Offset = Offset.sext(AddendBitWidth);
7991     BitWidth = AddendBitWidth;
7992   } else if (BitWidth > AddendBitWidth) {
7993     Addend = Addend.sext(BitWidth);
7994   }
7995 
7996   bool Ov = false;
7997   llvm::APSInt ResOffset = Offset;
7998   if (BinOpKind == BO_Add)
7999     ResOffset = Offset.sadd_ov(Addend, Ov);
8000   else {
8001     assert(AddendIsRight && BinOpKind == BO_Sub &&
8002            "operator must be add or sub with addend on the right");
8003     ResOffset = Offset.ssub_ov(Addend, Ov);
8004   }
8005 
8006   // We add an offset to a pointer here so we should support an offset as big as
8007   // possible.
8008   if (Ov) {
8009     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
8010            "index (intermediate) result too big");
8011     Offset = Offset.sext(2 * BitWidth);
8012     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
8013     return;
8014   }
8015 
8016   Offset = ResOffset;
8017 }
8018 
8019 namespace {
8020 
8021 // This is a wrapper class around StringLiteral to support offsetted string
8022 // literals as format strings. It takes the offset into account when returning
8023 // the string and its length or the source locations to display notes correctly.
8024 class FormatStringLiteral {
8025   const StringLiteral *FExpr;
8026   int64_t Offset;
8027 
8028  public:
8029   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
8030       : FExpr(fexpr), Offset(Offset) {}
8031 
8032   StringRef getString() const {
8033     return FExpr->getString().drop_front(Offset);
8034   }
8035 
8036   unsigned getByteLength() const {
8037     return FExpr->getByteLength() - getCharByteWidth() * Offset;
8038   }
8039 
8040   unsigned getLength() const { return FExpr->getLength() - Offset; }
8041   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
8042 
8043   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
8044 
8045   QualType getType() const { return FExpr->getType(); }
8046 
8047   bool isAscii() const { return FExpr->isAscii(); }
8048   bool isWide() const { return FExpr->isWide(); }
8049   bool isUTF8() const { return FExpr->isUTF8(); }
8050   bool isUTF16() const { return FExpr->isUTF16(); }
8051   bool isUTF32() const { return FExpr->isUTF32(); }
8052   bool isPascal() const { return FExpr->isPascal(); }
8053 
8054   SourceLocation getLocationOfByte(
8055       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
8056       const TargetInfo &Target, unsigned *StartToken = nullptr,
8057       unsigned *StartTokenByteOffset = nullptr) const {
8058     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
8059                                     StartToken, StartTokenByteOffset);
8060   }
8061 
8062   SourceLocation getBeginLoc() const LLVM_READONLY {
8063     return FExpr->getBeginLoc().getLocWithOffset(Offset);
8064   }
8065 
8066   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
8067 };
8068 
8069 }  // namespace
8070 
8071 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
8072                               const Expr *OrigFormatExpr,
8073                               ArrayRef<const Expr *> Args,
8074                               bool HasVAListArg, unsigned format_idx,
8075                               unsigned firstDataArg,
8076                               Sema::FormatStringType Type,
8077                               bool inFunctionCall,
8078                               Sema::VariadicCallType CallType,
8079                               llvm::SmallBitVector &CheckedVarArgs,
8080                               UncoveredArgHandler &UncoveredArg,
8081                               bool IgnoreStringsWithoutSpecifiers);
8082 
8083 // Determine if an expression is a string literal or constant string.
8084 // If this function returns false on the arguments to a function expecting a
8085 // format string, we will usually need to emit a warning.
8086 // True string literals are then checked by CheckFormatString.
8087 static StringLiteralCheckType
8088 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
8089                       bool HasVAListArg, unsigned format_idx,
8090                       unsigned firstDataArg, Sema::FormatStringType Type,
8091                       Sema::VariadicCallType CallType, bool InFunctionCall,
8092                       llvm::SmallBitVector &CheckedVarArgs,
8093                       UncoveredArgHandler &UncoveredArg,
8094                       llvm::APSInt Offset,
8095                       bool IgnoreStringsWithoutSpecifiers = false) {
8096   if (S.isConstantEvaluated())
8097     return SLCT_NotALiteral;
8098  tryAgain:
8099   assert(Offset.isSigned() && "invalid offset");
8100 
8101   if (E->isTypeDependent() || E->isValueDependent())
8102     return SLCT_NotALiteral;
8103 
8104   E = E->IgnoreParenCasts();
8105 
8106   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
8107     // Technically -Wformat-nonliteral does not warn about this case.
8108     // The behavior of printf and friends in this case is implementation
8109     // dependent.  Ideally if the format string cannot be null then
8110     // it should have a 'nonnull' attribute in the function prototype.
8111     return SLCT_UncheckedLiteral;
8112 
8113   switch (E->getStmtClass()) {
8114   case Stmt::BinaryConditionalOperatorClass:
8115   case Stmt::ConditionalOperatorClass: {
8116     // The expression is a literal if both sub-expressions were, and it was
8117     // completely checked only if both sub-expressions were checked.
8118     const AbstractConditionalOperator *C =
8119         cast<AbstractConditionalOperator>(E);
8120 
8121     // Determine whether it is necessary to check both sub-expressions, for
8122     // example, because the condition expression is a constant that can be
8123     // evaluated at compile time.
8124     bool CheckLeft = true, CheckRight = true;
8125 
8126     bool Cond;
8127     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
8128                                                  S.isConstantEvaluated())) {
8129       if (Cond)
8130         CheckRight = false;
8131       else
8132         CheckLeft = false;
8133     }
8134 
8135     // We need to maintain the offsets for the right and the left hand side
8136     // separately to check if every possible indexed expression is a valid
8137     // string literal. They might have different offsets for different string
8138     // literals in the end.
8139     StringLiteralCheckType Left;
8140     if (!CheckLeft)
8141       Left = SLCT_UncheckedLiteral;
8142     else {
8143       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
8144                                    HasVAListArg, format_idx, firstDataArg,
8145                                    Type, CallType, InFunctionCall,
8146                                    CheckedVarArgs, UncoveredArg, Offset,
8147                                    IgnoreStringsWithoutSpecifiers);
8148       if (Left == SLCT_NotALiteral || !CheckRight) {
8149         return Left;
8150       }
8151     }
8152 
8153     StringLiteralCheckType Right = checkFormatStringExpr(
8154         S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
8155         Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
8156         IgnoreStringsWithoutSpecifiers);
8157 
8158     return (CheckLeft && Left < Right) ? Left : Right;
8159   }
8160 
8161   case Stmt::ImplicitCastExprClass:
8162     E = cast<ImplicitCastExpr>(E)->getSubExpr();
8163     goto tryAgain;
8164 
8165   case Stmt::OpaqueValueExprClass:
8166     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
8167       E = src;
8168       goto tryAgain;
8169     }
8170     return SLCT_NotALiteral;
8171 
8172   case Stmt::PredefinedExprClass:
8173     // While __func__, etc., are technically not string literals, they
8174     // cannot contain format specifiers and thus are not a security
8175     // liability.
8176     return SLCT_UncheckedLiteral;
8177 
8178   case Stmt::DeclRefExprClass: {
8179     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
8180 
8181     // As an exception, do not flag errors for variables binding to
8182     // const string literals.
8183     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
8184       bool isConstant = false;
8185       QualType T = DR->getType();
8186 
8187       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
8188         isConstant = AT->getElementType().isConstant(S.Context);
8189       } else if (const PointerType *PT = T->getAs<PointerType>()) {
8190         isConstant = T.isConstant(S.Context) &&
8191                      PT->getPointeeType().isConstant(S.Context);
8192       } else if (T->isObjCObjectPointerType()) {
8193         // In ObjC, there is usually no "const ObjectPointer" type,
8194         // so don't check if the pointee type is constant.
8195         isConstant = T.isConstant(S.Context);
8196       }
8197 
8198       if (isConstant) {
8199         if (const Expr *Init = VD->getAnyInitializer()) {
8200           // Look through initializers like const char c[] = { "foo" }
8201           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
8202             if (InitList->isStringLiteralInit())
8203               Init = InitList->getInit(0)->IgnoreParenImpCasts();
8204           }
8205           return checkFormatStringExpr(S, Init, Args,
8206                                        HasVAListArg, format_idx,
8207                                        firstDataArg, Type, CallType,
8208                                        /*InFunctionCall*/ false, CheckedVarArgs,
8209                                        UncoveredArg, Offset);
8210         }
8211       }
8212 
8213       // For vprintf* functions (i.e., HasVAListArg==true), we add a
8214       // special check to see if the format string is a function parameter
8215       // of the function calling the printf function.  If the function
8216       // has an attribute indicating it is a printf-like function, then we
8217       // should suppress warnings concerning non-literals being used in a call
8218       // to a vprintf function.  For example:
8219       //
8220       // void
8221       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
8222       //      va_list ap;
8223       //      va_start(ap, fmt);
8224       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
8225       //      ...
8226       // }
8227       if (HasVAListArg) {
8228         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
8229           if (const Decl *D = dyn_cast<Decl>(PV->getDeclContext())) {
8230             int PVIndex = PV->getFunctionScopeIndex() + 1;
8231             for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) {
8232               // adjust for implicit parameter
8233               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D))
8234                 if (MD->isInstance())
8235                   ++PVIndex;
8236               // We also check if the formats are compatible.
8237               // We can't pass a 'scanf' string to a 'printf' function.
8238               if (PVIndex == PVFormat->getFormatIdx() &&
8239                   Type == S.GetFormatStringType(PVFormat))
8240                 return SLCT_UncheckedLiteral;
8241             }
8242           }
8243         }
8244       }
8245     }
8246 
8247     return SLCT_NotALiteral;
8248   }
8249 
8250   case Stmt::CallExprClass:
8251   case Stmt::CXXMemberCallExprClass: {
8252     const CallExpr *CE = cast<CallExpr>(E);
8253     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
8254       bool IsFirst = true;
8255       StringLiteralCheckType CommonResult;
8256       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
8257         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
8258         StringLiteralCheckType Result = checkFormatStringExpr(
8259             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
8260             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
8261             IgnoreStringsWithoutSpecifiers);
8262         if (IsFirst) {
8263           CommonResult = Result;
8264           IsFirst = false;
8265         }
8266       }
8267       if (!IsFirst)
8268         return CommonResult;
8269 
8270       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
8271         unsigned BuiltinID = FD->getBuiltinID();
8272         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
8273             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
8274           const Expr *Arg = CE->getArg(0);
8275           return checkFormatStringExpr(S, Arg, Args,
8276                                        HasVAListArg, format_idx,
8277                                        firstDataArg, Type, CallType,
8278                                        InFunctionCall, CheckedVarArgs,
8279                                        UncoveredArg, Offset,
8280                                        IgnoreStringsWithoutSpecifiers);
8281         }
8282       }
8283     }
8284 
8285     return SLCT_NotALiteral;
8286   }
8287   case Stmt::ObjCMessageExprClass: {
8288     const auto *ME = cast<ObjCMessageExpr>(E);
8289     if (const auto *MD = ME->getMethodDecl()) {
8290       if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
8291         // As a special case heuristic, if we're using the method -[NSBundle
8292         // localizedStringForKey:value:table:], ignore any key strings that lack
8293         // format specifiers. The idea is that if the key doesn't have any
8294         // format specifiers then its probably just a key to map to the
8295         // localized strings. If it does have format specifiers though, then its
8296         // likely that the text of the key is the format string in the
8297         // programmer's language, and should be checked.
8298         const ObjCInterfaceDecl *IFace;
8299         if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
8300             IFace->getIdentifier()->isStr("NSBundle") &&
8301             MD->getSelector().isKeywordSelector(
8302                 {"localizedStringForKey", "value", "table"})) {
8303           IgnoreStringsWithoutSpecifiers = true;
8304         }
8305 
8306         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
8307         return checkFormatStringExpr(
8308             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
8309             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
8310             IgnoreStringsWithoutSpecifiers);
8311       }
8312     }
8313 
8314     return SLCT_NotALiteral;
8315   }
8316   case Stmt::ObjCStringLiteralClass:
8317   case Stmt::StringLiteralClass: {
8318     const StringLiteral *StrE = nullptr;
8319 
8320     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
8321       StrE = ObjCFExpr->getString();
8322     else
8323       StrE = cast<StringLiteral>(E);
8324 
8325     if (StrE) {
8326       if (Offset.isNegative() || Offset > StrE->getLength()) {
8327         // TODO: It would be better to have an explicit warning for out of
8328         // bounds literals.
8329         return SLCT_NotALiteral;
8330       }
8331       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
8332       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
8333                         firstDataArg, Type, InFunctionCall, CallType,
8334                         CheckedVarArgs, UncoveredArg,
8335                         IgnoreStringsWithoutSpecifiers);
8336       return SLCT_CheckedLiteral;
8337     }
8338 
8339     return SLCT_NotALiteral;
8340   }
8341   case Stmt::BinaryOperatorClass: {
8342     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
8343 
8344     // A string literal + an int offset is still a string literal.
8345     if (BinOp->isAdditiveOp()) {
8346       Expr::EvalResult LResult, RResult;
8347 
8348       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
8349           LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
8350       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
8351           RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
8352 
8353       if (LIsInt != RIsInt) {
8354         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
8355 
8356         if (LIsInt) {
8357           if (BinOpKind == BO_Add) {
8358             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
8359             E = BinOp->getRHS();
8360             goto tryAgain;
8361           }
8362         } else {
8363           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
8364           E = BinOp->getLHS();
8365           goto tryAgain;
8366         }
8367       }
8368     }
8369 
8370     return SLCT_NotALiteral;
8371   }
8372   case Stmt::UnaryOperatorClass: {
8373     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
8374     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
8375     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
8376       Expr::EvalResult IndexResult;
8377       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
8378                                        Expr::SE_NoSideEffects,
8379                                        S.isConstantEvaluated())) {
8380         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
8381                    /*RHS is int*/ true);
8382         E = ASE->getBase();
8383         goto tryAgain;
8384       }
8385     }
8386 
8387     return SLCT_NotALiteral;
8388   }
8389 
8390   default:
8391     return SLCT_NotALiteral;
8392   }
8393 }
8394 
8395 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
8396   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
8397       .Case("scanf", FST_Scanf)
8398       .Cases("printf", "printf0", FST_Printf)
8399       .Cases("NSString", "CFString", FST_NSString)
8400       .Case("strftime", FST_Strftime)
8401       .Case("strfmon", FST_Strfmon)
8402       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
8403       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
8404       .Case("os_trace", FST_OSLog)
8405       .Case("os_log", FST_OSLog)
8406       .Default(FST_Unknown);
8407 }
8408 
8409 /// CheckFormatArguments - Check calls to printf and scanf (and similar
8410 /// functions) for correct use of format strings.
8411 /// Returns true if a format string has been fully checked.
8412 bool Sema::CheckFormatArguments(const FormatAttr *Format,
8413                                 ArrayRef<const Expr *> Args,
8414                                 bool IsCXXMember,
8415                                 VariadicCallType CallType,
8416                                 SourceLocation Loc, SourceRange Range,
8417                                 llvm::SmallBitVector &CheckedVarArgs) {
8418   FormatStringInfo FSI;
8419   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
8420     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
8421                                 FSI.FirstDataArg, GetFormatStringType(Format),
8422                                 CallType, Loc, Range, CheckedVarArgs);
8423   return false;
8424 }
8425 
8426 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
8427                                 bool HasVAListArg, unsigned format_idx,
8428                                 unsigned firstDataArg, FormatStringType Type,
8429                                 VariadicCallType CallType,
8430                                 SourceLocation Loc, SourceRange Range,
8431                                 llvm::SmallBitVector &CheckedVarArgs) {
8432   // CHECK: printf/scanf-like function is called with no format string.
8433   if (format_idx >= Args.size()) {
8434     Diag(Loc, diag::warn_missing_format_string) << Range;
8435     return false;
8436   }
8437 
8438   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
8439 
8440   // CHECK: format string is not a string literal.
8441   //
8442   // Dynamically generated format strings are difficult to
8443   // automatically vet at compile time.  Requiring that format strings
8444   // are string literals: (1) permits the checking of format strings by
8445   // the compiler and thereby (2) can practically remove the source of
8446   // many format string exploits.
8447 
8448   // Format string can be either ObjC string (e.g. @"%d") or
8449   // C string (e.g. "%d")
8450   // ObjC string uses the same format specifiers as C string, so we can use
8451   // the same format string checking logic for both ObjC and C strings.
8452   UncoveredArgHandler UncoveredArg;
8453   StringLiteralCheckType CT =
8454       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
8455                             format_idx, firstDataArg, Type, CallType,
8456                             /*IsFunctionCall*/ true, CheckedVarArgs,
8457                             UncoveredArg,
8458                             /*no string offset*/ llvm::APSInt(64, false) = 0);
8459 
8460   // Generate a diagnostic where an uncovered argument is detected.
8461   if (UncoveredArg.hasUncoveredArg()) {
8462     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
8463     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
8464     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
8465   }
8466 
8467   if (CT != SLCT_NotALiteral)
8468     // Literal format string found, check done!
8469     return CT == SLCT_CheckedLiteral;
8470 
8471   // Strftime is particular as it always uses a single 'time' argument,
8472   // so it is safe to pass a non-literal string.
8473   if (Type == FST_Strftime)
8474     return false;
8475 
8476   // Do not emit diag when the string param is a macro expansion and the
8477   // format is either NSString or CFString. This is a hack to prevent
8478   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
8479   // which are usually used in place of NS and CF string literals.
8480   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
8481   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
8482     return false;
8483 
8484   // If there are no arguments specified, warn with -Wformat-security, otherwise
8485   // warn only with -Wformat-nonliteral.
8486   if (Args.size() == firstDataArg) {
8487     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
8488       << OrigFormatExpr->getSourceRange();
8489     switch (Type) {
8490     default:
8491       break;
8492     case FST_Kprintf:
8493     case FST_FreeBSDKPrintf:
8494     case FST_Printf:
8495       Diag(FormatLoc, diag::note_format_security_fixit)
8496         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
8497       break;
8498     case FST_NSString:
8499       Diag(FormatLoc, diag::note_format_security_fixit)
8500         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
8501       break;
8502     }
8503   } else {
8504     Diag(FormatLoc, diag::warn_format_nonliteral)
8505       << OrigFormatExpr->getSourceRange();
8506   }
8507   return false;
8508 }
8509 
8510 namespace {
8511 
8512 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
8513 protected:
8514   Sema &S;
8515   const FormatStringLiteral *FExpr;
8516   const Expr *OrigFormatExpr;
8517   const Sema::FormatStringType FSType;
8518   const unsigned FirstDataArg;
8519   const unsigned NumDataArgs;
8520   const char *Beg; // Start of format string.
8521   const bool HasVAListArg;
8522   ArrayRef<const Expr *> Args;
8523   unsigned FormatIdx;
8524   llvm::SmallBitVector CoveredArgs;
8525   bool usesPositionalArgs = false;
8526   bool atFirstArg = true;
8527   bool inFunctionCall;
8528   Sema::VariadicCallType CallType;
8529   llvm::SmallBitVector &CheckedVarArgs;
8530   UncoveredArgHandler &UncoveredArg;
8531 
8532 public:
8533   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
8534                      const Expr *origFormatExpr,
8535                      const Sema::FormatStringType type, unsigned firstDataArg,
8536                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
8537                      ArrayRef<const Expr *> Args, unsigned formatIdx,
8538                      bool inFunctionCall, Sema::VariadicCallType callType,
8539                      llvm::SmallBitVector &CheckedVarArgs,
8540                      UncoveredArgHandler &UncoveredArg)
8541       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
8542         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
8543         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
8544         inFunctionCall(inFunctionCall), CallType(callType),
8545         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
8546     CoveredArgs.resize(numDataArgs);
8547     CoveredArgs.reset();
8548   }
8549 
8550   void DoneProcessing();
8551 
8552   void HandleIncompleteSpecifier(const char *startSpecifier,
8553                                  unsigned specifierLen) override;
8554 
8555   void HandleInvalidLengthModifier(
8556                            const analyze_format_string::FormatSpecifier &FS,
8557                            const analyze_format_string::ConversionSpecifier &CS,
8558                            const char *startSpecifier, unsigned specifierLen,
8559                            unsigned DiagID);
8560 
8561   void HandleNonStandardLengthModifier(
8562                     const analyze_format_string::FormatSpecifier &FS,
8563                     const char *startSpecifier, unsigned specifierLen);
8564 
8565   void HandleNonStandardConversionSpecifier(
8566                     const analyze_format_string::ConversionSpecifier &CS,
8567                     const char *startSpecifier, unsigned specifierLen);
8568 
8569   void HandlePosition(const char *startPos, unsigned posLen) override;
8570 
8571   void HandleInvalidPosition(const char *startSpecifier,
8572                              unsigned specifierLen,
8573                              analyze_format_string::PositionContext p) override;
8574 
8575   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
8576 
8577   void HandleNullChar(const char *nullCharacter) override;
8578 
8579   template <typename Range>
8580   static void
8581   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
8582                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
8583                        bool IsStringLocation, Range StringRange,
8584                        ArrayRef<FixItHint> Fixit = None);
8585 
8586 protected:
8587   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
8588                                         const char *startSpec,
8589                                         unsigned specifierLen,
8590                                         const char *csStart, unsigned csLen);
8591 
8592   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
8593                                          const char *startSpec,
8594                                          unsigned specifierLen);
8595 
8596   SourceRange getFormatStringRange();
8597   CharSourceRange getSpecifierRange(const char *startSpecifier,
8598                                     unsigned specifierLen);
8599   SourceLocation getLocationOfByte(const char *x);
8600 
8601   const Expr *getDataArg(unsigned i) const;
8602 
8603   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
8604                     const analyze_format_string::ConversionSpecifier &CS,
8605                     const char *startSpecifier, unsigned specifierLen,
8606                     unsigned argIndex);
8607 
8608   template <typename Range>
8609   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
8610                             bool IsStringLocation, Range StringRange,
8611                             ArrayRef<FixItHint> Fixit = None);
8612 };
8613 
8614 } // namespace
8615 
8616 SourceRange CheckFormatHandler::getFormatStringRange() {
8617   return OrigFormatExpr->getSourceRange();
8618 }
8619 
8620 CharSourceRange CheckFormatHandler::
8621 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
8622   SourceLocation Start = getLocationOfByte(startSpecifier);
8623   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
8624 
8625   // Advance the end SourceLocation by one due to half-open ranges.
8626   End = End.getLocWithOffset(1);
8627 
8628   return CharSourceRange::getCharRange(Start, End);
8629 }
8630 
8631 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
8632   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
8633                                   S.getLangOpts(), S.Context.getTargetInfo());
8634 }
8635 
8636 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
8637                                                    unsigned specifierLen){
8638   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
8639                        getLocationOfByte(startSpecifier),
8640                        /*IsStringLocation*/true,
8641                        getSpecifierRange(startSpecifier, specifierLen));
8642 }
8643 
8644 void CheckFormatHandler::HandleInvalidLengthModifier(
8645     const analyze_format_string::FormatSpecifier &FS,
8646     const analyze_format_string::ConversionSpecifier &CS,
8647     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
8648   using namespace analyze_format_string;
8649 
8650   const LengthModifier &LM = FS.getLengthModifier();
8651   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8652 
8653   // See if we know how to fix this length modifier.
8654   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8655   if (FixedLM) {
8656     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8657                          getLocationOfByte(LM.getStart()),
8658                          /*IsStringLocation*/true,
8659                          getSpecifierRange(startSpecifier, specifierLen));
8660 
8661     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8662       << FixedLM->toString()
8663       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8664 
8665   } else {
8666     FixItHint Hint;
8667     if (DiagID == diag::warn_format_nonsensical_length)
8668       Hint = FixItHint::CreateRemoval(LMRange);
8669 
8670     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8671                          getLocationOfByte(LM.getStart()),
8672                          /*IsStringLocation*/true,
8673                          getSpecifierRange(startSpecifier, specifierLen),
8674                          Hint);
8675   }
8676 }
8677 
8678 void CheckFormatHandler::HandleNonStandardLengthModifier(
8679     const analyze_format_string::FormatSpecifier &FS,
8680     const char *startSpecifier, unsigned specifierLen) {
8681   using namespace analyze_format_string;
8682 
8683   const LengthModifier &LM = FS.getLengthModifier();
8684   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8685 
8686   // See if we know how to fix this length modifier.
8687   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8688   if (FixedLM) {
8689     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8690                            << LM.toString() << 0,
8691                          getLocationOfByte(LM.getStart()),
8692                          /*IsStringLocation*/true,
8693                          getSpecifierRange(startSpecifier, specifierLen));
8694 
8695     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8696       << FixedLM->toString()
8697       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8698 
8699   } else {
8700     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8701                            << LM.toString() << 0,
8702                          getLocationOfByte(LM.getStart()),
8703                          /*IsStringLocation*/true,
8704                          getSpecifierRange(startSpecifier, specifierLen));
8705   }
8706 }
8707 
8708 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
8709     const analyze_format_string::ConversionSpecifier &CS,
8710     const char *startSpecifier, unsigned specifierLen) {
8711   using namespace analyze_format_string;
8712 
8713   // See if we know how to fix this conversion specifier.
8714   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
8715   if (FixedCS) {
8716     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8717                           << CS.toString() << /*conversion specifier*/1,
8718                          getLocationOfByte(CS.getStart()),
8719                          /*IsStringLocation*/true,
8720                          getSpecifierRange(startSpecifier, specifierLen));
8721 
8722     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
8723     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
8724       << FixedCS->toString()
8725       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
8726   } else {
8727     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8728                           << CS.toString() << /*conversion specifier*/1,
8729                          getLocationOfByte(CS.getStart()),
8730                          /*IsStringLocation*/true,
8731                          getSpecifierRange(startSpecifier, specifierLen));
8732   }
8733 }
8734 
8735 void CheckFormatHandler::HandlePosition(const char *startPos,
8736                                         unsigned posLen) {
8737   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
8738                                getLocationOfByte(startPos),
8739                                /*IsStringLocation*/true,
8740                                getSpecifierRange(startPos, posLen));
8741 }
8742 
8743 void
8744 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
8745                                      analyze_format_string::PositionContext p) {
8746   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
8747                          << (unsigned) p,
8748                        getLocationOfByte(startPos), /*IsStringLocation*/true,
8749                        getSpecifierRange(startPos, posLen));
8750 }
8751 
8752 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
8753                                             unsigned posLen) {
8754   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
8755                                getLocationOfByte(startPos),
8756                                /*IsStringLocation*/true,
8757                                getSpecifierRange(startPos, posLen));
8758 }
8759 
8760 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
8761   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
8762     // The presence of a null character is likely an error.
8763     EmitFormatDiagnostic(
8764       S.PDiag(diag::warn_printf_format_string_contains_null_char),
8765       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
8766       getFormatStringRange());
8767   }
8768 }
8769 
8770 // Note that this may return NULL if there was an error parsing or building
8771 // one of the argument expressions.
8772 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
8773   return Args[FirstDataArg + i];
8774 }
8775 
8776 void CheckFormatHandler::DoneProcessing() {
8777   // Does the number of data arguments exceed the number of
8778   // format conversions in the format string?
8779   if (!HasVAListArg) {
8780       // Find any arguments that weren't covered.
8781     CoveredArgs.flip();
8782     signed notCoveredArg = CoveredArgs.find_first();
8783     if (notCoveredArg >= 0) {
8784       assert((unsigned)notCoveredArg < NumDataArgs);
8785       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
8786     } else {
8787       UncoveredArg.setAllCovered();
8788     }
8789   }
8790 }
8791 
8792 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
8793                                    const Expr *ArgExpr) {
8794   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
8795          "Invalid state");
8796 
8797   if (!ArgExpr)
8798     return;
8799 
8800   SourceLocation Loc = ArgExpr->getBeginLoc();
8801 
8802   if (S.getSourceManager().isInSystemMacro(Loc))
8803     return;
8804 
8805   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
8806   for (auto E : DiagnosticExprs)
8807     PDiag << E->getSourceRange();
8808 
8809   CheckFormatHandler::EmitFormatDiagnostic(
8810                                   S, IsFunctionCall, DiagnosticExprs[0],
8811                                   PDiag, Loc, /*IsStringLocation*/false,
8812                                   DiagnosticExprs[0]->getSourceRange());
8813 }
8814 
8815 bool
8816 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
8817                                                      SourceLocation Loc,
8818                                                      const char *startSpec,
8819                                                      unsigned specifierLen,
8820                                                      const char *csStart,
8821                                                      unsigned csLen) {
8822   bool keepGoing = true;
8823   if (argIndex < NumDataArgs) {
8824     // Consider the argument coverered, even though the specifier doesn't
8825     // make sense.
8826     CoveredArgs.set(argIndex);
8827   }
8828   else {
8829     // If argIndex exceeds the number of data arguments we
8830     // don't issue a warning because that is just a cascade of warnings (and
8831     // they may have intended '%%' anyway). We don't want to continue processing
8832     // the format string after this point, however, as we will like just get
8833     // gibberish when trying to match arguments.
8834     keepGoing = false;
8835   }
8836 
8837   StringRef Specifier(csStart, csLen);
8838 
8839   // If the specifier in non-printable, it could be the first byte of a UTF-8
8840   // sequence. In that case, print the UTF-8 code point. If not, print the byte
8841   // hex value.
8842   std::string CodePointStr;
8843   if (!llvm::sys::locale::isPrint(*csStart)) {
8844     llvm::UTF32 CodePoint;
8845     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
8846     const llvm::UTF8 *E =
8847         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
8848     llvm::ConversionResult Result =
8849         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
8850 
8851     if (Result != llvm::conversionOK) {
8852       unsigned char FirstChar = *csStart;
8853       CodePoint = (llvm::UTF32)FirstChar;
8854     }
8855 
8856     llvm::raw_string_ostream OS(CodePointStr);
8857     if (CodePoint < 256)
8858       OS << "\\x" << llvm::format("%02x", CodePoint);
8859     else if (CodePoint <= 0xFFFF)
8860       OS << "\\u" << llvm::format("%04x", CodePoint);
8861     else
8862       OS << "\\U" << llvm::format("%08x", CodePoint);
8863     OS.flush();
8864     Specifier = CodePointStr;
8865   }
8866 
8867   EmitFormatDiagnostic(
8868       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
8869       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
8870 
8871   return keepGoing;
8872 }
8873 
8874 void
8875 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
8876                                                       const char *startSpec,
8877                                                       unsigned specifierLen) {
8878   EmitFormatDiagnostic(
8879     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
8880     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
8881 }
8882 
8883 bool
8884 CheckFormatHandler::CheckNumArgs(
8885   const analyze_format_string::FormatSpecifier &FS,
8886   const analyze_format_string::ConversionSpecifier &CS,
8887   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
8888 
8889   if (argIndex >= NumDataArgs) {
8890     PartialDiagnostic PDiag = FS.usesPositionalArg()
8891       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
8892            << (argIndex+1) << NumDataArgs)
8893       : S.PDiag(diag::warn_printf_insufficient_data_args);
8894     EmitFormatDiagnostic(
8895       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
8896       getSpecifierRange(startSpecifier, specifierLen));
8897 
8898     // Since more arguments than conversion tokens are given, by extension
8899     // all arguments are covered, so mark this as so.
8900     UncoveredArg.setAllCovered();
8901     return false;
8902   }
8903   return true;
8904 }
8905 
8906 template<typename Range>
8907 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
8908                                               SourceLocation Loc,
8909                                               bool IsStringLocation,
8910                                               Range StringRange,
8911                                               ArrayRef<FixItHint> FixIt) {
8912   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
8913                        Loc, IsStringLocation, StringRange, FixIt);
8914 }
8915 
8916 /// If the format string is not within the function call, emit a note
8917 /// so that the function call and string are in diagnostic messages.
8918 ///
8919 /// \param InFunctionCall if true, the format string is within the function
8920 /// call and only one diagnostic message will be produced.  Otherwise, an
8921 /// extra note will be emitted pointing to location of the format string.
8922 ///
8923 /// \param ArgumentExpr the expression that is passed as the format string
8924 /// argument in the function call.  Used for getting locations when two
8925 /// diagnostics are emitted.
8926 ///
8927 /// \param PDiag the callee should already have provided any strings for the
8928 /// diagnostic message.  This function only adds locations and fixits
8929 /// to diagnostics.
8930 ///
8931 /// \param Loc primary location for diagnostic.  If two diagnostics are
8932 /// required, one will be at Loc and a new SourceLocation will be created for
8933 /// the other one.
8934 ///
8935 /// \param IsStringLocation if true, Loc points to the format string should be
8936 /// used for the note.  Otherwise, Loc points to the argument list and will
8937 /// be used with PDiag.
8938 ///
8939 /// \param StringRange some or all of the string to highlight.  This is
8940 /// templated so it can accept either a CharSourceRange or a SourceRange.
8941 ///
8942 /// \param FixIt optional fix it hint for the format string.
8943 template <typename Range>
8944 void CheckFormatHandler::EmitFormatDiagnostic(
8945     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
8946     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
8947     Range StringRange, ArrayRef<FixItHint> FixIt) {
8948   if (InFunctionCall) {
8949     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
8950     D << StringRange;
8951     D << FixIt;
8952   } else {
8953     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
8954       << ArgumentExpr->getSourceRange();
8955 
8956     const Sema::SemaDiagnosticBuilder &Note =
8957       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
8958              diag::note_format_string_defined);
8959 
8960     Note << StringRange;
8961     Note << FixIt;
8962   }
8963 }
8964 
8965 //===--- CHECK: Printf format string checking ------------------------------===//
8966 
8967 namespace {
8968 
8969 class CheckPrintfHandler : public CheckFormatHandler {
8970 public:
8971   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8972                      const Expr *origFormatExpr,
8973                      const Sema::FormatStringType type, unsigned firstDataArg,
8974                      unsigned numDataArgs, bool isObjC, const char *beg,
8975                      bool hasVAListArg, ArrayRef<const Expr *> Args,
8976                      unsigned formatIdx, bool inFunctionCall,
8977                      Sema::VariadicCallType CallType,
8978                      llvm::SmallBitVector &CheckedVarArgs,
8979                      UncoveredArgHandler &UncoveredArg)
8980       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8981                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
8982                            inFunctionCall, CallType, CheckedVarArgs,
8983                            UncoveredArg) {}
8984 
8985   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
8986 
8987   /// Returns true if '%@' specifiers are allowed in the format string.
8988   bool allowsObjCArg() const {
8989     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
8990            FSType == Sema::FST_OSTrace;
8991   }
8992 
8993   bool HandleInvalidPrintfConversionSpecifier(
8994                                       const analyze_printf::PrintfSpecifier &FS,
8995                                       const char *startSpecifier,
8996                                       unsigned specifierLen) override;
8997 
8998   void handleInvalidMaskType(StringRef MaskType) override;
8999 
9000   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
9001                              const char *startSpecifier, unsigned specifierLen,
9002                              const TargetInfo &Target) override;
9003   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
9004                        const char *StartSpecifier,
9005                        unsigned SpecifierLen,
9006                        const Expr *E);
9007 
9008   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
9009                     const char *startSpecifier, unsigned specifierLen);
9010   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
9011                            const analyze_printf::OptionalAmount &Amt,
9012                            unsigned type,
9013                            const char *startSpecifier, unsigned specifierLen);
9014   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
9015                   const analyze_printf::OptionalFlag &flag,
9016                   const char *startSpecifier, unsigned specifierLen);
9017   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
9018                          const analyze_printf::OptionalFlag &ignoredFlag,
9019                          const analyze_printf::OptionalFlag &flag,
9020                          const char *startSpecifier, unsigned specifierLen);
9021   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
9022                            const Expr *E);
9023 
9024   void HandleEmptyObjCModifierFlag(const char *startFlag,
9025                                    unsigned flagLen) override;
9026 
9027   void HandleInvalidObjCModifierFlag(const char *startFlag,
9028                                             unsigned flagLen) override;
9029 
9030   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
9031                                            const char *flagsEnd,
9032                                            const char *conversionPosition)
9033                                              override;
9034 };
9035 
9036 } // namespace
9037 
9038 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
9039                                       const analyze_printf::PrintfSpecifier &FS,
9040                                       const char *startSpecifier,
9041                                       unsigned specifierLen) {
9042   const analyze_printf::PrintfConversionSpecifier &CS =
9043     FS.getConversionSpecifier();
9044 
9045   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
9046                                           getLocationOfByte(CS.getStart()),
9047                                           startSpecifier, specifierLen,
9048                                           CS.getStart(), CS.getLength());
9049 }
9050 
9051 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
9052   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
9053 }
9054 
9055 bool CheckPrintfHandler::HandleAmount(
9056                                const analyze_format_string::OptionalAmount &Amt,
9057                                unsigned k, const char *startSpecifier,
9058                                unsigned specifierLen) {
9059   if (Amt.hasDataArgument()) {
9060     if (!HasVAListArg) {
9061       unsigned argIndex = Amt.getArgIndex();
9062       if (argIndex >= NumDataArgs) {
9063         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
9064                                << k,
9065                              getLocationOfByte(Amt.getStart()),
9066                              /*IsStringLocation*/true,
9067                              getSpecifierRange(startSpecifier, specifierLen));
9068         // Don't do any more checking.  We will just emit
9069         // spurious errors.
9070         return false;
9071       }
9072 
9073       // Type check the data argument.  It should be an 'int'.
9074       // Although not in conformance with C99, we also allow the argument to be
9075       // an 'unsigned int' as that is a reasonably safe case.  GCC also
9076       // doesn't emit a warning for that case.
9077       CoveredArgs.set(argIndex);
9078       const Expr *Arg = getDataArg(argIndex);
9079       if (!Arg)
9080         return false;
9081 
9082       QualType T = Arg->getType();
9083 
9084       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
9085       assert(AT.isValid());
9086 
9087       if (!AT.matchesType(S.Context, T)) {
9088         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
9089                                << k << AT.getRepresentativeTypeName(S.Context)
9090                                << T << Arg->getSourceRange(),
9091                              getLocationOfByte(Amt.getStart()),
9092                              /*IsStringLocation*/true,
9093                              getSpecifierRange(startSpecifier, specifierLen));
9094         // Don't do any more checking.  We will just emit
9095         // spurious errors.
9096         return false;
9097       }
9098     }
9099   }
9100   return true;
9101 }
9102 
9103 void CheckPrintfHandler::HandleInvalidAmount(
9104                                       const analyze_printf::PrintfSpecifier &FS,
9105                                       const analyze_printf::OptionalAmount &Amt,
9106                                       unsigned type,
9107                                       const char *startSpecifier,
9108                                       unsigned specifierLen) {
9109   const analyze_printf::PrintfConversionSpecifier &CS =
9110     FS.getConversionSpecifier();
9111 
9112   FixItHint fixit =
9113     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
9114       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
9115                                  Amt.getConstantLength()))
9116       : FixItHint();
9117 
9118   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
9119                          << type << CS.toString(),
9120                        getLocationOfByte(Amt.getStart()),
9121                        /*IsStringLocation*/true,
9122                        getSpecifierRange(startSpecifier, specifierLen),
9123                        fixit);
9124 }
9125 
9126 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
9127                                     const analyze_printf::OptionalFlag &flag,
9128                                     const char *startSpecifier,
9129                                     unsigned specifierLen) {
9130   // Warn about pointless flag with a fixit removal.
9131   const analyze_printf::PrintfConversionSpecifier &CS =
9132     FS.getConversionSpecifier();
9133   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
9134                          << flag.toString() << CS.toString(),
9135                        getLocationOfByte(flag.getPosition()),
9136                        /*IsStringLocation*/true,
9137                        getSpecifierRange(startSpecifier, specifierLen),
9138                        FixItHint::CreateRemoval(
9139                          getSpecifierRange(flag.getPosition(), 1)));
9140 }
9141 
9142 void CheckPrintfHandler::HandleIgnoredFlag(
9143                                 const analyze_printf::PrintfSpecifier &FS,
9144                                 const analyze_printf::OptionalFlag &ignoredFlag,
9145                                 const analyze_printf::OptionalFlag &flag,
9146                                 const char *startSpecifier,
9147                                 unsigned specifierLen) {
9148   // Warn about ignored flag with a fixit removal.
9149   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
9150                          << ignoredFlag.toString() << flag.toString(),
9151                        getLocationOfByte(ignoredFlag.getPosition()),
9152                        /*IsStringLocation*/true,
9153                        getSpecifierRange(startSpecifier, specifierLen),
9154                        FixItHint::CreateRemoval(
9155                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
9156 }
9157 
9158 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
9159                                                      unsigned flagLen) {
9160   // Warn about an empty flag.
9161   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
9162                        getLocationOfByte(startFlag),
9163                        /*IsStringLocation*/true,
9164                        getSpecifierRange(startFlag, flagLen));
9165 }
9166 
9167 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
9168                                                        unsigned flagLen) {
9169   // Warn about an invalid flag.
9170   auto Range = getSpecifierRange(startFlag, flagLen);
9171   StringRef flag(startFlag, flagLen);
9172   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
9173                       getLocationOfByte(startFlag),
9174                       /*IsStringLocation*/true,
9175                       Range, FixItHint::CreateRemoval(Range));
9176 }
9177 
9178 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
9179     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
9180     // Warn about using '[...]' without a '@' conversion.
9181     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
9182     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
9183     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
9184                          getLocationOfByte(conversionPosition),
9185                          /*IsStringLocation*/true,
9186                          Range, FixItHint::CreateRemoval(Range));
9187 }
9188 
9189 // Determines if the specified is a C++ class or struct containing
9190 // a member with the specified name and kind (e.g. a CXXMethodDecl named
9191 // "c_str()").
9192 template<typename MemberKind>
9193 static llvm::SmallPtrSet<MemberKind*, 1>
9194 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
9195   const RecordType *RT = Ty->getAs<RecordType>();
9196   llvm::SmallPtrSet<MemberKind*, 1> Results;
9197 
9198   if (!RT)
9199     return Results;
9200   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
9201   if (!RD || !RD->getDefinition())
9202     return Results;
9203 
9204   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
9205                  Sema::LookupMemberName);
9206   R.suppressDiagnostics();
9207 
9208   // We just need to include all members of the right kind turned up by the
9209   // filter, at this point.
9210   if (S.LookupQualifiedName(R, RT->getDecl()))
9211     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
9212       NamedDecl *decl = (*I)->getUnderlyingDecl();
9213       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
9214         Results.insert(FK);
9215     }
9216   return Results;
9217 }
9218 
9219 /// Check if we could call '.c_str()' on an object.
9220 ///
9221 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
9222 /// allow the call, or if it would be ambiguous).
9223 bool Sema::hasCStrMethod(const Expr *E) {
9224   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
9225 
9226   MethodSet Results =
9227       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
9228   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
9229        MI != ME; ++MI)
9230     if ((*MI)->getMinRequiredArguments() == 0)
9231       return true;
9232   return false;
9233 }
9234 
9235 // Check if a (w)string was passed when a (w)char* was needed, and offer a
9236 // better diagnostic if so. AT is assumed to be valid.
9237 // Returns true when a c_str() conversion method is found.
9238 bool CheckPrintfHandler::checkForCStrMembers(
9239     const analyze_printf::ArgType &AT, const Expr *E) {
9240   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
9241 
9242   MethodSet Results =
9243       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
9244 
9245   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
9246        MI != ME; ++MI) {
9247     const CXXMethodDecl *Method = *MI;
9248     if (Method->getMinRequiredArguments() == 0 &&
9249         AT.matchesType(S.Context, Method->getReturnType())) {
9250       // FIXME: Suggest parens if the expression needs them.
9251       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
9252       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
9253           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
9254       return true;
9255     }
9256   }
9257 
9258   return false;
9259 }
9260 
9261 bool CheckPrintfHandler::HandlePrintfSpecifier(
9262     const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
9263     unsigned specifierLen, const TargetInfo &Target) {
9264   using namespace analyze_format_string;
9265   using namespace analyze_printf;
9266 
9267   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
9268 
9269   if (FS.consumesDataArgument()) {
9270     if (atFirstArg) {
9271         atFirstArg = false;
9272         usesPositionalArgs = FS.usesPositionalArg();
9273     }
9274     else if (usesPositionalArgs != FS.usesPositionalArg()) {
9275       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9276                                         startSpecifier, specifierLen);
9277       return false;
9278     }
9279   }
9280 
9281   // First check if the field width, precision, and conversion specifier
9282   // have matching data arguments.
9283   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
9284                     startSpecifier, specifierLen)) {
9285     return false;
9286   }
9287 
9288   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
9289                     startSpecifier, specifierLen)) {
9290     return false;
9291   }
9292 
9293   if (!CS.consumesDataArgument()) {
9294     // FIXME: Technically specifying a precision or field width here
9295     // makes no sense.  Worth issuing a warning at some point.
9296     return true;
9297   }
9298 
9299   // Consume the argument.
9300   unsigned argIndex = FS.getArgIndex();
9301   if (argIndex < NumDataArgs) {
9302     // The check to see if the argIndex is valid will come later.
9303     // We set the bit here because we may exit early from this
9304     // function if we encounter some other error.
9305     CoveredArgs.set(argIndex);
9306   }
9307 
9308   // FreeBSD kernel extensions.
9309   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
9310       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
9311     // We need at least two arguments.
9312     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
9313       return false;
9314 
9315     // Claim the second argument.
9316     CoveredArgs.set(argIndex + 1);
9317 
9318     // Type check the first argument (int for %b, pointer for %D)
9319     const Expr *Ex = getDataArg(argIndex);
9320     const analyze_printf::ArgType &AT =
9321       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
9322         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
9323     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
9324       EmitFormatDiagnostic(
9325           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9326               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
9327               << false << Ex->getSourceRange(),
9328           Ex->getBeginLoc(), /*IsStringLocation*/ false,
9329           getSpecifierRange(startSpecifier, specifierLen));
9330 
9331     // Type check the second argument (char * for both %b and %D)
9332     Ex = getDataArg(argIndex + 1);
9333     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
9334     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
9335       EmitFormatDiagnostic(
9336           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9337               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
9338               << false << Ex->getSourceRange(),
9339           Ex->getBeginLoc(), /*IsStringLocation*/ false,
9340           getSpecifierRange(startSpecifier, specifierLen));
9341 
9342      return true;
9343   }
9344 
9345   // Check for using an Objective-C specific conversion specifier
9346   // in a non-ObjC literal.
9347   if (!allowsObjCArg() && CS.isObjCArg()) {
9348     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9349                                                   specifierLen);
9350   }
9351 
9352   // %P can only be used with os_log.
9353   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
9354     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9355                                                   specifierLen);
9356   }
9357 
9358   // %n is not allowed with os_log.
9359   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
9360     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
9361                          getLocationOfByte(CS.getStart()),
9362                          /*IsStringLocation*/ false,
9363                          getSpecifierRange(startSpecifier, specifierLen));
9364 
9365     return true;
9366   }
9367 
9368   // Only scalars are allowed for os_trace.
9369   if (FSType == Sema::FST_OSTrace &&
9370       (CS.getKind() == ConversionSpecifier::PArg ||
9371        CS.getKind() == ConversionSpecifier::sArg ||
9372        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
9373     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9374                                                   specifierLen);
9375   }
9376 
9377   // Check for use of public/private annotation outside of os_log().
9378   if (FSType != Sema::FST_OSLog) {
9379     if (FS.isPublic().isSet()) {
9380       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
9381                                << "public",
9382                            getLocationOfByte(FS.isPublic().getPosition()),
9383                            /*IsStringLocation*/ false,
9384                            getSpecifierRange(startSpecifier, specifierLen));
9385     }
9386     if (FS.isPrivate().isSet()) {
9387       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
9388                                << "private",
9389                            getLocationOfByte(FS.isPrivate().getPosition()),
9390                            /*IsStringLocation*/ false,
9391                            getSpecifierRange(startSpecifier, specifierLen));
9392     }
9393   }
9394 
9395   const llvm::Triple &Triple = Target.getTriple();
9396   if (CS.getKind() == ConversionSpecifier::nArg &&
9397       (Triple.isAndroid() || Triple.isOSFuchsia())) {
9398     EmitFormatDiagnostic(S.PDiag(diag::warn_printf_narg_not_supported),
9399                          getLocationOfByte(CS.getStart()),
9400                          /*IsStringLocation*/ false,
9401                          getSpecifierRange(startSpecifier, specifierLen));
9402   }
9403 
9404   // Check for invalid use of field width
9405   if (!FS.hasValidFieldWidth()) {
9406     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
9407         startSpecifier, specifierLen);
9408   }
9409 
9410   // Check for invalid use of precision
9411   if (!FS.hasValidPrecision()) {
9412     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
9413         startSpecifier, specifierLen);
9414   }
9415 
9416   // Precision is mandatory for %P specifier.
9417   if (CS.getKind() == ConversionSpecifier::PArg &&
9418       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
9419     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
9420                          getLocationOfByte(startSpecifier),
9421                          /*IsStringLocation*/ false,
9422                          getSpecifierRange(startSpecifier, specifierLen));
9423   }
9424 
9425   // Check each flag does not conflict with any other component.
9426   if (!FS.hasValidThousandsGroupingPrefix())
9427     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
9428   if (!FS.hasValidLeadingZeros())
9429     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
9430   if (!FS.hasValidPlusPrefix())
9431     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
9432   if (!FS.hasValidSpacePrefix())
9433     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
9434   if (!FS.hasValidAlternativeForm())
9435     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
9436   if (!FS.hasValidLeftJustified())
9437     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
9438 
9439   // Check that flags are not ignored by another flag
9440   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
9441     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
9442         startSpecifier, specifierLen);
9443   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
9444     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
9445             startSpecifier, specifierLen);
9446 
9447   // Check the length modifier is valid with the given conversion specifier.
9448   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
9449                                  S.getLangOpts()))
9450     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9451                                 diag::warn_format_nonsensical_length);
9452   else if (!FS.hasStandardLengthModifier())
9453     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9454   else if (!FS.hasStandardLengthConversionCombination())
9455     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9456                                 diag::warn_format_non_standard_conversion_spec);
9457 
9458   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
9459     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9460 
9461   // The remaining checks depend on the data arguments.
9462   if (HasVAListArg)
9463     return true;
9464 
9465   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9466     return false;
9467 
9468   const Expr *Arg = getDataArg(argIndex);
9469   if (!Arg)
9470     return true;
9471 
9472   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
9473 }
9474 
9475 static bool requiresParensToAddCast(const Expr *E) {
9476   // FIXME: We should have a general way to reason about operator
9477   // precedence and whether parens are actually needed here.
9478   // Take care of a few common cases where they aren't.
9479   const Expr *Inside = E->IgnoreImpCasts();
9480   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
9481     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
9482 
9483   switch (Inside->getStmtClass()) {
9484   case Stmt::ArraySubscriptExprClass:
9485   case Stmt::CallExprClass:
9486   case Stmt::CharacterLiteralClass:
9487   case Stmt::CXXBoolLiteralExprClass:
9488   case Stmt::DeclRefExprClass:
9489   case Stmt::FloatingLiteralClass:
9490   case Stmt::IntegerLiteralClass:
9491   case Stmt::MemberExprClass:
9492   case Stmt::ObjCArrayLiteralClass:
9493   case Stmt::ObjCBoolLiteralExprClass:
9494   case Stmt::ObjCBoxedExprClass:
9495   case Stmt::ObjCDictionaryLiteralClass:
9496   case Stmt::ObjCEncodeExprClass:
9497   case Stmt::ObjCIvarRefExprClass:
9498   case Stmt::ObjCMessageExprClass:
9499   case Stmt::ObjCPropertyRefExprClass:
9500   case Stmt::ObjCStringLiteralClass:
9501   case Stmt::ObjCSubscriptRefExprClass:
9502   case Stmt::ParenExprClass:
9503   case Stmt::StringLiteralClass:
9504   case Stmt::UnaryOperatorClass:
9505     return false;
9506   default:
9507     return true;
9508   }
9509 }
9510 
9511 static std::pair<QualType, StringRef>
9512 shouldNotPrintDirectly(const ASTContext &Context,
9513                        QualType IntendedTy,
9514                        const Expr *E) {
9515   // Use a 'while' to peel off layers of typedefs.
9516   QualType TyTy = IntendedTy;
9517   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
9518     StringRef Name = UserTy->getDecl()->getName();
9519     QualType CastTy = llvm::StringSwitch<QualType>(Name)
9520       .Case("CFIndex", Context.getNSIntegerType())
9521       .Case("NSInteger", Context.getNSIntegerType())
9522       .Case("NSUInteger", Context.getNSUIntegerType())
9523       .Case("SInt32", Context.IntTy)
9524       .Case("UInt32", Context.UnsignedIntTy)
9525       .Default(QualType());
9526 
9527     if (!CastTy.isNull())
9528       return std::make_pair(CastTy, Name);
9529 
9530     TyTy = UserTy->desugar();
9531   }
9532 
9533   // Strip parens if necessary.
9534   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
9535     return shouldNotPrintDirectly(Context,
9536                                   PE->getSubExpr()->getType(),
9537                                   PE->getSubExpr());
9538 
9539   // If this is a conditional expression, then its result type is constructed
9540   // via usual arithmetic conversions and thus there might be no necessary
9541   // typedef sugar there.  Recurse to operands to check for NSInteger &
9542   // Co. usage condition.
9543   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9544     QualType TrueTy, FalseTy;
9545     StringRef TrueName, FalseName;
9546 
9547     std::tie(TrueTy, TrueName) =
9548       shouldNotPrintDirectly(Context,
9549                              CO->getTrueExpr()->getType(),
9550                              CO->getTrueExpr());
9551     std::tie(FalseTy, FalseName) =
9552       shouldNotPrintDirectly(Context,
9553                              CO->getFalseExpr()->getType(),
9554                              CO->getFalseExpr());
9555 
9556     if (TrueTy == FalseTy)
9557       return std::make_pair(TrueTy, TrueName);
9558     else if (TrueTy.isNull())
9559       return std::make_pair(FalseTy, FalseName);
9560     else if (FalseTy.isNull())
9561       return std::make_pair(TrueTy, TrueName);
9562   }
9563 
9564   return std::make_pair(QualType(), StringRef());
9565 }
9566 
9567 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
9568 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
9569 /// type do not count.
9570 static bool
9571 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
9572   QualType From = ICE->getSubExpr()->getType();
9573   QualType To = ICE->getType();
9574   // It's an integer promotion if the destination type is the promoted
9575   // source type.
9576   if (ICE->getCastKind() == CK_IntegralCast &&
9577       From->isPromotableIntegerType() &&
9578       S.Context.getPromotedIntegerType(From) == To)
9579     return true;
9580   // Look through vector types, since we do default argument promotion for
9581   // those in OpenCL.
9582   if (const auto *VecTy = From->getAs<ExtVectorType>())
9583     From = VecTy->getElementType();
9584   if (const auto *VecTy = To->getAs<ExtVectorType>())
9585     To = VecTy->getElementType();
9586   // It's a floating promotion if the source type is a lower rank.
9587   return ICE->getCastKind() == CK_FloatingCast &&
9588          S.Context.getFloatingTypeOrder(From, To) < 0;
9589 }
9590 
9591 bool
9592 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
9593                                     const char *StartSpecifier,
9594                                     unsigned SpecifierLen,
9595                                     const Expr *E) {
9596   using namespace analyze_format_string;
9597   using namespace analyze_printf;
9598 
9599   // Now type check the data expression that matches the
9600   // format specifier.
9601   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
9602   if (!AT.isValid())
9603     return true;
9604 
9605   QualType ExprTy = E->getType();
9606   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
9607     ExprTy = TET->getUnderlyingExpr()->getType();
9608   }
9609 
9610   // Diagnose attempts to print a boolean value as a character. Unlike other
9611   // -Wformat diagnostics, this is fine from a type perspective, but it still
9612   // doesn't make sense.
9613   if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
9614       E->isKnownToHaveBooleanValue()) {
9615     const CharSourceRange &CSR =
9616         getSpecifierRange(StartSpecifier, SpecifierLen);
9617     SmallString<4> FSString;
9618     llvm::raw_svector_ostream os(FSString);
9619     FS.toString(os);
9620     EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
9621                              << FSString,
9622                          E->getExprLoc(), false, CSR);
9623     return true;
9624   }
9625 
9626   analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
9627   if (Match == analyze_printf::ArgType::Match)
9628     return true;
9629 
9630   // Look through argument promotions for our error message's reported type.
9631   // This includes the integral and floating promotions, but excludes array
9632   // and function pointer decay (seeing that an argument intended to be a
9633   // string has type 'char [6]' is probably more confusing than 'char *') and
9634   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
9635   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
9636     if (isArithmeticArgumentPromotion(S, ICE)) {
9637       E = ICE->getSubExpr();
9638       ExprTy = E->getType();
9639 
9640       // Check if we didn't match because of an implicit cast from a 'char'
9641       // or 'short' to an 'int'.  This is done because printf is a varargs
9642       // function.
9643       if (ICE->getType() == S.Context.IntTy ||
9644           ICE->getType() == S.Context.UnsignedIntTy) {
9645         // All further checking is done on the subexpression
9646         const analyze_printf::ArgType::MatchKind ImplicitMatch =
9647             AT.matchesType(S.Context, ExprTy);
9648         if (ImplicitMatch == analyze_printf::ArgType::Match)
9649           return true;
9650         if (ImplicitMatch == ArgType::NoMatchPedantic ||
9651             ImplicitMatch == ArgType::NoMatchTypeConfusion)
9652           Match = ImplicitMatch;
9653       }
9654     }
9655   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
9656     // Special case for 'a', which has type 'int' in C.
9657     // Note, however, that we do /not/ want to treat multibyte constants like
9658     // 'MooV' as characters! This form is deprecated but still exists. In
9659     // addition, don't treat expressions as of type 'char' if one byte length
9660     // modifier is provided.
9661     if (ExprTy == S.Context.IntTy &&
9662         FS.getLengthModifier().getKind() != LengthModifier::AsChar)
9663       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
9664         ExprTy = S.Context.CharTy;
9665   }
9666 
9667   // Look through enums to their underlying type.
9668   bool IsEnum = false;
9669   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
9670     ExprTy = EnumTy->getDecl()->getIntegerType();
9671     IsEnum = true;
9672   }
9673 
9674   // %C in an Objective-C context prints a unichar, not a wchar_t.
9675   // If the argument is an integer of some kind, believe the %C and suggest
9676   // a cast instead of changing the conversion specifier.
9677   QualType IntendedTy = ExprTy;
9678   if (isObjCContext() &&
9679       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
9680     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
9681         !ExprTy->isCharType()) {
9682       // 'unichar' is defined as a typedef of unsigned short, but we should
9683       // prefer using the typedef if it is visible.
9684       IntendedTy = S.Context.UnsignedShortTy;
9685 
9686       // While we are here, check if the value is an IntegerLiteral that happens
9687       // to be within the valid range.
9688       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
9689         const llvm::APInt &V = IL->getValue();
9690         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
9691           return true;
9692       }
9693 
9694       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
9695                           Sema::LookupOrdinaryName);
9696       if (S.LookupName(Result, S.getCurScope())) {
9697         NamedDecl *ND = Result.getFoundDecl();
9698         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
9699           if (TD->getUnderlyingType() == IntendedTy)
9700             IntendedTy = S.Context.getTypedefType(TD);
9701       }
9702     }
9703   }
9704 
9705   // Special-case some of Darwin's platform-independence types by suggesting
9706   // casts to primitive types that are known to be large enough.
9707   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
9708   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
9709     QualType CastTy;
9710     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
9711     if (!CastTy.isNull()) {
9712       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
9713       // (long in ASTContext). Only complain to pedants.
9714       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
9715           (AT.isSizeT() || AT.isPtrdiffT()) &&
9716           AT.matchesType(S.Context, CastTy))
9717         Match = ArgType::NoMatchPedantic;
9718       IntendedTy = CastTy;
9719       ShouldNotPrintDirectly = true;
9720     }
9721   }
9722 
9723   // We may be able to offer a FixItHint if it is a supported type.
9724   PrintfSpecifier fixedFS = FS;
9725   bool Success =
9726       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
9727 
9728   if (Success) {
9729     // Get the fix string from the fixed format specifier
9730     SmallString<16> buf;
9731     llvm::raw_svector_ostream os(buf);
9732     fixedFS.toString(os);
9733 
9734     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
9735 
9736     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
9737       unsigned Diag;
9738       switch (Match) {
9739       case ArgType::Match: llvm_unreachable("expected non-matching");
9740       case ArgType::NoMatchPedantic:
9741         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9742         break;
9743       case ArgType::NoMatchTypeConfusion:
9744         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9745         break;
9746       case ArgType::NoMatch:
9747         Diag = diag::warn_format_conversion_argument_type_mismatch;
9748         break;
9749       }
9750 
9751       // In this case, the specifier is wrong and should be changed to match
9752       // the argument.
9753       EmitFormatDiagnostic(S.PDiag(Diag)
9754                                << AT.getRepresentativeTypeName(S.Context)
9755                                << IntendedTy << IsEnum << E->getSourceRange(),
9756                            E->getBeginLoc(),
9757                            /*IsStringLocation*/ false, SpecRange,
9758                            FixItHint::CreateReplacement(SpecRange, os.str()));
9759     } else {
9760       // The canonical type for formatting this value is different from the
9761       // actual type of the expression. (This occurs, for example, with Darwin's
9762       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
9763       // should be printed as 'long' for 64-bit compatibility.)
9764       // Rather than emitting a normal format/argument mismatch, we want to
9765       // add a cast to the recommended type (and correct the format string
9766       // if necessary).
9767       SmallString<16> CastBuf;
9768       llvm::raw_svector_ostream CastFix(CastBuf);
9769       CastFix << "(";
9770       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
9771       CastFix << ")";
9772 
9773       SmallVector<FixItHint,4> Hints;
9774       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
9775         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
9776 
9777       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
9778         // If there's already a cast present, just replace it.
9779         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
9780         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
9781 
9782       } else if (!requiresParensToAddCast(E)) {
9783         // If the expression has high enough precedence,
9784         // just write the C-style cast.
9785         Hints.push_back(
9786             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9787       } else {
9788         // Otherwise, add parens around the expression as well as the cast.
9789         CastFix << "(";
9790         Hints.push_back(
9791             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9792 
9793         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
9794         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
9795       }
9796 
9797       if (ShouldNotPrintDirectly) {
9798         // The expression has a type that should not be printed directly.
9799         // We extract the name from the typedef because we don't want to show
9800         // the underlying type in the diagnostic.
9801         StringRef Name;
9802         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
9803           Name = TypedefTy->getDecl()->getName();
9804         else
9805           Name = CastTyName;
9806         unsigned Diag = Match == ArgType::NoMatchPedantic
9807                             ? diag::warn_format_argument_needs_cast_pedantic
9808                             : diag::warn_format_argument_needs_cast;
9809         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
9810                                            << E->getSourceRange(),
9811                              E->getBeginLoc(), /*IsStringLocation=*/false,
9812                              SpecRange, Hints);
9813       } else {
9814         // In this case, the expression could be printed using a different
9815         // specifier, but we've decided that the specifier is probably correct
9816         // and we should cast instead. Just use the normal warning message.
9817         EmitFormatDiagnostic(
9818             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9819                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
9820                 << E->getSourceRange(),
9821             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
9822       }
9823     }
9824   } else {
9825     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
9826                                                    SpecifierLen);
9827     // Since the warning for passing non-POD types to variadic functions
9828     // was deferred until now, we emit a warning for non-POD
9829     // arguments here.
9830     switch (S.isValidVarArgType(ExprTy)) {
9831     case Sema::VAK_Valid:
9832     case Sema::VAK_ValidInCXX11: {
9833       unsigned Diag;
9834       switch (Match) {
9835       case ArgType::Match: llvm_unreachable("expected non-matching");
9836       case ArgType::NoMatchPedantic:
9837         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9838         break;
9839       case ArgType::NoMatchTypeConfusion:
9840         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9841         break;
9842       case ArgType::NoMatch:
9843         Diag = diag::warn_format_conversion_argument_type_mismatch;
9844         break;
9845       }
9846 
9847       EmitFormatDiagnostic(
9848           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
9849                         << IsEnum << CSR << E->getSourceRange(),
9850           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9851       break;
9852     }
9853     case Sema::VAK_Undefined:
9854     case Sema::VAK_MSVCUndefined:
9855       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
9856                                << S.getLangOpts().CPlusPlus11 << ExprTy
9857                                << CallType
9858                                << AT.getRepresentativeTypeName(S.Context) << CSR
9859                                << E->getSourceRange(),
9860                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9861       checkForCStrMembers(AT, E);
9862       break;
9863 
9864     case Sema::VAK_Invalid:
9865       if (ExprTy->isObjCObjectType())
9866         EmitFormatDiagnostic(
9867             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
9868                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9869                 << AT.getRepresentativeTypeName(S.Context) << CSR
9870                 << E->getSourceRange(),
9871             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9872       else
9873         // FIXME: If this is an initializer list, suggest removing the braces
9874         // or inserting a cast to the target type.
9875         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
9876             << isa<InitListExpr>(E) << ExprTy << CallType
9877             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
9878       break;
9879     }
9880 
9881     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
9882            "format string specifier index out of range");
9883     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
9884   }
9885 
9886   return true;
9887 }
9888 
9889 //===--- CHECK: Scanf format string checking ------------------------------===//
9890 
9891 namespace {
9892 
9893 class CheckScanfHandler : public CheckFormatHandler {
9894 public:
9895   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
9896                     const Expr *origFormatExpr, Sema::FormatStringType type,
9897                     unsigned firstDataArg, unsigned numDataArgs,
9898                     const char *beg, bool hasVAListArg,
9899                     ArrayRef<const Expr *> Args, unsigned formatIdx,
9900                     bool inFunctionCall, Sema::VariadicCallType CallType,
9901                     llvm::SmallBitVector &CheckedVarArgs,
9902                     UncoveredArgHandler &UncoveredArg)
9903       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
9904                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
9905                            inFunctionCall, CallType, CheckedVarArgs,
9906                            UncoveredArg) {}
9907 
9908   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
9909                             const char *startSpecifier,
9910                             unsigned specifierLen) override;
9911 
9912   bool HandleInvalidScanfConversionSpecifier(
9913           const analyze_scanf::ScanfSpecifier &FS,
9914           const char *startSpecifier,
9915           unsigned specifierLen) override;
9916 
9917   void HandleIncompleteScanList(const char *start, const char *end) override;
9918 };
9919 
9920 } // namespace
9921 
9922 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
9923                                                  const char *end) {
9924   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
9925                        getLocationOfByte(end), /*IsStringLocation*/true,
9926                        getSpecifierRange(start, end - start));
9927 }
9928 
9929 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
9930                                         const analyze_scanf::ScanfSpecifier &FS,
9931                                         const char *startSpecifier,
9932                                         unsigned specifierLen) {
9933   const analyze_scanf::ScanfConversionSpecifier &CS =
9934     FS.getConversionSpecifier();
9935 
9936   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
9937                                           getLocationOfByte(CS.getStart()),
9938                                           startSpecifier, specifierLen,
9939                                           CS.getStart(), CS.getLength());
9940 }
9941 
9942 bool CheckScanfHandler::HandleScanfSpecifier(
9943                                        const analyze_scanf::ScanfSpecifier &FS,
9944                                        const char *startSpecifier,
9945                                        unsigned specifierLen) {
9946   using namespace analyze_scanf;
9947   using namespace analyze_format_string;
9948 
9949   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
9950 
9951   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
9952   // be used to decide if we are using positional arguments consistently.
9953   if (FS.consumesDataArgument()) {
9954     if (atFirstArg) {
9955       atFirstArg = false;
9956       usesPositionalArgs = FS.usesPositionalArg();
9957     }
9958     else if (usesPositionalArgs != FS.usesPositionalArg()) {
9959       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9960                                         startSpecifier, specifierLen);
9961       return false;
9962     }
9963   }
9964 
9965   // Check if the field with is non-zero.
9966   const OptionalAmount &Amt = FS.getFieldWidth();
9967   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
9968     if (Amt.getConstantAmount() == 0) {
9969       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
9970                                                    Amt.getConstantLength());
9971       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
9972                            getLocationOfByte(Amt.getStart()),
9973                            /*IsStringLocation*/true, R,
9974                            FixItHint::CreateRemoval(R));
9975     }
9976   }
9977 
9978   if (!FS.consumesDataArgument()) {
9979     // FIXME: Technically specifying a precision or field width here
9980     // makes no sense.  Worth issuing a warning at some point.
9981     return true;
9982   }
9983 
9984   // Consume the argument.
9985   unsigned argIndex = FS.getArgIndex();
9986   if (argIndex < NumDataArgs) {
9987       // The check to see if the argIndex is valid will come later.
9988       // We set the bit here because we may exit early from this
9989       // function if we encounter some other error.
9990     CoveredArgs.set(argIndex);
9991   }
9992 
9993   // Check the length modifier is valid with the given conversion specifier.
9994   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
9995                                  S.getLangOpts()))
9996     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9997                                 diag::warn_format_nonsensical_length);
9998   else if (!FS.hasStandardLengthModifier())
9999     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
10000   else if (!FS.hasStandardLengthConversionCombination())
10001     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
10002                                 diag::warn_format_non_standard_conversion_spec);
10003 
10004   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
10005     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
10006 
10007   // The remaining checks depend on the data arguments.
10008   if (HasVAListArg)
10009     return true;
10010 
10011   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
10012     return false;
10013 
10014   // Check that the argument type matches the format specifier.
10015   const Expr *Ex = getDataArg(argIndex);
10016   if (!Ex)
10017     return true;
10018 
10019   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
10020 
10021   if (!AT.isValid()) {
10022     return true;
10023   }
10024 
10025   analyze_format_string::ArgType::MatchKind Match =
10026       AT.matchesType(S.Context, Ex->getType());
10027   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
10028   if (Match == analyze_format_string::ArgType::Match)
10029     return true;
10030 
10031   ScanfSpecifier fixedFS = FS;
10032   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
10033                                  S.getLangOpts(), S.Context);
10034 
10035   unsigned Diag =
10036       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
10037                : diag::warn_format_conversion_argument_type_mismatch;
10038 
10039   if (Success) {
10040     // Get the fix string from the fixed format specifier.
10041     SmallString<128> buf;
10042     llvm::raw_svector_ostream os(buf);
10043     fixedFS.toString(os);
10044 
10045     EmitFormatDiagnostic(
10046         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
10047                       << Ex->getType() << false << Ex->getSourceRange(),
10048         Ex->getBeginLoc(),
10049         /*IsStringLocation*/ false,
10050         getSpecifierRange(startSpecifier, specifierLen),
10051         FixItHint::CreateReplacement(
10052             getSpecifierRange(startSpecifier, specifierLen), os.str()));
10053   } else {
10054     EmitFormatDiagnostic(S.PDiag(Diag)
10055                              << AT.getRepresentativeTypeName(S.Context)
10056                              << Ex->getType() << false << Ex->getSourceRange(),
10057                          Ex->getBeginLoc(),
10058                          /*IsStringLocation*/ false,
10059                          getSpecifierRange(startSpecifier, specifierLen));
10060   }
10061 
10062   return true;
10063 }
10064 
10065 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
10066                               const Expr *OrigFormatExpr,
10067                               ArrayRef<const Expr *> Args,
10068                               bool HasVAListArg, unsigned format_idx,
10069                               unsigned firstDataArg,
10070                               Sema::FormatStringType Type,
10071                               bool inFunctionCall,
10072                               Sema::VariadicCallType CallType,
10073                               llvm::SmallBitVector &CheckedVarArgs,
10074                               UncoveredArgHandler &UncoveredArg,
10075                               bool IgnoreStringsWithoutSpecifiers) {
10076   // CHECK: is the format string a wide literal?
10077   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
10078     CheckFormatHandler::EmitFormatDiagnostic(
10079         S, inFunctionCall, Args[format_idx],
10080         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
10081         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
10082     return;
10083   }
10084 
10085   // Str - The format string.  NOTE: this is NOT null-terminated!
10086   StringRef StrRef = FExpr->getString();
10087   const char *Str = StrRef.data();
10088   // Account for cases where the string literal is truncated in a declaration.
10089   const ConstantArrayType *T =
10090     S.Context.getAsConstantArrayType(FExpr->getType());
10091   assert(T && "String literal not of constant array type!");
10092   size_t TypeSize = T->getSize().getZExtValue();
10093   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
10094   const unsigned numDataArgs = Args.size() - firstDataArg;
10095 
10096   if (IgnoreStringsWithoutSpecifiers &&
10097       !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
10098           Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
10099     return;
10100 
10101   // Emit a warning if the string literal is truncated and does not contain an
10102   // embedded null character.
10103   if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) {
10104     CheckFormatHandler::EmitFormatDiagnostic(
10105         S, inFunctionCall, Args[format_idx],
10106         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
10107         FExpr->getBeginLoc(),
10108         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
10109     return;
10110   }
10111 
10112   // CHECK: empty format string?
10113   if (StrLen == 0 && numDataArgs > 0) {
10114     CheckFormatHandler::EmitFormatDiagnostic(
10115         S, inFunctionCall, Args[format_idx],
10116         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
10117         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
10118     return;
10119   }
10120 
10121   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
10122       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
10123       Type == Sema::FST_OSTrace) {
10124     CheckPrintfHandler H(
10125         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
10126         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
10127         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
10128         CheckedVarArgs, UncoveredArg);
10129 
10130     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
10131                                                   S.getLangOpts(),
10132                                                   S.Context.getTargetInfo(),
10133                                             Type == Sema::FST_FreeBSDKPrintf))
10134       H.DoneProcessing();
10135   } else if (Type == Sema::FST_Scanf) {
10136     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
10137                         numDataArgs, Str, HasVAListArg, Args, format_idx,
10138                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
10139 
10140     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
10141                                                  S.getLangOpts(),
10142                                                  S.Context.getTargetInfo()))
10143       H.DoneProcessing();
10144   } // TODO: handle other formats
10145 }
10146 
10147 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
10148   // Str - The format string.  NOTE: this is NOT null-terminated!
10149   StringRef StrRef = FExpr->getString();
10150   const char *Str = StrRef.data();
10151   // Account for cases where the string literal is truncated in a declaration.
10152   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
10153   assert(T && "String literal not of constant array type!");
10154   size_t TypeSize = T->getSize().getZExtValue();
10155   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
10156   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
10157                                                          getLangOpts(),
10158                                                          Context.getTargetInfo());
10159 }
10160 
10161 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
10162 
10163 // Returns the related absolute value function that is larger, of 0 if one
10164 // does not exist.
10165 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
10166   switch (AbsFunction) {
10167   default:
10168     return 0;
10169 
10170   case Builtin::BI__builtin_abs:
10171     return Builtin::BI__builtin_labs;
10172   case Builtin::BI__builtin_labs:
10173     return Builtin::BI__builtin_llabs;
10174   case Builtin::BI__builtin_llabs:
10175     return 0;
10176 
10177   case Builtin::BI__builtin_fabsf:
10178     return Builtin::BI__builtin_fabs;
10179   case Builtin::BI__builtin_fabs:
10180     return Builtin::BI__builtin_fabsl;
10181   case Builtin::BI__builtin_fabsl:
10182     return 0;
10183 
10184   case Builtin::BI__builtin_cabsf:
10185     return Builtin::BI__builtin_cabs;
10186   case Builtin::BI__builtin_cabs:
10187     return Builtin::BI__builtin_cabsl;
10188   case Builtin::BI__builtin_cabsl:
10189     return 0;
10190 
10191   case Builtin::BIabs:
10192     return Builtin::BIlabs;
10193   case Builtin::BIlabs:
10194     return Builtin::BIllabs;
10195   case Builtin::BIllabs:
10196     return 0;
10197 
10198   case Builtin::BIfabsf:
10199     return Builtin::BIfabs;
10200   case Builtin::BIfabs:
10201     return Builtin::BIfabsl;
10202   case Builtin::BIfabsl:
10203     return 0;
10204 
10205   case Builtin::BIcabsf:
10206    return Builtin::BIcabs;
10207   case Builtin::BIcabs:
10208     return Builtin::BIcabsl;
10209   case Builtin::BIcabsl:
10210     return 0;
10211   }
10212 }
10213 
10214 // Returns the argument type of the absolute value function.
10215 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
10216                                              unsigned AbsType) {
10217   if (AbsType == 0)
10218     return QualType();
10219 
10220   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
10221   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
10222   if (Error != ASTContext::GE_None)
10223     return QualType();
10224 
10225   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
10226   if (!FT)
10227     return QualType();
10228 
10229   if (FT->getNumParams() != 1)
10230     return QualType();
10231 
10232   return FT->getParamType(0);
10233 }
10234 
10235 // Returns the best absolute value function, or zero, based on type and
10236 // current absolute value function.
10237 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
10238                                    unsigned AbsFunctionKind) {
10239   unsigned BestKind = 0;
10240   uint64_t ArgSize = Context.getTypeSize(ArgType);
10241   for (unsigned Kind = AbsFunctionKind; Kind != 0;
10242        Kind = getLargerAbsoluteValueFunction(Kind)) {
10243     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
10244     if (Context.getTypeSize(ParamType) >= ArgSize) {
10245       if (BestKind == 0)
10246         BestKind = Kind;
10247       else if (Context.hasSameType(ParamType, ArgType)) {
10248         BestKind = Kind;
10249         break;
10250       }
10251     }
10252   }
10253   return BestKind;
10254 }
10255 
10256 enum AbsoluteValueKind {
10257   AVK_Integer,
10258   AVK_Floating,
10259   AVK_Complex
10260 };
10261 
10262 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
10263   if (T->isIntegralOrEnumerationType())
10264     return AVK_Integer;
10265   if (T->isRealFloatingType())
10266     return AVK_Floating;
10267   if (T->isAnyComplexType())
10268     return AVK_Complex;
10269 
10270   llvm_unreachable("Type not integer, floating, or complex");
10271 }
10272 
10273 // Changes the absolute value function to a different type.  Preserves whether
10274 // the function is a builtin.
10275 static unsigned changeAbsFunction(unsigned AbsKind,
10276                                   AbsoluteValueKind ValueKind) {
10277   switch (ValueKind) {
10278   case AVK_Integer:
10279     switch (AbsKind) {
10280     default:
10281       return 0;
10282     case Builtin::BI__builtin_fabsf:
10283     case Builtin::BI__builtin_fabs:
10284     case Builtin::BI__builtin_fabsl:
10285     case Builtin::BI__builtin_cabsf:
10286     case Builtin::BI__builtin_cabs:
10287     case Builtin::BI__builtin_cabsl:
10288       return Builtin::BI__builtin_abs;
10289     case Builtin::BIfabsf:
10290     case Builtin::BIfabs:
10291     case Builtin::BIfabsl:
10292     case Builtin::BIcabsf:
10293     case Builtin::BIcabs:
10294     case Builtin::BIcabsl:
10295       return Builtin::BIabs;
10296     }
10297   case AVK_Floating:
10298     switch (AbsKind) {
10299     default:
10300       return 0;
10301     case Builtin::BI__builtin_abs:
10302     case Builtin::BI__builtin_labs:
10303     case Builtin::BI__builtin_llabs:
10304     case Builtin::BI__builtin_cabsf:
10305     case Builtin::BI__builtin_cabs:
10306     case Builtin::BI__builtin_cabsl:
10307       return Builtin::BI__builtin_fabsf;
10308     case Builtin::BIabs:
10309     case Builtin::BIlabs:
10310     case Builtin::BIllabs:
10311     case Builtin::BIcabsf:
10312     case Builtin::BIcabs:
10313     case Builtin::BIcabsl:
10314       return Builtin::BIfabsf;
10315     }
10316   case AVK_Complex:
10317     switch (AbsKind) {
10318     default:
10319       return 0;
10320     case Builtin::BI__builtin_abs:
10321     case Builtin::BI__builtin_labs:
10322     case Builtin::BI__builtin_llabs:
10323     case Builtin::BI__builtin_fabsf:
10324     case Builtin::BI__builtin_fabs:
10325     case Builtin::BI__builtin_fabsl:
10326       return Builtin::BI__builtin_cabsf;
10327     case Builtin::BIabs:
10328     case Builtin::BIlabs:
10329     case Builtin::BIllabs:
10330     case Builtin::BIfabsf:
10331     case Builtin::BIfabs:
10332     case Builtin::BIfabsl:
10333       return Builtin::BIcabsf;
10334     }
10335   }
10336   llvm_unreachable("Unable to convert function");
10337 }
10338 
10339 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
10340   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
10341   if (!FnInfo)
10342     return 0;
10343 
10344   switch (FDecl->getBuiltinID()) {
10345   default:
10346     return 0;
10347   case Builtin::BI__builtin_abs:
10348   case Builtin::BI__builtin_fabs:
10349   case Builtin::BI__builtin_fabsf:
10350   case Builtin::BI__builtin_fabsl:
10351   case Builtin::BI__builtin_labs:
10352   case Builtin::BI__builtin_llabs:
10353   case Builtin::BI__builtin_cabs:
10354   case Builtin::BI__builtin_cabsf:
10355   case Builtin::BI__builtin_cabsl:
10356   case Builtin::BIabs:
10357   case Builtin::BIlabs:
10358   case Builtin::BIllabs:
10359   case Builtin::BIfabs:
10360   case Builtin::BIfabsf:
10361   case Builtin::BIfabsl:
10362   case Builtin::BIcabs:
10363   case Builtin::BIcabsf:
10364   case Builtin::BIcabsl:
10365     return FDecl->getBuiltinID();
10366   }
10367   llvm_unreachable("Unknown Builtin type");
10368 }
10369 
10370 // If the replacement is valid, emit a note with replacement function.
10371 // Additionally, suggest including the proper header if not already included.
10372 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
10373                             unsigned AbsKind, QualType ArgType) {
10374   bool EmitHeaderHint = true;
10375   const char *HeaderName = nullptr;
10376   const char *FunctionName = nullptr;
10377   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
10378     FunctionName = "std::abs";
10379     if (ArgType->isIntegralOrEnumerationType()) {
10380       HeaderName = "cstdlib";
10381     } else if (ArgType->isRealFloatingType()) {
10382       HeaderName = "cmath";
10383     } else {
10384       llvm_unreachable("Invalid Type");
10385     }
10386 
10387     // Lookup all std::abs
10388     if (NamespaceDecl *Std = S.getStdNamespace()) {
10389       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
10390       R.suppressDiagnostics();
10391       S.LookupQualifiedName(R, Std);
10392 
10393       for (const auto *I : R) {
10394         const FunctionDecl *FDecl = nullptr;
10395         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
10396           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
10397         } else {
10398           FDecl = dyn_cast<FunctionDecl>(I);
10399         }
10400         if (!FDecl)
10401           continue;
10402 
10403         // Found std::abs(), check that they are the right ones.
10404         if (FDecl->getNumParams() != 1)
10405           continue;
10406 
10407         // Check that the parameter type can handle the argument.
10408         QualType ParamType = FDecl->getParamDecl(0)->getType();
10409         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
10410             S.Context.getTypeSize(ArgType) <=
10411                 S.Context.getTypeSize(ParamType)) {
10412           // Found a function, don't need the header hint.
10413           EmitHeaderHint = false;
10414           break;
10415         }
10416       }
10417     }
10418   } else {
10419     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
10420     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
10421 
10422     if (HeaderName) {
10423       DeclarationName DN(&S.Context.Idents.get(FunctionName));
10424       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
10425       R.suppressDiagnostics();
10426       S.LookupName(R, S.getCurScope());
10427 
10428       if (R.isSingleResult()) {
10429         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
10430         if (FD && FD->getBuiltinID() == AbsKind) {
10431           EmitHeaderHint = false;
10432         } else {
10433           return;
10434         }
10435       } else if (!R.empty()) {
10436         return;
10437       }
10438     }
10439   }
10440 
10441   S.Diag(Loc, diag::note_replace_abs_function)
10442       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
10443 
10444   if (!HeaderName)
10445     return;
10446 
10447   if (!EmitHeaderHint)
10448     return;
10449 
10450   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
10451                                                     << FunctionName;
10452 }
10453 
10454 template <std::size_t StrLen>
10455 static bool IsStdFunction(const FunctionDecl *FDecl,
10456                           const char (&Str)[StrLen]) {
10457   if (!FDecl)
10458     return false;
10459   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
10460     return false;
10461   if (!FDecl->isInStdNamespace())
10462     return false;
10463 
10464   return true;
10465 }
10466 
10467 // Warn when using the wrong abs() function.
10468 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
10469                                       const FunctionDecl *FDecl) {
10470   if (Call->getNumArgs() != 1)
10471     return;
10472 
10473   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
10474   bool IsStdAbs = IsStdFunction(FDecl, "abs");
10475   if (AbsKind == 0 && !IsStdAbs)
10476     return;
10477 
10478   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10479   QualType ParamType = Call->getArg(0)->getType();
10480 
10481   // Unsigned types cannot be negative.  Suggest removing the absolute value
10482   // function call.
10483   if (ArgType->isUnsignedIntegerType()) {
10484     const char *FunctionName =
10485         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
10486     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
10487     Diag(Call->getExprLoc(), diag::note_remove_abs)
10488         << FunctionName
10489         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
10490     return;
10491   }
10492 
10493   // Taking the absolute value of a pointer is very suspicious, they probably
10494   // wanted to index into an array, dereference a pointer, call a function, etc.
10495   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
10496     unsigned DiagType = 0;
10497     if (ArgType->isFunctionType())
10498       DiagType = 1;
10499     else if (ArgType->isArrayType())
10500       DiagType = 2;
10501 
10502     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
10503     return;
10504   }
10505 
10506   // std::abs has overloads which prevent most of the absolute value problems
10507   // from occurring.
10508   if (IsStdAbs)
10509     return;
10510 
10511   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
10512   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
10513 
10514   // The argument and parameter are the same kind.  Check if they are the right
10515   // size.
10516   if (ArgValueKind == ParamValueKind) {
10517     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
10518       return;
10519 
10520     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
10521     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
10522         << FDecl << ArgType << ParamType;
10523 
10524     if (NewAbsKind == 0)
10525       return;
10526 
10527     emitReplacement(*this, Call->getExprLoc(),
10528                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10529     return;
10530   }
10531 
10532   // ArgValueKind != ParamValueKind
10533   // The wrong type of absolute value function was used.  Attempt to find the
10534   // proper one.
10535   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
10536   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
10537   if (NewAbsKind == 0)
10538     return;
10539 
10540   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
10541       << FDecl << ParamValueKind << ArgValueKind;
10542 
10543   emitReplacement(*this, Call->getExprLoc(),
10544                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10545 }
10546 
10547 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
10548 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
10549                                 const FunctionDecl *FDecl) {
10550   if (!Call || !FDecl) return;
10551 
10552   // Ignore template specializations and macros.
10553   if (inTemplateInstantiation()) return;
10554   if (Call->getExprLoc().isMacroID()) return;
10555 
10556   // Only care about the one template argument, two function parameter std::max
10557   if (Call->getNumArgs() != 2) return;
10558   if (!IsStdFunction(FDecl, "max")) return;
10559   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
10560   if (!ArgList) return;
10561   if (ArgList->size() != 1) return;
10562 
10563   // Check that template type argument is unsigned integer.
10564   const auto& TA = ArgList->get(0);
10565   if (TA.getKind() != TemplateArgument::Type) return;
10566   QualType ArgType = TA.getAsType();
10567   if (!ArgType->isUnsignedIntegerType()) return;
10568 
10569   // See if either argument is a literal zero.
10570   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
10571     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
10572     if (!MTE) return false;
10573     const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
10574     if (!Num) return false;
10575     if (Num->getValue() != 0) return false;
10576     return true;
10577   };
10578 
10579   const Expr *FirstArg = Call->getArg(0);
10580   const Expr *SecondArg = Call->getArg(1);
10581   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
10582   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
10583 
10584   // Only warn when exactly one argument is zero.
10585   if (IsFirstArgZero == IsSecondArgZero) return;
10586 
10587   SourceRange FirstRange = FirstArg->getSourceRange();
10588   SourceRange SecondRange = SecondArg->getSourceRange();
10589 
10590   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
10591 
10592   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
10593       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
10594 
10595   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
10596   SourceRange RemovalRange;
10597   if (IsFirstArgZero) {
10598     RemovalRange = SourceRange(FirstRange.getBegin(),
10599                                SecondRange.getBegin().getLocWithOffset(-1));
10600   } else {
10601     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
10602                                SecondRange.getEnd());
10603   }
10604 
10605   Diag(Call->getExprLoc(), diag::note_remove_max_call)
10606         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
10607         << FixItHint::CreateRemoval(RemovalRange);
10608 }
10609 
10610 //===--- CHECK: Standard memory functions ---------------------------------===//
10611 
10612 /// Takes the expression passed to the size_t parameter of functions
10613 /// such as memcmp, strncat, etc and warns if it's a comparison.
10614 ///
10615 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
10616 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
10617                                            IdentifierInfo *FnName,
10618                                            SourceLocation FnLoc,
10619                                            SourceLocation RParenLoc) {
10620   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
10621   if (!Size)
10622     return false;
10623 
10624   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
10625   if (!Size->isComparisonOp() && !Size->isLogicalOp())
10626     return false;
10627 
10628   SourceRange SizeRange = Size->getSourceRange();
10629   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
10630       << SizeRange << FnName;
10631   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
10632       << FnName
10633       << FixItHint::CreateInsertion(
10634              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
10635       << FixItHint::CreateRemoval(RParenLoc);
10636   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
10637       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
10638       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
10639                                     ")");
10640 
10641   return true;
10642 }
10643 
10644 /// Determine whether the given type is or contains a dynamic class type
10645 /// (e.g., whether it has a vtable).
10646 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
10647                                                      bool &IsContained) {
10648   // Look through array types while ignoring qualifiers.
10649   const Type *Ty = T->getBaseElementTypeUnsafe();
10650   IsContained = false;
10651 
10652   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
10653   RD = RD ? RD->getDefinition() : nullptr;
10654   if (!RD || RD->isInvalidDecl())
10655     return nullptr;
10656 
10657   if (RD->isDynamicClass())
10658     return RD;
10659 
10660   // Check all the fields.  If any bases were dynamic, the class is dynamic.
10661   // It's impossible for a class to transitively contain itself by value, so
10662   // infinite recursion is impossible.
10663   for (auto *FD : RD->fields()) {
10664     bool SubContained;
10665     if (const CXXRecordDecl *ContainedRD =
10666             getContainedDynamicClass(FD->getType(), SubContained)) {
10667       IsContained = true;
10668       return ContainedRD;
10669     }
10670   }
10671 
10672   return nullptr;
10673 }
10674 
10675 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
10676   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
10677     if (Unary->getKind() == UETT_SizeOf)
10678       return Unary;
10679   return nullptr;
10680 }
10681 
10682 /// If E is a sizeof expression, returns its argument expression,
10683 /// otherwise returns NULL.
10684 static const Expr *getSizeOfExprArg(const Expr *E) {
10685   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10686     if (!SizeOf->isArgumentType())
10687       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
10688   return nullptr;
10689 }
10690 
10691 /// If E is a sizeof expression, returns its argument type.
10692 static QualType getSizeOfArgType(const Expr *E) {
10693   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10694     return SizeOf->getTypeOfArgument();
10695   return QualType();
10696 }
10697 
10698 namespace {
10699 
10700 struct SearchNonTrivialToInitializeField
10701     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
10702   using Super =
10703       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
10704 
10705   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
10706 
10707   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
10708                      SourceLocation SL) {
10709     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10710       asDerived().visitArray(PDIK, AT, SL);
10711       return;
10712     }
10713 
10714     Super::visitWithKind(PDIK, FT, SL);
10715   }
10716 
10717   void visitARCStrong(QualType FT, SourceLocation SL) {
10718     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10719   }
10720   void visitARCWeak(QualType FT, SourceLocation SL) {
10721     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10722   }
10723   void visitStruct(QualType FT, SourceLocation SL) {
10724     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
10725       visit(FD->getType(), FD->getLocation());
10726   }
10727   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
10728                   const ArrayType *AT, SourceLocation SL) {
10729     visit(getContext().getBaseElementType(AT), SL);
10730   }
10731   void visitTrivial(QualType FT, SourceLocation SL) {}
10732 
10733   static void diag(QualType RT, const Expr *E, Sema &S) {
10734     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
10735   }
10736 
10737   ASTContext &getContext() { return S.getASTContext(); }
10738 
10739   const Expr *E;
10740   Sema &S;
10741 };
10742 
10743 struct SearchNonTrivialToCopyField
10744     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
10745   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
10746 
10747   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
10748 
10749   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
10750                      SourceLocation SL) {
10751     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10752       asDerived().visitArray(PCK, AT, SL);
10753       return;
10754     }
10755 
10756     Super::visitWithKind(PCK, FT, SL);
10757   }
10758 
10759   void visitARCStrong(QualType FT, SourceLocation SL) {
10760     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10761   }
10762   void visitARCWeak(QualType FT, SourceLocation SL) {
10763     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10764   }
10765   void visitStruct(QualType FT, SourceLocation SL) {
10766     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
10767       visit(FD->getType(), FD->getLocation());
10768   }
10769   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
10770                   SourceLocation SL) {
10771     visit(getContext().getBaseElementType(AT), SL);
10772   }
10773   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
10774                 SourceLocation SL) {}
10775   void visitTrivial(QualType FT, SourceLocation SL) {}
10776   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
10777 
10778   static void diag(QualType RT, const Expr *E, Sema &S) {
10779     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
10780   }
10781 
10782   ASTContext &getContext() { return S.getASTContext(); }
10783 
10784   const Expr *E;
10785   Sema &S;
10786 };
10787 
10788 }
10789 
10790 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
10791 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
10792   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
10793 
10794   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
10795     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
10796       return false;
10797 
10798     return doesExprLikelyComputeSize(BO->getLHS()) ||
10799            doesExprLikelyComputeSize(BO->getRHS());
10800   }
10801 
10802   return getAsSizeOfExpr(SizeofExpr) != nullptr;
10803 }
10804 
10805 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
10806 ///
10807 /// \code
10808 ///   #define MACRO 0
10809 ///   foo(MACRO);
10810 ///   foo(0);
10811 /// \endcode
10812 ///
10813 /// This should return true for the first call to foo, but not for the second
10814 /// (regardless of whether foo is a macro or function).
10815 static bool isArgumentExpandedFromMacro(SourceManager &SM,
10816                                         SourceLocation CallLoc,
10817                                         SourceLocation ArgLoc) {
10818   if (!CallLoc.isMacroID())
10819     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
10820 
10821   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
10822          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
10823 }
10824 
10825 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
10826 /// last two arguments transposed.
10827 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
10828   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
10829     return;
10830 
10831   const Expr *SizeArg =
10832     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
10833 
10834   auto isLiteralZero = [](const Expr *E) {
10835     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
10836   };
10837 
10838   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
10839   SourceLocation CallLoc = Call->getRParenLoc();
10840   SourceManager &SM = S.getSourceManager();
10841   if (isLiteralZero(SizeArg) &&
10842       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
10843 
10844     SourceLocation DiagLoc = SizeArg->getExprLoc();
10845 
10846     // Some platforms #define bzero to __builtin_memset. See if this is the
10847     // case, and if so, emit a better diagnostic.
10848     if (BId == Builtin::BIbzero ||
10849         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
10850                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
10851       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
10852       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
10853     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
10854       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
10855       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
10856     }
10857     return;
10858   }
10859 
10860   // If the second argument to a memset is a sizeof expression and the third
10861   // isn't, this is also likely an error. This should catch
10862   // 'memset(buf, sizeof(buf), 0xff)'.
10863   if (BId == Builtin::BImemset &&
10864       doesExprLikelyComputeSize(Call->getArg(1)) &&
10865       !doesExprLikelyComputeSize(Call->getArg(2))) {
10866     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
10867     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
10868     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
10869     return;
10870   }
10871 }
10872 
10873 /// Check for dangerous or invalid arguments to memset().
10874 ///
10875 /// This issues warnings on known problematic, dangerous or unspecified
10876 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
10877 /// function calls.
10878 ///
10879 /// \param Call The call expression to diagnose.
10880 void Sema::CheckMemaccessArguments(const CallExpr *Call,
10881                                    unsigned BId,
10882                                    IdentifierInfo *FnName) {
10883   assert(BId != 0);
10884 
10885   // It is possible to have a non-standard definition of memset.  Validate
10886   // we have enough arguments, and if not, abort further checking.
10887   unsigned ExpectedNumArgs =
10888       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
10889   if (Call->getNumArgs() < ExpectedNumArgs)
10890     return;
10891 
10892   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
10893                       BId == Builtin::BIstrndup ? 1 : 2);
10894   unsigned LenArg =
10895       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
10896   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
10897 
10898   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
10899                                      Call->getBeginLoc(), Call->getRParenLoc()))
10900     return;
10901 
10902   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
10903   CheckMemaccessSize(*this, BId, Call);
10904 
10905   // We have special checking when the length is a sizeof expression.
10906   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
10907   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
10908   llvm::FoldingSetNodeID SizeOfArgID;
10909 
10910   // Although widely used, 'bzero' is not a standard function. Be more strict
10911   // with the argument types before allowing diagnostics and only allow the
10912   // form bzero(ptr, sizeof(...)).
10913   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10914   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
10915     return;
10916 
10917   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
10918     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
10919     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
10920 
10921     QualType DestTy = Dest->getType();
10922     QualType PointeeTy;
10923     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
10924       PointeeTy = DestPtrTy->getPointeeType();
10925 
10926       // Never warn about void type pointers. This can be used to suppress
10927       // false positives.
10928       if (PointeeTy->isVoidType())
10929         continue;
10930 
10931       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
10932       // actually comparing the expressions for equality. Because computing the
10933       // expression IDs can be expensive, we only do this if the diagnostic is
10934       // enabled.
10935       if (SizeOfArg &&
10936           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
10937                            SizeOfArg->getExprLoc())) {
10938         // We only compute IDs for expressions if the warning is enabled, and
10939         // cache the sizeof arg's ID.
10940         if (SizeOfArgID == llvm::FoldingSetNodeID())
10941           SizeOfArg->Profile(SizeOfArgID, Context, true);
10942         llvm::FoldingSetNodeID DestID;
10943         Dest->Profile(DestID, Context, true);
10944         if (DestID == SizeOfArgID) {
10945           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
10946           //       over sizeof(src) as well.
10947           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
10948           StringRef ReadableName = FnName->getName();
10949 
10950           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
10951             if (UnaryOp->getOpcode() == UO_AddrOf)
10952               ActionIdx = 1; // If its an address-of operator, just remove it.
10953           if (!PointeeTy->isIncompleteType() &&
10954               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
10955             ActionIdx = 2; // If the pointee's size is sizeof(char),
10956                            // suggest an explicit length.
10957 
10958           // If the function is defined as a builtin macro, do not show macro
10959           // expansion.
10960           SourceLocation SL = SizeOfArg->getExprLoc();
10961           SourceRange DSR = Dest->getSourceRange();
10962           SourceRange SSR = SizeOfArg->getSourceRange();
10963           SourceManager &SM = getSourceManager();
10964 
10965           if (SM.isMacroArgExpansion(SL)) {
10966             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
10967             SL = SM.getSpellingLoc(SL);
10968             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
10969                              SM.getSpellingLoc(DSR.getEnd()));
10970             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
10971                              SM.getSpellingLoc(SSR.getEnd()));
10972           }
10973 
10974           DiagRuntimeBehavior(SL, SizeOfArg,
10975                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
10976                                 << ReadableName
10977                                 << PointeeTy
10978                                 << DestTy
10979                                 << DSR
10980                                 << SSR);
10981           DiagRuntimeBehavior(SL, SizeOfArg,
10982                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
10983                                 << ActionIdx
10984                                 << SSR);
10985 
10986           break;
10987         }
10988       }
10989 
10990       // Also check for cases where the sizeof argument is the exact same
10991       // type as the memory argument, and where it points to a user-defined
10992       // record type.
10993       if (SizeOfArgTy != QualType()) {
10994         if (PointeeTy->isRecordType() &&
10995             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
10996           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
10997                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
10998                                 << FnName << SizeOfArgTy << ArgIdx
10999                                 << PointeeTy << Dest->getSourceRange()
11000                                 << LenExpr->getSourceRange());
11001           break;
11002         }
11003       }
11004     } else if (DestTy->isArrayType()) {
11005       PointeeTy = DestTy;
11006     }
11007 
11008     if (PointeeTy == QualType())
11009       continue;
11010 
11011     // Always complain about dynamic classes.
11012     bool IsContained;
11013     if (const CXXRecordDecl *ContainedRD =
11014             getContainedDynamicClass(PointeeTy, IsContained)) {
11015 
11016       unsigned OperationType = 0;
11017       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
11018       // "overwritten" if we're warning about the destination for any call
11019       // but memcmp; otherwise a verb appropriate to the call.
11020       if (ArgIdx != 0 || IsCmp) {
11021         if (BId == Builtin::BImemcpy)
11022           OperationType = 1;
11023         else if(BId == Builtin::BImemmove)
11024           OperationType = 2;
11025         else if (IsCmp)
11026           OperationType = 3;
11027       }
11028 
11029       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11030                           PDiag(diag::warn_dyn_class_memaccess)
11031                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
11032                               << IsContained << ContainedRD << OperationType
11033                               << Call->getCallee()->getSourceRange());
11034     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
11035              BId != Builtin::BImemset)
11036       DiagRuntimeBehavior(
11037         Dest->getExprLoc(), Dest,
11038         PDiag(diag::warn_arc_object_memaccess)
11039           << ArgIdx << FnName << PointeeTy
11040           << Call->getCallee()->getSourceRange());
11041     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
11042       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
11043           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
11044         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11045                             PDiag(diag::warn_cstruct_memaccess)
11046                                 << ArgIdx << FnName << PointeeTy << 0);
11047         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
11048       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
11049                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
11050         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11051                             PDiag(diag::warn_cstruct_memaccess)
11052                                 << ArgIdx << FnName << PointeeTy << 1);
11053         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
11054       } else {
11055         continue;
11056       }
11057     } else
11058       continue;
11059 
11060     DiagRuntimeBehavior(
11061       Dest->getExprLoc(), Dest,
11062       PDiag(diag::note_bad_memaccess_silence)
11063         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
11064     break;
11065   }
11066 }
11067 
11068 // A little helper routine: ignore addition and subtraction of integer literals.
11069 // This intentionally does not ignore all integer constant expressions because
11070 // we don't want to remove sizeof().
11071 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
11072   Ex = Ex->IgnoreParenCasts();
11073 
11074   while (true) {
11075     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
11076     if (!BO || !BO->isAdditiveOp())
11077       break;
11078 
11079     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
11080     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
11081 
11082     if (isa<IntegerLiteral>(RHS))
11083       Ex = LHS;
11084     else if (isa<IntegerLiteral>(LHS))
11085       Ex = RHS;
11086     else
11087       break;
11088   }
11089 
11090   return Ex;
11091 }
11092 
11093 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
11094                                                       ASTContext &Context) {
11095   // Only handle constant-sized or VLAs, but not flexible members.
11096   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
11097     // Only issue the FIXIT for arrays of size > 1.
11098     if (CAT->getSize().getSExtValue() <= 1)
11099       return false;
11100   } else if (!Ty->isVariableArrayType()) {
11101     return false;
11102   }
11103   return true;
11104 }
11105 
11106 // Warn if the user has made the 'size' argument to strlcpy or strlcat
11107 // be the size of the source, instead of the destination.
11108 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
11109                                     IdentifierInfo *FnName) {
11110 
11111   // Don't crash if the user has the wrong number of arguments
11112   unsigned NumArgs = Call->getNumArgs();
11113   if ((NumArgs != 3) && (NumArgs != 4))
11114     return;
11115 
11116   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
11117   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
11118   const Expr *CompareWithSrc = nullptr;
11119 
11120   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
11121                                      Call->getBeginLoc(), Call->getRParenLoc()))
11122     return;
11123 
11124   // Look for 'strlcpy(dst, x, sizeof(x))'
11125   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
11126     CompareWithSrc = Ex;
11127   else {
11128     // Look for 'strlcpy(dst, x, strlen(x))'
11129     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
11130       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
11131           SizeCall->getNumArgs() == 1)
11132         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
11133     }
11134   }
11135 
11136   if (!CompareWithSrc)
11137     return;
11138 
11139   // Determine if the argument to sizeof/strlen is equal to the source
11140   // argument.  In principle there's all kinds of things you could do
11141   // here, for instance creating an == expression and evaluating it with
11142   // EvaluateAsBooleanCondition, but this uses a more direct technique:
11143   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
11144   if (!SrcArgDRE)
11145     return;
11146 
11147   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
11148   if (!CompareWithSrcDRE ||
11149       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
11150     return;
11151 
11152   const Expr *OriginalSizeArg = Call->getArg(2);
11153   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
11154       << OriginalSizeArg->getSourceRange() << FnName;
11155 
11156   // Output a FIXIT hint if the destination is an array (rather than a
11157   // pointer to an array).  This could be enhanced to handle some
11158   // pointers if we know the actual size, like if DstArg is 'array+2'
11159   // we could say 'sizeof(array)-2'.
11160   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
11161   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
11162     return;
11163 
11164   SmallString<128> sizeString;
11165   llvm::raw_svector_ostream OS(sizeString);
11166   OS << "sizeof(";
11167   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11168   OS << ")";
11169 
11170   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
11171       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
11172                                       OS.str());
11173 }
11174 
11175 /// Check if two expressions refer to the same declaration.
11176 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
11177   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
11178     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
11179       return D1->getDecl() == D2->getDecl();
11180   return false;
11181 }
11182 
11183 static const Expr *getStrlenExprArg(const Expr *E) {
11184   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
11185     const FunctionDecl *FD = CE->getDirectCallee();
11186     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
11187       return nullptr;
11188     return CE->getArg(0)->IgnoreParenCasts();
11189   }
11190   return nullptr;
11191 }
11192 
11193 // Warn on anti-patterns as the 'size' argument to strncat.
11194 // The correct size argument should look like following:
11195 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
11196 void Sema::CheckStrncatArguments(const CallExpr *CE,
11197                                  IdentifierInfo *FnName) {
11198   // Don't crash if the user has the wrong number of arguments.
11199   if (CE->getNumArgs() < 3)
11200     return;
11201   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
11202   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
11203   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
11204 
11205   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
11206                                      CE->getRParenLoc()))
11207     return;
11208 
11209   // Identify common expressions, which are wrongly used as the size argument
11210   // to strncat and may lead to buffer overflows.
11211   unsigned PatternType = 0;
11212   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
11213     // - sizeof(dst)
11214     if (referToTheSameDecl(SizeOfArg, DstArg))
11215       PatternType = 1;
11216     // - sizeof(src)
11217     else if (referToTheSameDecl(SizeOfArg, SrcArg))
11218       PatternType = 2;
11219   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
11220     if (BE->getOpcode() == BO_Sub) {
11221       const Expr *L = BE->getLHS()->IgnoreParenCasts();
11222       const Expr *R = BE->getRHS()->IgnoreParenCasts();
11223       // - sizeof(dst) - strlen(dst)
11224       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
11225           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
11226         PatternType = 1;
11227       // - sizeof(src) - (anything)
11228       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
11229         PatternType = 2;
11230     }
11231   }
11232 
11233   if (PatternType == 0)
11234     return;
11235 
11236   // Generate the diagnostic.
11237   SourceLocation SL = LenArg->getBeginLoc();
11238   SourceRange SR = LenArg->getSourceRange();
11239   SourceManager &SM = getSourceManager();
11240 
11241   // If the function is defined as a builtin macro, do not show macro expansion.
11242   if (SM.isMacroArgExpansion(SL)) {
11243     SL = SM.getSpellingLoc(SL);
11244     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
11245                      SM.getSpellingLoc(SR.getEnd()));
11246   }
11247 
11248   // Check if the destination is an array (rather than a pointer to an array).
11249   QualType DstTy = DstArg->getType();
11250   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
11251                                                                     Context);
11252   if (!isKnownSizeArray) {
11253     if (PatternType == 1)
11254       Diag(SL, diag::warn_strncat_wrong_size) << SR;
11255     else
11256       Diag(SL, diag::warn_strncat_src_size) << SR;
11257     return;
11258   }
11259 
11260   if (PatternType == 1)
11261     Diag(SL, diag::warn_strncat_large_size) << SR;
11262   else
11263     Diag(SL, diag::warn_strncat_src_size) << SR;
11264 
11265   SmallString<128> sizeString;
11266   llvm::raw_svector_ostream OS(sizeString);
11267   OS << "sizeof(";
11268   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11269   OS << ") - ";
11270   OS << "strlen(";
11271   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11272   OS << ") - 1";
11273 
11274   Diag(SL, diag::note_strncat_wrong_size)
11275     << FixItHint::CreateReplacement(SR, OS.str());
11276 }
11277 
11278 namespace {
11279 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
11280                                 const UnaryOperator *UnaryExpr, const Decl *D) {
11281   if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) {
11282     S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
11283         << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
11284     return;
11285   }
11286 }
11287 
11288 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
11289                                  const UnaryOperator *UnaryExpr) {
11290   if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
11291     const Decl *D = Lvalue->getDecl();
11292     if (isa<DeclaratorDecl>(D))
11293       if (!dyn_cast<DeclaratorDecl>(D)->getType()->isReferenceType())
11294         return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
11295   }
11296 
11297   if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
11298     return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
11299                                       Lvalue->getMemberDecl());
11300 }
11301 
11302 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
11303                             const UnaryOperator *UnaryExpr) {
11304   const auto *Lambda = dyn_cast<LambdaExpr>(
11305       UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens());
11306   if (!Lambda)
11307     return;
11308 
11309   S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
11310       << CalleeName << 2 /*object: lambda expression*/;
11311 }
11312 
11313 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
11314                                   const DeclRefExpr *Lvalue) {
11315   const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
11316   if (Var == nullptr)
11317     return;
11318 
11319   S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
11320       << CalleeName << 0 /*object: */ << Var;
11321 }
11322 
11323 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
11324                             const CastExpr *Cast) {
11325   SmallString<128> SizeString;
11326   llvm::raw_svector_ostream OS(SizeString);
11327 
11328   clang::CastKind Kind = Cast->getCastKind();
11329   if (Kind == clang::CK_BitCast &&
11330       !Cast->getSubExpr()->getType()->isFunctionPointerType())
11331     return;
11332   if (Kind == clang::CK_IntegralToPointer &&
11333       !isa<IntegerLiteral>(
11334           Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
11335     return;
11336 
11337   switch (Cast->getCastKind()) {
11338   case clang::CK_BitCast:
11339   case clang::CK_IntegralToPointer:
11340   case clang::CK_FunctionToPointerDecay:
11341     OS << '\'';
11342     Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
11343     OS << '\'';
11344     break;
11345   default:
11346     return;
11347   }
11348 
11349   S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
11350       << CalleeName << 0 /*object: */ << OS.str();
11351 }
11352 } // namespace
11353 
11354 /// Alerts the user that they are attempting to free a non-malloc'd object.
11355 void Sema::CheckFreeArguments(const CallExpr *E) {
11356   const std::string CalleeName =
11357       cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
11358 
11359   { // Prefer something that doesn't involve a cast to make things simpler.
11360     const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
11361     if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
11362       switch (UnaryExpr->getOpcode()) {
11363       case UnaryOperator::Opcode::UO_AddrOf:
11364         return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
11365       case UnaryOperator::Opcode::UO_Plus:
11366         return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
11367       default:
11368         break;
11369       }
11370 
11371     if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
11372       if (Lvalue->getType()->isArrayType())
11373         return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
11374 
11375     if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
11376       Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
11377           << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
11378       return;
11379     }
11380 
11381     if (isa<BlockExpr>(Arg)) {
11382       Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
11383           << CalleeName << 1 /*object: block*/;
11384       return;
11385     }
11386   }
11387   // Maybe the cast was important, check after the other cases.
11388   if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
11389     return CheckFreeArgumentsCast(*this, CalleeName, Cast);
11390 }
11391 
11392 void
11393 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
11394                          SourceLocation ReturnLoc,
11395                          bool isObjCMethod,
11396                          const AttrVec *Attrs,
11397                          const FunctionDecl *FD) {
11398   // Check if the return value is null but should not be.
11399   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
11400        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
11401       CheckNonNullExpr(*this, RetValExp))
11402     Diag(ReturnLoc, diag::warn_null_ret)
11403       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
11404 
11405   // C++11 [basic.stc.dynamic.allocation]p4:
11406   //   If an allocation function declared with a non-throwing
11407   //   exception-specification fails to allocate storage, it shall return
11408   //   a null pointer. Any other allocation function that fails to allocate
11409   //   storage shall indicate failure only by throwing an exception [...]
11410   if (FD) {
11411     OverloadedOperatorKind Op = FD->getOverloadedOperator();
11412     if (Op == OO_New || Op == OO_Array_New) {
11413       const FunctionProtoType *Proto
11414         = FD->getType()->castAs<FunctionProtoType>();
11415       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
11416           CheckNonNullExpr(*this, RetValExp))
11417         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
11418           << FD << getLangOpts().CPlusPlus11;
11419     }
11420   }
11421 
11422   // PPC MMA non-pointer types are not allowed as return type. Checking the type
11423   // here prevent the user from using a PPC MMA type as trailing return type.
11424   if (Context.getTargetInfo().getTriple().isPPC64())
11425     CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
11426 }
11427 
11428 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
11429 
11430 /// Check for comparisons of floating point operands using != and ==.
11431 /// Issue a warning if these are no self-comparisons, as they are not likely
11432 /// to do what the programmer intended.
11433 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
11434   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
11435   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
11436 
11437   // Special case: check for x == x (which is OK).
11438   // Do not emit warnings for such cases.
11439   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
11440     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
11441       if (DRL->getDecl() == DRR->getDecl())
11442         return;
11443 
11444   // Special case: check for comparisons against literals that can be exactly
11445   //  represented by APFloat.  In such cases, do not emit a warning.  This
11446   //  is a heuristic: often comparison against such literals are used to
11447   //  detect if a value in a variable has not changed.  This clearly can
11448   //  lead to false negatives.
11449   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
11450     if (FLL->isExact())
11451       return;
11452   } else
11453     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
11454       if (FLR->isExact())
11455         return;
11456 
11457   // Check for comparisons with builtin types.
11458   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
11459     if (CL->getBuiltinCallee())
11460       return;
11461 
11462   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
11463     if (CR->getBuiltinCallee())
11464       return;
11465 
11466   // Emit the diagnostic.
11467   Diag(Loc, diag::warn_floatingpoint_eq)
11468     << LHS->getSourceRange() << RHS->getSourceRange();
11469 }
11470 
11471 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
11472 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
11473 
11474 namespace {
11475 
11476 /// Structure recording the 'active' range of an integer-valued
11477 /// expression.
11478 struct IntRange {
11479   /// The number of bits active in the int. Note that this includes exactly one
11480   /// sign bit if !NonNegative.
11481   unsigned Width;
11482 
11483   /// True if the int is known not to have negative values. If so, all leading
11484   /// bits before Width are known zero, otherwise they are known to be the
11485   /// same as the MSB within Width.
11486   bool NonNegative;
11487 
11488   IntRange(unsigned Width, bool NonNegative)
11489       : Width(Width), NonNegative(NonNegative) {}
11490 
11491   /// Number of bits excluding the sign bit.
11492   unsigned valueBits() const {
11493     return NonNegative ? Width : Width - 1;
11494   }
11495 
11496   /// Returns the range of the bool type.
11497   static IntRange forBoolType() {
11498     return IntRange(1, true);
11499   }
11500 
11501   /// Returns the range of an opaque value of the given integral type.
11502   static IntRange forValueOfType(ASTContext &C, QualType T) {
11503     return forValueOfCanonicalType(C,
11504                           T->getCanonicalTypeInternal().getTypePtr());
11505   }
11506 
11507   /// Returns the range of an opaque value of a canonical integral type.
11508   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
11509     assert(T->isCanonicalUnqualified());
11510 
11511     if (const VectorType *VT = dyn_cast<VectorType>(T))
11512       T = VT->getElementType().getTypePtr();
11513     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11514       T = CT->getElementType().getTypePtr();
11515     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11516       T = AT->getValueType().getTypePtr();
11517 
11518     if (!C.getLangOpts().CPlusPlus) {
11519       // For enum types in C code, use the underlying datatype.
11520       if (const EnumType *ET = dyn_cast<EnumType>(T))
11521         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
11522     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
11523       // For enum types in C++, use the known bit width of the enumerators.
11524       EnumDecl *Enum = ET->getDecl();
11525       // In C++11, enums can have a fixed underlying type. Use this type to
11526       // compute the range.
11527       if (Enum->isFixed()) {
11528         return IntRange(C.getIntWidth(QualType(T, 0)),
11529                         !ET->isSignedIntegerOrEnumerationType());
11530       }
11531 
11532       unsigned NumPositive = Enum->getNumPositiveBits();
11533       unsigned NumNegative = Enum->getNumNegativeBits();
11534 
11535       if (NumNegative == 0)
11536         return IntRange(NumPositive, true/*NonNegative*/);
11537       else
11538         return IntRange(std::max(NumPositive + 1, NumNegative),
11539                         false/*NonNegative*/);
11540     }
11541 
11542     if (const auto *EIT = dyn_cast<BitIntType>(T))
11543       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11544 
11545     const BuiltinType *BT = cast<BuiltinType>(T);
11546     assert(BT->isInteger());
11547 
11548     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11549   }
11550 
11551   /// Returns the "target" range of a canonical integral type, i.e.
11552   /// the range of values expressible in the type.
11553   ///
11554   /// This matches forValueOfCanonicalType except that enums have the
11555   /// full range of their type, not the range of their enumerators.
11556   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
11557     assert(T->isCanonicalUnqualified());
11558 
11559     if (const VectorType *VT = dyn_cast<VectorType>(T))
11560       T = VT->getElementType().getTypePtr();
11561     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11562       T = CT->getElementType().getTypePtr();
11563     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11564       T = AT->getValueType().getTypePtr();
11565     if (const EnumType *ET = dyn_cast<EnumType>(T))
11566       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
11567 
11568     if (const auto *EIT = dyn_cast<BitIntType>(T))
11569       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11570 
11571     const BuiltinType *BT = cast<BuiltinType>(T);
11572     assert(BT->isInteger());
11573 
11574     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11575   }
11576 
11577   /// Returns the supremum of two ranges: i.e. their conservative merge.
11578   static IntRange join(IntRange L, IntRange R) {
11579     bool Unsigned = L.NonNegative && R.NonNegative;
11580     return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
11581                     L.NonNegative && R.NonNegative);
11582   }
11583 
11584   /// Return the range of a bitwise-AND of the two ranges.
11585   static IntRange bit_and(IntRange L, IntRange R) {
11586     unsigned Bits = std::max(L.Width, R.Width);
11587     bool NonNegative = false;
11588     if (L.NonNegative) {
11589       Bits = std::min(Bits, L.Width);
11590       NonNegative = true;
11591     }
11592     if (R.NonNegative) {
11593       Bits = std::min(Bits, R.Width);
11594       NonNegative = true;
11595     }
11596     return IntRange(Bits, NonNegative);
11597   }
11598 
11599   /// Return the range of a sum of the two ranges.
11600   static IntRange sum(IntRange L, IntRange R) {
11601     bool Unsigned = L.NonNegative && R.NonNegative;
11602     return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
11603                     Unsigned);
11604   }
11605 
11606   /// Return the range of a difference of the two ranges.
11607   static IntRange difference(IntRange L, IntRange R) {
11608     // We need a 1-bit-wider range if:
11609     //   1) LHS can be negative: least value can be reduced.
11610     //   2) RHS can be negative: greatest value can be increased.
11611     bool CanWiden = !L.NonNegative || !R.NonNegative;
11612     bool Unsigned = L.NonNegative && R.Width == 0;
11613     return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
11614                         !Unsigned,
11615                     Unsigned);
11616   }
11617 
11618   /// Return the range of a product of the two ranges.
11619   static IntRange product(IntRange L, IntRange R) {
11620     // If both LHS and RHS can be negative, we can form
11621     //   -2^L * -2^R = 2^(L + R)
11622     // which requires L + R + 1 value bits to represent.
11623     bool CanWiden = !L.NonNegative && !R.NonNegative;
11624     bool Unsigned = L.NonNegative && R.NonNegative;
11625     return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
11626                     Unsigned);
11627   }
11628 
11629   /// Return the range of a remainder operation between the two ranges.
11630   static IntRange rem(IntRange L, IntRange R) {
11631     // The result of a remainder can't be larger than the result of
11632     // either side. The sign of the result is the sign of the LHS.
11633     bool Unsigned = L.NonNegative;
11634     return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
11635                     Unsigned);
11636   }
11637 };
11638 
11639 } // namespace
11640 
11641 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
11642                               unsigned MaxWidth) {
11643   if (value.isSigned() && value.isNegative())
11644     return IntRange(value.getMinSignedBits(), false);
11645 
11646   if (value.getBitWidth() > MaxWidth)
11647     value = value.trunc(MaxWidth);
11648 
11649   // isNonNegative() just checks the sign bit without considering
11650   // signedness.
11651   return IntRange(value.getActiveBits(), true);
11652 }
11653 
11654 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
11655                               unsigned MaxWidth) {
11656   if (result.isInt())
11657     return GetValueRange(C, result.getInt(), MaxWidth);
11658 
11659   if (result.isVector()) {
11660     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
11661     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
11662       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
11663       R = IntRange::join(R, El);
11664     }
11665     return R;
11666   }
11667 
11668   if (result.isComplexInt()) {
11669     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
11670     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
11671     return IntRange::join(R, I);
11672   }
11673 
11674   // This can happen with lossless casts to intptr_t of "based" lvalues.
11675   // Assume it might use arbitrary bits.
11676   // FIXME: The only reason we need to pass the type in here is to get
11677   // the sign right on this one case.  It would be nice if APValue
11678   // preserved this.
11679   assert(result.isLValue() || result.isAddrLabelDiff());
11680   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
11681 }
11682 
11683 static QualType GetExprType(const Expr *E) {
11684   QualType Ty = E->getType();
11685   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
11686     Ty = AtomicRHS->getValueType();
11687   return Ty;
11688 }
11689 
11690 /// Pseudo-evaluate the given integer expression, estimating the
11691 /// range of values it might take.
11692 ///
11693 /// \param MaxWidth The width to which the value will be truncated.
11694 /// \param Approximate If \c true, return a likely range for the result: in
11695 ///        particular, assume that arithmetic on narrower types doesn't leave
11696 ///        those types. If \c false, return a range including all possible
11697 ///        result values.
11698 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
11699                              bool InConstantContext, bool Approximate) {
11700   E = E->IgnoreParens();
11701 
11702   // Try a full evaluation first.
11703   Expr::EvalResult result;
11704   if (E->EvaluateAsRValue(result, C, InConstantContext))
11705     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
11706 
11707   // I think we only want to look through implicit casts here; if the
11708   // user has an explicit widening cast, we should treat the value as
11709   // being of the new, wider type.
11710   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
11711     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
11712       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
11713                           Approximate);
11714 
11715     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
11716 
11717     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
11718                          CE->getCastKind() == CK_BooleanToSignedIntegral;
11719 
11720     // Assume that non-integer casts can span the full range of the type.
11721     if (!isIntegerCast)
11722       return OutputTypeRange;
11723 
11724     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
11725                                      std::min(MaxWidth, OutputTypeRange.Width),
11726                                      InConstantContext, Approximate);
11727 
11728     // Bail out if the subexpr's range is as wide as the cast type.
11729     if (SubRange.Width >= OutputTypeRange.Width)
11730       return OutputTypeRange;
11731 
11732     // Otherwise, we take the smaller width, and we're non-negative if
11733     // either the output type or the subexpr is.
11734     return IntRange(SubRange.Width,
11735                     SubRange.NonNegative || OutputTypeRange.NonNegative);
11736   }
11737 
11738   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11739     // If we can fold the condition, just take that operand.
11740     bool CondResult;
11741     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
11742       return GetExprRange(C,
11743                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
11744                           MaxWidth, InConstantContext, Approximate);
11745 
11746     // Otherwise, conservatively merge.
11747     // GetExprRange requires an integer expression, but a throw expression
11748     // results in a void type.
11749     Expr *E = CO->getTrueExpr();
11750     IntRange L = E->getType()->isVoidType()
11751                      ? IntRange{0, true}
11752                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
11753     E = CO->getFalseExpr();
11754     IntRange R = E->getType()->isVoidType()
11755                      ? IntRange{0, true}
11756                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
11757     return IntRange::join(L, R);
11758   }
11759 
11760   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11761     IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
11762 
11763     switch (BO->getOpcode()) {
11764     case BO_Cmp:
11765       llvm_unreachable("builtin <=> should have class type");
11766 
11767     // Boolean-valued operations are single-bit and positive.
11768     case BO_LAnd:
11769     case BO_LOr:
11770     case BO_LT:
11771     case BO_GT:
11772     case BO_LE:
11773     case BO_GE:
11774     case BO_EQ:
11775     case BO_NE:
11776       return IntRange::forBoolType();
11777 
11778     // The type of the assignments is the type of the LHS, so the RHS
11779     // is not necessarily the same type.
11780     case BO_MulAssign:
11781     case BO_DivAssign:
11782     case BO_RemAssign:
11783     case BO_AddAssign:
11784     case BO_SubAssign:
11785     case BO_XorAssign:
11786     case BO_OrAssign:
11787       // TODO: bitfields?
11788       return IntRange::forValueOfType(C, GetExprType(E));
11789 
11790     // Simple assignments just pass through the RHS, which will have
11791     // been coerced to the LHS type.
11792     case BO_Assign:
11793       // TODO: bitfields?
11794       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11795                           Approximate);
11796 
11797     // Operations with opaque sources are black-listed.
11798     case BO_PtrMemD:
11799     case BO_PtrMemI:
11800       return IntRange::forValueOfType(C, GetExprType(E));
11801 
11802     // Bitwise-and uses the *infinum* of the two source ranges.
11803     case BO_And:
11804     case BO_AndAssign:
11805       Combine = IntRange::bit_and;
11806       break;
11807 
11808     // Left shift gets black-listed based on a judgement call.
11809     case BO_Shl:
11810       // ...except that we want to treat '1 << (blah)' as logically
11811       // positive.  It's an important idiom.
11812       if (IntegerLiteral *I
11813             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
11814         if (I->getValue() == 1) {
11815           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
11816           return IntRange(R.Width, /*NonNegative*/ true);
11817         }
11818       }
11819       LLVM_FALLTHROUGH;
11820 
11821     case BO_ShlAssign:
11822       return IntRange::forValueOfType(C, GetExprType(E));
11823 
11824     // Right shift by a constant can narrow its left argument.
11825     case BO_Shr:
11826     case BO_ShrAssign: {
11827       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext,
11828                                 Approximate);
11829 
11830       // If the shift amount is a positive constant, drop the width by
11831       // that much.
11832       if (Optional<llvm::APSInt> shift =
11833               BO->getRHS()->getIntegerConstantExpr(C)) {
11834         if (shift->isNonNegative()) {
11835           unsigned zext = shift->getZExtValue();
11836           if (zext >= L.Width)
11837             L.Width = (L.NonNegative ? 0 : 1);
11838           else
11839             L.Width -= zext;
11840         }
11841       }
11842 
11843       return L;
11844     }
11845 
11846     // Comma acts as its right operand.
11847     case BO_Comma:
11848       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11849                           Approximate);
11850 
11851     case BO_Add:
11852       if (!Approximate)
11853         Combine = IntRange::sum;
11854       break;
11855 
11856     case BO_Sub:
11857       if (BO->getLHS()->getType()->isPointerType())
11858         return IntRange::forValueOfType(C, GetExprType(E));
11859       if (!Approximate)
11860         Combine = IntRange::difference;
11861       break;
11862 
11863     case BO_Mul:
11864       if (!Approximate)
11865         Combine = IntRange::product;
11866       break;
11867 
11868     // The width of a division result is mostly determined by the size
11869     // of the LHS.
11870     case BO_Div: {
11871       // Don't 'pre-truncate' the operands.
11872       unsigned opWidth = C.getIntWidth(GetExprType(E));
11873       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext,
11874                                 Approximate);
11875 
11876       // If the divisor is constant, use that.
11877       if (Optional<llvm::APSInt> divisor =
11878               BO->getRHS()->getIntegerConstantExpr(C)) {
11879         unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
11880         if (log2 >= L.Width)
11881           L.Width = (L.NonNegative ? 0 : 1);
11882         else
11883           L.Width = std::min(L.Width - log2, MaxWidth);
11884         return L;
11885       }
11886 
11887       // Otherwise, just use the LHS's width.
11888       // FIXME: This is wrong if the LHS could be its minimal value and the RHS
11889       // could be -1.
11890       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext,
11891                                 Approximate);
11892       return IntRange(L.Width, L.NonNegative && R.NonNegative);
11893     }
11894 
11895     case BO_Rem:
11896       Combine = IntRange::rem;
11897       break;
11898 
11899     // The default behavior is okay for these.
11900     case BO_Xor:
11901     case BO_Or:
11902       break;
11903     }
11904 
11905     // Combine the two ranges, but limit the result to the type in which we
11906     // performed the computation.
11907     QualType T = GetExprType(E);
11908     unsigned opWidth = C.getIntWidth(T);
11909     IntRange L =
11910         GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate);
11911     IntRange R =
11912         GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate);
11913     IntRange C = Combine(L, R);
11914     C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
11915     C.Width = std::min(C.Width, MaxWidth);
11916     return C;
11917   }
11918 
11919   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
11920     switch (UO->getOpcode()) {
11921     // Boolean-valued operations are white-listed.
11922     case UO_LNot:
11923       return IntRange::forBoolType();
11924 
11925     // Operations with opaque sources are black-listed.
11926     case UO_Deref:
11927     case UO_AddrOf: // should be impossible
11928       return IntRange::forValueOfType(C, GetExprType(E));
11929 
11930     default:
11931       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11932                           Approximate);
11933     }
11934   }
11935 
11936   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
11937     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
11938                         Approximate);
11939 
11940   if (const auto *BitField = E->getSourceBitField())
11941     return IntRange(BitField->getBitWidthValue(C),
11942                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
11943 
11944   return IntRange::forValueOfType(C, GetExprType(E));
11945 }
11946 
11947 static IntRange GetExprRange(ASTContext &C, const Expr *E,
11948                              bool InConstantContext, bool Approximate) {
11949   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
11950                       Approximate);
11951 }
11952 
11953 /// Checks whether the given value, which currently has the given
11954 /// source semantics, has the same value when coerced through the
11955 /// target semantics.
11956 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
11957                                  const llvm::fltSemantics &Src,
11958                                  const llvm::fltSemantics &Tgt) {
11959   llvm::APFloat truncated = value;
11960 
11961   bool ignored;
11962   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
11963   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
11964 
11965   return truncated.bitwiseIsEqual(value);
11966 }
11967 
11968 /// Checks whether the given value, which currently has the given
11969 /// source semantics, has the same value when coerced through the
11970 /// target semantics.
11971 ///
11972 /// The value might be a vector of floats (or a complex number).
11973 static bool IsSameFloatAfterCast(const APValue &value,
11974                                  const llvm::fltSemantics &Src,
11975                                  const llvm::fltSemantics &Tgt) {
11976   if (value.isFloat())
11977     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
11978 
11979   if (value.isVector()) {
11980     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
11981       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
11982         return false;
11983     return true;
11984   }
11985 
11986   assert(value.isComplexFloat());
11987   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
11988           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
11989 }
11990 
11991 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
11992                                        bool IsListInit = false);
11993 
11994 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
11995   // Suppress cases where we are comparing against an enum constant.
11996   if (const DeclRefExpr *DR =
11997       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
11998     if (isa<EnumConstantDecl>(DR->getDecl()))
11999       return true;
12000 
12001   // Suppress cases where the value is expanded from a macro, unless that macro
12002   // is how a language represents a boolean literal. This is the case in both C
12003   // and Objective-C.
12004   SourceLocation BeginLoc = E->getBeginLoc();
12005   if (BeginLoc.isMacroID()) {
12006     StringRef MacroName = Lexer::getImmediateMacroName(
12007         BeginLoc, S.getSourceManager(), S.getLangOpts());
12008     return MacroName != "YES" && MacroName != "NO" &&
12009            MacroName != "true" && MacroName != "false";
12010   }
12011 
12012   return false;
12013 }
12014 
12015 static bool isKnownToHaveUnsignedValue(Expr *E) {
12016   return E->getType()->isIntegerType() &&
12017          (!E->getType()->isSignedIntegerType() ||
12018           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
12019 }
12020 
12021 namespace {
12022 /// The promoted range of values of a type. In general this has the
12023 /// following structure:
12024 ///
12025 ///     |-----------| . . . |-----------|
12026 ///     ^           ^       ^           ^
12027 ///    Min       HoleMin  HoleMax      Max
12028 ///
12029 /// ... where there is only a hole if a signed type is promoted to unsigned
12030 /// (in which case Min and Max are the smallest and largest representable
12031 /// values).
12032 struct PromotedRange {
12033   // Min, or HoleMax if there is a hole.
12034   llvm::APSInt PromotedMin;
12035   // Max, or HoleMin if there is a hole.
12036   llvm::APSInt PromotedMax;
12037 
12038   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
12039     if (R.Width == 0)
12040       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
12041     else if (R.Width >= BitWidth && !Unsigned) {
12042       // Promotion made the type *narrower*. This happens when promoting
12043       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
12044       // Treat all values of 'signed int' as being in range for now.
12045       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
12046       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
12047     } else {
12048       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
12049                         .extOrTrunc(BitWidth);
12050       PromotedMin.setIsUnsigned(Unsigned);
12051 
12052       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
12053                         .extOrTrunc(BitWidth);
12054       PromotedMax.setIsUnsigned(Unsigned);
12055     }
12056   }
12057 
12058   // Determine whether this range is contiguous (has no hole).
12059   bool isContiguous() const { return PromotedMin <= PromotedMax; }
12060 
12061   // Where a constant value is within the range.
12062   enum ComparisonResult {
12063     LT = 0x1,
12064     LE = 0x2,
12065     GT = 0x4,
12066     GE = 0x8,
12067     EQ = 0x10,
12068     NE = 0x20,
12069     InRangeFlag = 0x40,
12070 
12071     Less = LE | LT | NE,
12072     Min = LE | InRangeFlag,
12073     InRange = InRangeFlag,
12074     Max = GE | InRangeFlag,
12075     Greater = GE | GT | NE,
12076 
12077     OnlyValue = LE | GE | EQ | InRangeFlag,
12078     InHole = NE
12079   };
12080 
12081   ComparisonResult compare(const llvm::APSInt &Value) const {
12082     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
12083            Value.isUnsigned() == PromotedMin.isUnsigned());
12084     if (!isContiguous()) {
12085       assert(Value.isUnsigned() && "discontiguous range for signed compare");
12086       if (Value.isMinValue()) return Min;
12087       if (Value.isMaxValue()) return Max;
12088       if (Value >= PromotedMin) return InRange;
12089       if (Value <= PromotedMax) return InRange;
12090       return InHole;
12091     }
12092 
12093     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
12094     case -1: return Less;
12095     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
12096     case 1:
12097       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
12098       case -1: return InRange;
12099       case 0: return Max;
12100       case 1: return Greater;
12101       }
12102     }
12103 
12104     llvm_unreachable("impossible compare result");
12105   }
12106 
12107   static llvm::Optional<StringRef>
12108   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
12109     if (Op == BO_Cmp) {
12110       ComparisonResult LTFlag = LT, GTFlag = GT;
12111       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
12112 
12113       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
12114       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
12115       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
12116       return llvm::None;
12117     }
12118 
12119     ComparisonResult TrueFlag, FalseFlag;
12120     if (Op == BO_EQ) {
12121       TrueFlag = EQ;
12122       FalseFlag = NE;
12123     } else if (Op == BO_NE) {
12124       TrueFlag = NE;
12125       FalseFlag = EQ;
12126     } else {
12127       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
12128         TrueFlag = LT;
12129         FalseFlag = GE;
12130       } else {
12131         TrueFlag = GT;
12132         FalseFlag = LE;
12133       }
12134       if (Op == BO_GE || Op == BO_LE)
12135         std::swap(TrueFlag, FalseFlag);
12136     }
12137     if (R & TrueFlag)
12138       return StringRef("true");
12139     if (R & FalseFlag)
12140       return StringRef("false");
12141     return llvm::None;
12142   }
12143 };
12144 }
12145 
12146 static bool HasEnumType(Expr *E) {
12147   // Strip off implicit integral promotions.
12148   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
12149     if (ICE->getCastKind() != CK_IntegralCast &&
12150         ICE->getCastKind() != CK_NoOp)
12151       break;
12152     E = ICE->getSubExpr();
12153   }
12154 
12155   return E->getType()->isEnumeralType();
12156 }
12157 
12158 static int classifyConstantValue(Expr *Constant) {
12159   // The values of this enumeration are used in the diagnostics
12160   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
12161   enum ConstantValueKind {
12162     Miscellaneous = 0,
12163     LiteralTrue,
12164     LiteralFalse
12165   };
12166   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
12167     return BL->getValue() ? ConstantValueKind::LiteralTrue
12168                           : ConstantValueKind::LiteralFalse;
12169   return ConstantValueKind::Miscellaneous;
12170 }
12171 
12172 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
12173                                         Expr *Constant, Expr *Other,
12174                                         const llvm::APSInt &Value,
12175                                         bool RhsConstant) {
12176   if (S.inTemplateInstantiation())
12177     return false;
12178 
12179   Expr *OriginalOther = Other;
12180 
12181   Constant = Constant->IgnoreParenImpCasts();
12182   Other = Other->IgnoreParenImpCasts();
12183 
12184   // Suppress warnings on tautological comparisons between values of the same
12185   // enumeration type. There are only two ways we could warn on this:
12186   //  - If the constant is outside the range of representable values of
12187   //    the enumeration. In such a case, we should warn about the cast
12188   //    to enumeration type, not about the comparison.
12189   //  - If the constant is the maximum / minimum in-range value. For an
12190   //    enumeratin type, such comparisons can be meaningful and useful.
12191   if (Constant->getType()->isEnumeralType() &&
12192       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
12193     return false;
12194 
12195   IntRange OtherValueRange = GetExprRange(
12196       S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false);
12197 
12198   QualType OtherT = Other->getType();
12199   if (const auto *AT = OtherT->getAs<AtomicType>())
12200     OtherT = AT->getValueType();
12201   IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
12202 
12203   // Special case for ObjC BOOL on targets where its a typedef for a signed char
12204   // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
12205   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
12206                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
12207                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
12208 
12209   // Whether we're treating Other as being a bool because of the form of
12210   // expression despite it having another type (typically 'int' in C).
12211   bool OtherIsBooleanDespiteType =
12212       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
12213   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
12214     OtherTypeRange = OtherValueRange = IntRange::forBoolType();
12215 
12216   // Check if all values in the range of possible values of this expression
12217   // lead to the same comparison outcome.
12218   PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(),
12219                                         Value.isUnsigned());
12220   auto Cmp = OtherPromotedValueRange.compare(Value);
12221   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
12222   if (!Result)
12223     return false;
12224 
12225   // Also consider the range determined by the type alone. This allows us to
12226   // classify the warning under the proper diagnostic group.
12227   bool TautologicalTypeCompare = false;
12228   {
12229     PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
12230                                          Value.isUnsigned());
12231     auto TypeCmp = OtherPromotedTypeRange.compare(Value);
12232     if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
12233                                                        RhsConstant)) {
12234       TautologicalTypeCompare = true;
12235       Cmp = TypeCmp;
12236       Result = TypeResult;
12237     }
12238   }
12239 
12240   // Don't warn if the non-constant operand actually always evaluates to the
12241   // same value.
12242   if (!TautologicalTypeCompare && OtherValueRange.Width == 0)
12243     return false;
12244 
12245   // Suppress the diagnostic for an in-range comparison if the constant comes
12246   // from a macro or enumerator. We don't want to diagnose
12247   //
12248   //   some_long_value <= INT_MAX
12249   //
12250   // when sizeof(int) == sizeof(long).
12251   bool InRange = Cmp & PromotedRange::InRangeFlag;
12252   if (InRange && IsEnumConstOrFromMacro(S, Constant))
12253     return false;
12254 
12255   // A comparison of an unsigned bit-field against 0 is really a type problem,
12256   // even though at the type level the bit-field might promote to 'signed int'.
12257   if (Other->refersToBitField() && InRange && Value == 0 &&
12258       Other->getType()->isUnsignedIntegerOrEnumerationType())
12259     TautologicalTypeCompare = true;
12260 
12261   // If this is a comparison to an enum constant, include that
12262   // constant in the diagnostic.
12263   const EnumConstantDecl *ED = nullptr;
12264   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
12265     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
12266 
12267   // Should be enough for uint128 (39 decimal digits)
12268   SmallString<64> PrettySourceValue;
12269   llvm::raw_svector_ostream OS(PrettySourceValue);
12270   if (ED) {
12271     OS << '\'' << *ED << "' (" << Value << ")";
12272   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
12273                Constant->IgnoreParenImpCasts())) {
12274     OS << (BL->getValue() ? "YES" : "NO");
12275   } else {
12276     OS << Value;
12277   }
12278 
12279   if (!TautologicalTypeCompare) {
12280     S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
12281         << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative
12282         << E->getOpcodeStr() << OS.str() << *Result
12283         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12284     return true;
12285   }
12286 
12287   if (IsObjCSignedCharBool) {
12288     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
12289                           S.PDiag(diag::warn_tautological_compare_objc_bool)
12290                               << OS.str() << *Result);
12291     return true;
12292   }
12293 
12294   // FIXME: We use a somewhat different formatting for the in-range cases and
12295   // cases involving boolean values for historical reasons. We should pick a
12296   // consistent way of presenting these diagnostics.
12297   if (!InRange || Other->isKnownToHaveBooleanValue()) {
12298 
12299     S.DiagRuntimeBehavior(
12300         E->getOperatorLoc(), E,
12301         S.PDiag(!InRange ? diag::warn_out_of_range_compare
12302                          : diag::warn_tautological_bool_compare)
12303             << OS.str() << classifyConstantValue(Constant) << OtherT
12304             << OtherIsBooleanDespiteType << *Result
12305             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
12306   } else {
12307     bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
12308     unsigned Diag =
12309         (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
12310             ? (HasEnumType(OriginalOther)
12311                    ? diag::warn_unsigned_enum_always_true_comparison
12312                    : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
12313                               : diag::warn_unsigned_always_true_comparison)
12314             : diag::warn_tautological_constant_compare;
12315 
12316     S.Diag(E->getOperatorLoc(), Diag)
12317         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
12318         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12319   }
12320 
12321   return true;
12322 }
12323 
12324 /// Analyze the operands of the given comparison.  Implements the
12325 /// fallback case from AnalyzeComparison.
12326 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
12327   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12328   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12329 }
12330 
12331 /// Implements -Wsign-compare.
12332 ///
12333 /// \param E the binary operator to check for warnings
12334 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
12335   // The type the comparison is being performed in.
12336   QualType T = E->getLHS()->getType();
12337 
12338   // Only analyze comparison operators where both sides have been converted to
12339   // the same type.
12340   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
12341     return AnalyzeImpConvsInComparison(S, E);
12342 
12343   // Don't analyze value-dependent comparisons directly.
12344   if (E->isValueDependent())
12345     return AnalyzeImpConvsInComparison(S, E);
12346 
12347   Expr *LHS = E->getLHS();
12348   Expr *RHS = E->getRHS();
12349 
12350   if (T->isIntegralType(S.Context)) {
12351     Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context);
12352     Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context);
12353 
12354     // We don't care about expressions whose result is a constant.
12355     if (RHSValue && LHSValue)
12356       return AnalyzeImpConvsInComparison(S, E);
12357 
12358     // We only care about expressions where just one side is literal
12359     if ((bool)RHSValue ^ (bool)LHSValue) {
12360       // Is the constant on the RHS or LHS?
12361       const bool RhsConstant = (bool)RHSValue;
12362       Expr *Const = RhsConstant ? RHS : LHS;
12363       Expr *Other = RhsConstant ? LHS : RHS;
12364       const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
12365 
12366       // Check whether an integer constant comparison results in a value
12367       // of 'true' or 'false'.
12368       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
12369         return AnalyzeImpConvsInComparison(S, E);
12370     }
12371   }
12372 
12373   if (!T->hasUnsignedIntegerRepresentation()) {
12374     // We don't do anything special if this isn't an unsigned integral
12375     // comparison:  we're only interested in integral comparisons, and
12376     // signed comparisons only happen in cases we don't care to warn about.
12377     return AnalyzeImpConvsInComparison(S, E);
12378   }
12379 
12380   LHS = LHS->IgnoreParenImpCasts();
12381   RHS = RHS->IgnoreParenImpCasts();
12382 
12383   if (!S.getLangOpts().CPlusPlus) {
12384     // Avoid warning about comparison of integers with different signs when
12385     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
12386     // the type of `E`.
12387     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
12388       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12389     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
12390       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12391   }
12392 
12393   // Check to see if one of the (unmodified) operands is of different
12394   // signedness.
12395   Expr *signedOperand, *unsignedOperand;
12396   if (LHS->getType()->hasSignedIntegerRepresentation()) {
12397     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
12398            "unsigned comparison between two signed integer expressions?");
12399     signedOperand = LHS;
12400     unsignedOperand = RHS;
12401   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
12402     signedOperand = RHS;
12403     unsignedOperand = LHS;
12404   } else {
12405     return AnalyzeImpConvsInComparison(S, E);
12406   }
12407 
12408   // Otherwise, calculate the effective range of the signed operand.
12409   IntRange signedRange = GetExprRange(
12410       S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true);
12411 
12412   // Go ahead and analyze implicit conversions in the operands.  Note
12413   // that we skip the implicit conversions on both sides.
12414   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
12415   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
12416 
12417   // If the signed range is non-negative, -Wsign-compare won't fire.
12418   if (signedRange.NonNegative)
12419     return;
12420 
12421   // For (in)equality comparisons, if the unsigned operand is a
12422   // constant which cannot collide with a overflowed signed operand,
12423   // then reinterpreting the signed operand as unsigned will not
12424   // change the result of the comparison.
12425   if (E->isEqualityOp()) {
12426     unsigned comparisonWidth = S.Context.getIntWidth(T);
12427     IntRange unsignedRange =
12428         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(),
12429                      /*Approximate*/ true);
12430 
12431     // We should never be unable to prove that the unsigned operand is
12432     // non-negative.
12433     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
12434 
12435     if (unsignedRange.Width < comparisonWidth)
12436       return;
12437   }
12438 
12439   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
12440                         S.PDiag(diag::warn_mixed_sign_comparison)
12441                             << LHS->getType() << RHS->getType()
12442                             << LHS->getSourceRange() << RHS->getSourceRange());
12443 }
12444 
12445 /// Analyzes an attempt to assign the given value to a bitfield.
12446 ///
12447 /// Returns true if there was something fishy about the attempt.
12448 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
12449                                       SourceLocation InitLoc) {
12450   assert(Bitfield->isBitField());
12451   if (Bitfield->isInvalidDecl())
12452     return false;
12453 
12454   // White-list bool bitfields.
12455   QualType BitfieldType = Bitfield->getType();
12456   if (BitfieldType->isBooleanType())
12457      return false;
12458 
12459   if (BitfieldType->isEnumeralType()) {
12460     EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
12461     // If the underlying enum type was not explicitly specified as an unsigned
12462     // type and the enum contain only positive values, MSVC++ will cause an
12463     // inconsistency by storing this as a signed type.
12464     if (S.getLangOpts().CPlusPlus11 &&
12465         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
12466         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
12467         BitfieldEnumDecl->getNumNegativeBits() == 0) {
12468       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
12469           << BitfieldEnumDecl;
12470     }
12471   }
12472 
12473   if (Bitfield->getType()->isBooleanType())
12474     return false;
12475 
12476   // Ignore value- or type-dependent expressions.
12477   if (Bitfield->getBitWidth()->isValueDependent() ||
12478       Bitfield->getBitWidth()->isTypeDependent() ||
12479       Init->isValueDependent() ||
12480       Init->isTypeDependent())
12481     return false;
12482 
12483   Expr *OriginalInit = Init->IgnoreParenImpCasts();
12484   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
12485 
12486   Expr::EvalResult Result;
12487   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
12488                                    Expr::SE_AllowSideEffects)) {
12489     // The RHS is not constant.  If the RHS has an enum type, make sure the
12490     // bitfield is wide enough to hold all the values of the enum without
12491     // truncation.
12492     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
12493       EnumDecl *ED = EnumTy->getDecl();
12494       bool SignedBitfield = BitfieldType->isSignedIntegerType();
12495 
12496       // Enum types are implicitly signed on Windows, so check if there are any
12497       // negative enumerators to see if the enum was intended to be signed or
12498       // not.
12499       bool SignedEnum = ED->getNumNegativeBits() > 0;
12500 
12501       // Check for surprising sign changes when assigning enum values to a
12502       // bitfield of different signedness.  If the bitfield is signed and we
12503       // have exactly the right number of bits to store this unsigned enum,
12504       // suggest changing the enum to an unsigned type. This typically happens
12505       // on Windows where unfixed enums always use an underlying type of 'int'.
12506       unsigned DiagID = 0;
12507       if (SignedEnum && !SignedBitfield) {
12508         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
12509       } else if (SignedBitfield && !SignedEnum &&
12510                  ED->getNumPositiveBits() == FieldWidth) {
12511         DiagID = diag::warn_signed_bitfield_enum_conversion;
12512       }
12513 
12514       if (DiagID) {
12515         S.Diag(InitLoc, DiagID) << Bitfield << ED;
12516         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
12517         SourceRange TypeRange =
12518             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
12519         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
12520             << SignedEnum << TypeRange;
12521       }
12522 
12523       // Compute the required bitwidth. If the enum has negative values, we need
12524       // one more bit than the normal number of positive bits to represent the
12525       // sign bit.
12526       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
12527                                                   ED->getNumNegativeBits())
12528                                        : ED->getNumPositiveBits();
12529 
12530       // Check the bitwidth.
12531       if (BitsNeeded > FieldWidth) {
12532         Expr *WidthExpr = Bitfield->getBitWidth();
12533         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
12534             << Bitfield << ED;
12535         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
12536             << BitsNeeded << ED << WidthExpr->getSourceRange();
12537       }
12538     }
12539 
12540     return false;
12541   }
12542 
12543   llvm::APSInt Value = Result.Val.getInt();
12544 
12545   unsigned OriginalWidth = Value.getBitWidth();
12546 
12547   if (!Value.isSigned() || Value.isNegative())
12548     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
12549       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
12550         OriginalWidth = Value.getMinSignedBits();
12551 
12552   if (OriginalWidth <= FieldWidth)
12553     return false;
12554 
12555   // Compute the value which the bitfield will contain.
12556   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
12557   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
12558 
12559   // Check whether the stored value is equal to the original value.
12560   TruncatedValue = TruncatedValue.extend(OriginalWidth);
12561   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
12562     return false;
12563 
12564   // Special-case bitfields of width 1: booleans are naturally 0/1, and
12565   // therefore don't strictly fit into a signed bitfield of width 1.
12566   if (FieldWidth == 1 && Value == 1)
12567     return false;
12568 
12569   std::string PrettyValue = toString(Value, 10);
12570   std::string PrettyTrunc = toString(TruncatedValue, 10);
12571 
12572   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
12573     << PrettyValue << PrettyTrunc << OriginalInit->getType()
12574     << Init->getSourceRange();
12575 
12576   return true;
12577 }
12578 
12579 /// Analyze the given simple or compound assignment for warning-worthy
12580 /// operations.
12581 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
12582   // Just recurse on the LHS.
12583   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12584 
12585   // We want to recurse on the RHS as normal unless we're assigning to
12586   // a bitfield.
12587   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
12588     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
12589                                   E->getOperatorLoc())) {
12590       // Recurse, ignoring any implicit conversions on the RHS.
12591       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
12592                                         E->getOperatorLoc());
12593     }
12594   }
12595 
12596   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12597 
12598   // Diagnose implicitly sequentially-consistent atomic assignment.
12599   if (E->getLHS()->getType()->isAtomicType())
12600     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12601 }
12602 
12603 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
12604 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
12605                             SourceLocation CContext, unsigned diag,
12606                             bool pruneControlFlow = false) {
12607   if (pruneControlFlow) {
12608     S.DiagRuntimeBehavior(E->getExprLoc(), E,
12609                           S.PDiag(diag)
12610                               << SourceType << T << E->getSourceRange()
12611                               << SourceRange(CContext));
12612     return;
12613   }
12614   S.Diag(E->getExprLoc(), diag)
12615     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
12616 }
12617 
12618 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
12619 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
12620                             SourceLocation CContext,
12621                             unsigned diag, bool pruneControlFlow = false) {
12622   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
12623 }
12624 
12625 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
12626   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
12627       S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
12628 }
12629 
12630 static void adornObjCBoolConversionDiagWithTernaryFixit(
12631     Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
12632   Expr *Ignored = SourceExpr->IgnoreImplicit();
12633   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
12634     Ignored = OVE->getSourceExpr();
12635   bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
12636                      isa<BinaryOperator>(Ignored) ||
12637                      isa<CXXOperatorCallExpr>(Ignored);
12638   SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
12639   if (NeedsParens)
12640     Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
12641             << FixItHint::CreateInsertion(EndLoc, ")");
12642   Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
12643 }
12644 
12645 /// Diagnose an implicit cast from a floating point value to an integer value.
12646 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
12647                                     SourceLocation CContext) {
12648   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
12649   const bool PruneWarnings = S.inTemplateInstantiation();
12650 
12651   Expr *InnerE = E->IgnoreParenImpCasts();
12652   // We also want to warn on, e.g., "int i = -1.234"
12653   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
12654     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
12655       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
12656 
12657   const bool IsLiteral =
12658       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
12659 
12660   llvm::APFloat Value(0.0);
12661   bool IsConstant =
12662     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
12663   if (!IsConstant) {
12664     if (isObjCSignedCharBool(S, T)) {
12665       return adornObjCBoolConversionDiagWithTernaryFixit(
12666           S, E,
12667           S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
12668               << E->getType());
12669     }
12670 
12671     return DiagnoseImpCast(S, E, T, CContext,
12672                            diag::warn_impcast_float_integer, PruneWarnings);
12673   }
12674 
12675   bool isExact = false;
12676 
12677   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
12678                             T->hasUnsignedIntegerRepresentation());
12679   llvm::APFloat::opStatus Result = Value.convertToInteger(
12680       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
12681 
12682   // FIXME: Force the precision of the source value down so we don't print
12683   // digits which are usually useless (we don't really care here if we
12684   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
12685   // would automatically print the shortest representation, but it's a bit
12686   // tricky to implement.
12687   SmallString<16> PrettySourceValue;
12688   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
12689   precision = (precision * 59 + 195) / 196;
12690   Value.toString(PrettySourceValue, precision);
12691 
12692   if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
12693     return adornObjCBoolConversionDiagWithTernaryFixit(
12694         S, E,
12695         S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
12696             << PrettySourceValue);
12697   }
12698 
12699   if (Result == llvm::APFloat::opOK && isExact) {
12700     if (IsLiteral) return;
12701     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
12702                            PruneWarnings);
12703   }
12704 
12705   // Conversion of a floating-point value to a non-bool integer where the
12706   // integral part cannot be represented by the integer type is undefined.
12707   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
12708     return DiagnoseImpCast(
12709         S, E, T, CContext,
12710         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
12711                   : diag::warn_impcast_float_to_integer_out_of_range,
12712         PruneWarnings);
12713 
12714   unsigned DiagID = 0;
12715   if (IsLiteral) {
12716     // Warn on floating point literal to integer.
12717     DiagID = diag::warn_impcast_literal_float_to_integer;
12718   } else if (IntegerValue == 0) {
12719     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
12720       return DiagnoseImpCast(S, E, T, CContext,
12721                              diag::warn_impcast_float_integer, PruneWarnings);
12722     }
12723     // Warn on non-zero to zero conversion.
12724     DiagID = diag::warn_impcast_float_to_integer_zero;
12725   } else {
12726     if (IntegerValue.isUnsigned()) {
12727       if (!IntegerValue.isMaxValue()) {
12728         return DiagnoseImpCast(S, E, T, CContext,
12729                                diag::warn_impcast_float_integer, PruneWarnings);
12730       }
12731     } else {  // IntegerValue.isSigned()
12732       if (!IntegerValue.isMaxSignedValue() &&
12733           !IntegerValue.isMinSignedValue()) {
12734         return DiagnoseImpCast(S, E, T, CContext,
12735                                diag::warn_impcast_float_integer, PruneWarnings);
12736       }
12737     }
12738     // Warn on evaluatable floating point expression to integer conversion.
12739     DiagID = diag::warn_impcast_float_to_integer;
12740   }
12741 
12742   SmallString<16> PrettyTargetValue;
12743   if (IsBool)
12744     PrettyTargetValue = Value.isZero() ? "false" : "true";
12745   else
12746     IntegerValue.toString(PrettyTargetValue);
12747 
12748   if (PruneWarnings) {
12749     S.DiagRuntimeBehavior(E->getExprLoc(), E,
12750                           S.PDiag(DiagID)
12751                               << E->getType() << T.getUnqualifiedType()
12752                               << PrettySourceValue << PrettyTargetValue
12753                               << E->getSourceRange() << SourceRange(CContext));
12754   } else {
12755     S.Diag(E->getExprLoc(), DiagID)
12756         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
12757         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
12758   }
12759 }
12760 
12761 /// Analyze the given compound assignment for the possible losing of
12762 /// floating-point precision.
12763 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
12764   assert(isa<CompoundAssignOperator>(E) &&
12765          "Must be compound assignment operation");
12766   // Recurse on the LHS and RHS in here
12767   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12768   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12769 
12770   if (E->getLHS()->getType()->isAtomicType())
12771     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
12772 
12773   // Now check the outermost expression
12774   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
12775   const auto *RBT = cast<CompoundAssignOperator>(E)
12776                         ->getComputationResultType()
12777                         ->getAs<BuiltinType>();
12778 
12779   // The below checks assume source is floating point.
12780   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
12781 
12782   // If source is floating point but target is an integer.
12783   if (ResultBT->isInteger())
12784     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
12785                            E->getExprLoc(), diag::warn_impcast_float_integer);
12786 
12787   if (!ResultBT->isFloatingPoint())
12788     return;
12789 
12790   // If both source and target are floating points, warn about losing precision.
12791   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12792       QualType(ResultBT, 0), QualType(RBT, 0));
12793   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
12794     // warn about dropping FP rank.
12795     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
12796                     diag::warn_impcast_float_result_precision);
12797 }
12798 
12799 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
12800                                       IntRange Range) {
12801   if (!Range.Width) return "0";
12802 
12803   llvm::APSInt ValueInRange = Value;
12804   ValueInRange.setIsSigned(!Range.NonNegative);
12805   ValueInRange = ValueInRange.trunc(Range.Width);
12806   return toString(ValueInRange, 10);
12807 }
12808 
12809 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
12810   if (!isa<ImplicitCastExpr>(Ex))
12811     return false;
12812 
12813   Expr *InnerE = Ex->IgnoreParenImpCasts();
12814   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
12815   const Type *Source =
12816     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
12817   if (Target->isDependentType())
12818     return false;
12819 
12820   const BuiltinType *FloatCandidateBT =
12821     dyn_cast<BuiltinType>(ToBool ? Source : Target);
12822   const Type *BoolCandidateType = ToBool ? Target : Source;
12823 
12824   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
12825           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
12826 }
12827 
12828 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
12829                                              SourceLocation CC) {
12830   unsigned NumArgs = TheCall->getNumArgs();
12831   for (unsigned i = 0; i < NumArgs; ++i) {
12832     Expr *CurrA = TheCall->getArg(i);
12833     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
12834       continue;
12835 
12836     bool IsSwapped = ((i > 0) &&
12837         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
12838     IsSwapped |= ((i < (NumArgs - 1)) &&
12839         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
12840     if (IsSwapped) {
12841       // Warn on this floating-point to bool conversion.
12842       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
12843                       CurrA->getType(), CC,
12844                       diag::warn_impcast_floating_point_to_bool);
12845     }
12846   }
12847 }
12848 
12849 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
12850                                    SourceLocation CC) {
12851   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
12852                         E->getExprLoc()))
12853     return;
12854 
12855   // Don't warn on functions which have return type nullptr_t.
12856   if (isa<CallExpr>(E))
12857     return;
12858 
12859   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
12860   const Expr::NullPointerConstantKind NullKind =
12861       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
12862   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
12863     return;
12864 
12865   // Return if target type is a safe conversion.
12866   if (T->isAnyPointerType() || T->isBlockPointerType() ||
12867       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
12868     return;
12869 
12870   SourceLocation Loc = E->getSourceRange().getBegin();
12871 
12872   // Venture through the macro stacks to get to the source of macro arguments.
12873   // The new location is a better location than the complete location that was
12874   // passed in.
12875   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
12876   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
12877 
12878   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
12879   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
12880     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
12881         Loc, S.SourceMgr, S.getLangOpts());
12882     if (MacroName == "NULL")
12883       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
12884   }
12885 
12886   // Only warn if the null and context location are in the same macro expansion.
12887   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
12888     return;
12889 
12890   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
12891       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
12892       << FixItHint::CreateReplacement(Loc,
12893                                       S.getFixItZeroLiteralForType(T, Loc));
12894 }
12895 
12896 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12897                                   ObjCArrayLiteral *ArrayLiteral);
12898 
12899 static void
12900 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12901                            ObjCDictionaryLiteral *DictionaryLiteral);
12902 
12903 /// Check a single element within a collection literal against the
12904 /// target element type.
12905 static void checkObjCCollectionLiteralElement(Sema &S,
12906                                               QualType TargetElementType,
12907                                               Expr *Element,
12908                                               unsigned ElementKind) {
12909   // Skip a bitcast to 'id' or qualified 'id'.
12910   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
12911     if (ICE->getCastKind() == CK_BitCast &&
12912         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
12913       Element = ICE->getSubExpr();
12914   }
12915 
12916   QualType ElementType = Element->getType();
12917   ExprResult ElementResult(Element);
12918   if (ElementType->getAs<ObjCObjectPointerType>() &&
12919       S.CheckSingleAssignmentConstraints(TargetElementType,
12920                                          ElementResult,
12921                                          false, false)
12922         != Sema::Compatible) {
12923     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
12924         << ElementType << ElementKind << TargetElementType
12925         << Element->getSourceRange();
12926   }
12927 
12928   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
12929     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
12930   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
12931     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
12932 }
12933 
12934 /// Check an Objective-C array literal being converted to the given
12935 /// target type.
12936 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12937                                   ObjCArrayLiteral *ArrayLiteral) {
12938   if (!S.NSArrayDecl)
12939     return;
12940 
12941   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12942   if (!TargetObjCPtr)
12943     return;
12944 
12945   if (TargetObjCPtr->isUnspecialized() ||
12946       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12947         != S.NSArrayDecl->getCanonicalDecl())
12948     return;
12949 
12950   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12951   if (TypeArgs.size() != 1)
12952     return;
12953 
12954   QualType TargetElementType = TypeArgs[0];
12955   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
12956     checkObjCCollectionLiteralElement(S, TargetElementType,
12957                                       ArrayLiteral->getElement(I),
12958                                       0);
12959   }
12960 }
12961 
12962 /// Check an Objective-C dictionary literal being converted to the given
12963 /// target type.
12964 static void
12965 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12966                            ObjCDictionaryLiteral *DictionaryLiteral) {
12967   if (!S.NSDictionaryDecl)
12968     return;
12969 
12970   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12971   if (!TargetObjCPtr)
12972     return;
12973 
12974   if (TargetObjCPtr->isUnspecialized() ||
12975       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12976         != S.NSDictionaryDecl->getCanonicalDecl())
12977     return;
12978 
12979   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12980   if (TypeArgs.size() != 2)
12981     return;
12982 
12983   QualType TargetKeyType = TypeArgs[0];
12984   QualType TargetObjectType = TypeArgs[1];
12985   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
12986     auto Element = DictionaryLiteral->getKeyValueElement(I);
12987     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
12988     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
12989   }
12990 }
12991 
12992 // Helper function to filter out cases for constant width constant conversion.
12993 // Don't warn on char array initialization or for non-decimal values.
12994 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
12995                                           SourceLocation CC) {
12996   // If initializing from a constant, and the constant starts with '0',
12997   // then it is a binary, octal, or hexadecimal.  Allow these constants
12998   // to fill all the bits, even if there is a sign change.
12999   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
13000     const char FirstLiteralCharacter =
13001         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
13002     if (FirstLiteralCharacter == '0')
13003       return false;
13004   }
13005 
13006   // If the CC location points to a '{', and the type is char, then assume
13007   // assume it is an array initialization.
13008   if (CC.isValid() && T->isCharType()) {
13009     const char FirstContextCharacter =
13010         S.getSourceManager().getCharacterData(CC)[0];
13011     if (FirstContextCharacter == '{')
13012       return false;
13013   }
13014 
13015   return true;
13016 }
13017 
13018 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
13019   const auto *IL = dyn_cast<IntegerLiteral>(E);
13020   if (!IL) {
13021     if (auto *UO = dyn_cast<UnaryOperator>(E)) {
13022       if (UO->getOpcode() == UO_Minus)
13023         return dyn_cast<IntegerLiteral>(UO->getSubExpr());
13024     }
13025   }
13026 
13027   return IL;
13028 }
13029 
13030 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
13031   E = E->IgnoreParenImpCasts();
13032   SourceLocation ExprLoc = E->getExprLoc();
13033 
13034   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
13035     BinaryOperator::Opcode Opc = BO->getOpcode();
13036     Expr::EvalResult Result;
13037     // Do not diagnose unsigned shifts.
13038     if (Opc == BO_Shl) {
13039       const auto *LHS = getIntegerLiteral(BO->getLHS());
13040       const auto *RHS = getIntegerLiteral(BO->getRHS());
13041       if (LHS && LHS->getValue() == 0)
13042         S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
13043       else if (!E->isValueDependent() && LHS && RHS &&
13044                RHS->getValue().isNonNegative() &&
13045                E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
13046         S.Diag(ExprLoc, diag::warn_left_shift_always)
13047             << (Result.Val.getInt() != 0);
13048       else if (E->getType()->isSignedIntegerType())
13049         S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
13050     }
13051   }
13052 
13053   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
13054     const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
13055     const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
13056     if (!LHS || !RHS)
13057       return;
13058     if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
13059         (RHS->getValue() == 0 || RHS->getValue() == 1))
13060       // Do not diagnose common idioms.
13061       return;
13062     if (LHS->getValue() != 0 && RHS->getValue() != 0)
13063       S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
13064   }
13065 }
13066 
13067 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
13068                                     SourceLocation CC,
13069                                     bool *ICContext = nullptr,
13070                                     bool IsListInit = false) {
13071   if (E->isTypeDependent() || E->isValueDependent()) return;
13072 
13073   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
13074   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
13075   if (Source == Target) return;
13076   if (Target->isDependentType()) return;
13077 
13078   // If the conversion context location is invalid don't complain. We also
13079   // don't want to emit a warning if the issue occurs from the expansion of
13080   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
13081   // delay this check as long as possible. Once we detect we are in that
13082   // scenario, we just return.
13083   if (CC.isInvalid())
13084     return;
13085 
13086   if (Source->isAtomicType())
13087     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
13088 
13089   // Diagnose implicit casts to bool.
13090   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
13091     if (isa<StringLiteral>(E))
13092       // Warn on string literal to bool.  Checks for string literals in logical
13093       // and expressions, for instance, assert(0 && "error here"), are
13094       // prevented by a check in AnalyzeImplicitConversions().
13095       return DiagnoseImpCast(S, E, T, CC,
13096                              diag::warn_impcast_string_literal_to_bool);
13097     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
13098         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
13099       // This covers the literal expressions that evaluate to Objective-C
13100       // objects.
13101       return DiagnoseImpCast(S, E, T, CC,
13102                              diag::warn_impcast_objective_c_literal_to_bool);
13103     }
13104     if (Source->isPointerType() || Source->canDecayToPointerType()) {
13105       // Warn on pointer to bool conversion that is always true.
13106       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
13107                                      SourceRange(CC));
13108     }
13109   }
13110 
13111   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
13112   // is a typedef for signed char (macOS), then that constant value has to be 1
13113   // or 0.
13114   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
13115     Expr::EvalResult Result;
13116     if (E->EvaluateAsInt(Result, S.getASTContext(),
13117                          Expr::SE_AllowSideEffects)) {
13118       if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
13119         adornObjCBoolConversionDiagWithTernaryFixit(
13120             S, E,
13121             S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
13122                 << toString(Result.Val.getInt(), 10));
13123       }
13124       return;
13125     }
13126   }
13127 
13128   // Check implicit casts from Objective-C collection literals to specialized
13129   // collection types, e.g., NSArray<NSString *> *.
13130   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
13131     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
13132   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
13133     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
13134 
13135   // Strip vector types.
13136   if (isa<VectorType>(Source)) {
13137     if (Target->isVLSTBuiltinType() &&
13138         (S.Context.areCompatibleSveTypes(QualType(Target, 0),
13139                                          QualType(Source, 0)) ||
13140          S.Context.areLaxCompatibleSveTypes(QualType(Target, 0),
13141                                             QualType(Source, 0))))
13142       return;
13143 
13144     if (!isa<VectorType>(Target)) {
13145       if (S.SourceMgr.isInSystemMacro(CC))
13146         return;
13147       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
13148     }
13149 
13150     // If the vector cast is cast between two vectors of the same size, it is
13151     // a bitcast, not a conversion.
13152     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
13153       return;
13154 
13155     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
13156     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
13157   }
13158   if (auto VecTy = dyn_cast<VectorType>(Target))
13159     Target = VecTy->getElementType().getTypePtr();
13160 
13161   // Strip complex types.
13162   if (isa<ComplexType>(Source)) {
13163     if (!isa<ComplexType>(Target)) {
13164       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
13165         return;
13166 
13167       return DiagnoseImpCast(S, E, T, CC,
13168                              S.getLangOpts().CPlusPlus
13169                                  ? diag::err_impcast_complex_scalar
13170                                  : diag::warn_impcast_complex_scalar);
13171     }
13172 
13173     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
13174     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
13175   }
13176 
13177   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
13178   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
13179 
13180   // If the source is floating point...
13181   if (SourceBT && SourceBT->isFloatingPoint()) {
13182     // ...and the target is floating point...
13183     if (TargetBT && TargetBT->isFloatingPoint()) {
13184       // ...then warn if we're dropping FP rank.
13185 
13186       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
13187           QualType(SourceBT, 0), QualType(TargetBT, 0));
13188       if (Order > 0) {
13189         // Don't warn about float constants that are precisely
13190         // representable in the target type.
13191         Expr::EvalResult result;
13192         if (E->EvaluateAsRValue(result, S.Context)) {
13193           // Value might be a float, a float vector, or a float complex.
13194           if (IsSameFloatAfterCast(result.Val,
13195                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
13196                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
13197             return;
13198         }
13199 
13200         if (S.SourceMgr.isInSystemMacro(CC))
13201           return;
13202 
13203         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
13204       }
13205       // ... or possibly if we're increasing rank, too
13206       else if (Order < 0) {
13207         if (S.SourceMgr.isInSystemMacro(CC))
13208           return;
13209 
13210         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
13211       }
13212       return;
13213     }
13214 
13215     // If the target is integral, always warn.
13216     if (TargetBT && TargetBT->isInteger()) {
13217       if (S.SourceMgr.isInSystemMacro(CC))
13218         return;
13219 
13220       DiagnoseFloatingImpCast(S, E, T, CC);
13221     }
13222 
13223     // Detect the case where a call result is converted from floating-point to
13224     // to bool, and the final argument to the call is converted from bool, to
13225     // discover this typo:
13226     //
13227     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
13228     //
13229     // FIXME: This is an incredibly special case; is there some more general
13230     // way to detect this class of misplaced-parentheses bug?
13231     if (Target->isBooleanType() && isa<CallExpr>(E)) {
13232       // Check last argument of function call to see if it is an
13233       // implicit cast from a type matching the type the result
13234       // is being cast to.
13235       CallExpr *CEx = cast<CallExpr>(E);
13236       if (unsigned NumArgs = CEx->getNumArgs()) {
13237         Expr *LastA = CEx->getArg(NumArgs - 1);
13238         Expr *InnerE = LastA->IgnoreParenImpCasts();
13239         if (isa<ImplicitCastExpr>(LastA) &&
13240             InnerE->getType()->isBooleanType()) {
13241           // Warn on this floating-point to bool conversion
13242           DiagnoseImpCast(S, E, T, CC,
13243                           diag::warn_impcast_floating_point_to_bool);
13244         }
13245       }
13246     }
13247     return;
13248   }
13249 
13250   // Valid casts involving fixed point types should be accounted for here.
13251   if (Source->isFixedPointType()) {
13252     if (Target->isUnsaturatedFixedPointType()) {
13253       Expr::EvalResult Result;
13254       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
13255                                   S.isConstantEvaluated())) {
13256         llvm::APFixedPoint Value = Result.Val.getFixedPoint();
13257         llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
13258         llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T);
13259         if (Value > MaxVal || Value < MinVal) {
13260           S.DiagRuntimeBehavior(E->getExprLoc(), E,
13261                                 S.PDiag(diag::warn_impcast_fixed_point_range)
13262                                     << Value.toString() << T
13263                                     << E->getSourceRange()
13264                                     << clang::SourceRange(CC));
13265           return;
13266         }
13267       }
13268     } else if (Target->isIntegerType()) {
13269       Expr::EvalResult Result;
13270       if (!S.isConstantEvaluated() &&
13271           E->EvaluateAsFixedPoint(Result, S.Context,
13272                                   Expr::SE_AllowSideEffects)) {
13273         llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
13274 
13275         bool Overflowed;
13276         llvm::APSInt IntResult = FXResult.convertToInt(
13277             S.Context.getIntWidth(T),
13278             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
13279 
13280         if (Overflowed) {
13281           S.DiagRuntimeBehavior(E->getExprLoc(), E,
13282                                 S.PDiag(diag::warn_impcast_fixed_point_range)
13283                                     << FXResult.toString() << T
13284                                     << E->getSourceRange()
13285                                     << clang::SourceRange(CC));
13286           return;
13287         }
13288       }
13289     }
13290   } else if (Target->isUnsaturatedFixedPointType()) {
13291     if (Source->isIntegerType()) {
13292       Expr::EvalResult Result;
13293       if (!S.isConstantEvaluated() &&
13294           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
13295         llvm::APSInt Value = Result.Val.getInt();
13296 
13297         bool Overflowed;
13298         llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
13299             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
13300 
13301         if (Overflowed) {
13302           S.DiagRuntimeBehavior(E->getExprLoc(), E,
13303                                 S.PDiag(diag::warn_impcast_fixed_point_range)
13304                                     << toString(Value, /*Radix=*/10) << T
13305                                     << E->getSourceRange()
13306                                     << clang::SourceRange(CC));
13307           return;
13308         }
13309       }
13310     }
13311   }
13312 
13313   // If we are casting an integer type to a floating point type without
13314   // initialization-list syntax, we might lose accuracy if the floating
13315   // point type has a narrower significand than the integer type.
13316   if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
13317       TargetBT->isFloatingType() && !IsListInit) {
13318     // Determine the number of precision bits in the source integer type.
13319     IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(),
13320                                         /*Approximate*/ true);
13321     unsigned int SourcePrecision = SourceRange.Width;
13322 
13323     // Determine the number of precision bits in the
13324     // target floating point type.
13325     unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
13326         S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
13327 
13328     if (SourcePrecision > 0 && TargetPrecision > 0 &&
13329         SourcePrecision > TargetPrecision) {
13330 
13331       if (Optional<llvm::APSInt> SourceInt =
13332               E->getIntegerConstantExpr(S.Context)) {
13333         // If the source integer is a constant, convert it to the target
13334         // floating point type. Issue a warning if the value changes
13335         // during the whole conversion.
13336         llvm::APFloat TargetFloatValue(
13337             S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
13338         llvm::APFloat::opStatus ConversionStatus =
13339             TargetFloatValue.convertFromAPInt(
13340                 *SourceInt, SourceBT->isSignedInteger(),
13341                 llvm::APFloat::rmNearestTiesToEven);
13342 
13343         if (ConversionStatus != llvm::APFloat::opOK) {
13344           SmallString<32> PrettySourceValue;
13345           SourceInt->toString(PrettySourceValue, 10);
13346           SmallString<32> PrettyTargetValue;
13347           TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
13348 
13349           S.DiagRuntimeBehavior(
13350               E->getExprLoc(), E,
13351               S.PDiag(diag::warn_impcast_integer_float_precision_constant)
13352                   << PrettySourceValue << PrettyTargetValue << E->getType() << T
13353                   << E->getSourceRange() << clang::SourceRange(CC));
13354         }
13355       } else {
13356         // Otherwise, the implicit conversion may lose precision.
13357         DiagnoseImpCast(S, E, T, CC,
13358                         diag::warn_impcast_integer_float_precision);
13359       }
13360     }
13361   }
13362 
13363   DiagnoseNullConversion(S, E, T, CC);
13364 
13365   S.DiscardMisalignedMemberAddress(Target, E);
13366 
13367   if (Target->isBooleanType())
13368     DiagnoseIntInBoolContext(S, E);
13369 
13370   if (!Source->isIntegerType() || !Target->isIntegerType())
13371     return;
13372 
13373   // TODO: remove this early return once the false positives for constant->bool
13374   // in templates, macros, etc, are reduced or removed.
13375   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
13376     return;
13377 
13378   if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
13379       !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
13380     return adornObjCBoolConversionDiagWithTernaryFixit(
13381         S, E,
13382         S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
13383             << E->getType());
13384   }
13385 
13386   IntRange SourceTypeRange =
13387       IntRange::forTargetOfCanonicalType(S.Context, Source);
13388   IntRange LikelySourceRange =
13389       GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true);
13390   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
13391 
13392   if (LikelySourceRange.Width > TargetRange.Width) {
13393     // If the source is a constant, use a default-on diagnostic.
13394     // TODO: this should happen for bitfield stores, too.
13395     Expr::EvalResult Result;
13396     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
13397                          S.isConstantEvaluated())) {
13398       llvm::APSInt Value(32);
13399       Value = Result.Val.getInt();
13400 
13401       if (S.SourceMgr.isInSystemMacro(CC))
13402         return;
13403 
13404       std::string PrettySourceValue = toString(Value, 10);
13405       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13406 
13407       S.DiagRuntimeBehavior(
13408           E->getExprLoc(), E,
13409           S.PDiag(diag::warn_impcast_integer_precision_constant)
13410               << PrettySourceValue << PrettyTargetValue << E->getType() << T
13411               << E->getSourceRange() << SourceRange(CC));
13412       return;
13413     }
13414 
13415     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
13416     if (S.SourceMgr.isInSystemMacro(CC))
13417       return;
13418 
13419     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
13420       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
13421                              /* pruneControlFlow */ true);
13422     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
13423   }
13424 
13425   if (TargetRange.Width > SourceTypeRange.Width) {
13426     if (auto *UO = dyn_cast<UnaryOperator>(E))
13427       if (UO->getOpcode() == UO_Minus)
13428         if (Source->isUnsignedIntegerType()) {
13429           if (Target->isUnsignedIntegerType())
13430             return DiagnoseImpCast(S, E, T, CC,
13431                                    diag::warn_impcast_high_order_zero_bits);
13432           if (Target->isSignedIntegerType())
13433             return DiagnoseImpCast(S, E, T, CC,
13434                                    diag::warn_impcast_nonnegative_result);
13435         }
13436   }
13437 
13438   if (TargetRange.Width == LikelySourceRange.Width &&
13439       !TargetRange.NonNegative && LikelySourceRange.NonNegative &&
13440       Source->isSignedIntegerType()) {
13441     // Warn when doing a signed to signed conversion, warn if the positive
13442     // source value is exactly the width of the target type, which will
13443     // cause a negative value to be stored.
13444 
13445     Expr::EvalResult Result;
13446     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
13447         !S.SourceMgr.isInSystemMacro(CC)) {
13448       llvm::APSInt Value = Result.Val.getInt();
13449       if (isSameWidthConstantConversion(S, E, T, CC)) {
13450         std::string PrettySourceValue = toString(Value, 10);
13451         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13452 
13453         S.DiagRuntimeBehavior(
13454             E->getExprLoc(), E,
13455             S.PDiag(diag::warn_impcast_integer_precision_constant)
13456                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13457                 << E->getSourceRange() << SourceRange(CC));
13458         return;
13459       }
13460     }
13461 
13462     // Fall through for non-constants to give a sign conversion warning.
13463   }
13464 
13465   if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) ||
13466       (!TargetRange.NonNegative && LikelySourceRange.NonNegative &&
13467        LikelySourceRange.Width == TargetRange.Width)) {
13468     if (S.SourceMgr.isInSystemMacro(CC))
13469       return;
13470 
13471     unsigned DiagID = diag::warn_impcast_integer_sign;
13472 
13473     // Traditionally, gcc has warned about this under -Wsign-compare.
13474     // We also want to warn about it in -Wconversion.
13475     // So if -Wconversion is off, use a completely identical diagnostic
13476     // in the sign-compare group.
13477     // The conditional-checking code will
13478     if (ICContext) {
13479       DiagID = diag::warn_impcast_integer_sign_conditional;
13480       *ICContext = true;
13481     }
13482 
13483     return DiagnoseImpCast(S, E, T, CC, DiagID);
13484   }
13485 
13486   // Diagnose conversions between different enumeration types.
13487   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
13488   // type, to give us better diagnostics.
13489   QualType SourceType = E->getType();
13490   if (!S.getLangOpts().CPlusPlus) {
13491     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13492       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
13493         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
13494         SourceType = S.Context.getTypeDeclType(Enum);
13495         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
13496       }
13497   }
13498 
13499   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
13500     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
13501       if (SourceEnum->getDecl()->hasNameForLinkage() &&
13502           TargetEnum->getDecl()->hasNameForLinkage() &&
13503           SourceEnum != TargetEnum) {
13504         if (S.SourceMgr.isInSystemMacro(CC))
13505           return;
13506 
13507         return DiagnoseImpCast(S, E, SourceType, T, CC,
13508                                diag::warn_impcast_different_enum_types);
13509       }
13510 }
13511 
13512 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13513                                      SourceLocation CC, QualType T);
13514 
13515 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
13516                                     SourceLocation CC, bool &ICContext) {
13517   E = E->IgnoreParenImpCasts();
13518 
13519   if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
13520     return CheckConditionalOperator(S, CO, CC, T);
13521 
13522   AnalyzeImplicitConversions(S, E, CC);
13523   if (E->getType() != T)
13524     return CheckImplicitConversion(S, E, T, CC, &ICContext);
13525 }
13526 
13527 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13528                                      SourceLocation CC, QualType T) {
13529   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
13530 
13531   Expr *TrueExpr = E->getTrueExpr();
13532   if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
13533     TrueExpr = BCO->getCommon();
13534 
13535   bool Suspicious = false;
13536   CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
13537   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
13538 
13539   if (T->isBooleanType())
13540     DiagnoseIntInBoolContext(S, E);
13541 
13542   // If -Wconversion would have warned about either of the candidates
13543   // for a signedness conversion to the context type...
13544   if (!Suspicious) return;
13545 
13546   // ...but it's currently ignored...
13547   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
13548     return;
13549 
13550   // ...then check whether it would have warned about either of the
13551   // candidates for a signedness conversion to the condition type.
13552   if (E->getType() == T) return;
13553 
13554   Suspicious = false;
13555   CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(),
13556                           E->getType(), CC, &Suspicious);
13557   if (!Suspicious)
13558     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
13559                             E->getType(), CC, &Suspicious);
13560 }
13561 
13562 /// Check conversion of given expression to boolean.
13563 /// Input argument E is a logical expression.
13564 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
13565   if (S.getLangOpts().Bool)
13566     return;
13567   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
13568     return;
13569   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
13570 }
13571 
13572 namespace {
13573 struct AnalyzeImplicitConversionsWorkItem {
13574   Expr *E;
13575   SourceLocation CC;
13576   bool IsListInit;
13577 };
13578 }
13579 
13580 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
13581 /// that should be visited are added to WorkList.
13582 static void AnalyzeImplicitConversions(
13583     Sema &S, AnalyzeImplicitConversionsWorkItem Item,
13584     llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
13585   Expr *OrigE = Item.E;
13586   SourceLocation CC = Item.CC;
13587 
13588   QualType T = OrigE->getType();
13589   Expr *E = OrigE->IgnoreParenImpCasts();
13590 
13591   // Propagate whether we are in a C++ list initialization expression.
13592   // If so, we do not issue warnings for implicit int-float conversion
13593   // precision loss, because C++11 narrowing already handles it.
13594   bool IsListInit = Item.IsListInit ||
13595                     (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
13596 
13597   if (E->isTypeDependent() || E->isValueDependent())
13598     return;
13599 
13600   Expr *SourceExpr = E;
13601   // Examine, but don't traverse into the source expression of an
13602   // OpaqueValueExpr, since it may have multiple parents and we don't want to
13603   // emit duplicate diagnostics. Its fine to examine the form or attempt to
13604   // evaluate it in the context of checking the specific conversion to T though.
13605   if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
13606     if (auto *Src = OVE->getSourceExpr())
13607       SourceExpr = Src;
13608 
13609   if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
13610     if (UO->getOpcode() == UO_Not &&
13611         UO->getSubExpr()->isKnownToHaveBooleanValue())
13612       S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
13613           << OrigE->getSourceRange() << T->isBooleanType()
13614           << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
13615 
13616   if (const auto *BO = dyn_cast<BinaryOperator>(SourceExpr))
13617     if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&
13618         BO->getLHS()->isKnownToHaveBooleanValue() &&
13619         BO->getRHS()->isKnownToHaveBooleanValue() &&
13620         BO->getLHS()->HasSideEffects(S.Context) &&
13621         BO->getRHS()->HasSideEffects(S.Context)) {
13622       S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical)
13623           << (BO->getOpcode() == BO_And ? "&" : "|") << OrigE->getSourceRange()
13624           << FixItHint::CreateReplacement(
13625                  BO->getOperatorLoc(),
13626                  (BO->getOpcode() == BO_And ? "&&" : "||"));
13627       S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int);
13628     }
13629 
13630   // For conditional operators, we analyze the arguments as if they
13631   // were being fed directly into the output.
13632   if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
13633     CheckConditionalOperator(S, CO, CC, T);
13634     return;
13635   }
13636 
13637   // Check implicit argument conversions for function calls.
13638   if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
13639     CheckImplicitArgumentConversions(S, Call, CC);
13640 
13641   // Go ahead and check any implicit conversions we might have skipped.
13642   // The non-canonical typecheck is just an optimization;
13643   // CheckImplicitConversion will filter out dead implicit conversions.
13644   if (SourceExpr->getType() != T)
13645     CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit);
13646 
13647   // Now continue drilling into this expression.
13648 
13649   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
13650     // The bound subexpressions in a PseudoObjectExpr are not reachable
13651     // as transitive children.
13652     // FIXME: Use a more uniform representation for this.
13653     for (auto *SE : POE->semantics())
13654       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
13655         WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
13656   }
13657 
13658   // Skip past explicit casts.
13659   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
13660     E = CE->getSubExpr()->IgnoreParenImpCasts();
13661     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
13662       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
13663     WorkList.push_back({E, CC, IsListInit});
13664     return;
13665   }
13666 
13667   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13668     // Do a somewhat different check with comparison operators.
13669     if (BO->isComparisonOp())
13670       return AnalyzeComparison(S, BO);
13671 
13672     // And with simple assignments.
13673     if (BO->getOpcode() == BO_Assign)
13674       return AnalyzeAssignment(S, BO);
13675     // And with compound assignments.
13676     if (BO->isAssignmentOp())
13677       return AnalyzeCompoundAssignment(S, BO);
13678   }
13679 
13680   // These break the otherwise-useful invariant below.  Fortunately,
13681   // we don't really need to recurse into them, because any internal
13682   // expressions should have been analyzed already when they were
13683   // built into statements.
13684   if (isa<StmtExpr>(E)) return;
13685 
13686   // Don't descend into unevaluated contexts.
13687   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
13688 
13689   // Now just recurse over the expression's children.
13690   CC = E->getExprLoc();
13691   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
13692   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
13693   for (Stmt *SubStmt : E->children()) {
13694     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
13695     if (!ChildExpr)
13696       continue;
13697 
13698     if (IsLogicalAndOperator &&
13699         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
13700       // Ignore checking string literals that are in logical and operators.
13701       // This is a common pattern for asserts.
13702       continue;
13703     WorkList.push_back({ChildExpr, CC, IsListInit});
13704   }
13705 
13706   if (BO && BO->isLogicalOp()) {
13707     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
13708     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13709       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13710 
13711     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
13712     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13713       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13714   }
13715 
13716   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
13717     if (U->getOpcode() == UO_LNot) {
13718       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
13719     } else if (U->getOpcode() != UO_AddrOf) {
13720       if (U->getSubExpr()->getType()->isAtomicType())
13721         S.Diag(U->getSubExpr()->getBeginLoc(),
13722                diag::warn_atomic_implicit_seq_cst);
13723     }
13724   }
13725 }
13726 
13727 /// AnalyzeImplicitConversions - Find and report any interesting
13728 /// implicit conversions in the given expression.  There are a couple
13729 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
13730 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
13731                                        bool IsListInit/*= false*/) {
13732   llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
13733   WorkList.push_back({OrigE, CC, IsListInit});
13734   while (!WorkList.empty())
13735     AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
13736 }
13737 
13738 /// Diagnose integer type and any valid implicit conversion to it.
13739 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
13740   // Taking into account implicit conversions,
13741   // allow any integer.
13742   if (!E->getType()->isIntegerType()) {
13743     S.Diag(E->getBeginLoc(),
13744            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
13745     return true;
13746   }
13747   // Potentially emit standard warnings for implicit conversions if enabled
13748   // using -Wconversion.
13749   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
13750   return false;
13751 }
13752 
13753 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
13754 // Returns true when emitting a warning about taking the address of a reference.
13755 static bool CheckForReference(Sema &SemaRef, const Expr *E,
13756                               const PartialDiagnostic &PD) {
13757   E = E->IgnoreParenImpCasts();
13758 
13759   const FunctionDecl *FD = nullptr;
13760 
13761   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13762     if (!DRE->getDecl()->getType()->isReferenceType())
13763       return false;
13764   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13765     if (!M->getMemberDecl()->getType()->isReferenceType())
13766       return false;
13767   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
13768     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
13769       return false;
13770     FD = Call->getDirectCallee();
13771   } else {
13772     return false;
13773   }
13774 
13775   SemaRef.Diag(E->getExprLoc(), PD);
13776 
13777   // If possible, point to location of function.
13778   if (FD) {
13779     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
13780   }
13781 
13782   return true;
13783 }
13784 
13785 // Returns true if the SourceLocation is expanded from any macro body.
13786 // Returns false if the SourceLocation is invalid, is from not in a macro
13787 // expansion, or is from expanded from a top-level macro argument.
13788 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
13789   if (Loc.isInvalid())
13790     return false;
13791 
13792   while (Loc.isMacroID()) {
13793     if (SM.isMacroBodyExpansion(Loc))
13794       return true;
13795     Loc = SM.getImmediateMacroCallerLoc(Loc);
13796   }
13797 
13798   return false;
13799 }
13800 
13801 /// Diagnose pointers that are always non-null.
13802 /// \param E the expression containing the pointer
13803 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
13804 /// compared to a null pointer
13805 /// \param IsEqual True when the comparison is equal to a null pointer
13806 /// \param Range Extra SourceRange to highlight in the diagnostic
13807 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
13808                                         Expr::NullPointerConstantKind NullKind,
13809                                         bool IsEqual, SourceRange Range) {
13810   if (!E)
13811     return;
13812 
13813   // Don't warn inside macros.
13814   if (E->getExprLoc().isMacroID()) {
13815     const SourceManager &SM = getSourceManager();
13816     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
13817         IsInAnyMacroBody(SM, Range.getBegin()))
13818       return;
13819   }
13820   E = E->IgnoreImpCasts();
13821 
13822   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
13823 
13824   if (isa<CXXThisExpr>(E)) {
13825     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
13826                                 : diag::warn_this_bool_conversion;
13827     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
13828     return;
13829   }
13830 
13831   bool IsAddressOf = false;
13832 
13833   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13834     if (UO->getOpcode() != UO_AddrOf)
13835       return;
13836     IsAddressOf = true;
13837     E = UO->getSubExpr();
13838   }
13839 
13840   if (IsAddressOf) {
13841     unsigned DiagID = IsCompare
13842                           ? diag::warn_address_of_reference_null_compare
13843                           : diag::warn_address_of_reference_bool_conversion;
13844     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
13845                                          << IsEqual;
13846     if (CheckForReference(*this, E, PD)) {
13847       return;
13848     }
13849   }
13850 
13851   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
13852     bool IsParam = isa<NonNullAttr>(NonnullAttr);
13853     std::string Str;
13854     llvm::raw_string_ostream S(Str);
13855     E->printPretty(S, nullptr, getPrintingPolicy());
13856     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
13857                                 : diag::warn_cast_nonnull_to_bool;
13858     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
13859       << E->getSourceRange() << Range << IsEqual;
13860     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
13861   };
13862 
13863   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
13864   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
13865     if (auto *Callee = Call->getDirectCallee()) {
13866       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
13867         ComplainAboutNonnullParamOrCall(A);
13868         return;
13869       }
13870     }
13871   }
13872 
13873   // Expect to find a single Decl.  Skip anything more complicated.
13874   ValueDecl *D = nullptr;
13875   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
13876     D = R->getDecl();
13877   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13878     D = M->getMemberDecl();
13879   }
13880 
13881   // Weak Decls can be null.
13882   if (!D || D->isWeak())
13883     return;
13884 
13885   // Check for parameter decl with nonnull attribute
13886   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
13887     if (getCurFunction() &&
13888         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
13889       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
13890         ComplainAboutNonnullParamOrCall(A);
13891         return;
13892       }
13893 
13894       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
13895         // Skip function template not specialized yet.
13896         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
13897           return;
13898         auto ParamIter = llvm::find(FD->parameters(), PV);
13899         assert(ParamIter != FD->param_end());
13900         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
13901 
13902         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
13903           if (!NonNull->args_size()) {
13904               ComplainAboutNonnullParamOrCall(NonNull);
13905               return;
13906           }
13907 
13908           for (const ParamIdx &ArgNo : NonNull->args()) {
13909             if (ArgNo.getASTIndex() == ParamNo) {
13910               ComplainAboutNonnullParamOrCall(NonNull);
13911               return;
13912             }
13913           }
13914         }
13915       }
13916     }
13917   }
13918 
13919   QualType T = D->getType();
13920   const bool IsArray = T->isArrayType();
13921   const bool IsFunction = T->isFunctionType();
13922 
13923   // Address of function is used to silence the function warning.
13924   if (IsAddressOf && IsFunction) {
13925     return;
13926   }
13927 
13928   // Found nothing.
13929   if (!IsAddressOf && !IsFunction && !IsArray)
13930     return;
13931 
13932   // Pretty print the expression for the diagnostic.
13933   std::string Str;
13934   llvm::raw_string_ostream S(Str);
13935   E->printPretty(S, nullptr, getPrintingPolicy());
13936 
13937   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
13938                               : diag::warn_impcast_pointer_to_bool;
13939   enum {
13940     AddressOf,
13941     FunctionPointer,
13942     ArrayPointer
13943   } DiagType;
13944   if (IsAddressOf)
13945     DiagType = AddressOf;
13946   else if (IsFunction)
13947     DiagType = FunctionPointer;
13948   else if (IsArray)
13949     DiagType = ArrayPointer;
13950   else
13951     llvm_unreachable("Could not determine diagnostic.");
13952   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
13953                                 << Range << IsEqual;
13954 
13955   if (!IsFunction)
13956     return;
13957 
13958   // Suggest '&' to silence the function warning.
13959   Diag(E->getExprLoc(), diag::note_function_warning_silence)
13960       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
13961 
13962   // Check to see if '()' fixit should be emitted.
13963   QualType ReturnType;
13964   UnresolvedSet<4> NonTemplateOverloads;
13965   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
13966   if (ReturnType.isNull())
13967     return;
13968 
13969   if (IsCompare) {
13970     // There are two cases here.  If there is null constant, the only suggest
13971     // for a pointer return type.  If the null is 0, then suggest if the return
13972     // type is a pointer or an integer type.
13973     if (!ReturnType->isPointerType()) {
13974       if (NullKind == Expr::NPCK_ZeroExpression ||
13975           NullKind == Expr::NPCK_ZeroLiteral) {
13976         if (!ReturnType->isIntegerType())
13977           return;
13978       } else {
13979         return;
13980       }
13981     }
13982   } else { // !IsCompare
13983     // For function to bool, only suggest if the function pointer has bool
13984     // return type.
13985     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
13986       return;
13987   }
13988   Diag(E->getExprLoc(), diag::note_function_to_function_call)
13989       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
13990 }
13991 
13992 /// Diagnoses "dangerous" implicit conversions within the given
13993 /// expression (which is a full expression).  Implements -Wconversion
13994 /// and -Wsign-compare.
13995 ///
13996 /// \param CC the "context" location of the implicit conversion, i.e.
13997 ///   the most location of the syntactic entity requiring the implicit
13998 ///   conversion
13999 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
14000   // Don't diagnose in unevaluated contexts.
14001   if (isUnevaluatedContext())
14002     return;
14003 
14004   // Don't diagnose for value- or type-dependent expressions.
14005   if (E->isTypeDependent() || E->isValueDependent())
14006     return;
14007 
14008   // Check for array bounds violations in cases where the check isn't triggered
14009   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
14010   // ArraySubscriptExpr is on the RHS of a variable initialization.
14011   CheckArrayAccess(E);
14012 
14013   // This is not the right CC for (e.g.) a variable initialization.
14014   AnalyzeImplicitConversions(*this, E, CC);
14015 }
14016 
14017 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
14018 /// Input argument E is a logical expression.
14019 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
14020   ::CheckBoolLikeConversion(*this, E, CC);
14021 }
14022 
14023 /// Diagnose when expression is an integer constant expression and its evaluation
14024 /// results in integer overflow
14025 void Sema::CheckForIntOverflow (Expr *E) {
14026   // Use a work list to deal with nested struct initializers.
14027   SmallVector<Expr *, 2> Exprs(1, E);
14028 
14029   do {
14030     Expr *OriginalE = Exprs.pop_back_val();
14031     Expr *E = OriginalE->IgnoreParenCasts();
14032 
14033     if (isa<BinaryOperator>(E)) {
14034       E->EvaluateForOverflow(Context);
14035       continue;
14036     }
14037 
14038     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
14039       Exprs.append(InitList->inits().begin(), InitList->inits().end());
14040     else if (isa<ObjCBoxedExpr>(OriginalE))
14041       E->EvaluateForOverflow(Context);
14042     else if (auto Call = dyn_cast<CallExpr>(E))
14043       Exprs.append(Call->arg_begin(), Call->arg_end());
14044     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
14045       Exprs.append(Message->arg_begin(), Message->arg_end());
14046   } while (!Exprs.empty());
14047 }
14048 
14049 namespace {
14050 
14051 /// Visitor for expressions which looks for unsequenced operations on the
14052 /// same object.
14053 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
14054   using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
14055 
14056   /// A tree of sequenced regions within an expression. Two regions are
14057   /// unsequenced if one is an ancestor or a descendent of the other. When we
14058   /// finish processing an expression with sequencing, such as a comma
14059   /// expression, we fold its tree nodes into its parent, since they are
14060   /// unsequenced with respect to nodes we will visit later.
14061   class SequenceTree {
14062     struct Value {
14063       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
14064       unsigned Parent : 31;
14065       unsigned Merged : 1;
14066     };
14067     SmallVector<Value, 8> Values;
14068 
14069   public:
14070     /// A region within an expression which may be sequenced with respect
14071     /// to some other region.
14072     class Seq {
14073       friend class SequenceTree;
14074 
14075       unsigned Index;
14076 
14077       explicit Seq(unsigned N) : Index(N) {}
14078 
14079     public:
14080       Seq() : Index(0) {}
14081     };
14082 
14083     SequenceTree() { Values.push_back(Value(0)); }
14084     Seq root() const { return Seq(0); }
14085 
14086     /// Create a new sequence of operations, which is an unsequenced
14087     /// subset of \p Parent. This sequence of operations is sequenced with
14088     /// respect to other children of \p Parent.
14089     Seq allocate(Seq Parent) {
14090       Values.push_back(Value(Parent.Index));
14091       return Seq(Values.size() - 1);
14092     }
14093 
14094     /// Merge a sequence of operations into its parent.
14095     void merge(Seq S) {
14096       Values[S.Index].Merged = true;
14097     }
14098 
14099     /// Determine whether two operations are unsequenced. This operation
14100     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
14101     /// should have been merged into its parent as appropriate.
14102     bool isUnsequenced(Seq Cur, Seq Old) {
14103       unsigned C = representative(Cur.Index);
14104       unsigned Target = representative(Old.Index);
14105       while (C >= Target) {
14106         if (C == Target)
14107           return true;
14108         C = Values[C].Parent;
14109       }
14110       return false;
14111     }
14112 
14113   private:
14114     /// Pick a representative for a sequence.
14115     unsigned representative(unsigned K) {
14116       if (Values[K].Merged)
14117         // Perform path compression as we go.
14118         return Values[K].Parent = representative(Values[K].Parent);
14119       return K;
14120     }
14121   };
14122 
14123   /// An object for which we can track unsequenced uses.
14124   using Object = const NamedDecl *;
14125 
14126   /// Different flavors of object usage which we track. We only track the
14127   /// least-sequenced usage of each kind.
14128   enum UsageKind {
14129     /// A read of an object. Multiple unsequenced reads are OK.
14130     UK_Use,
14131 
14132     /// A modification of an object which is sequenced before the value
14133     /// computation of the expression, such as ++n in C++.
14134     UK_ModAsValue,
14135 
14136     /// A modification of an object which is not sequenced before the value
14137     /// computation of the expression, such as n++.
14138     UK_ModAsSideEffect,
14139 
14140     UK_Count = UK_ModAsSideEffect + 1
14141   };
14142 
14143   /// Bundle together a sequencing region and the expression corresponding
14144   /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
14145   struct Usage {
14146     const Expr *UsageExpr;
14147     SequenceTree::Seq Seq;
14148 
14149     Usage() : UsageExpr(nullptr) {}
14150   };
14151 
14152   struct UsageInfo {
14153     Usage Uses[UK_Count];
14154 
14155     /// Have we issued a diagnostic for this object already?
14156     bool Diagnosed;
14157 
14158     UsageInfo() : Diagnosed(false) {}
14159   };
14160   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
14161 
14162   Sema &SemaRef;
14163 
14164   /// Sequenced regions within the expression.
14165   SequenceTree Tree;
14166 
14167   /// Declaration modifications and references which we have seen.
14168   UsageInfoMap UsageMap;
14169 
14170   /// The region we are currently within.
14171   SequenceTree::Seq Region;
14172 
14173   /// Filled in with declarations which were modified as a side-effect
14174   /// (that is, post-increment operations).
14175   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
14176 
14177   /// Expressions to check later. We defer checking these to reduce
14178   /// stack usage.
14179   SmallVectorImpl<const Expr *> &WorkList;
14180 
14181   /// RAII object wrapping the visitation of a sequenced subexpression of an
14182   /// expression. At the end of this process, the side-effects of the evaluation
14183   /// become sequenced with respect to the value computation of the result, so
14184   /// we downgrade any UK_ModAsSideEffect within the evaluation to
14185   /// UK_ModAsValue.
14186   struct SequencedSubexpression {
14187     SequencedSubexpression(SequenceChecker &Self)
14188       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
14189       Self.ModAsSideEffect = &ModAsSideEffect;
14190     }
14191 
14192     ~SequencedSubexpression() {
14193       for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
14194         // Add a new usage with usage kind UK_ModAsValue, and then restore
14195         // the previous usage with UK_ModAsSideEffect (thus clearing it if
14196         // the previous one was empty).
14197         UsageInfo &UI = Self.UsageMap[M.first];
14198         auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
14199         Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
14200         SideEffectUsage = M.second;
14201       }
14202       Self.ModAsSideEffect = OldModAsSideEffect;
14203     }
14204 
14205     SequenceChecker &Self;
14206     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
14207     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
14208   };
14209 
14210   /// RAII object wrapping the visitation of a subexpression which we might
14211   /// choose to evaluate as a constant. If any subexpression is evaluated and
14212   /// found to be non-constant, this allows us to suppress the evaluation of
14213   /// the outer expression.
14214   class EvaluationTracker {
14215   public:
14216     EvaluationTracker(SequenceChecker &Self)
14217         : Self(Self), Prev(Self.EvalTracker) {
14218       Self.EvalTracker = this;
14219     }
14220 
14221     ~EvaluationTracker() {
14222       Self.EvalTracker = Prev;
14223       if (Prev)
14224         Prev->EvalOK &= EvalOK;
14225     }
14226 
14227     bool evaluate(const Expr *E, bool &Result) {
14228       if (!EvalOK || E->isValueDependent())
14229         return false;
14230       EvalOK = E->EvaluateAsBooleanCondition(
14231           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
14232       return EvalOK;
14233     }
14234 
14235   private:
14236     SequenceChecker &Self;
14237     EvaluationTracker *Prev;
14238     bool EvalOK = true;
14239   } *EvalTracker = nullptr;
14240 
14241   /// Find the object which is produced by the specified expression,
14242   /// if any.
14243   Object getObject(const Expr *E, bool Mod) const {
14244     E = E->IgnoreParenCasts();
14245     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
14246       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
14247         return getObject(UO->getSubExpr(), Mod);
14248     } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
14249       if (BO->getOpcode() == BO_Comma)
14250         return getObject(BO->getRHS(), Mod);
14251       if (Mod && BO->isAssignmentOp())
14252         return getObject(BO->getLHS(), Mod);
14253     } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14254       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
14255       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
14256         return ME->getMemberDecl();
14257     } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
14258       // FIXME: If this is a reference, map through to its value.
14259       return DRE->getDecl();
14260     return nullptr;
14261   }
14262 
14263   /// Note that an object \p O was modified or used by an expression
14264   /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
14265   /// the object \p O as obtained via the \p UsageMap.
14266   void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
14267     // Get the old usage for the given object and usage kind.
14268     Usage &U = UI.Uses[UK];
14269     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
14270       // If we have a modification as side effect and are in a sequenced
14271       // subexpression, save the old Usage so that we can restore it later
14272       // in SequencedSubexpression::~SequencedSubexpression.
14273       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
14274         ModAsSideEffect->push_back(std::make_pair(O, U));
14275       // Then record the new usage with the current sequencing region.
14276       U.UsageExpr = UsageExpr;
14277       U.Seq = Region;
14278     }
14279   }
14280 
14281   /// Check whether a modification or use of an object \p O in an expression
14282   /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
14283   /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
14284   /// \p IsModMod is true when we are checking for a mod-mod unsequenced
14285   /// usage and false we are checking for a mod-use unsequenced usage.
14286   void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
14287                   UsageKind OtherKind, bool IsModMod) {
14288     if (UI.Diagnosed)
14289       return;
14290 
14291     const Usage &U = UI.Uses[OtherKind];
14292     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
14293       return;
14294 
14295     const Expr *Mod = U.UsageExpr;
14296     const Expr *ModOrUse = UsageExpr;
14297     if (OtherKind == UK_Use)
14298       std::swap(Mod, ModOrUse);
14299 
14300     SemaRef.DiagRuntimeBehavior(
14301         Mod->getExprLoc(), {Mod, ModOrUse},
14302         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
14303                                : diag::warn_unsequenced_mod_use)
14304             << O << SourceRange(ModOrUse->getExprLoc()));
14305     UI.Diagnosed = true;
14306   }
14307 
14308   // A note on note{Pre, Post}{Use, Mod}:
14309   //
14310   // (It helps to follow the algorithm with an expression such as
14311   //  "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
14312   //  operations before C++17 and both are well-defined in C++17).
14313   //
14314   // When visiting a node which uses/modify an object we first call notePreUse
14315   // or notePreMod before visiting its sub-expression(s). At this point the
14316   // children of the current node have not yet been visited and so the eventual
14317   // uses/modifications resulting from the children of the current node have not
14318   // been recorded yet.
14319   //
14320   // We then visit the children of the current node. After that notePostUse or
14321   // notePostMod is called. These will 1) detect an unsequenced modification
14322   // as side effect (as in "k++ + k") and 2) add a new usage with the
14323   // appropriate usage kind.
14324   //
14325   // We also have to be careful that some operation sequences modification as
14326   // side effect as well (for example: || or ,). To account for this we wrap
14327   // the visitation of such a sub-expression (for example: the LHS of || or ,)
14328   // with SequencedSubexpression. SequencedSubexpression is an RAII object
14329   // which record usages which are modifications as side effect, and then
14330   // downgrade them (or more accurately restore the previous usage which was a
14331   // modification as side effect) when exiting the scope of the sequenced
14332   // subexpression.
14333 
14334   void notePreUse(Object O, const Expr *UseExpr) {
14335     UsageInfo &UI = UsageMap[O];
14336     // Uses conflict with other modifications.
14337     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
14338   }
14339 
14340   void notePostUse(Object O, const Expr *UseExpr) {
14341     UsageInfo &UI = UsageMap[O];
14342     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
14343                /*IsModMod=*/false);
14344     addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
14345   }
14346 
14347   void notePreMod(Object O, const Expr *ModExpr) {
14348     UsageInfo &UI = UsageMap[O];
14349     // Modifications conflict with other modifications and with uses.
14350     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
14351     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
14352   }
14353 
14354   void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
14355     UsageInfo &UI = UsageMap[O];
14356     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
14357                /*IsModMod=*/true);
14358     addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
14359   }
14360 
14361 public:
14362   SequenceChecker(Sema &S, const Expr *E,
14363                   SmallVectorImpl<const Expr *> &WorkList)
14364       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
14365     Visit(E);
14366     // Silence a -Wunused-private-field since WorkList is now unused.
14367     // TODO: Evaluate if it can be used, and if not remove it.
14368     (void)this->WorkList;
14369   }
14370 
14371   void VisitStmt(const Stmt *S) {
14372     // Skip all statements which aren't expressions for now.
14373   }
14374 
14375   void VisitExpr(const Expr *E) {
14376     // By default, just recurse to evaluated subexpressions.
14377     Base::VisitStmt(E);
14378   }
14379 
14380   void VisitCastExpr(const CastExpr *E) {
14381     Object O = Object();
14382     if (E->getCastKind() == CK_LValueToRValue)
14383       O = getObject(E->getSubExpr(), false);
14384 
14385     if (O)
14386       notePreUse(O, E);
14387     VisitExpr(E);
14388     if (O)
14389       notePostUse(O, E);
14390   }
14391 
14392   void VisitSequencedExpressions(const Expr *SequencedBefore,
14393                                  const Expr *SequencedAfter) {
14394     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
14395     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
14396     SequenceTree::Seq OldRegion = Region;
14397 
14398     {
14399       SequencedSubexpression SeqBefore(*this);
14400       Region = BeforeRegion;
14401       Visit(SequencedBefore);
14402     }
14403 
14404     Region = AfterRegion;
14405     Visit(SequencedAfter);
14406 
14407     Region = OldRegion;
14408 
14409     Tree.merge(BeforeRegion);
14410     Tree.merge(AfterRegion);
14411   }
14412 
14413   void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
14414     // C++17 [expr.sub]p1:
14415     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
14416     //   expression E1 is sequenced before the expression E2.
14417     if (SemaRef.getLangOpts().CPlusPlus17)
14418       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
14419     else {
14420       Visit(ASE->getLHS());
14421       Visit(ASE->getRHS());
14422     }
14423   }
14424 
14425   void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14426   void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14427   void VisitBinPtrMem(const BinaryOperator *BO) {
14428     // C++17 [expr.mptr.oper]p4:
14429     //  Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
14430     //  the expression E1 is sequenced before the expression E2.
14431     if (SemaRef.getLangOpts().CPlusPlus17)
14432       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14433     else {
14434       Visit(BO->getLHS());
14435       Visit(BO->getRHS());
14436     }
14437   }
14438 
14439   void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14440   void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14441   void VisitBinShlShr(const BinaryOperator *BO) {
14442     // C++17 [expr.shift]p4:
14443     //  The expression E1 is sequenced before the expression E2.
14444     if (SemaRef.getLangOpts().CPlusPlus17)
14445       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14446     else {
14447       Visit(BO->getLHS());
14448       Visit(BO->getRHS());
14449     }
14450   }
14451 
14452   void VisitBinComma(const BinaryOperator *BO) {
14453     // C++11 [expr.comma]p1:
14454     //   Every value computation and side effect associated with the left
14455     //   expression is sequenced before every value computation and side
14456     //   effect associated with the right expression.
14457     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14458   }
14459 
14460   void VisitBinAssign(const BinaryOperator *BO) {
14461     SequenceTree::Seq RHSRegion;
14462     SequenceTree::Seq LHSRegion;
14463     if (SemaRef.getLangOpts().CPlusPlus17) {
14464       RHSRegion = Tree.allocate(Region);
14465       LHSRegion = Tree.allocate(Region);
14466     } else {
14467       RHSRegion = Region;
14468       LHSRegion = Region;
14469     }
14470     SequenceTree::Seq OldRegion = Region;
14471 
14472     // C++11 [expr.ass]p1:
14473     //  [...] the assignment is sequenced after the value computation
14474     //  of the right and left operands, [...]
14475     //
14476     // so check it before inspecting the operands and update the
14477     // map afterwards.
14478     Object O = getObject(BO->getLHS(), /*Mod=*/true);
14479     if (O)
14480       notePreMod(O, BO);
14481 
14482     if (SemaRef.getLangOpts().CPlusPlus17) {
14483       // C++17 [expr.ass]p1:
14484       //  [...] The right operand is sequenced before the left operand. [...]
14485       {
14486         SequencedSubexpression SeqBefore(*this);
14487         Region = RHSRegion;
14488         Visit(BO->getRHS());
14489       }
14490 
14491       Region = LHSRegion;
14492       Visit(BO->getLHS());
14493 
14494       if (O && isa<CompoundAssignOperator>(BO))
14495         notePostUse(O, BO);
14496 
14497     } else {
14498       // C++11 does not specify any sequencing between the LHS and RHS.
14499       Region = LHSRegion;
14500       Visit(BO->getLHS());
14501 
14502       if (O && isa<CompoundAssignOperator>(BO))
14503         notePostUse(O, BO);
14504 
14505       Region = RHSRegion;
14506       Visit(BO->getRHS());
14507     }
14508 
14509     // C++11 [expr.ass]p1:
14510     //  the assignment is sequenced [...] before the value computation of the
14511     //  assignment expression.
14512     // C11 6.5.16/3 has no such rule.
14513     Region = OldRegion;
14514     if (O)
14515       notePostMod(O, BO,
14516                   SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14517                                                   : UK_ModAsSideEffect);
14518     if (SemaRef.getLangOpts().CPlusPlus17) {
14519       Tree.merge(RHSRegion);
14520       Tree.merge(LHSRegion);
14521     }
14522   }
14523 
14524   void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
14525     VisitBinAssign(CAO);
14526   }
14527 
14528   void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14529   void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14530   void VisitUnaryPreIncDec(const UnaryOperator *UO) {
14531     Object O = getObject(UO->getSubExpr(), true);
14532     if (!O)
14533       return VisitExpr(UO);
14534 
14535     notePreMod(O, UO);
14536     Visit(UO->getSubExpr());
14537     // C++11 [expr.pre.incr]p1:
14538     //   the expression ++x is equivalent to x+=1
14539     notePostMod(O, UO,
14540                 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14541                                                 : UK_ModAsSideEffect);
14542   }
14543 
14544   void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14545   void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14546   void VisitUnaryPostIncDec(const UnaryOperator *UO) {
14547     Object O = getObject(UO->getSubExpr(), true);
14548     if (!O)
14549       return VisitExpr(UO);
14550 
14551     notePreMod(O, UO);
14552     Visit(UO->getSubExpr());
14553     notePostMod(O, UO, UK_ModAsSideEffect);
14554   }
14555 
14556   void VisitBinLOr(const BinaryOperator *BO) {
14557     // C++11 [expr.log.or]p2:
14558     //  If the second expression is evaluated, every value computation and
14559     //  side effect associated with the first expression is sequenced before
14560     //  every value computation and side effect associated with the
14561     //  second expression.
14562     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14563     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14564     SequenceTree::Seq OldRegion = Region;
14565 
14566     EvaluationTracker Eval(*this);
14567     {
14568       SequencedSubexpression Sequenced(*this);
14569       Region = LHSRegion;
14570       Visit(BO->getLHS());
14571     }
14572 
14573     // C++11 [expr.log.or]p1:
14574     //  [...] the second operand is not evaluated if the first operand
14575     //  evaluates to true.
14576     bool EvalResult = false;
14577     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14578     bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
14579     if (ShouldVisitRHS) {
14580       Region = RHSRegion;
14581       Visit(BO->getRHS());
14582     }
14583 
14584     Region = OldRegion;
14585     Tree.merge(LHSRegion);
14586     Tree.merge(RHSRegion);
14587   }
14588 
14589   void VisitBinLAnd(const BinaryOperator *BO) {
14590     // C++11 [expr.log.and]p2:
14591     //  If the second expression is evaluated, every value computation and
14592     //  side effect associated with the first expression is sequenced before
14593     //  every value computation and side effect associated with the
14594     //  second expression.
14595     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14596     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14597     SequenceTree::Seq OldRegion = Region;
14598 
14599     EvaluationTracker Eval(*this);
14600     {
14601       SequencedSubexpression Sequenced(*this);
14602       Region = LHSRegion;
14603       Visit(BO->getLHS());
14604     }
14605 
14606     // C++11 [expr.log.and]p1:
14607     //  [...] the second operand is not evaluated if the first operand is false.
14608     bool EvalResult = false;
14609     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14610     bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
14611     if (ShouldVisitRHS) {
14612       Region = RHSRegion;
14613       Visit(BO->getRHS());
14614     }
14615 
14616     Region = OldRegion;
14617     Tree.merge(LHSRegion);
14618     Tree.merge(RHSRegion);
14619   }
14620 
14621   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
14622     // C++11 [expr.cond]p1:
14623     //  [...] Every value computation and side effect associated with the first
14624     //  expression is sequenced before every value computation and side effect
14625     //  associated with the second or third expression.
14626     SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
14627 
14628     // No sequencing is specified between the true and false expression.
14629     // However since exactly one of both is going to be evaluated we can
14630     // consider them to be sequenced. This is needed to avoid warning on
14631     // something like "x ? y+= 1 : y += 2;" in the case where we will visit
14632     // both the true and false expressions because we can't evaluate x.
14633     // This will still allow us to detect an expression like (pre C++17)
14634     // "(x ? y += 1 : y += 2) = y".
14635     //
14636     // We don't wrap the visitation of the true and false expression with
14637     // SequencedSubexpression because we don't want to downgrade modifications
14638     // as side effect in the true and false expressions after the visition
14639     // is done. (for example in the expression "(x ? y++ : y++) + y" we should
14640     // not warn between the two "y++", but we should warn between the "y++"
14641     // and the "y".
14642     SequenceTree::Seq TrueRegion = Tree.allocate(Region);
14643     SequenceTree::Seq FalseRegion = Tree.allocate(Region);
14644     SequenceTree::Seq OldRegion = Region;
14645 
14646     EvaluationTracker Eval(*this);
14647     {
14648       SequencedSubexpression Sequenced(*this);
14649       Region = ConditionRegion;
14650       Visit(CO->getCond());
14651     }
14652 
14653     // C++11 [expr.cond]p1:
14654     // [...] The first expression is contextually converted to bool (Clause 4).
14655     // It is evaluated and if it is true, the result of the conditional
14656     // expression is the value of the second expression, otherwise that of the
14657     // third expression. Only one of the second and third expressions is
14658     // evaluated. [...]
14659     bool EvalResult = false;
14660     bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
14661     bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
14662     bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
14663     if (ShouldVisitTrueExpr) {
14664       Region = TrueRegion;
14665       Visit(CO->getTrueExpr());
14666     }
14667     if (ShouldVisitFalseExpr) {
14668       Region = FalseRegion;
14669       Visit(CO->getFalseExpr());
14670     }
14671 
14672     Region = OldRegion;
14673     Tree.merge(ConditionRegion);
14674     Tree.merge(TrueRegion);
14675     Tree.merge(FalseRegion);
14676   }
14677 
14678   void VisitCallExpr(const CallExpr *CE) {
14679     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
14680 
14681     if (CE->isUnevaluatedBuiltinCall(Context))
14682       return;
14683 
14684     // C++11 [intro.execution]p15:
14685     //   When calling a function [...], every value computation and side effect
14686     //   associated with any argument expression, or with the postfix expression
14687     //   designating the called function, is sequenced before execution of every
14688     //   expression or statement in the body of the function [and thus before
14689     //   the value computation of its result].
14690     SequencedSubexpression Sequenced(*this);
14691     SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
14692       // C++17 [expr.call]p5
14693       //   The postfix-expression is sequenced before each expression in the
14694       //   expression-list and any default argument. [...]
14695       SequenceTree::Seq CalleeRegion;
14696       SequenceTree::Seq OtherRegion;
14697       if (SemaRef.getLangOpts().CPlusPlus17) {
14698         CalleeRegion = Tree.allocate(Region);
14699         OtherRegion = Tree.allocate(Region);
14700       } else {
14701         CalleeRegion = Region;
14702         OtherRegion = Region;
14703       }
14704       SequenceTree::Seq OldRegion = Region;
14705 
14706       // Visit the callee expression first.
14707       Region = CalleeRegion;
14708       if (SemaRef.getLangOpts().CPlusPlus17) {
14709         SequencedSubexpression Sequenced(*this);
14710         Visit(CE->getCallee());
14711       } else {
14712         Visit(CE->getCallee());
14713       }
14714 
14715       // Then visit the argument expressions.
14716       Region = OtherRegion;
14717       for (const Expr *Argument : CE->arguments())
14718         Visit(Argument);
14719 
14720       Region = OldRegion;
14721       if (SemaRef.getLangOpts().CPlusPlus17) {
14722         Tree.merge(CalleeRegion);
14723         Tree.merge(OtherRegion);
14724       }
14725     });
14726   }
14727 
14728   void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
14729     // C++17 [over.match.oper]p2:
14730     //   [...] the operator notation is first transformed to the equivalent
14731     //   function-call notation as summarized in Table 12 (where @ denotes one
14732     //   of the operators covered in the specified subclause). However, the
14733     //   operands are sequenced in the order prescribed for the built-in
14734     //   operator (Clause 8).
14735     //
14736     // From the above only overloaded binary operators and overloaded call
14737     // operators have sequencing rules in C++17 that we need to handle
14738     // separately.
14739     if (!SemaRef.getLangOpts().CPlusPlus17 ||
14740         (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
14741       return VisitCallExpr(CXXOCE);
14742 
14743     enum {
14744       NoSequencing,
14745       LHSBeforeRHS,
14746       RHSBeforeLHS,
14747       LHSBeforeRest
14748     } SequencingKind;
14749     switch (CXXOCE->getOperator()) {
14750     case OO_Equal:
14751     case OO_PlusEqual:
14752     case OO_MinusEqual:
14753     case OO_StarEqual:
14754     case OO_SlashEqual:
14755     case OO_PercentEqual:
14756     case OO_CaretEqual:
14757     case OO_AmpEqual:
14758     case OO_PipeEqual:
14759     case OO_LessLessEqual:
14760     case OO_GreaterGreaterEqual:
14761       SequencingKind = RHSBeforeLHS;
14762       break;
14763 
14764     case OO_LessLess:
14765     case OO_GreaterGreater:
14766     case OO_AmpAmp:
14767     case OO_PipePipe:
14768     case OO_Comma:
14769     case OO_ArrowStar:
14770     case OO_Subscript:
14771       SequencingKind = LHSBeforeRHS;
14772       break;
14773 
14774     case OO_Call:
14775       SequencingKind = LHSBeforeRest;
14776       break;
14777 
14778     default:
14779       SequencingKind = NoSequencing;
14780       break;
14781     }
14782 
14783     if (SequencingKind == NoSequencing)
14784       return VisitCallExpr(CXXOCE);
14785 
14786     // This is a call, so all subexpressions are sequenced before the result.
14787     SequencedSubexpression Sequenced(*this);
14788 
14789     SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
14790       assert(SemaRef.getLangOpts().CPlusPlus17 &&
14791              "Should only get there with C++17 and above!");
14792       assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
14793              "Should only get there with an overloaded binary operator"
14794              " or an overloaded call operator!");
14795 
14796       if (SequencingKind == LHSBeforeRest) {
14797         assert(CXXOCE->getOperator() == OO_Call &&
14798                "We should only have an overloaded call operator here!");
14799 
14800         // This is very similar to VisitCallExpr, except that we only have the
14801         // C++17 case. The postfix-expression is the first argument of the
14802         // CXXOperatorCallExpr. The expressions in the expression-list, if any,
14803         // are in the following arguments.
14804         //
14805         // Note that we intentionally do not visit the callee expression since
14806         // it is just a decayed reference to a function.
14807         SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
14808         SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
14809         SequenceTree::Seq OldRegion = Region;
14810 
14811         assert(CXXOCE->getNumArgs() >= 1 &&
14812                "An overloaded call operator must have at least one argument"
14813                " for the postfix-expression!");
14814         const Expr *PostfixExpr = CXXOCE->getArgs()[0];
14815         llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
14816                                           CXXOCE->getNumArgs() - 1);
14817 
14818         // Visit the postfix-expression first.
14819         {
14820           Region = PostfixExprRegion;
14821           SequencedSubexpression Sequenced(*this);
14822           Visit(PostfixExpr);
14823         }
14824 
14825         // Then visit the argument expressions.
14826         Region = ArgsRegion;
14827         for (const Expr *Arg : Args)
14828           Visit(Arg);
14829 
14830         Region = OldRegion;
14831         Tree.merge(PostfixExprRegion);
14832         Tree.merge(ArgsRegion);
14833       } else {
14834         assert(CXXOCE->getNumArgs() == 2 &&
14835                "Should only have two arguments here!");
14836         assert((SequencingKind == LHSBeforeRHS ||
14837                 SequencingKind == RHSBeforeLHS) &&
14838                "Unexpected sequencing kind!");
14839 
14840         // We do not visit the callee expression since it is just a decayed
14841         // reference to a function.
14842         const Expr *E1 = CXXOCE->getArg(0);
14843         const Expr *E2 = CXXOCE->getArg(1);
14844         if (SequencingKind == RHSBeforeLHS)
14845           std::swap(E1, E2);
14846 
14847         return VisitSequencedExpressions(E1, E2);
14848       }
14849     });
14850   }
14851 
14852   void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
14853     // This is a call, so all subexpressions are sequenced before the result.
14854     SequencedSubexpression Sequenced(*this);
14855 
14856     if (!CCE->isListInitialization())
14857       return VisitExpr(CCE);
14858 
14859     // In C++11, list initializations are sequenced.
14860     SmallVector<SequenceTree::Seq, 32> Elts;
14861     SequenceTree::Seq Parent = Region;
14862     for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
14863                                               E = CCE->arg_end();
14864          I != E; ++I) {
14865       Region = Tree.allocate(Parent);
14866       Elts.push_back(Region);
14867       Visit(*I);
14868     }
14869 
14870     // Forget that the initializers are sequenced.
14871     Region = Parent;
14872     for (unsigned I = 0; I < Elts.size(); ++I)
14873       Tree.merge(Elts[I]);
14874   }
14875 
14876   void VisitInitListExpr(const InitListExpr *ILE) {
14877     if (!SemaRef.getLangOpts().CPlusPlus11)
14878       return VisitExpr(ILE);
14879 
14880     // In C++11, list initializations are sequenced.
14881     SmallVector<SequenceTree::Seq, 32> Elts;
14882     SequenceTree::Seq Parent = Region;
14883     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
14884       const Expr *E = ILE->getInit(I);
14885       if (!E)
14886         continue;
14887       Region = Tree.allocate(Parent);
14888       Elts.push_back(Region);
14889       Visit(E);
14890     }
14891 
14892     // Forget that the initializers are sequenced.
14893     Region = Parent;
14894     for (unsigned I = 0; I < Elts.size(); ++I)
14895       Tree.merge(Elts[I]);
14896   }
14897 };
14898 
14899 } // namespace
14900 
14901 void Sema::CheckUnsequencedOperations(const Expr *E) {
14902   SmallVector<const Expr *, 8> WorkList;
14903   WorkList.push_back(E);
14904   while (!WorkList.empty()) {
14905     const Expr *Item = WorkList.pop_back_val();
14906     SequenceChecker(*this, Item, WorkList);
14907   }
14908 }
14909 
14910 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
14911                               bool IsConstexpr) {
14912   llvm::SaveAndRestore<bool> ConstantContext(
14913       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
14914   CheckImplicitConversions(E, CheckLoc);
14915   if (!E->isInstantiationDependent())
14916     CheckUnsequencedOperations(E);
14917   if (!IsConstexpr && !E->isValueDependent())
14918     CheckForIntOverflow(E);
14919   DiagnoseMisalignedMembers();
14920 }
14921 
14922 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
14923                                        FieldDecl *BitField,
14924                                        Expr *Init) {
14925   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
14926 }
14927 
14928 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
14929                                          SourceLocation Loc) {
14930   if (!PType->isVariablyModifiedType())
14931     return;
14932   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
14933     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
14934     return;
14935   }
14936   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
14937     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
14938     return;
14939   }
14940   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
14941     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
14942     return;
14943   }
14944 
14945   const ArrayType *AT = S.Context.getAsArrayType(PType);
14946   if (!AT)
14947     return;
14948 
14949   if (AT->getSizeModifier() != ArrayType::Star) {
14950     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
14951     return;
14952   }
14953 
14954   S.Diag(Loc, diag::err_array_star_in_function_definition);
14955 }
14956 
14957 /// CheckParmsForFunctionDef - Check that the parameters of the given
14958 /// function are appropriate for the definition of a function. This
14959 /// takes care of any checks that cannot be performed on the
14960 /// declaration itself, e.g., that the types of each of the function
14961 /// parameters are complete.
14962 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
14963                                     bool CheckParameterNames) {
14964   bool HasInvalidParm = false;
14965   for (ParmVarDecl *Param : Parameters) {
14966     // C99 6.7.5.3p4: the parameters in a parameter type list in a
14967     // function declarator that is part of a function definition of
14968     // that function shall not have incomplete type.
14969     //
14970     // This is also C++ [dcl.fct]p6.
14971     if (!Param->isInvalidDecl() &&
14972         RequireCompleteType(Param->getLocation(), Param->getType(),
14973                             diag::err_typecheck_decl_incomplete_type)) {
14974       Param->setInvalidDecl();
14975       HasInvalidParm = true;
14976     }
14977 
14978     // C99 6.9.1p5: If the declarator includes a parameter type list, the
14979     // declaration of each parameter shall include an identifier.
14980     if (CheckParameterNames && Param->getIdentifier() == nullptr &&
14981         !Param->isImplicit() && !getLangOpts().CPlusPlus) {
14982       // Diagnose this as an extension in C17 and earlier.
14983       if (!getLangOpts().C2x)
14984         Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
14985     }
14986 
14987     // C99 6.7.5.3p12:
14988     //   If the function declarator is not part of a definition of that
14989     //   function, parameters may have incomplete type and may use the [*]
14990     //   notation in their sequences of declarator specifiers to specify
14991     //   variable length array types.
14992     QualType PType = Param->getOriginalType();
14993     // FIXME: This diagnostic should point the '[*]' if source-location
14994     // information is added for it.
14995     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
14996 
14997     // If the parameter is a c++ class type and it has to be destructed in the
14998     // callee function, declare the destructor so that it can be called by the
14999     // callee function. Do not perform any direct access check on the dtor here.
15000     if (!Param->isInvalidDecl()) {
15001       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
15002         if (!ClassDecl->isInvalidDecl() &&
15003             !ClassDecl->hasIrrelevantDestructor() &&
15004             !ClassDecl->isDependentContext() &&
15005             ClassDecl->isParamDestroyedInCallee()) {
15006           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
15007           MarkFunctionReferenced(Param->getLocation(), Destructor);
15008           DiagnoseUseOfDecl(Destructor, Param->getLocation());
15009         }
15010       }
15011     }
15012 
15013     // Parameters with the pass_object_size attribute only need to be marked
15014     // constant at function definitions. Because we lack information about
15015     // whether we're on a declaration or definition when we're instantiating the
15016     // attribute, we need to check for constness here.
15017     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
15018       if (!Param->getType().isConstQualified())
15019         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
15020             << Attr->getSpelling() << 1;
15021 
15022     // Check for parameter names shadowing fields from the class.
15023     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
15024       // The owning context for the parameter should be the function, but we
15025       // want to see if this function's declaration context is a record.
15026       DeclContext *DC = Param->getDeclContext();
15027       if (DC && DC->isFunctionOrMethod()) {
15028         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
15029           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
15030                                      RD, /*DeclIsField*/ false);
15031       }
15032     }
15033   }
15034 
15035   return HasInvalidParm;
15036 }
15037 
15038 Optional<std::pair<CharUnits, CharUnits>>
15039 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx);
15040 
15041 /// Compute the alignment and offset of the base class object given the
15042 /// derived-to-base cast expression and the alignment and offset of the derived
15043 /// class object.
15044 static std::pair<CharUnits, CharUnits>
15045 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
15046                                    CharUnits BaseAlignment, CharUnits Offset,
15047                                    ASTContext &Ctx) {
15048   for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
15049        ++PathI) {
15050     const CXXBaseSpecifier *Base = *PathI;
15051     const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
15052     if (Base->isVirtual()) {
15053       // The complete object may have a lower alignment than the non-virtual
15054       // alignment of the base, in which case the base may be misaligned. Choose
15055       // the smaller of the non-virtual alignment and BaseAlignment, which is a
15056       // conservative lower bound of the complete object alignment.
15057       CharUnits NonVirtualAlignment =
15058           Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment();
15059       BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
15060       Offset = CharUnits::Zero();
15061     } else {
15062       const ASTRecordLayout &RL =
15063           Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
15064       Offset += RL.getBaseClassOffset(BaseDecl);
15065     }
15066     DerivedType = Base->getType();
15067   }
15068 
15069   return std::make_pair(BaseAlignment, Offset);
15070 }
15071 
15072 /// Compute the alignment and offset of a binary additive operator.
15073 static Optional<std::pair<CharUnits, CharUnits>>
15074 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
15075                                      bool IsSub, ASTContext &Ctx) {
15076   QualType PointeeType = PtrE->getType()->getPointeeType();
15077 
15078   if (!PointeeType->isConstantSizeType())
15079     return llvm::None;
15080 
15081   auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
15082 
15083   if (!P)
15084     return llvm::None;
15085 
15086   CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
15087   if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
15088     CharUnits Offset = EltSize * IdxRes->getExtValue();
15089     if (IsSub)
15090       Offset = -Offset;
15091     return std::make_pair(P->first, P->second + Offset);
15092   }
15093 
15094   // If the integer expression isn't a constant expression, compute the lower
15095   // bound of the alignment using the alignment and offset of the pointer
15096   // expression and the element size.
15097   return std::make_pair(
15098       P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
15099       CharUnits::Zero());
15100 }
15101 
15102 /// This helper function takes an lvalue expression and returns the alignment of
15103 /// a VarDecl and a constant offset from the VarDecl.
15104 Optional<std::pair<CharUnits, CharUnits>>
15105 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) {
15106   E = E->IgnoreParens();
15107   switch (E->getStmtClass()) {
15108   default:
15109     break;
15110   case Stmt::CStyleCastExprClass:
15111   case Stmt::CXXStaticCastExprClass:
15112   case Stmt::ImplicitCastExprClass: {
15113     auto *CE = cast<CastExpr>(E);
15114     const Expr *From = CE->getSubExpr();
15115     switch (CE->getCastKind()) {
15116     default:
15117       break;
15118     case CK_NoOp:
15119       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15120     case CK_UncheckedDerivedToBase:
15121     case CK_DerivedToBase: {
15122       auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15123       if (!P)
15124         break;
15125       return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
15126                                                 P->second, Ctx);
15127     }
15128     }
15129     break;
15130   }
15131   case Stmt::ArraySubscriptExprClass: {
15132     auto *ASE = cast<ArraySubscriptExpr>(E);
15133     return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(),
15134                                                 false, Ctx);
15135   }
15136   case Stmt::DeclRefExprClass: {
15137     if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
15138       // FIXME: If VD is captured by copy or is an escaping __block variable,
15139       // use the alignment of VD's type.
15140       if (!VD->getType()->isReferenceType())
15141         return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
15142       if (VD->hasInit())
15143         return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
15144     }
15145     break;
15146   }
15147   case Stmt::MemberExprClass: {
15148     auto *ME = cast<MemberExpr>(E);
15149     auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
15150     if (!FD || FD->getType()->isReferenceType() ||
15151         FD->getParent()->isInvalidDecl())
15152       break;
15153     Optional<std::pair<CharUnits, CharUnits>> P;
15154     if (ME->isArrow())
15155       P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
15156     else
15157       P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
15158     if (!P)
15159       break;
15160     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
15161     uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
15162     return std::make_pair(P->first,
15163                           P->second + CharUnits::fromQuantity(Offset));
15164   }
15165   case Stmt::UnaryOperatorClass: {
15166     auto *UO = cast<UnaryOperator>(E);
15167     switch (UO->getOpcode()) {
15168     default:
15169       break;
15170     case UO_Deref:
15171       return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx);
15172     }
15173     break;
15174   }
15175   case Stmt::BinaryOperatorClass: {
15176     auto *BO = cast<BinaryOperator>(E);
15177     auto Opcode = BO->getOpcode();
15178     switch (Opcode) {
15179     default:
15180       break;
15181     case BO_Comma:
15182       return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx);
15183     }
15184     break;
15185   }
15186   }
15187   return llvm::None;
15188 }
15189 
15190 /// This helper function takes a pointer expression and returns the alignment of
15191 /// a VarDecl and a constant offset from the VarDecl.
15192 Optional<std::pair<CharUnits, CharUnits>>
15193 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) {
15194   E = E->IgnoreParens();
15195   switch (E->getStmtClass()) {
15196   default:
15197     break;
15198   case Stmt::CStyleCastExprClass:
15199   case Stmt::CXXStaticCastExprClass:
15200   case Stmt::ImplicitCastExprClass: {
15201     auto *CE = cast<CastExpr>(E);
15202     const Expr *From = CE->getSubExpr();
15203     switch (CE->getCastKind()) {
15204     default:
15205       break;
15206     case CK_NoOp:
15207       return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
15208     case CK_ArrayToPointerDecay:
15209       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15210     case CK_UncheckedDerivedToBase:
15211     case CK_DerivedToBase: {
15212       auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
15213       if (!P)
15214         break;
15215       return getDerivedToBaseAlignmentAndOffset(
15216           CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
15217     }
15218     }
15219     break;
15220   }
15221   case Stmt::CXXThisExprClass: {
15222     auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
15223     CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment();
15224     return std::make_pair(Alignment, CharUnits::Zero());
15225   }
15226   case Stmt::UnaryOperatorClass: {
15227     auto *UO = cast<UnaryOperator>(E);
15228     if (UO->getOpcode() == UO_AddrOf)
15229       return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx);
15230     break;
15231   }
15232   case Stmt::BinaryOperatorClass: {
15233     auto *BO = cast<BinaryOperator>(E);
15234     auto Opcode = BO->getOpcode();
15235     switch (Opcode) {
15236     default:
15237       break;
15238     case BO_Add:
15239     case BO_Sub: {
15240       const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
15241       if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
15242         std::swap(LHS, RHS);
15243       return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
15244                                                   Ctx);
15245     }
15246     case BO_Comma:
15247       return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
15248     }
15249     break;
15250   }
15251   }
15252   return llvm::None;
15253 }
15254 
15255 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
15256   // See if we can compute the alignment of a VarDecl and an offset from it.
15257   Optional<std::pair<CharUnits, CharUnits>> P =
15258       getBaseAlignmentAndOffsetFromPtr(E, S.Context);
15259 
15260   if (P)
15261     return P->first.alignmentAtOffset(P->second);
15262 
15263   // If that failed, return the type's alignment.
15264   return S.Context.getTypeAlignInChars(E->getType()->getPointeeType());
15265 }
15266 
15267 /// CheckCastAlign - Implements -Wcast-align, which warns when a
15268 /// pointer cast increases the alignment requirements.
15269 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
15270   // This is actually a lot of work to potentially be doing on every
15271   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
15272   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
15273     return;
15274 
15275   // Ignore dependent types.
15276   if (T->isDependentType() || Op->getType()->isDependentType())
15277     return;
15278 
15279   // Require that the destination be a pointer type.
15280   const PointerType *DestPtr = T->getAs<PointerType>();
15281   if (!DestPtr) return;
15282 
15283   // If the destination has alignment 1, we're done.
15284   QualType DestPointee = DestPtr->getPointeeType();
15285   if (DestPointee->isIncompleteType()) return;
15286   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
15287   if (DestAlign.isOne()) return;
15288 
15289   // Require that the source be a pointer type.
15290   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
15291   if (!SrcPtr) return;
15292   QualType SrcPointee = SrcPtr->getPointeeType();
15293 
15294   // Explicitly allow casts from cv void*.  We already implicitly
15295   // allowed casts to cv void*, since they have alignment 1.
15296   // Also allow casts involving incomplete types, which implicitly
15297   // includes 'void'.
15298   if (SrcPointee->isIncompleteType()) return;
15299 
15300   CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
15301 
15302   if (SrcAlign >= DestAlign) return;
15303 
15304   Diag(TRange.getBegin(), diag::warn_cast_align)
15305     << Op->getType() << T
15306     << static_cast<unsigned>(SrcAlign.getQuantity())
15307     << static_cast<unsigned>(DestAlign.getQuantity())
15308     << TRange << Op->getSourceRange();
15309 }
15310 
15311 /// Check whether this array fits the idiom of a size-one tail padded
15312 /// array member of a struct.
15313 ///
15314 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
15315 /// commonly used to emulate flexible arrays in C89 code.
15316 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
15317                                     const NamedDecl *ND) {
15318   if (Size != 1 || !ND) return false;
15319 
15320   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
15321   if (!FD) return false;
15322 
15323   // Don't consider sizes resulting from macro expansions or template argument
15324   // substitution to form C89 tail-padded arrays.
15325 
15326   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
15327   while (TInfo) {
15328     TypeLoc TL = TInfo->getTypeLoc();
15329     // Look through typedefs.
15330     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
15331       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
15332       TInfo = TDL->getTypeSourceInfo();
15333       continue;
15334     }
15335     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
15336       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
15337       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
15338         return false;
15339     }
15340     break;
15341   }
15342 
15343   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
15344   if (!RD) return false;
15345   if (RD->isUnion()) return false;
15346   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
15347     if (!CRD->isStandardLayout()) return false;
15348   }
15349 
15350   // See if this is the last field decl in the record.
15351   const Decl *D = FD;
15352   while ((D = D->getNextDeclInContext()))
15353     if (isa<FieldDecl>(D))
15354       return false;
15355   return true;
15356 }
15357 
15358 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
15359                             const ArraySubscriptExpr *ASE,
15360                             bool AllowOnePastEnd, bool IndexNegated) {
15361   // Already diagnosed by the constant evaluator.
15362   if (isConstantEvaluated())
15363     return;
15364 
15365   IndexExpr = IndexExpr->IgnoreParenImpCasts();
15366   if (IndexExpr->isValueDependent())
15367     return;
15368 
15369   const Type *EffectiveType =
15370       BaseExpr->getType()->getPointeeOrArrayElementType();
15371   BaseExpr = BaseExpr->IgnoreParenCasts();
15372   const ConstantArrayType *ArrayTy =
15373       Context.getAsConstantArrayType(BaseExpr->getType());
15374 
15375   const Type *BaseType =
15376       ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
15377   bool IsUnboundedArray = (BaseType == nullptr);
15378   if (EffectiveType->isDependentType() ||
15379       (!IsUnboundedArray && BaseType->isDependentType()))
15380     return;
15381 
15382   Expr::EvalResult Result;
15383   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
15384     return;
15385 
15386   llvm::APSInt index = Result.Val.getInt();
15387   if (IndexNegated) {
15388     index.setIsUnsigned(false);
15389     index = -index;
15390   }
15391 
15392   const NamedDecl *ND = nullptr;
15393   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15394     ND = DRE->getDecl();
15395   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
15396     ND = ME->getMemberDecl();
15397 
15398   if (IsUnboundedArray) {
15399     if (index.isUnsigned() || !index.isNegative()) {
15400       const auto &ASTC = getASTContext();
15401       unsigned AddrBits =
15402           ASTC.getTargetInfo().getPointerWidth(ASTC.getTargetAddressSpace(
15403               EffectiveType->getCanonicalTypeInternal()));
15404       if (index.getBitWidth() < AddrBits)
15405         index = index.zext(AddrBits);
15406       Optional<CharUnits> ElemCharUnits =
15407           ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
15408       // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
15409       // pointer) bounds-checking isn't meaningful.
15410       if (!ElemCharUnits)
15411         return;
15412       llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
15413       // If index has more active bits than address space, we already know
15414       // we have a bounds violation to warn about.  Otherwise, compute
15415       // address of (index + 1)th element, and warn about bounds violation
15416       // only if that address exceeds address space.
15417       if (index.getActiveBits() <= AddrBits) {
15418         bool Overflow;
15419         llvm::APInt Product(index);
15420         Product += 1;
15421         Product = Product.umul_ov(ElemBytes, Overflow);
15422         if (!Overflow && Product.getActiveBits() <= AddrBits)
15423           return;
15424       }
15425 
15426       // Need to compute max possible elements in address space, since that
15427       // is included in diag message.
15428       llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
15429       MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
15430       MaxElems += 1;
15431       ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
15432       MaxElems = MaxElems.udiv(ElemBytes);
15433 
15434       unsigned DiagID =
15435           ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
15436               : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
15437 
15438       // Diag message shows element size in bits and in "bytes" (platform-
15439       // dependent CharUnits)
15440       DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15441                           PDiag(DiagID)
15442                               << toString(index, 10, true) << AddrBits
15443                               << (unsigned)ASTC.toBits(*ElemCharUnits)
15444                               << toString(ElemBytes, 10, false)
15445                               << toString(MaxElems, 10, false)
15446                               << (unsigned)MaxElems.getLimitedValue(~0U)
15447                               << IndexExpr->getSourceRange());
15448 
15449       if (!ND) {
15450         // Try harder to find a NamedDecl to point at in the note.
15451         while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15452           BaseExpr = ASE->getBase()->IgnoreParenCasts();
15453         if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15454           ND = DRE->getDecl();
15455         if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15456           ND = ME->getMemberDecl();
15457       }
15458 
15459       if (ND)
15460         DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15461                             PDiag(diag::note_array_declared_here) << ND);
15462     }
15463     return;
15464   }
15465 
15466   if (index.isUnsigned() || !index.isNegative()) {
15467     // It is possible that the type of the base expression after
15468     // IgnoreParenCasts is incomplete, even though the type of the base
15469     // expression before IgnoreParenCasts is complete (see PR39746 for an
15470     // example). In this case we have no information about whether the array
15471     // access exceeds the array bounds. However we can still diagnose an array
15472     // access which precedes the array bounds.
15473     if (BaseType->isIncompleteType())
15474       return;
15475 
15476     llvm::APInt size = ArrayTy->getSize();
15477     if (!size.isStrictlyPositive())
15478       return;
15479 
15480     if (BaseType != EffectiveType) {
15481       // Make sure we're comparing apples to apples when comparing index to size
15482       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
15483       uint64_t array_typesize = Context.getTypeSize(BaseType);
15484       // Handle ptrarith_typesize being zero, such as when casting to void*
15485       if (!ptrarith_typesize) ptrarith_typesize = 1;
15486       if (ptrarith_typesize != array_typesize) {
15487         // There's a cast to a different size type involved
15488         uint64_t ratio = array_typesize / ptrarith_typesize;
15489         // TODO: Be smarter about handling cases where array_typesize is not a
15490         // multiple of ptrarith_typesize
15491         if (ptrarith_typesize * ratio == array_typesize)
15492           size *= llvm::APInt(size.getBitWidth(), ratio);
15493       }
15494     }
15495 
15496     if (size.getBitWidth() > index.getBitWidth())
15497       index = index.zext(size.getBitWidth());
15498     else if (size.getBitWidth() < index.getBitWidth())
15499       size = size.zext(index.getBitWidth());
15500 
15501     // For array subscripting the index must be less than size, but for pointer
15502     // arithmetic also allow the index (offset) to be equal to size since
15503     // computing the next address after the end of the array is legal and
15504     // commonly done e.g. in C++ iterators and range-based for loops.
15505     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
15506       return;
15507 
15508     // Also don't warn for arrays of size 1 which are members of some
15509     // structure. These are often used to approximate flexible arrays in C89
15510     // code.
15511     if (IsTailPaddedMemberArray(*this, size, ND))
15512       return;
15513 
15514     // Suppress the warning if the subscript expression (as identified by the
15515     // ']' location) and the index expression are both from macro expansions
15516     // within a system header.
15517     if (ASE) {
15518       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
15519           ASE->getRBracketLoc());
15520       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
15521         SourceLocation IndexLoc =
15522             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
15523         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
15524           return;
15525       }
15526     }
15527 
15528     unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
15529                           : diag::warn_ptr_arith_exceeds_bounds;
15530 
15531     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15532                         PDiag(DiagID) << toString(index, 10, true)
15533                                       << toString(size, 10, true)
15534                                       << (unsigned)size.getLimitedValue(~0U)
15535                                       << IndexExpr->getSourceRange());
15536   } else {
15537     unsigned DiagID = diag::warn_array_index_precedes_bounds;
15538     if (!ASE) {
15539       DiagID = diag::warn_ptr_arith_precedes_bounds;
15540       if (index.isNegative()) index = -index;
15541     }
15542 
15543     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15544                         PDiag(DiagID) << toString(index, 10, true)
15545                                       << IndexExpr->getSourceRange());
15546   }
15547 
15548   if (!ND) {
15549     // Try harder to find a NamedDecl to point at in the note.
15550     while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15551       BaseExpr = ASE->getBase()->IgnoreParenCasts();
15552     if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15553       ND = DRE->getDecl();
15554     if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15555       ND = ME->getMemberDecl();
15556   }
15557 
15558   if (ND)
15559     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15560                         PDiag(diag::note_array_declared_here) << ND);
15561 }
15562 
15563 void Sema::CheckArrayAccess(const Expr *expr) {
15564   int AllowOnePastEnd = 0;
15565   while (expr) {
15566     expr = expr->IgnoreParenImpCasts();
15567     switch (expr->getStmtClass()) {
15568       case Stmt::ArraySubscriptExprClass: {
15569         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
15570         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
15571                          AllowOnePastEnd > 0);
15572         expr = ASE->getBase();
15573         break;
15574       }
15575       case Stmt::MemberExprClass: {
15576         expr = cast<MemberExpr>(expr)->getBase();
15577         break;
15578       }
15579       case Stmt::OMPArraySectionExprClass: {
15580         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
15581         if (ASE->getLowerBound())
15582           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
15583                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
15584         return;
15585       }
15586       case Stmt::UnaryOperatorClass: {
15587         // Only unwrap the * and & unary operators
15588         const UnaryOperator *UO = cast<UnaryOperator>(expr);
15589         expr = UO->getSubExpr();
15590         switch (UO->getOpcode()) {
15591           case UO_AddrOf:
15592             AllowOnePastEnd++;
15593             break;
15594           case UO_Deref:
15595             AllowOnePastEnd--;
15596             break;
15597           default:
15598             return;
15599         }
15600         break;
15601       }
15602       case Stmt::ConditionalOperatorClass: {
15603         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
15604         if (const Expr *lhs = cond->getLHS())
15605           CheckArrayAccess(lhs);
15606         if (const Expr *rhs = cond->getRHS())
15607           CheckArrayAccess(rhs);
15608         return;
15609       }
15610       case Stmt::CXXOperatorCallExprClass: {
15611         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
15612         for (const auto *Arg : OCE->arguments())
15613           CheckArrayAccess(Arg);
15614         return;
15615       }
15616       default:
15617         return;
15618     }
15619   }
15620 }
15621 
15622 //===--- CHECK: Objective-C retain cycles ----------------------------------//
15623 
15624 namespace {
15625 
15626 struct RetainCycleOwner {
15627   VarDecl *Variable = nullptr;
15628   SourceRange Range;
15629   SourceLocation Loc;
15630   bool Indirect = false;
15631 
15632   RetainCycleOwner() = default;
15633 
15634   void setLocsFrom(Expr *e) {
15635     Loc = e->getExprLoc();
15636     Range = e->getSourceRange();
15637   }
15638 };
15639 
15640 } // namespace
15641 
15642 /// Consider whether capturing the given variable can possibly lead to
15643 /// a retain cycle.
15644 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
15645   // In ARC, it's captured strongly iff the variable has __strong
15646   // lifetime.  In MRR, it's captured strongly if the variable is
15647   // __block and has an appropriate type.
15648   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
15649     return false;
15650 
15651   owner.Variable = var;
15652   if (ref)
15653     owner.setLocsFrom(ref);
15654   return true;
15655 }
15656 
15657 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
15658   while (true) {
15659     e = e->IgnoreParens();
15660     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
15661       switch (cast->getCastKind()) {
15662       case CK_BitCast:
15663       case CK_LValueBitCast:
15664       case CK_LValueToRValue:
15665       case CK_ARCReclaimReturnedObject:
15666         e = cast->getSubExpr();
15667         continue;
15668 
15669       default:
15670         return false;
15671       }
15672     }
15673 
15674     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
15675       ObjCIvarDecl *ivar = ref->getDecl();
15676       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
15677         return false;
15678 
15679       // Try to find a retain cycle in the base.
15680       if (!findRetainCycleOwner(S, ref->getBase(), owner))
15681         return false;
15682 
15683       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
15684       owner.Indirect = true;
15685       return true;
15686     }
15687 
15688     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
15689       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
15690       if (!var) return false;
15691       return considerVariable(var, ref, owner);
15692     }
15693 
15694     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
15695       if (member->isArrow()) return false;
15696 
15697       // Don't count this as an indirect ownership.
15698       e = member->getBase();
15699       continue;
15700     }
15701 
15702     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
15703       // Only pay attention to pseudo-objects on property references.
15704       ObjCPropertyRefExpr *pre
15705         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
15706                                               ->IgnoreParens());
15707       if (!pre) return false;
15708       if (pre->isImplicitProperty()) return false;
15709       ObjCPropertyDecl *property = pre->getExplicitProperty();
15710       if (!property->isRetaining() &&
15711           !(property->getPropertyIvarDecl() &&
15712             property->getPropertyIvarDecl()->getType()
15713               .getObjCLifetime() == Qualifiers::OCL_Strong))
15714           return false;
15715 
15716       owner.Indirect = true;
15717       if (pre->isSuperReceiver()) {
15718         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
15719         if (!owner.Variable)
15720           return false;
15721         owner.Loc = pre->getLocation();
15722         owner.Range = pre->getSourceRange();
15723         return true;
15724       }
15725       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
15726                               ->getSourceExpr());
15727       continue;
15728     }
15729 
15730     // Array ivars?
15731 
15732     return false;
15733   }
15734 }
15735 
15736 namespace {
15737 
15738   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
15739     ASTContext &Context;
15740     VarDecl *Variable;
15741     Expr *Capturer = nullptr;
15742     bool VarWillBeReased = false;
15743 
15744     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
15745         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
15746           Context(Context), Variable(variable) {}
15747 
15748     void VisitDeclRefExpr(DeclRefExpr *ref) {
15749       if (ref->getDecl() == Variable && !Capturer)
15750         Capturer = ref;
15751     }
15752 
15753     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
15754       if (Capturer) return;
15755       Visit(ref->getBase());
15756       if (Capturer && ref->isFreeIvar())
15757         Capturer = ref;
15758     }
15759 
15760     void VisitBlockExpr(BlockExpr *block) {
15761       // Look inside nested blocks
15762       if (block->getBlockDecl()->capturesVariable(Variable))
15763         Visit(block->getBlockDecl()->getBody());
15764     }
15765 
15766     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
15767       if (Capturer) return;
15768       if (OVE->getSourceExpr())
15769         Visit(OVE->getSourceExpr());
15770     }
15771 
15772     void VisitBinaryOperator(BinaryOperator *BinOp) {
15773       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
15774         return;
15775       Expr *LHS = BinOp->getLHS();
15776       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
15777         if (DRE->getDecl() != Variable)
15778           return;
15779         if (Expr *RHS = BinOp->getRHS()) {
15780           RHS = RHS->IgnoreParenCasts();
15781           Optional<llvm::APSInt> Value;
15782           VarWillBeReased =
15783               (RHS && (Value = RHS->getIntegerConstantExpr(Context)) &&
15784                *Value == 0);
15785         }
15786       }
15787     }
15788   };
15789 
15790 } // namespace
15791 
15792 /// Check whether the given argument is a block which captures a
15793 /// variable.
15794 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
15795   assert(owner.Variable && owner.Loc.isValid());
15796 
15797   e = e->IgnoreParenCasts();
15798 
15799   // Look through [^{...} copy] and Block_copy(^{...}).
15800   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
15801     Selector Cmd = ME->getSelector();
15802     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
15803       e = ME->getInstanceReceiver();
15804       if (!e)
15805         return nullptr;
15806       e = e->IgnoreParenCasts();
15807     }
15808   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
15809     if (CE->getNumArgs() == 1) {
15810       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
15811       if (Fn) {
15812         const IdentifierInfo *FnI = Fn->getIdentifier();
15813         if (FnI && FnI->isStr("_Block_copy")) {
15814           e = CE->getArg(0)->IgnoreParenCasts();
15815         }
15816       }
15817     }
15818   }
15819 
15820   BlockExpr *block = dyn_cast<BlockExpr>(e);
15821   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
15822     return nullptr;
15823 
15824   FindCaptureVisitor visitor(S.Context, owner.Variable);
15825   visitor.Visit(block->getBlockDecl()->getBody());
15826   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
15827 }
15828 
15829 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
15830                                 RetainCycleOwner &owner) {
15831   assert(capturer);
15832   assert(owner.Variable && owner.Loc.isValid());
15833 
15834   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
15835     << owner.Variable << capturer->getSourceRange();
15836   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
15837     << owner.Indirect << owner.Range;
15838 }
15839 
15840 /// Check for a keyword selector that starts with the word 'add' or
15841 /// 'set'.
15842 static bool isSetterLikeSelector(Selector sel) {
15843   if (sel.isUnarySelector()) return false;
15844 
15845   StringRef str = sel.getNameForSlot(0);
15846   while (!str.empty() && str.front() == '_') str = str.substr(1);
15847   if (str.startswith("set"))
15848     str = str.substr(3);
15849   else if (str.startswith("add")) {
15850     // Specially allow 'addOperationWithBlock:'.
15851     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
15852       return false;
15853     str = str.substr(3);
15854   }
15855   else
15856     return false;
15857 
15858   if (str.empty()) return true;
15859   return !isLowercase(str.front());
15860 }
15861 
15862 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
15863                                                     ObjCMessageExpr *Message) {
15864   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
15865                                                 Message->getReceiverInterface(),
15866                                                 NSAPI::ClassId_NSMutableArray);
15867   if (!IsMutableArray) {
15868     return None;
15869   }
15870 
15871   Selector Sel = Message->getSelector();
15872 
15873   Optional<NSAPI::NSArrayMethodKind> MKOpt =
15874     S.NSAPIObj->getNSArrayMethodKind(Sel);
15875   if (!MKOpt) {
15876     return None;
15877   }
15878 
15879   NSAPI::NSArrayMethodKind MK = *MKOpt;
15880 
15881   switch (MK) {
15882     case NSAPI::NSMutableArr_addObject:
15883     case NSAPI::NSMutableArr_insertObjectAtIndex:
15884     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
15885       return 0;
15886     case NSAPI::NSMutableArr_replaceObjectAtIndex:
15887       return 1;
15888 
15889     default:
15890       return None;
15891   }
15892 
15893   return None;
15894 }
15895 
15896 static
15897 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
15898                                                   ObjCMessageExpr *Message) {
15899   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
15900                                             Message->getReceiverInterface(),
15901                                             NSAPI::ClassId_NSMutableDictionary);
15902   if (!IsMutableDictionary) {
15903     return None;
15904   }
15905 
15906   Selector Sel = Message->getSelector();
15907 
15908   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
15909     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
15910   if (!MKOpt) {
15911     return None;
15912   }
15913 
15914   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
15915 
15916   switch (MK) {
15917     case NSAPI::NSMutableDict_setObjectForKey:
15918     case NSAPI::NSMutableDict_setValueForKey:
15919     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
15920       return 0;
15921 
15922     default:
15923       return None;
15924   }
15925 
15926   return None;
15927 }
15928 
15929 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
15930   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
15931                                                 Message->getReceiverInterface(),
15932                                                 NSAPI::ClassId_NSMutableSet);
15933 
15934   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
15935                                             Message->getReceiverInterface(),
15936                                             NSAPI::ClassId_NSMutableOrderedSet);
15937   if (!IsMutableSet && !IsMutableOrderedSet) {
15938     return None;
15939   }
15940 
15941   Selector Sel = Message->getSelector();
15942 
15943   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
15944   if (!MKOpt) {
15945     return None;
15946   }
15947 
15948   NSAPI::NSSetMethodKind MK = *MKOpt;
15949 
15950   switch (MK) {
15951     case NSAPI::NSMutableSet_addObject:
15952     case NSAPI::NSOrderedSet_setObjectAtIndex:
15953     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
15954     case NSAPI::NSOrderedSet_insertObjectAtIndex:
15955       return 0;
15956     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
15957       return 1;
15958   }
15959 
15960   return None;
15961 }
15962 
15963 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
15964   if (!Message->isInstanceMessage()) {
15965     return;
15966   }
15967 
15968   Optional<int> ArgOpt;
15969 
15970   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
15971       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
15972       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
15973     return;
15974   }
15975 
15976   int ArgIndex = *ArgOpt;
15977 
15978   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
15979   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
15980     Arg = OE->getSourceExpr()->IgnoreImpCasts();
15981   }
15982 
15983   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
15984     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
15985       if (ArgRE->isObjCSelfExpr()) {
15986         Diag(Message->getSourceRange().getBegin(),
15987              diag::warn_objc_circular_container)
15988           << ArgRE->getDecl() << StringRef("'super'");
15989       }
15990     }
15991   } else {
15992     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
15993 
15994     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
15995       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
15996     }
15997 
15998     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
15999       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
16000         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
16001           ValueDecl *Decl = ReceiverRE->getDecl();
16002           Diag(Message->getSourceRange().getBegin(),
16003                diag::warn_objc_circular_container)
16004             << Decl << Decl;
16005           if (!ArgRE->isObjCSelfExpr()) {
16006             Diag(Decl->getLocation(),
16007                  diag::note_objc_circular_container_declared_here)
16008               << Decl;
16009           }
16010         }
16011       }
16012     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
16013       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
16014         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
16015           ObjCIvarDecl *Decl = IvarRE->getDecl();
16016           Diag(Message->getSourceRange().getBegin(),
16017                diag::warn_objc_circular_container)
16018             << Decl << Decl;
16019           Diag(Decl->getLocation(),
16020                diag::note_objc_circular_container_declared_here)
16021             << Decl;
16022         }
16023       }
16024     }
16025   }
16026 }
16027 
16028 /// Check a message send to see if it's likely to cause a retain cycle.
16029 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
16030   // Only check instance methods whose selector looks like a setter.
16031   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
16032     return;
16033 
16034   // Try to find a variable that the receiver is strongly owned by.
16035   RetainCycleOwner owner;
16036   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
16037     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
16038       return;
16039   } else {
16040     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
16041     owner.Variable = getCurMethodDecl()->getSelfDecl();
16042     owner.Loc = msg->getSuperLoc();
16043     owner.Range = msg->getSuperLoc();
16044   }
16045 
16046   // Check whether the receiver is captured by any of the arguments.
16047   const ObjCMethodDecl *MD = msg->getMethodDecl();
16048   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
16049     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
16050       // noescape blocks should not be retained by the method.
16051       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
16052         continue;
16053       return diagnoseRetainCycle(*this, capturer, owner);
16054     }
16055   }
16056 }
16057 
16058 /// Check a property assign to see if it's likely to cause a retain cycle.
16059 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
16060   RetainCycleOwner owner;
16061   if (!findRetainCycleOwner(*this, receiver, owner))
16062     return;
16063 
16064   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
16065     diagnoseRetainCycle(*this, capturer, owner);
16066 }
16067 
16068 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
16069   RetainCycleOwner Owner;
16070   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
16071     return;
16072 
16073   // Because we don't have an expression for the variable, we have to set the
16074   // location explicitly here.
16075   Owner.Loc = Var->getLocation();
16076   Owner.Range = Var->getSourceRange();
16077 
16078   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
16079     diagnoseRetainCycle(*this, Capturer, Owner);
16080 }
16081 
16082 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
16083                                      Expr *RHS, bool isProperty) {
16084   // Check if RHS is an Objective-C object literal, which also can get
16085   // immediately zapped in a weak reference.  Note that we explicitly
16086   // allow ObjCStringLiterals, since those are designed to never really die.
16087   RHS = RHS->IgnoreParenImpCasts();
16088 
16089   // This enum needs to match with the 'select' in
16090   // warn_objc_arc_literal_assign (off-by-1).
16091   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
16092   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
16093     return false;
16094 
16095   S.Diag(Loc, diag::warn_arc_literal_assign)
16096     << (unsigned) Kind
16097     << (isProperty ? 0 : 1)
16098     << RHS->getSourceRange();
16099 
16100   return true;
16101 }
16102 
16103 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
16104                                     Qualifiers::ObjCLifetime LT,
16105                                     Expr *RHS, bool isProperty) {
16106   // Strip off any implicit cast added to get to the one ARC-specific.
16107   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
16108     if (cast->getCastKind() == CK_ARCConsumeObject) {
16109       S.Diag(Loc, diag::warn_arc_retained_assign)
16110         << (LT == Qualifiers::OCL_ExplicitNone)
16111         << (isProperty ? 0 : 1)
16112         << RHS->getSourceRange();
16113       return true;
16114     }
16115     RHS = cast->getSubExpr();
16116   }
16117 
16118   if (LT == Qualifiers::OCL_Weak &&
16119       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
16120     return true;
16121 
16122   return false;
16123 }
16124 
16125 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
16126                               QualType LHS, Expr *RHS) {
16127   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
16128 
16129   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
16130     return false;
16131 
16132   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
16133     return true;
16134 
16135   return false;
16136 }
16137 
16138 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
16139                               Expr *LHS, Expr *RHS) {
16140   QualType LHSType;
16141   // PropertyRef on LHS type need be directly obtained from
16142   // its declaration as it has a PseudoType.
16143   ObjCPropertyRefExpr *PRE
16144     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
16145   if (PRE && !PRE->isImplicitProperty()) {
16146     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
16147     if (PD)
16148       LHSType = PD->getType();
16149   }
16150 
16151   if (LHSType.isNull())
16152     LHSType = LHS->getType();
16153 
16154   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
16155 
16156   if (LT == Qualifiers::OCL_Weak) {
16157     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
16158       getCurFunction()->markSafeWeakUse(LHS);
16159   }
16160 
16161   if (checkUnsafeAssigns(Loc, LHSType, RHS))
16162     return;
16163 
16164   // FIXME. Check for other life times.
16165   if (LT != Qualifiers::OCL_None)
16166     return;
16167 
16168   if (PRE) {
16169     if (PRE->isImplicitProperty())
16170       return;
16171     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
16172     if (!PD)
16173       return;
16174 
16175     unsigned Attributes = PD->getPropertyAttributes();
16176     if (Attributes & ObjCPropertyAttribute::kind_assign) {
16177       // when 'assign' attribute was not explicitly specified
16178       // by user, ignore it and rely on property type itself
16179       // for lifetime info.
16180       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
16181       if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
16182           LHSType->isObjCRetainableType())
16183         return;
16184 
16185       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
16186         if (cast->getCastKind() == CK_ARCConsumeObject) {
16187           Diag(Loc, diag::warn_arc_retained_property_assign)
16188           << RHS->getSourceRange();
16189           return;
16190         }
16191         RHS = cast->getSubExpr();
16192       }
16193     } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
16194       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
16195         return;
16196     }
16197   }
16198 }
16199 
16200 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
16201 
16202 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
16203                                         SourceLocation StmtLoc,
16204                                         const NullStmt *Body) {
16205   // Do not warn if the body is a macro that expands to nothing, e.g:
16206   //
16207   // #define CALL(x)
16208   // if (condition)
16209   //   CALL(0);
16210   if (Body->hasLeadingEmptyMacro())
16211     return false;
16212 
16213   // Get line numbers of statement and body.
16214   bool StmtLineInvalid;
16215   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
16216                                                       &StmtLineInvalid);
16217   if (StmtLineInvalid)
16218     return false;
16219 
16220   bool BodyLineInvalid;
16221   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
16222                                                       &BodyLineInvalid);
16223   if (BodyLineInvalid)
16224     return false;
16225 
16226   // Warn if null statement and body are on the same line.
16227   if (StmtLine != BodyLine)
16228     return false;
16229 
16230   return true;
16231 }
16232 
16233 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
16234                                  const Stmt *Body,
16235                                  unsigned DiagID) {
16236   // Since this is a syntactic check, don't emit diagnostic for template
16237   // instantiations, this just adds noise.
16238   if (CurrentInstantiationScope)
16239     return;
16240 
16241   // The body should be a null statement.
16242   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
16243   if (!NBody)
16244     return;
16245 
16246   // Do the usual checks.
16247   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
16248     return;
16249 
16250   Diag(NBody->getSemiLoc(), DiagID);
16251   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
16252 }
16253 
16254 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
16255                                  const Stmt *PossibleBody) {
16256   assert(!CurrentInstantiationScope); // Ensured by caller
16257 
16258   SourceLocation StmtLoc;
16259   const Stmt *Body;
16260   unsigned DiagID;
16261   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
16262     StmtLoc = FS->getRParenLoc();
16263     Body = FS->getBody();
16264     DiagID = diag::warn_empty_for_body;
16265   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
16266     StmtLoc = WS->getCond()->getSourceRange().getEnd();
16267     Body = WS->getBody();
16268     DiagID = diag::warn_empty_while_body;
16269   } else
16270     return; // Neither `for' nor `while'.
16271 
16272   // The body should be a null statement.
16273   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
16274   if (!NBody)
16275     return;
16276 
16277   // Skip expensive checks if diagnostic is disabled.
16278   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
16279     return;
16280 
16281   // Do the usual checks.
16282   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
16283     return;
16284 
16285   // `for(...);' and `while(...);' are popular idioms, so in order to keep
16286   // noise level low, emit diagnostics only if for/while is followed by a
16287   // CompoundStmt, e.g.:
16288   //    for (int i = 0; i < n; i++);
16289   //    {
16290   //      a(i);
16291   //    }
16292   // or if for/while is followed by a statement with more indentation
16293   // than for/while itself:
16294   //    for (int i = 0; i < n; i++);
16295   //      a(i);
16296   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
16297   if (!ProbableTypo) {
16298     bool BodyColInvalid;
16299     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
16300         PossibleBody->getBeginLoc(), &BodyColInvalid);
16301     if (BodyColInvalid)
16302       return;
16303 
16304     bool StmtColInvalid;
16305     unsigned StmtCol =
16306         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
16307     if (StmtColInvalid)
16308       return;
16309 
16310     if (BodyCol > StmtCol)
16311       ProbableTypo = true;
16312   }
16313 
16314   if (ProbableTypo) {
16315     Diag(NBody->getSemiLoc(), DiagID);
16316     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
16317   }
16318 }
16319 
16320 //===--- CHECK: Warn on self move with std::move. -------------------------===//
16321 
16322 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
16323 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
16324                              SourceLocation OpLoc) {
16325   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
16326     return;
16327 
16328   if (inTemplateInstantiation())
16329     return;
16330 
16331   // Strip parens and casts away.
16332   LHSExpr = LHSExpr->IgnoreParenImpCasts();
16333   RHSExpr = RHSExpr->IgnoreParenImpCasts();
16334 
16335   // Check for a call expression
16336   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
16337   if (!CE || CE->getNumArgs() != 1)
16338     return;
16339 
16340   // Check for a call to std::move
16341   if (!CE->isCallToStdMove())
16342     return;
16343 
16344   // Get argument from std::move
16345   RHSExpr = CE->getArg(0);
16346 
16347   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
16348   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
16349 
16350   // Two DeclRefExpr's, check that the decls are the same.
16351   if (LHSDeclRef && RHSDeclRef) {
16352     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16353       return;
16354     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16355         RHSDeclRef->getDecl()->getCanonicalDecl())
16356       return;
16357 
16358     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
16359                                         << LHSExpr->getSourceRange()
16360                                         << RHSExpr->getSourceRange();
16361     return;
16362   }
16363 
16364   // Member variables require a different approach to check for self moves.
16365   // MemberExpr's are the same if every nested MemberExpr refers to the same
16366   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
16367   // the base Expr's are CXXThisExpr's.
16368   const Expr *LHSBase = LHSExpr;
16369   const Expr *RHSBase = RHSExpr;
16370   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
16371   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
16372   if (!LHSME || !RHSME)
16373     return;
16374 
16375   while (LHSME && RHSME) {
16376     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
16377         RHSME->getMemberDecl()->getCanonicalDecl())
16378       return;
16379 
16380     LHSBase = LHSME->getBase();
16381     RHSBase = RHSME->getBase();
16382     LHSME = dyn_cast<MemberExpr>(LHSBase);
16383     RHSME = dyn_cast<MemberExpr>(RHSBase);
16384   }
16385 
16386   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
16387   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
16388   if (LHSDeclRef && RHSDeclRef) {
16389     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16390       return;
16391     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16392         RHSDeclRef->getDecl()->getCanonicalDecl())
16393       return;
16394 
16395     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
16396                                         << LHSExpr->getSourceRange()
16397                                         << RHSExpr->getSourceRange();
16398     return;
16399   }
16400 
16401   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
16402     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
16403                                         << LHSExpr->getSourceRange()
16404                                         << RHSExpr->getSourceRange();
16405 }
16406 
16407 //===--- Layout compatibility ----------------------------------------------//
16408 
16409 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
16410 
16411 /// Check if two enumeration types are layout-compatible.
16412 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
16413   // C++11 [dcl.enum] p8:
16414   // Two enumeration types are layout-compatible if they have the same
16415   // underlying type.
16416   return ED1->isComplete() && ED2->isComplete() &&
16417          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
16418 }
16419 
16420 /// Check if two fields are layout-compatible.
16421 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
16422                                FieldDecl *Field2) {
16423   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
16424     return false;
16425 
16426   if (Field1->isBitField() != Field2->isBitField())
16427     return false;
16428 
16429   if (Field1->isBitField()) {
16430     // Make sure that the bit-fields are the same length.
16431     unsigned Bits1 = Field1->getBitWidthValue(C);
16432     unsigned Bits2 = Field2->getBitWidthValue(C);
16433 
16434     if (Bits1 != Bits2)
16435       return false;
16436   }
16437 
16438   return true;
16439 }
16440 
16441 /// Check if two standard-layout structs are layout-compatible.
16442 /// (C++11 [class.mem] p17)
16443 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
16444                                      RecordDecl *RD2) {
16445   // If both records are C++ classes, check that base classes match.
16446   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
16447     // If one of records is a CXXRecordDecl we are in C++ mode,
16448     // thus the other one is a CXXRecordDecl, too.
16449     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
16450     // Check number of base classes.
16451     if (D1CXX->getNumBases() != D2CXX->getNumBases())
16452       return false;
16453 
16454     // Check the base classes.
16455     for (CXXRecordDecl::base_class_const_iterator
16456                Base1 = D1CXX->bases_begin(),
16457            BaseEnd1 = D1CXX->bases_end(),
16458               Base2 = D2CXX->bases_begin();
16459          Base1 != BaseEnd1;
16460          ++Base1, ++Base2) {
16461       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
16462         return false;
16463     }
16464   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
16465     // If only RD2 is a C++ class, it should have zero base classes.
16466     if (D2CXX->getNumBases() > 0)
16467       return false;
16468   }
16469 
16470   // Check the fields.
16471   RecordDecl::field_iterator Field2 = RD2->field_begin(),
16472                              Field2End = RD2->field_end(),
16473                              Field1 = RD1->field_begin(),
16474                              Field1End = RD1->field_end();
16475   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
16476     if (!isLayoutCompatible(C, *Field1, *Field2))
16477       return false;
16478   }
16479   if (Field1 != Field1End || Field2 != Field2End)
16480     return false;
16481 
16482   return true;
16483 }
16484 
16485 /// Check if two standard-layout unions are layout-compatible.
16486 /// (C++11 [class.mem] p18)
16487 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
16488                                     RecordDecl *RD2) {
16489   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
16490   for (auto *Field2 : RD2->fields())
16491     UnmatchedFields.insert(Field2);
16492 
16493   for (auto *Field1 : RD1->fields()) {
16494     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
16495         I = UnmatchedFields.begin(),
16496         E = UnmatchedFields.end();
16497 
16498     for ( ; I != E; ++I) {
16499       if (isLayoutCompatible(C, Field1, *I)) {
16500         bool Result = UnmatchedFields.erase(*I);
16501         (void) Result;
16502         assert(Result);
16503         break;
16504       }
16505     }
16506     if (I == E)
16507       return false;
16508   }
16509 
16510   return UnmatchedFields.empty();
16511 }
16512 
16513 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
16514                                RecordDecl *RD2) {
16515   if (RD1->isUnion() != RD2->isUnion())
16516     return false;
16517 
16518   if (RD1->isUnion())
16519     return isLayoutCompatibleUnion(C, RD1, RD2);
16520   else
16521     return isLayoutCompatibleStruct(C, RD1, RD2);
16522 }
16523 
16524 /// Check if two types are layout-compatible in C++11 sense.
16525 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
16526   if (T1.isNull() || T2.isNull())
16527     return false;
16528 
16529   // C++11 [basic.types] p11:
16530   // If two types T1 and T2 are the same type, then T1 and T2 are
16531   // layout-compatible types.
16532   if (C.hasSameType(T1, T2))
16533     return true;
16534 
16535   T1 = T1.getCanonicalType().getUnqualifiedType();
16536   T2 = T2.getCanonicalType().getUnqualifiedType();
16537 
16538   const Type::TypeClass TC1 = T1->getTypeClass();
16539   const Type::TypeClass TC2 = T2->getTypeClass();
16540 
16541   if (TC1 != TC2)
16542     return false;
16543 
16544   if (TC1 == Type::Enum) {
16545     return isLayoutCompatible(C,
16546                               cast<EnumType>(T1)->getDecl(),
16547                               cast<EnumType>(T2)->getDecl());
16548   } else if (TC1 == Type::Record) {
16549     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
16550       return false;
16551 
16552     return isLayoutCompatible(C,
16553                               cast<RecordType>(T1)->getDecl(),
16554                               cast<RecordType>(T2)->getDecl());
16555   }
16556 
16557   return false;
16558 }
16559 
16560 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
16561 
16562 /// Given a type tag expression find the type tag itself.
16563 ///
16564 /// \param TypeExpr Type tag expression, as it appears in user's code.
16565 ///
16566 /// \param VD Declaration of an identifier that appears in a type tag.
16567 ///
16568 /// \param MagicValue Type tag magic value.
16569 ///
16570 /// \param isConstantEvaluated whether the evalaution should be performed in
16571 
16572 /// constant context.
16573 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
16574                             const ValueDecl **VD, uint64_t *MagicValue,
16575                             bool isConstantEvaluated) {
16576   while(true) {
16577     if (!TypeExpr)
16578       return false;
16579 
16580     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
16581 
16582     switch (TypeExpr->getStmtClass()) {
16583     case Stmt::UnaryOperatorClass: {
16584       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
16585       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
16586         TypeExpr = UO->getSubExpr();
16587         continue;
16588       }
16589       return false;
16590     }
16591 
16592     case Stmt::DeclRefExprClass: {
16593       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
16594       *VD = DRE->getDecl();
16595       return true;
16596     }
16597 
16598     case Stmt::IntegerLiteralClass: {
16599       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
16600       llvm::APInt MagicValueAPInt = IL->getValue();
16601       if (MagicValueAPInt.getActiveBits() <= 64) {
16602         *MagicValue = MagicValueAPInt.getZExtValue();
16603         return true;
16604       } else
16605         return false;
16606     }
16607 
16608     case Stmt::BinaryConditionalOperatorClass:
16609     case Stmt::ConditionalOperatorClass: {
16610       const AbstractConditionalOperator *ACO =
16611           cast<AbstractConditionalOperator>(TypeExpr);
16612       bool Result;
16613       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
16614                                                      isConstantEvaluated)) {
16615         if (Result)
16616           TypeExpr = ACO->getTrueExpr();
16617         else
16618           TypeExpr = ACO->getFalseExpr();
16619         continue;
16620       }
16621       return false;
16622     }
16623 
16624     case Stmt::BinaryOperatorClass: {
16625       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
16626       if (BO->getOpcode() == BO_Comma) {
16627         TypeExpr = BO->getRHS();
16628         continue;
16629       }
16630       return false;
16631     }
16632 
16633     default:
16634       return false;
16635     }
16636   }
16637 }
16638 
16639 /// Retrieve the C type corresponding to type tag TypeExpr.
16640 ///
16641 /// \param TypeExpr Expression that specifies a type tag.
16642 ///
16643 /// \param MagicValues Registered magic values.
16644 ///
16645 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
16646 ///        kind.
16647 ///
16648 /// \param TypeInfo Information about the corresponding C type.
16649 ///
16650 /// \param isConstantEvaluated whether the evalaution should be performed in
16651 /// constant context.
16652 ///
16653 /// \returns true if the corresponding C type was found.
16654 static bool GetMatchingCType(
16655     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
16656     const ASTContext &Ctx,
16657     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
16658         *MagicValues,
16659     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
16660     bool isConstantEvaluated) {
16661   FoundWrongKind = false;
16662 
16663   // Variable declaration that has type_tag_for_datatype attribute.
16664   const ValueDecl *VD = nullptr;
16665 
16666   uint64_t MagicValue;
16667 
16668   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
16669     return false;
16670 
16671   if (VD) {
16672     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
16673       if (I->getArgumentKind() != ArgumentKind) {
16674         FoundWrongKind = true;
16675         return false;
16676       }
16677       TypeInfo.Type = I->getMatchingCType();
16678       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
16679       TypeInfo.MustBeNull = I->getMustBeNull();
16680       return true;
16681     }
16682     return false;
16683   }
16684 
16685   if (!MagicValues)
16686     return false;
16687 
16688   llvm::DenseMap<Sema::TypeTagMagicValue,
16689                  Sema::TypeTagData>::const_iterator I =
16690       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
16691   if (I == MagicValues->end())
16692     return false;
16693 
16694   TypeInfo = I->second;
16695   return true;
16696 }
16697 
16698 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
16699                                       uint64_t MagicValue, QualType Type,
16700                                       bool LayoutCompatible,
16701                                       bool MustBeNull) {
16702   if (!TypeTagForDatatypeMagicValues)
16703     TypeTagForDatatypeMagicValues.reset(
16704         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
16705 
16706   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
16707   (*TypeTagForDatatypeMagicValues)[Magic] =
16708       TypeTagData(Type, LayoutCompatible, MustBeNull);
16709 }
16710 
16711 static bool IsSameCharType(QualType T1, QualType T2) {
16712   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
16713   if (!BT1)
16714     return false;
16715 
16716   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
16717   if (!BT2)
16718     return false;
16719 
16720   BuiltinType::Kind T1Kind = BT1->getKind();
16721   BuiltinType::Kind T2Kind = BT2->getKind();
16722 
16723   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
16724          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
16725          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
16726          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
16727 }
16728 
16729 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
16730                                     const ArrayRef<const Expr *> ExprArgs,
16731                                     SourceLocation CallSiteLoc) {
16732   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
16733   bool IsPointerAttr = Attr->getIsPointer();
16734 
16735   // Retrieve the argument representing the 'type_tag'.
16736   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
16737   if (TypeTagIdxAST >= ExprArgs.size()) {
16738     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16739         << 0 << Attr->getTypeTagIdx().getSourceIndex();
16740     return;
16741   }
16742   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
16743   bool FoundWrongKind;
16744   TypeTagData TypeInfo;
16745   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
16746                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
16747                         TypeInfo, isConstantEvaluated())) {
16748     if (FoundWrongKind)
16749       Diag(TypeTagExpr->getExprLoc(),
16750            diag::warn_type_tag_for_datatype_wrong_kind)
16751         << TypeTagExpr->getSourceRange();
16752     return;
16753   }
16754 
16755   // Retrieve the argument representing the 'arg_idx'.
16756   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
16757   if (ArgumentIdxAST >= ExprArgs.size()) {
16758     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16759         << 1 << Attr->getArgumentIdx().getSourceIndex();
16760     return;
16761   }
16762   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
16763   if (IsPointerAttr) {
16764     // Skip implicit cast of pointer to `void *' (as a function argument).
16765     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
16766       if (ICE->getType()->isVoidPointerType() &&
16767           ICE->getCastKind() == CK_BitCast)
16768         ArgumentExpr = ICE->getSubExpr();
16769   }
16770   QualType ArgumentType = ArgumentExpr->getType();
16771 
16772   // Passing a `void*' pointer shouldn't trigger a warning.
16773   if (IsPointerAttr && ArgumentType->isVoidPointerType())
16774     return;
16775 
16776   if (TypeInfo.MustBeNull) {
16777     // Type tag with matching void type requires a null pointer.
16778     if (!ArgumentExpr->isNullPointerConstant(Context,
16779                                              Expr::NPC_ValueDependentIsNotNull)) {
16780       Diag(ArgumentExpr->getExprLoc(),
16781            diag::warn_type_safety_null_pointer_required)
16782           << ArgumentKind->getName()
16783           << ArgumentExpr->getSourceRange()
16784           << TypeTagExpr->getSourceRange();
16785     }
16786     return;
16787   }
16788 
16789   QualType RequiredType = TypeInfo.Type;
16790   if (IsPointerAttr)
16791     RequiredType = Context.getPointerType(RequiredType);
16792 
16793   bool mismatch = false;
16794   if (!TypeInfo.LayoutCompatible) {
16795     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
16796 
16797     // C++11 [basic.fundamental] p1:
16798     // Plain char, signed char, and unsigned char are three distinct types.
16799     //
16800     // But we treat plain `char' as equivalent to `signed char' or `unsigned
16801     // char' depending on the current char signedness mode.
16802     if (mismatch)
16803       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
16804                                            RequiredType->getPointeeType())) ||
16805           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
16806         mismatch = false;
16807   } else
16808     if (IsPointerAttr)
16809       mismatch = !isLayoutCompatible(Context,
16810                                      ArgumentType->getPointeeType(),
16811                                      RequiredType->getPointeeType());
16812     else
16813       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
16814 
16815   if (mismatch)
16816     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
16817         << ArgumentType << ArgumentKind
16818         << TypeInfo.LayoutCompatible << RequiredType
16819         << ArgumentExpr->getSourceRange()
16820         << TypeTagExpr->getSourceRange();
16821 }
16822 
16823 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
16824                                          CharUnits Alignment) {
16825   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
16826 }
16827 
16828 void Sema::DiagnoseMisalignedMembers() {
16829   for (MisalignedMember &m : MisalignedMembers) {
16830     const NamedDecl *ND = m.RD;
16831     if (ND->getName().empty()) {
16832       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
16833         ND = TD;
16834     }
16835     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
16836         << m.MD << ND << m.E->getSourceRange();
16837   }
16838   MisalignedMembers.clear();
16839 }
16840 
16841 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
16842   E = E->IgnoreParens();
16843   if (!T->isPointerType() && !T->isIntegerType())
16844     return;
16845   if (isa<UnaryOperator>(E) &&
16846       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
16847     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
16848     if (isa<MemberExpr>(Op)) {
16849       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
16850       if (MA != MisalignedMembers.end() &&
16851           (T->isIntegerType() ||
16852            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
16853                                    Context.getTypeAlignInChars(
16854                                        T->getPointeeType()) <= MA->Alignment))))
16855         MisalignedMembers.erase(MA);
16856     }
16857   }
16858 }
16859 
16860 void Sema::RefersToMemberWithReducedAlignment(
16861     Expr *E,
16862     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
16863         Action) {
16864   const auto *ME = dyn_cast<MemberExpr>(E);
16865   if (!ME)
16866     return;
16867 
16868   // No need to check expressions with an __unaligned-qualified type.
16869   if (E->getType().getQualifiers().hasUnaligned())
16870     return;
16871 
16872   // For a chain of MemberExpr like "a.b.c.d" this list
16873   // will keep FieldDecl's like [d, c, b].
16874   SmallVector<FieldDecl *, 4> ReverseMemberChain;
16875   const MemberExpr *TopME = nullptr;
16876   bool AnyIsPacked = false;
16877   do {
16878     QualType BaseType = ME->getBase()->getType();
16879     if (BaseType->isDependentType())
16880       return;
16881     if (ME->isArrow())
16882       BaseType = BaseType->getPointeeType();
16883     RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
16884     if (RD->isInvalidDecl())
16885       return;
16886 
16887     ValueDecl *MD = ME->getMemberDecl();
16888     auto *FD = dyn_cast<FieldDecl>(MD);
16889     // We do not care about non-data members.
16890     if (!FD || FD->isInvalidDecl())
16891       return;
16892 
16893     AnyIsPacked =
16894         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
16895     ReverseMemberChain.push_back(FD);
16896 
16897     TopME = ME;
16898     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
16899   } while (ME);
16900   assert(TopME && "We did not compute a topmost MemberExpr!");
16901 
16902   // Not the scope of this diagnostic.
16903   if (!AnyIsPacked)
16904     return;
16905 
16906   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
16907   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
16908   // TODO: The innermost base of the member expression may be too complicated.
16909   // For now, just disregard these cases. This is left for future
16910   // improvement.
16911   if (!DRE && !isa<CXXThisExpr>(TopBase))
16912       return;
16913 
16914   // Alignment expected by the whole expression.
16915   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
16916 
16917   // No need to do anything else with this case.
16918   if (ExpectedAlignment.isOne())
16919     return;
16920 
16921   // Synthesize offset of the whole access.
16922   CharUnits Offset;
16923   for (const FieldDecl *FD : llvm::reverse(ReverseMemberChain))
16924     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(FD));
16925 
16926   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
16927   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
16928       ReverseMemberChain.back()->getParent()->getTypeForDecl());
16929 
16930   // The base expression of the innermost MemberExpr may give
16931   // stronger guarantees than the class containing the member.
16932   if (DRE && !TopME->isArrow()) {
16933     const ValueDecl *VD = DRE->getDecl();
16934     if (!VD->getType()->isReferenceType())
16935       CompleteObjectAlignment =
16936           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
16937   }
16938 
16939   // Check if the synthesized offset fulfills the alignment.
16940   if (Offset % ExpectedAlignment != 0 ||
16941       // It may fulfill the offset it but the effective alignment may still be
16942       // lower than the expected expression alignment.
16943       CompleteObjectAlignment < ExpectedAlignment) {
16944     // If this happens, we want to determine a sensible culprit of this.
16945     // Intuitively, watching the chain of member expressions from right to
16946     // left, we start with the required alignment (as required by the field
16947     // type) but some packed attribute in that chain has reduced the alignment.
16948     // It may happen that another packed structure increases it again. But if
16949     // we are here such increase has not been enough. So pointing the first
16950     // FieldDecl that either is packed or else its RecordDecl is,
16951     // seems reasonable.
16952     FieldDecl *FD = nullptr;
16953     CharUnits Alignment;
16954     for (FieldDecl *FDI : ReverseMemberChain) {
16955       if (FDI->hasAttr<PackedAttr>() ||
16956           FDI->getParent()->hasAttr<PackedAttr>()) {
16957         FD = FDI;
16958         Alignment = std::min(
16959             Context.getTypeAlignInChars(FD->getType()),
16960             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
16961         break;
16962       }
16963     }
16964     assert(FD && "We did not find a packed FieldDecl!");
16965     Action(E, FD->getParent(), FD, Alignment);
16966   }
16967 }
16968 
16969 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
16970   using namespace std::placeholders;
16971 
16972   RefersToMemberWithReducedAlignment(
16973       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
16974                      _2, _3, _4));
16975 }
16976 
16977 // Check if \p Ty is a valid type for the elementwise math builtins. If it is
16978 // not a valid type, emit an error message and return true. Otherwise return
16979 // false.
16980 static bool checkMathBuiltinElementType(Sema &S, SourceLocation Loc,
16981                                         QualType Ty) {
16982   if (!Ty->getAs<VectorType>() && !ConstantMatrixType::isValidElementType(Ty)) {
16983     S.Diag(Loc, diag::err_builtin_invalid_arg_type)
16984         << 1 << /* vector, integer or float ty*/ 0 << Ty;
16985     return true;
16986   }
16987   return false;
16988 }
16989 
16990 bool Sema::PrepareBuiltinElementwiseMathOneArgCall(CallExpr *TheCall) {
16991   if (checkArgCount(*this, TheCall, 1))
16992     return true;
16993 
16994   ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
16995   if (A.isInvalid())
16996     return true;
16997 
16998   TheCall->setArg(0, A.get());
16999   QualType TyA = A.get()->getType();
17000 
17001   if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA))
17002     return true;
17003 
17004   TheCall->setType(TyA);
17005   return false;
17006 }
17007 
17008 bool Sema::SemaBuiltinElementwiseMath(CallExpr *TheCall) {
17009   if (checkArgCount(*this, TheCall, 2))
17010     return true;
17011 
17012   ExprResult A = TheCall->getArg(0);
17013   ExprResult B = TheCall->getArg(1);
17014   // Do standard promotions between the two arguments, returning their common
17015   // type.
17016   QualType Res =
17017       UsualArithmeticConversions(A, B, TheCall->getExprLoc(), ACK_Comparison);
17018   if (A.isInvalid() || B.isInvalid())
17019     return true;
17020 
17021   QualType TyA = A.get()->getType();
17022   QualType TyB = B.get()->getType();
17023 
17024   if (Res.isNull() || TyA.getCanonicalType() != TyB.getCanonicalType())
17025     return Diag(A.get()->getBeginLoc(),
17026                 diag::err_typecheck_call_different_arg_types)
17027            << TyA << TyB;
17028 
17029   if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA))
17030     return true;
17031 
17032   TheCall->setArg(0, A.get());
17033   TheCall->setArg(1, B.get());
17034   TheCall->setType(Res);
17035   return false;
17036 }
17037 
17038 bool Sema::PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall) {
17039   if (checkArgCount(*this, TheCall, 1))
17040     return true;
17041 
17042   ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
17043   if (A.isInvalid())
17044     return true;
17045 
17046   TheCall->setArg(0, A.get());
17047   return false;
17048 }
17049 
17050 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall,
17051                                             ExprResult CallResult) {
17052   if (checkArgCount(*this, TheCall, 1))
17053     return ExprError();
17054 
17055   ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
17056   if (MatrixArg.isInvalid())
17057     return MatrixArg;
17058   Expr *Matrix = MatrixArg.get();
17059 
17060   auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
17061   if (!MType) {
17062     Diag(Matrix->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17063         << 1 << /* matrix ty*/ 1 << Matrix->getType();
17064     return ExprError();
17065   }
17066 
17067   // Create returned matrix type by swapping rows and columns of the argument
17068   // matrix type.
17069   QualType ResultType = Context.getConstantMatrixType(
17070       MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
17071 
17072   // Change the return type to the type of the returned matrix.
17073   TheCall->setType(ResultType);
17074 
17075   // Update call argument to use the possibly converted matrix argument.
17076   TheCall->setArg(0, Matrix);
17077   return CallResult;
17078 }
17079 
17080 // Get and verify the matrix dimensions.
17081 static llvm::Optional<unsigned>
17082 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {
17083   SourceLocation ErrorPos;
17084   Optional<llvm::APSInt> Value =
17085       Expr->getIntegerConstantExpr(S.Context, &ErrorPos);
17086   if (!Value) {
17087     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
17088         << Name;
17089     return {};
17090   }
17091   uint64_t Dim = Value->getZExtValue();
17092   if (!ConstantMatrixType::isDimensionValid(Dim)) {
17093     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
17094         << Name << ConstantMatrixType::getMaxElementsPerDimension();
17095     return {};
17096   }
17097   return Dim;
17098 }
17099 
17100 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
17101                                                   ExprResult CallResult) {
17102   if (!getLangOpts().MatrixTypes) {
17103     Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
17104     return ExprError();
17105   }
17106 
17107   if (checkArgCount(*this, TheCall, 4))
17108     return ExprError();
17109 
17110   unsigned PtrArgIdx = 0;
17111   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
17112   Expr *RowsExpr = TheCall->getArg(1);
17113   Expr *ColumnsExpr = TheCall->getArg(2);
17114   Expr *StrideExpr = TheCall->getArg(3);
17115 
17116   bool ArgError = false;
17117 
17118   // Check pointer argument.
17119   {
17120     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
17121     if (PtrConv.isInvalid())
17122       return PtrConv;
17123     PtrExpr = PtrConv.get();
17124     TheCall->setArg(0, PtrExpr);
17125     if (PtrExpr->isTypeDependent()) {
17126       TheCall->setType(Context.DependentTy);
17127       return TheCall;
17128     }
17129   }
17130 
17131   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17132   QualType ElementTy;
17133   if (!PtrTy) {
17134     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17135         << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType();
17136     ArgError = true;
17137   } else {
17138     ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
17139 
17140     if (!ConstantMatrixType::isValidElementType(ElementTy)) {
17141       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17142           << PtrArgIdx + 1 << /* pointer to element ty*/ 2
17143           << PtrExpr->getType();
17144       ArgError = true;
17145     }
17146   }
17147 
17148   // Apply default Lvalue conversions and convert the expression to size_t.
17149   auto ApplyArgumentConversions = [this](Expr *E) {
17150     ExprResult Conv = DefaultLvalueConversion(E);
17151     if (Conv.isInvalid())
17152       return Conv;
17153 
17154     return tryConvertExprToType(Conv.get(), Context.getSizeType());
17155   };
17156 
17157   // Apply conversion to row and column expressions.
17158   ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
17159   if (!RowsConv.isInvalid()) {
17160     RowsExpr = RowsConv.get();
17161     TheCall->setArg(1, RowsExpr);
17162   } else
17163     RowsExpr = nullptr;
17164 
17165   ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
17166   if (!ColumnsConv.isInvalid()) {
17167     ColumnsExpr = ColumnsConv.get();
17168     TheCall->setArg(2, ColumnsExpr);
17169   } else
17170     ColumnsExpr = nullptr;
17171 
17172   // If any any part of the result matrix type is still pending, just use
17173   // Context.DependentTy, until all parts are resolved.
17174   if ((RowsExpr && RowsExpr->isTypeDependent()) ||
17175       (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
17176     TheCall->setType(Context.DependentTy);
17177     return CallResult;
17178   }
17179 
17180   // Check row and column dimensions.
17181   llvm::Optional<unsigned> MaybeRows;
17182   if (RowsExpr)
17183     MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
17184 
17185   llvm::Optional<unsigned> MaybeColumns;
17186   if (ColumnsExpr)
17187     MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
17188 
17189   // Check stride argument.
17190   ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
17191   if (StrideConv.isInvalid())
17192     return ExprError();
17193   StrideExpr = StrideConv.get();
17194   TheCall->setArg(3, StrideExpr);
17195 
17196   if (MaybeRows) {
17197     if (Optional<llvm::APSInt> Value =
17198             StrideExpr->getIntegerConstantExpr(Context)) {
17199       uint64_t Stride = Value->getZExtValue();
17200       if (Stride < *MaybeRows) {
17201         Diag(StrideExpr->getBeginLoc(),
17202              diag::err_builtin_matrix_stride_too_small);
17203         ArgError = true;
17204       }
17205     }
17206   }
17207 
17208   if (ArgError || !MaybeRows || !MaybeColumns)
17209     return ExprError();
17210 
17211   TheCall->setType(
17212       Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
17213   return CallResult;
17214 }
17215 
17216 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
17217                                                    ExprResult CallResult) {
17218   if (checkArgCount(*this, TheCall, 3))
17219     return ExprError();
17220 
17221   unsigned PtrArgIdx = 1;
17222   Expr *MatrixExpr = TheCall->getArg(0);
17223   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
17224   Expr *StrideExpr = TheCall->getArg(2);
17225 
17226   bool ArgError = false;
17227 
17228   {
17229     ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
17230     if (MatrixConv.isInvalid())
17231       return MatrixConv;
17232     MatrixExpr = MatrixConv.get();
17233     TheCall->setArg(0, MatrixExpr);
17234   }
17235   if (MatrixExpr->isTypeDependent()) {
17236     TheCall->setType(Context.DependentTy);
17237     return TheCall;
17238   }
17239 
17240   auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
17241   if (!MatrixTy) {
17242     Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17243         << 1 << /*matrix ty */ 1 << MatrixExpr->getType();
17244     ArgError = true;
17245   }
17246 
17247   {
17248     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
17249     if (PtrConv.isInvalid())
17250       return PtrConv;
17251     PtrExpr = PtrConv.get();
17252     TheCall->setArg(1, PtrExpr);
17253     if (PtrExpr->isTypeDependent()) {
17254       TheCall->setType(Context.DependentTy);
17255       return TheCall;
17256     }
17257   }
17258 
17259   // Check pointer argument.
17260   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17261   if (!PtrTy) {
17262     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17263         << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType();
17264     ArgError = true;
17265   } else {
17266     QualType ElementTy = PtrTy->getPointeeType();
17267     if (ElementTy.isConstQualified()) {
17268       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
17269       ArgError = true;
17270     }
17271     ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
17272     if (MatrixTy &&
17273         !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
17274       Diag(PtrExpr->getBeginLoc(),
17275            diag::err_builtin_matrix_pointer_arg_mismatch)
17276           << ElementTy << MatrixTy->getElementType();
17277       ArgError = true;
17278     }
17279   }
17280 
17281   // Apply default Lvalue conversions and convert the stride expression to
17282   // size_t.
17283   {
17284     ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
17285     if (StrideConv.isInvalid())
17286       return StrideConv;
17287 
17288     StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
17289     if (StrideConv.isInvalid())
17290       return StrideConv;
17291     StrideExpr = StrideConv.get();
17292     TheCall->setArg(2, StrideExpr);
17293   }
17294 
17295   // Check stride argument.
17296   if (MatrixTy) {
17297     if (Optional<llvm::APSInt> Value =
17298             StrideExpr->getIntegerConstantExpr(Context)) {
17299       uint64_t Stride = Value->getZExtValue();
17300       if (Stride < MatrixTy->getNumRows()) {
17301         Diag(StrideExpr->getBeginLoc(),
17302              diag::err_builtin_matrix_stride_too_small);
17303         ArgError = true;
17304       }
17305     }
17306   }
17307 
17308   if (ArgError)
17309     return ExprError();
17310 
17311   return CallResult;
17312 }
17313 
17314 /// \brief Enforce the bounds of a TCB
17315 /// CheckTCBEnforcement - Enforces that every function in a named TCB only
17316 /// directly calls other functions in the same TCB as marked by the enforce_tcb
17317 /// and enforce_tcb_leaf attributes.
17318 void Sema::CheckTCBEnforcement(const CallExpr *TheCall,
17319                                const FunctionDecl *Callee) {
17320   const FunctionDecl *Caller = getCurFunctionDecl();
17321 
17322   // Calls to builtins are not enforced.
17323   if (!Caller || !Caller->hasAttr<EnforceTCBAttr>() ||
17324       Callee->getBuiltinID() != 0)
17325     return;
17326 
17327   // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
17328   // all TCBs the callee is a part of.
17329   llvm::StringSet<> CalleeTCBs;
17330   for_each(Callee->specific_attrs<EnforceTCBAttr>(),
17331            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
17332   for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(),
17333            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
17334 
17335   // Go through the TCBs the caller is a part of and emit warnings if Caller
17336   // is in a TCB that the Callee is not.
17337   for_each(
17338       Caller->specific_attrs<EnforceTCBAttr>(),
17339       [&](const auto *A) {
17340         StringRef CallerTCB = A->getTCBName();
17341         if (CalleeTCBs.count(CallerTCB) == 0) {
17342           this->Diag(TheCall->getExprLoc(),
17343                      diag::warn_tcb_enforcement_violation) << Callee
17344                                                            << CallerTCB;
17345         }
17346       });
17347 }
17348