1 //===- SemaChecking.cpp - Extra Semantic Checking -------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements extra semantic analysis beyond what is enforced
10 //  by the C type system.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/AST/APValue.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/Attr.h"
17 #include "clang/AST/AttrIterator.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclBase.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclarationName.h"
24 #include "clang/AST/EvaluatedExprVisitor.h"
25 #include "clang/AST/Expr.h"
26 #include "clang/AST/ExprCXX.h"
27 #include "clang/AST/ExprObjC.h"
28 #include "clang/AST/ExprOpenMP.h"
29 #include "clang/AST/FormatString.h"
30 #include "clang/AST/NSAPI.h"
31 #include "clang/AST/NonTrivialTypeVisitor.h"
32 #include "clang/AST/OperationKinds.h"
33 #include "clang/AST/RecordLayout.h"
34 #include "clang/AST/Stmt.h"
35 #include "clang/AST/TemplateBase.h"
36 #include "clang/AST/Type.h"
37 #include "clang/AST/TypeLoc.h"
38 #include "clang/AST/UnresolvedSet.h"
39 #include "clang/Basic/AddressSpaces.h"
40 #include "clang/Basic/CharInfo.h"
41 #include "clang/Basic/Diagnostic.h"
42 #include "clang/Basic/IdentifierTable.h"
43 #include "clang/Basic/LLVM.h"
44 #include "clang/Basic/LangOptions.h"
45 #include "clang/Basic/OpenCLOptions.h"
46 #include "clang/Basic/OperatorKinds.h"
47 #include "clang/Basic/PartialDiagnostic.h"
48 #include "clang/Basic/SourceLocation.h"
49 #include "clang/Basic/SourceManager.h"
50 #include "clang/Basic/Specifiers.h"
51 #include "clang/Basic/SyncScope.h"
52 #include "clang/Basic/TargetBuiltins.h"
53 #include "clang/Basic/TargetCXXABI.h"
54 #include "clang/Basic/TargetInfo.h"
55 #include "clang/Basic/TypeTraits.h"
56 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
57 #include "clang/Sema/Initialization.h"
58 #include "clang/Sema/Lookup.h"
59 #include "clang/Sema/Ownership.h"
60 #include "clang/Sema/Scope.h"
61 #include "clang/Sema/ScopeInfo.h"
62 #include "clang/Sema/Sema.h"
63 #include "clang/Sema/SemaInternal.h"
64 #include "llvm/ADT/APFloat.h"
65 #include "llvm/ADT/APInt.h"
66 #include "llvm/ADT/APSInt.h"
67 #include "llvm/ADT/ArrayRef.h"
68 #include "llvm/ADT/DenseMap.h"
69 #include "llvm/ADT/FoldingSet.h"
70 #include "llvm/ADT/None.h"
71 #include "llvm/ADT/Optional.h"
72 #include "llvm/ADT/STLExtras.h"
73 #include "llvm/ADT/SmallBitVector.h"
74 #include "llvm/ADT/SmallPtrSet.h"
75 #include "llvm/ADT/SmallString.h"
76 #include "llvm/ADT/SmallVector.h"
77 #include "llvm/ADT/StringRef.h"
78 #include "llvm/ADT/StringSet.h"
79 #include "llvm/ADT/StringSwitch.h"
80 #include "llvm/ADT/Triple.h"
81 #include "llvm/Support/AtomicOrdering.h"
82 #include "llvm/Support/Casting.h"
83 #include "llvm/Support/Compiler.h"
84 #include "llvm/Support/ConvertUTF.h"
85 #include "llvm/Support/ErrorHandling.h"
86 #include "llvm/Support/Format.h"
87 #include "llvm/Support/Locale.h"
88 #include "llvm/Support/MathExtras.h"
89 #include "llvm/Support/SaveAndRestore.h"
90 #include "llvm/Support/raw_ostream.h"
91 #include <algorithm>
92 #include <bitset>
93 #include <cassert>
94 #include <cstddef>
95 #include <cstdint>
96 #include <functional>
97 #include <limits>
98 #include <string>
99 #include <tuple>
100 #include <utility>
101 
102 using namespace clang;
103 using namespace sema;
104 
105 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
106                                                     unsigned ByteNo) const {
107   return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
108                                Context.getTargetInfo());
109 }
110 
111 /// Checks that a call expression's argument count is the desired number.
112 /// This is useful when doing custom type-checking.  Returns true on error.
113 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
114   unsigned argCount = call->getNumArgs();
115   if (argCount == desiredArgCount) return false;
116 
117   if (argCount < desiredArgCount)
118     return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args)
119            << 0 /*function call*/ << desiredArgCount << argCount
120            << call->getSourceRange();
121 
122   // Highlight all the excess arguments.
123   SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(),
124                     call->getArg(argCount - 1)->getEndLoc());
125 
126   return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
127     << 0 /*function call*/ << desiredArgCount << argCount
128     << call->getArg(1)->getSourceRange();
129 }
130 
131 /// Check that the first argument to __builtin_annotation is an integer
132 /// and the second argument is a non-wide string literal.
133 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
134   if (checkArgCount(S, TheCall, 2))
135     return true;
136 
137   // First argument should be an integer.
138   Expr *ValArg = TheCall->getArg(0);
139   QualType Ty = ValArg->getType();
140   if (!Ty->isIntegerType()) {
141     S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
142         << ValArg->getSourceRange();
143     return true;
144   }
145 
146   // Second argument should be a constant string.
147   Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
148   StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
149   if (!Literal || !Literal->isAscii()) {
150     S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
151         << StrArg->getSourceRange();
152     return true;
153   }
154 
155   TheCall->setType(Ty);
156   return false;
157 }
158 
159 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
160   // We need at least one argument.
161   if (TheCall->getNumArgs() < 1) {
162     S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
163         << 0 << 1 << TheCall->getNumArgs()
164         << TheCall->getCallee()->getSourceRange();
165     return true;
166   }
167 
168   // All arguments should be wide string literals.
169   for (Expr *Arg : TheCall->arguments()) {
170     auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
171     if (!Literal || !Literal->isWide()) {
172       S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
173           << Arg->getSourceRange();
174       return true;
175     }
176   }
177 
178   return false;
179 }
180 
181 /// Check that the argument to __builtin_addressof is a glvalue, and set the
182 /// result type to the corresponding pointer type.
183 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
184   if (checkArgCount(S, TheCall, 1))
185     return true;
186 
187   ExprResult Arg(TheCall->getArg(0));
188   QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
189   if (ResultType.isNull())
190     return true;
191 
192   TheCall->setArg(0, Arg.get());
193   TheCall->setType(ResultType);
194   return false;
195 }
196 
197 /// Check the number of arguments and set the result type to
198 /// the argument type.
199 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
200   if (checkArgCount(S, TheCall, 1))
201     return true;
202 
203   TheCall->setType(TheCall->getArg(0)->getType());
204   return false;
205 }
206 
207 /// Check that the value argument for __builtin_is_aligned(value, alignment) and
208 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
209 /// type (but not a function pointer) and that the alignment is a power-of-two.
210 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
211   if (checkArgCount(S, TheCall, 2))
212     return true;
213 
214   clang::Expr *Source = TheCall->getArg(0);
215   bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
216 
217   auto IsValidIntegerType = [](QualType Ty) {
218     return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
219   };
220   QualType SrcTy = Source->getType();
221   // We should also be able to use it with arrays (but not functions!).
222   if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
223     SrcTy = S.Context.getDecayedType(SrcTy);
224   }
225   if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
226       SrcTy->isFunctionPointerType()) {
227     // FIXME: this is not quite the right error message since we don't allow
228     // floating point types, or member pointers.
229     S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand)
230         << SrcTy;
231     return true;
232   }
233 
234   clang::Expr *AlignOp = TheCall->getArg(1);
235   if (!IsValidIntegerType(AlignOp->getType())) {
236     S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int)
237         << AlignOp->getType();
238     return true;
239   }
240   Expr::EvalResult AlignResult;
241   unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1;
242   // We can't check validity of alignment if it is value dependent.
243   if (!AlignOp->isValueDependent() &&
244       AlignOp->EvaluateAsInt(AlignResult, S.Context,
245                              Expr::SE_AllowSideEffects)) {
246     llvm::APSInt AlignValue = AlignResult.Val.getInt();
247     llvm::APSInt MaxValue(
248         llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits));
249     if (AlignValue < 1) {
250       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1;
251       return true;
252     }
253     if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) {
254       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big)
255           << MaxValue.toString(10);
256       return true;
257     }
258     if (!AlignValue.isPowerOf2()) {
259       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two);
260       return true;
261     }
262     if (AlignValue == 1) {
263       S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless)
264           << IsBooleanAlignBuiltin;
265     }
266   }
267 
268   ExprResult SrcArg = S.PerformCopyInitialization(
269       InitializedEntity::InitializeParameter(S.Context, SrcTy, false),
270       SourceLocation(), Source);
271   if (SrcArg.isInvalid())
272     return true;
273   TheCall->setArg(0, SrcArg.get());
274   ExprResult AlignArg =
275       S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
276                                       S.Context, AlignOp->getType(), false),
277                                   SourceLocation(), AlignOp);
278   if (AlignArg.isInvalid())
279     return true;
280   TheCall->setArg(1, AlignArg.get());
281   // For align_up/align_down, the return type is the same as the (potentially
282   // decayed) argument type including qualifiers. For is_aligned(), the result
283   // is always bool.
284   TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
285   return false;
286 }
287 
288 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall,
289                                 unsigned BuiltinID) {
290   if (checkArgCount(S, TheCall, 3))
291     return true;
292 
293   // First two arguments should be integers.
294   for (unsigned I = 0; I < 2; ++I) {
295     ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I));
296     if (Arg.isInvalid()) return true;
297     TheCall->setArg(I, Arg.get());
298 
299     QualType Ty = Arg.get()->getType();
300     if (!Ty->isIntegerType()) {
301       S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
302           << Ty << Arg.get()->getSourceRange();
303       return true;
304     }
305   }
306 
307   // Third argument should be a pointer to a non-const integer.
308   // IRGen correctly handles volatile, restrict, and address spaces, and
309   // the other qualifiers aren't possible.
310   {
311     ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(2));
312     if (Arg.isInvalid()) return true;
313     TheCall->setArg(2, Arg.get());
314 
315     QualType Ty = Arg.get()->getType();
316     const auto *PtrTy = Ty->getAs<PointerType>();
317     if (!PtrTy ||
318         !PtrTy->getPointeeType()->isIntegerType() ||
319         PtrTy->getPointeeType().isConstQualified()) {
320       S.Diag(Arg.get()->getBeginLoc(),
321              diag::err_overflow_builtin_must_be_ptr_int)
322         << Ty << Arg.get()->getSourceRange();
323       return true;
324     }
325   }
326 
327   // Disallow signed ExtIntType args larger than 128 bits to mul function until
328   // we improve backend support.
329   if (BuiltinID == Builtin::BI__builtin_mul_overflow) {
330     for (unsigned I = 0; I < 3; ++I) {
331       const auto Arg = TheCall->getArg(I);
332       // Third argument will be a pointer.
333       auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType();
334       if (Ty->isExtIntType() && Ty->isSignedIntegerType() &&
335           S.getASTContext().getIntWidth(Ty) > 128)
336         return S.Diag(Arg->getBeginLoc(),
337                       diag::err_overflow_builtin_ext_int_max_size)
338                << 128;
339     }
340   }
341 
342   return false;
343 }
344 
345 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
346   if (checkArgCount(S, BuiltinCall, 2))
347     return true;
348 
349   SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
350   Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
351   Expr *Call = BuiltinCall->getArg(0);
352   Expr *Chain = BuiltinCall->getArg(1);
353 
354   if (Call->getStmtClass() != Stmt::CallExprClass) {
355     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
356         << Call->getSourceRange();
357     return true;
358   }
359 
360   auto CE = cast<CallExpr>(Call);
361   if (CE->getCallee()->getType()->isBlockPointerType()) {
362     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
363         << Call->getSourceRange();
364     return true;
365   }
366 
367   const Decl *TargetDecl = CE->getCalleeDecl();
368   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
369     if (FD->getBuiltinID()) {
370       S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
371           << Call->getSourceRange();
372       return true;
373     }
374 
375   if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
376     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
377         << Call->getSourceRange();
378     return true;
379   }
380 
381   ExprResult ChainResult = S.UsualUnaryConversions(Chain);
382   if (ChainResult.isInvalid())
383     return true;
384   if (!ChainResult.get()->getType()->isPointerType()) {
385     S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
386         << Chain->getSourceRange();
387     return true;
388   }
389 
390   QualType ReturnTy = CE->getCallReturnType(S.Context);
391   QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
392   QualType BuiltinTy = S.Context.getFunctionType(
393       ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
394   QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
395 
396   Builtin =
397       S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
398 
399   BuiltinCall->setType(CE->getType());
400   BuiltinCall->setValueKind(CE->getValueKind());
401   BuiltinCall->setObjectKind(CE->getObjectKind());
402   BuiltinCall->setCallee(Builtin);
403   BuiltinCall->setArg(1, ChainResult.get());
404 
405   return false;
406 }
407 
408 namespace {
409 
410 class EstimateSizeFormatHandler
411     : public analyze_format_string::FormatStringHandler {
412   size_t Size;
413 
414 public:
415   EstimateSizeFormatHandler(StringRef Format)
416       : Size(std::min(Format.find(0), Format.size()) +
417              1 /* null byte always written by sprintf */) {}
418 
419   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
420                              const char *, unsigned SpecifierLen) override {
421 
422     const size_t FieldWidth = computeFieldWidth(FS);
423     const size_t Precision = computePrecision(FS);
424 
425     // The actual format.
426     switch (FS.getConversionSpecifier().getKind()) {
427     // Just a char.
428     case analyze_format_string::ConversionSpecifier::cArg:
429     case analyze_format_string::ConversionSpecifier::CArg:
430       Size += std::max(FieldWidth, (size_t)1);
431       break;
432     // Just an integer.
433     case analyze_format_string::ConversionSpecifier::dArg:
434     case analyze_format_string::ConversionSpecifier::DArg:
435     case analyze_format_string::ConversionSpecifier::iArg:
436     case analyze_format_string::ConversionSpecifier::oArg:
437     case analyze_format_string::ConversionSpecifier::OArg:
438     case analyze_format_string::ConversionSpecifier::uArg:
439     case analyze_format_string::ConversionSpecifier::UArg:
440     case analyze_format_string::ConversionSpecifier::xArg:
441     case analyze_format_string::ConversionSpecifier::XArg:
442       Size += std::max(FieldWidth, Precision);
443       break;
444 
445     // %g style conversion switches between %f or %e style dynamically.
446     // %f always takes less space, so default to it.
447     case analyze_format_string::ConversionSpecifier::gArg:
448     case analyze_format_string::ConversionSpecifier::GArg:
449 
450     // Floating point number in the form '[+]ddd.ddd'.
451     case analyze_format_string::ConversionSpecifier::fArg:
452     case analyze_format_string::ConversionSpecifier::FArg:
453       Size += std::max(FieldWidth, 1 /* integer part */ +
454                                        (Precision ? 1 + Precision
455                                                   : 0) /* period + decimal */);
456       break;
457 
458     // Floating point number in the form '[-]d.ddde[+-]dd'.
459     case analyze_format_string::ConversionSpecifier::eArg:
460     case analyze_format_string::ConversionSpecifier::EArg:
461       Size +=
462           std::max(FieldWidth,
463                    1 /* integer part */ +
464                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
465                        1 /* e or E letter */ + 2 /* exponent */);
466       break;
467 
468     // Floating point number in the form '[-]0xh.hhhhp±dd'.
469     case analyze_format_string::ConversionSpecifier::aArg:
470     case analyze_format_string::ConversionSpecifier::AArg:
471       Size +=
472           std::max(FieldWidth,
473                    2 /* 0x */ + 1 /* integer part */ +
474                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
475                        1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
476       break;
477 
478     // Just a string.
479     case analyze_format_string::ConversionSpecifier::sArg:
480     case analyze_format_string::ConversionSpecifier::SArg:
481       Size += FieldWidth;
482       break;
483 
484     // Just a pointer in the form '0xddd'.
485     case analyze_format_string::ConversionSpecifier::pArg:
486       Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
487       break;
488 
489     // A plain percent.
490     case analyze_format_string::ConversionSpecifier::PercentArg:
491       Size += 1;
492       break;
493 
494     default:
495       break;
496     }
497 
498     Size += FS.hasPlusPrefix() || FS.hasSpacePrefix();
499 
500     if (FS.hasAlternativeForm()) {
501       switch (FS.getConversionSpecifier().getKind()) {
502       default:
503         break;
504       // Force a leading '0'.
505       case analyze_format_string::ConversionSpecifier::oArg:
506         Size += 1;
507         break;
508       // Force a leading '0x'.
509       case analyze_format_string::ConversionSpecifier::xArg:
510       case analyze_format_string::ConversionSpecifier::XArg:
511         Size += 2;
512         break;
513       // Force a period '.' before decimal, even if precision is 0.
514       case analyze_format_string::ConversionSpecifier::aArg:
515       case analyze_format_string::ConversionSpecifier::AArg:
516       case analyze_format_string::ConversionSpecifier::eArg:
517       case analyze_format_string::ConversionSpecifier::EArg:
518       case analyze_format_string::ConversionSpecifier::fArg:
519       case analyze_format_string::ConversionSpecifier::FArg:
520       case analyze_format_string::ConversionSpecifier::gArg:
521       case analyze_format_string::ConversionSpecifier::GArg:
522         Size += (Precision ? 0 : 1);
523         break;
524       }
525     }
526     assert(SpecifierLen <= Size && "no underflow");
527     Size -= SpecifierLen;
528     return true;
529   }
530 
531   size_t getSizeLowerBound() const { return Size; }
532 
533 private:
534   static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
535     const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
536     size_t FieldWidth = 0;
537     if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant)
538       FieldWidth = FW.getConstantAmount();
539     return FieldWidth;
540   }
541 
542   static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
543     const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
544     size_t Precision = 0;
545 
546     // See man 3 printf for default precision value based on the specifier.
547     switch (FW.getHowSpecified()) {
548     case analyze_format_string::OptionalAmount::NotSpecified:
549       switch (FS.getConversionSpecifier().getKind()) {
550       default:
551         break;
552       case analyze_format_string::ConversionSpecifier::dArg: // %d
553       case analyze_format_string::ConversionSpecifier::DArg: // %D
554       case analyze_format_string::ConversionSpecifier::iArg: // %i
555         Precision = 1;
556         break;
557       case analyze_format_string::ConversionSpecifier::oArg: // %d
558       case analyze_format_string::ConversionSpecifier::OArg: // %D
559       case analyze_format_string::ConversionSpecifier::uArg: // %d
560       case analyze_format_string::ConversionSpecifier::UArg: // %D
561       case analyze_format_string::ConversionSpecifier::xArg: // %d
562       case analyze_format_string::ConversionSpecifier::XArg: // %D
563         Precision = 1;
564         break;
565       case analyze_format_string::ConversionSpecifier::fArg: // %f
566       case analyze_format_string::ConversionSpecifier::FArg: // %F
567       case analyze_format_string::ConversionSpecifier::eArg: // %e
568       case analyze_format_string::ConversionSpecifier::EArg: // %E
569       case analyze_format_string::ConversionSpecifier::gArg: // %g
570       case analyze_format_string::ConversionSpecifier::GArg: // %G
571         Precision = 6;
572         break;
573       case analyze_format_string::ConversionSpecifier::pArg: // %d
574         Precision = 1;
575         break;
576       }
577       break;
578     case analyze_format_string::OptionalAmount::Constant:
579       Precision = FW.getConstantAmount();
580       break;
581     default:
582       break;
583     }
584     return Precision;
585   }
586 };
587 
588 } // namespace
589 
590 /// Check a call to BuiltinID for buffer overflows. If BuiltinID is a
591 /// __builtin_*_chk function, then use the object size argument specified in the
592 /// source. Otherwise, infer the object size using __builtin_object_size.
593 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
594                                                CallExpr *TheCall) {
595   // FIXME: There are some more useful checks we could be doing here:
596   //  - Evaluate strlen of strcpy arguments, use as object size.
597 
598   if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
599       isConstantEvaluated())
600     return;
601 
602   unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true);
603   if (!BuiltinID)
604     return;
605 
606   const TargetInfo &TI = getASTContext().getTargetInfo();
607   unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
608 
609   unsigned DiagID = 0;
610   bool IsChkVariant = false;
611   Optional<llvm::APSInt> UsedSize;
612   unsigned SizeIndex, ObjectIndex;
613   switch (BuiltinID) {
614   default:
615     return;
616   case Builtin::BIsprintf:
617   case Builtin::BI__builtin___sprintf_chk: {
618     size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
619     auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
620 
621     if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) {
622 
623       if (!Format->isAscii() && !Format->isUTF8())
624         return;
625 
626       StringRef FormatStrRef = Format->getString();
627       EstimateSizeFormatHandler H(FormatStrRef);
628       const char *FormatBytes = FormatStrRef.data();
629       const ConstantArrayType *T =
630           Context.getAsConstantArrayType(Format->getType());
631       assert(T && "String literal not of constant array type!");
632       size_t TypeSize = T->getSize().getZExtValue();
633 
634       // In case there's a null byte somewhere.
635       size_t StrLen =
636           std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
637       if (!analyze_format_string::ParsePrintfString(
638               H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
639               Context.getTargetInfo(), false)) {
640         DiagID = diag::warn_fortify_source_format_overflow;
641         UsedSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
642                        .extOrTrunc(SizeTypeWidth);
643         if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
644           IsChkVariant = true;
645           ObjectIndex = 2;
646         } else {
647           IsChkVariant = false;
648           ObjectIndex = 0;
649         }
650         break;
651       }
652     }
653     return;
654   }
655   case Builtin::BI__builtin___memcpy_chk:
656   case Builtin::BI__builtin___memmove_chk:
657   case Builtin::BI__builtin___memset_chk:
658   case Builtin::BI__builtin___strlcat_chk:
659   case Builtin::BI__builtin___strlcpy_chk:
660   case Builtin::BI__builtin___strncat_chk:
661   case Builtin::BI__builtin___strncpy_chk:
662   case Builtin::BI__builtin___stpncpy_chk:
663   case Builtin::BI__builtin___memccpy_chk:
664   case Builtin::BI__builtin___mempcpy_chk: {
665     DiagID = diag::warn_builtin_chk_overflow;
666     IsChkVariant = true;
667     SizeIndex = TheCall->getNumArgs() - 2;
668     ObjectIndex = TheCall->getNumArgs() - 1;
669     break;
670   }
671 
672   case Builtin::BI__builtin___snprintf_chk:
673   case Builtin::BI__builtin___vsnprintf_chk: {
674     DiagID = diag::warn_builtin_chk_overflow;
675     IsChkVariant = true;
676     SizeIndex = 1;
677     ObjectIndex = 3;
678     break;
679   }
680 
681   case Builtin::BIstrncat:
682   case Builtin::BI__builtin_strncat:
683   case Builtin::BIstrncpy:
684   case Builtin::BI__builtin_strncpy:
685   case Builtin::BIstpncpy:
686   case Builtin::BI__builtin_stpncpy: {
687     // Whether these functions overflow depends on the runtime strlen of the
688     // string, not just the buffer size, so emitting the "always overflow"
689     // diagnostic isn't quite right. We should still diagnose passing a buffer
690     // size larger than the destination buffer though; this is a runtime abort
691     // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
692     DiagID = diag::warn_fortify_source_size_mismatch;
693     SizeIndex = TheCall->getNumArgs() - 1;
694     ObjectIndex = 0;
695     break;
696   }
697 
698   case Builtin::BImemcpy:
699   case Builtin::BI__builtin_memcpy:
700   case Builtin::BImemmove:
701   case Builtin::BI__builtin_memmove:
702   case Builtin::BImemset:
703   case Builtin::BI__builtin_memset:
704   case Builtin::BImempcpy:
705   case Builtin::BI__builtin_mempcpy: {
706     DiagID = diag::warn_fortify_source_overflow;
707     SizeIndex = TheCall->getNumArgs() - 1;
708     ObjectIndex = 0;
709     break;
710   }
711   case Builtin::BIsnprintf:
712   case Builtin::BI__builtin_snprintf:
713   case Builtin::BIvsnprintf:
714   case Builtin::BI__builtin_vsnprintf: {
715     DiagID = diag::warn_fortify_source_size_mismatch;
716     SizeIndex = 1;
717     ObjectIndex = 0;
718     break;
719   }
720   }
721 
722   llvm::APSInt ObjectSize;
723   // For __builtin___*_chk, the object size is explicitly provided by the caller
724   // (usually using __builtin_object_size). Use that value to check this call.
725   if (IsChkVariant) {
726     Expr::EvalResult Result;
727     Expr *SizeArg = TheCall->getArg(ObjectIndex);
728     if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
729       return;
730     ObjectSize = Result.Val.getInt();
731 
732   // Otherwise, try to evaluate an imaginary call to __builtin_object_size.
733   } else {
734     // If the parameter has a pass_object_size attribute, then we should use its
735     // (potentially) more strict checking mode. Otherwise, conservatively assume
736     // type 0.
737     int BOSType = 0;
738     if (const auto *POS =
739             FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>())
740       BOSType = POS->getType();
741 
742     Expr *ObjArg = TheCall->getArg(ObjectIndex);
743     uint64_t Result;
744     if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
745       return;
746     // Get the object size in the target's size_t width.
747     ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
748   }
749 
750   // Evaluate the number of bytes of the object that this call will use.
751   if (!UsedSize) {
752     Expr::EvalResult Result;
753     Expr *UsedSizeArg = TheCall->getArg(SizeIndex);
754     if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext()))
755       return;
756     UsedSize = Result.Val.getInt().extOrTrunc(SizeTypeWidth);
757   }
758 
759   if (UsedSize.getValue().ule(ObjectSize))
760     return;
761 
762   StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
763   // Skim off the details of whichever builtin was called to produce a better
764   // diagnostic, as it's unlikley that the user wrote the __builtin explicitly.
765   if (IsChkVariant) {
766     FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
767     FunctionName = FunctionName.drop_back(std::strlen("_chk"));
768   } else if (FunctionName.startswith("__builtin_")) {
769     FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
770   }
771 
772   DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
773                       PDiag(DiagID)
774                           << FunctionName << ObjectSize.toString(/*Radix=*/10)
775                           << UsedSize.getValue().toString(/*Radix=*/10));
776 }
777 
778 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
779                                      Scope::ScopeFlags NeededScopeFlags,
780                                      unsigned DiagID) {
781   // Scopes aren't available during instantiation. Fortunately, builtin
782   // functions cannot be template args so they cannot be formed through template
783   // instantiation. Therefore checking once during the parse is sufficient.
784   if (SemaRef.inTemplateInstantiation())
785     return false;
786 
787   Scope *S = SemaRef.getCurScope();
788   while (S && !S->isSEHExceptScope())
789     S = S->getParent();
790   if (!S || !(S->getFlags() & NeededScopeFlags)) {
791     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
792     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
793         << DRE->getDecl()->getIdentifier();
794     return true;
795   }
796 
797   return false;
798 }
799 
800 static inline bool isBlockPointer(Expr *Arg) {
801   return Arg->getType()->isBlockPointerType();
802 }
803 
804 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
805 /// void*, which is a requirement of device side enqueue.
806 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
807   const BlockPointerType *BPT =
808       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
809   ArrayRef<QualType> Params =
810       BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes();
811   unsigned ArgCounter = 0;
812   bool IllegalParams = false;
813   // Iterate through the block parameters until either one is found that is not
814   // a local void*, or the block is valid.
815   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
816        I != E; ++I, ++ArgCounter) {
817     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
818         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
819             LangAS::opencl_local) {
820       // Get the location of the error. If a block literal has been passed
821       // (BlockExpr) then we can point straight to the offending argument,
822       // else we just point to the variable reference.
823       SourceLocation ErrorLoc;
824       if (isa<BlockExpr>(BlockArg)) {
825         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
826         ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
827       } else if (isa<DeclRefExpr>(BlockArg)) {
828         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
829       }
830       S.Diag(ErrorLoc,
831              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
832       IllegalParams = true;
833     }
834   }
835 
836   return IllegalParams;
837 }
838 
839 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
840   if (!S.getOpenCLOptions().isAvailableOption("cl_khr_subgroups",
841                                               S.getLangOpts())) {
842     S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
843         << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
844     return true;
845   }
846   return false;
847 }
848 
849 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
850   if (checkArgCount(S, TheCall, 2))
851     return true;
852 
853   if (checkOpenCLSubgroupExt(S, TheCall))
854     return true;
855 
856   // First argument is an ndrange_t type.
857   Expr *NDRangeArg = TheCall->getArg(0);
858   if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
859     S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
860         << TheCall->getDirectCallee() << "'ndrange_t'";
861     return true;
862   }
863 
864   Expr *BlockArg = TheCall->getArg(1);
865   if (!isBlockPointer(BlockArg)) {
866     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
867         << TheCall->getDirectCallee() << "block";
868     return true;
869   }
870   return checkOpenCLBlockArgs(S, BlockArg);
871 }
872 
873 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
874 /// get_kernel_work_group_size
875 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
876 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
877   if (checkArgCount(S, TheCall, 1))
878     return true;
879 
880   Expr *BlockArg = TheCall->getArg(0);
881   if (!isBlockPointer(BlockArg)) {
882     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
883         << TheCall->getDirectCallee() << "block";
884     return true;
885   }
886   return checkOpenCLBlockArgs(S, BlockArg);
887 }
888 
889 /// Diagnose integer type and any valid implicit conversion to it.
890 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
891                                       const QualType &IntType);
892 
893 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
894                                             unsigned Start, unsigned End) {
895   bool IllegalParams = false;
896   for (unsigned I = Start; I <= End; ++I)
897     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
898                                               S.Context.getSizeType());
899   return IllegalParams;
900 }
901 
902 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
903 /// 'local void*' parameter of passed block.
904 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
905                                            Expr *BlockArg,
906                                            unsigned NumNonVarArgs) {
907   const BlockPointerType *BPT =
908       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
909   unsigned NumBlockParams =
910       BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams();
911   unsigned TotalNumArgs = TheCall->getNumArgs();
912 
913   // For each argument passed to the block, a corresponding uint needs to
914   // be passed to describe the size of the local memory.
915   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
916     S.Diag(TheCall->getBeginLoc(),
917            diag::err_opencl_enqueue_kernel_local_size_args);
918     return true;
919   }
920 
921   // Check that the sizes of the local memory are specified by integers.
922   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
923                                          TotalNumArgs - 1);
924 }
925 
926 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
927 /// overload formats specified in Table 6.13.17.1.
928 /// int enqueue_kernel(queue_t queue,
929 ///                    kernel_enqueue_flags_t flags,
930 ///                    const ndrange_t ndrange,
931 ///                    void (^block)(void))
932 /// int enqueue_kernel(queue_t queue,
933 ///                    kernel_enqueue_flags_t flags,
934 ///                    const ndrange_t ndrange,
935 ///                    uint num_events_in_wait_list,
936 ///                    clk_event_t *event_wait_list,
937 ///                    clk_event_t *event_ret,
938 ///                    void (^block)(void))
939 /// int enqueue_kernel(queue_t queue,
940 ///                    kernel_enqueue_flags_t flags,
941 ///                    const ndrange_t ndrange,
942 ///                    void (^block)(local void*, ...),
943 ///                    uint size0, ...)
944 /// int enqueue_kernel(queue_t queue,
945 ///                    kernel_enqueue_flags_t flags,
946 ///                    const ndrange_t ndrange,
947 ///                    uint num_events_in_wait_list,
948 ///                    clk_event_t *event_wait_list,
949 ///                    clk_event_t *event_ret,
950 ///                    void (^block)(local void*, ...),
951 ///                    uint size0, ...)
952 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
953   unsigned NumArgs = TheCall->getNumArgs();
954 
955   if (NumArgs < 4) {
956     S.Diag(TheCall->getBeginLoc(),
957            diag::err_typecheck_call_too_few_args_at_least)
958         << 0 << 4 << NumArgs;
959     return true;
960   }
961 
962   Expr *Arg0 = TheCall->getArg(0);
963   Expr *Arg1 = TheCall->getArg(1);
964   Expr *Arg2 = TheCall->getArg(2);
965   Expr *Arg3 = TheCall->getArg(3);
966 
967   // First argument always needs to be a queue_t type.
968   if (!Arg0->getType()->isQueueT()) {
969     S.Diag(TheCall->getArg(0)->getBeginLoc(),
970            diag::err_opencl_builtin_expected_type)
971         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
972     return true;
973   }
974 
975   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
976   if (!Arg1->getType()->isIntegerType()) {
977     S.Diag(TheCall->getArg(1)->getBeginLoc(),
978            diag::err_opencl_builtin_expected_type)
979         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
980     return true;
981   }
982 
983   // Third argument is always an ndrange_t type.
984   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
985     S.Diag(TheCall->getArg(2)->getBeginLoc(),
986            diag::err_opencl_builtin_expected_type)
987         << TheCall->getDirectCallee() << "'ndrange_t'";
988     return true;
989   }
990 
991   // With four arguments, there is only one form that the function could be
992   // called in: no events and no variable arguments.
993   if (NumArgs == 4) {
994     // check that the last argument is the right block type.
995     if (!isBlockPointer(Arg3)) {
996       S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
997           << TheCall->getDirectCallee() << "block";
998       return true;
999     }
1000     // we have a block type, check the prototype
1001     const BlockPointerType *BPT =
1002         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
1003     if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) {
1004       S.Diag(Arg3->getBeginLoc(),
1005              diag::err_opencl_enqueue_kernel_blocks_no_args);
1006       return true;
1007     }
1008     return false;
1009   }
1010   // we can have block + varargs.
1011   if (isBlockPointer(Arg3))
1012     return (checkOpenCLBlockArgs(S, Arg3) ||
1013             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
1014   // last two cases with either exactly 7 args or 7 args and varargs.
1015   if (NumArgs >= 7) {
1016     // check common block argument.
1017     Expr *Arg6 = TheCall->getArg(6);
1018     if (!isBlockPointer(Arg6)) {
1019       S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1020           << TheCall->getDirectCallee() << "block";
1021       return true;
1022     }
1023     if (checkOpenCLBlockArgs(S, Arg6))
1024       return true;
1025 
1026     // Forth argument has to be any integer type.
1027     if (!Arg3->getType()->isIntegerType()) {
1028       S.Diag(TheCall->getArg(3)->getBeginLoc(),
1029              diag::err_opencl_builtin_expected_type)
1030           << TheCall->getDirectCallee() << "integer";
1031       return true;
1032     }
1033     // check remaining common arguments.
1034     Expr *Arg4 = TheCall->getArg(4);
1035     Expr *Arg5 = TheCall->getArg(5);
1036 
1037     // Fifth argument is always passed as a pointer to clk_event_t.
1038     if (!Arg4->isNullPointerConstant(S.Context,
1039                                      Expr::NPC_ValueDependentIsNotNull) &&
1040         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
1041       S.Diag(TheCall->getArg(4)->getBeginLoc(),
1042              diag::err_opencl_builtin_expected_type)
1043           << TheCall->getDirectCallee()
1044           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1045       return true;
1046     }
1047 
1048     // Sixth argument is always passed as a pointer to clk_event_t.
1049     if (!Arg5->isNullPointerConstant(S.Context,
1050                                      Expr::NPC_ValueDependentIsNotNull) &&
1051         !(Arg5->getType()->isPointerType() &&
1052           Arg5->getType()->getPointeeType()->isClkEventT())) {
1053       S.Diag(TheCall->getArg(5)->getBeginLoc(),
1054              diag::err_opencl_builtin_expected_type)
1055           << TheCall->getDirectCallee()
1056           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1057       return true;
1058     }
1059 
1060     if (NumArgs == 7)
1061       return false;
1062 
1063     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
1064   }
1065 
1066   // None of the specific case has been detected, give generic error
1067   S.Diag(TheCall->getBeginLoc(),
1068          diag::err_opencl_enqueue_kernel_incorrect_args);
1069   return true;
1070 }
1071 
1072 /// Returns OpenCL access qual.
1073 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
1074     return D->getAttr<OpenCLAccessAttr>();
1075 }
1076 
1077 /// Returns true if pipe element type is different from the pointer.
1078 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
1079   const Expr *Arg0 = Call->getArg(0);
1080   // First argument type should always be pipe.
1081   if (!Arg0->getType()->isPipeType()) {
1082     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1083         << Call->getDirectCallee() << Arg0->getSourceRange();
1084     return true;
1085   }
1086   OpenCLAccessAttr *AccessQual =
1087       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
1088   // Validates the access qualifier is compatible with the call.
1089   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
1090   // read_only and write_only, and assumed to be read_only if no qualifier is
1091   // specified.
1092   switch (Call->getDirectCallee()->getBuiltinID()) {
1093   case Builtin::BIread_pipe:
1094   case Builtin::BIreserve_read_pipe:
1095   case Builtin::BIcommit_read_pipe:
1096   case Builtin::BIwork_group_reserve_read_pipe:
1097   case Builtin::BIsub_group_reserve_read_pipe:
1098   case Builtin::BIwork_group_commit_read_pipe:
1099   case Builtin::BIsub_group_commit_read_pipe:
1100     if (!(!AccessQual || AccessQual->isReadOnly())) {
1101       S.Diag(Arg0->getBeginLoc(),
1102              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1103           << "read_only" << Arg0->getSourceRange();
1104       return true;
1105     }
1106     break;
1107   case Builtin::BIwrite_pipe:
1108   case Builtin::BIreserve_write_pipe:
1109   case Builtin::BIcommit_write_pipe:
1110   case Builtin::BIwork_group_reserve_write_pipe:
1111   case Builtin::BIsub_group_reserve_write_pipe:
1112   case Builtin::BIwork_group_commit_write_pipe:
1113   case Builtin::BIsub_group_commit_write_pipe:
1114     if (!(AccessQual && AccessQual->isWriteOnly())) {
1115       S.Diag(Arg0->getBeginLoc(),
1116              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1117           << "write_only" << Arg0->getSourceRange();
1118       return true;
1119     }
1120     break;
1121   default:
1122     break;
1123   }
1124   return false;
1125 }
1126 
1127 /// Returns true if pipe element type is different from the pointer.
1128 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
1129   const Expr *Arg0 = Call->getArg(0);
1130   const Expr *ArgIdx = Call->getArg(Idx);
1131   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
1132   const QualType EltTy = PipeTy->getElementType();
1133   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
1134   // The Idx argument should be a pointer and the type of the pointer and
1135   // the type of pipe element should also be the same.
1136   if (!ArgTy ||
1137       !S.Context.hasSameType(
1138           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
1139     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1140         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
1141         << ArgIdx->getType() << ArgIdx->getSourceRange();
1142     return true;
1143   }
1144   return false;
1145 }
1146 
1147 // Performs semantic analysis for the read/write_pipe call.
1148 // \param S Reference to the semantic analyzer.
1149 // \param Call A pointer to the builtin call.
1150 // \return True if a semantic error has been found, false otherwise.
1151 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
1152   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
1153   // functions have two forms.
1154   switch (Call->getNumArgs()) {
1155   case 2:
1156     if (checkOpenCLPipeArg(S, Call))
1157       return true;
1158     // The call with 2 arguments should be
1159     // read/write_pipe(pipe T, T*).
1160     // Check packet type T.
1161     if (checkOpenCLPipePacketType(S, Call, 1))
1162       return true;
1163     break;
1164 
1165   case 4: {
1166     if (checkOpenCLPipeArg(S, Call))
1167       return true;
1168     // The call with 4 arguments should be
1169     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
1170     // Check reserve_id_t.
1171     if (!Call->getArg(1)->getType()->isReserveIDT()) {
1172       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1173           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1174           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1175       return true;
1176     }
1177 
1178     // Check the index.
1179     const Expr *Arg2 = Call->getArg(2);
1180     if (!Arg2->getType()->isIntegerType() &&
1181         !Arg2->getType()->isUnsignedIntegerType()) {
1182       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1183           << Call->getDirectCallee() << S.Context.UnsignedIntTy
1184           << Arg2->getType() << Arg2->getSourceRange();
1185       return true;
1186     }
1187 
1188     // Check packet type T.
1189     if (checkOpenCLPipePacketType(S, Call, 3))
1190       return true;
1191   } break;
1192   default:
1193     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
1194         << Call->getDirectCallee() << Call->getSourceRange();
1195     return true;
1196   }
1197 
1198   return false;
1199 }
1200 
1201 // Performs a semantic analysis on the {work_group_/sub_group_
1202 //        /_}reserve_{read/write}_pipe
1203 // \param S Reference to the semantic analyzer.
1204 // \param Call The call to the builtin function to be analyzed.
1205 // \return True if a semantic error was found, false otherwise.
1206 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
1207   if (checkArgCount(S, Call, 2))
1208     return true;
1209 
1210   if (checkOpenCLPipeArg(S, Call))
1211     return true;
1212 
1213   // Check the reserve size.
1214   if (!Call->getArg(1)->getType()->isIntegerType() &&
1215       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
1216     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1217         << Call->getDirectCallee() << S.Context.UnsignedIntTy
1218         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1219     return true;
1220   }
1221 
1222   // Since return type of reserve_read/write_pipe built-in function is
1223   // reserve_id_t, which is not defined in the builtin def file , we used int
1224   // as return type and need to override the return type of these functions.
1225   Call->setType(S.Context.OCLReserveIDTy);
1226 
1227   return false;
1228 }
1229 
1230 // Performs a semantic analysis on {work_group_/sub_group_
1231 //        /_}commit_{read/write}_pipe
1232 // \param S Reference to the semantic analyzer.
1233 // \param Call The call to the builtin function to be analyzed.
1234 // \return True if a semantic error was found, false otherwise.
1235 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
1236   if (checkArgCount(S, Call, 2))
1237     return true;
1238 
1239   if (checkOpenCLPipeArg(S, Call))
1240     return true;
1241 
1242   // Check reserve_id_t.
1243   if (!Call->getArg(1)->getType()->isReserveIDT()) {
1244     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1245         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1246         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1247     return true;
1248   }
1249 
1250   return false;
1251 }
1252 
1253 // Performs a semantic analysis on the call to built-in Pipe
1254 //        Query Functions.
1255 // \param S Reference to the semantic analyzer.
1256 // \param Call The call to the builtin function to be analyzed.
1257 // \return True if a semantic error was found, false otherwise.
1258 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
1259   if (checkArgCount(S, Call, 1))
1260     return true;
1261 
1262   if (!Call->getArg(0)->getType()->isPipeType()) {
1263     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1264         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
1265     return true;
1266   }
1267 
1268   return false;
1269 }
1270 
1271 // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
1272 // Performs semantic analysis for the to_global/local/private call.
1273 // \param S Reference to the semantic analyzer.
1274 // \param BuiltinID ID of the builtin function.
1275 // \param Call A pointer to the builtin call.
1276 // \return True if a semantic error has been found, false otherwise.
1277 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
1278                                     CallExpr *Call) {
1279   if (checkArgCount(S, Call, 1))
1280     return true;
1281 
1282   auto RT = Call->getArg(0)->getType();
1283   if (!RT->isPointerType() || RT->getPointeeType()
1284       .getAddressSpace() == LangAS::opencl_constant) {
1285     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
1286         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
1287     return true;
1288   }
1289 
1290   if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
1291     S.Diag(Call->getArg(0)->getBeginLoc(),
1292            diag::warn_opencl_generic_address_space_arg)
1293         << Call->getDirectCallee()->getNameInfo().getAsString()
1294         << Call->getArg(0)->getSourceRange();
1295   }
1296 
1297   RT = RT->getPointeeType();
1298   auto Qual = RT.getQualifiers();
1299   switch (BuiltinID) {
1300   case Builtin::BIto_global:
1301     Qual.setAddressSpace(LangAS::opencl_global);
1302     break;
1303   case Builtin::BIto_local:
1304     Qual.setAddressSpace(LangAS::opencl_local);
1305     break;
1306   case Builtin::BIto_private:
1307     Qual.setAddressSpace(LangAS::opencl_private);
1308     break;
1309   default:
1310     llvm_unreachable("Invalid builtin function");
1311   }
1312   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
1313       RT.getUnqualifiedType(), Qual)));
1314 
1315   return false;
1316 }
1317 
1318 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
1319   if (checkArgCount(S, TheCall, 1))
1320     return ExprError();
1321 
1322   // Compute __builtin_launder's parameter type from the argument.
1323   // The parameter type is:
1324   //  * The type of the argument if it's not an array or function type,
1325   //  Otherwise,
1326   //  * The decayed argument type.
1327   QualType ParamTy = [&]() {
1328     QualType ArgTy = TheCall->getArg(0)->getType();
1329     if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1330       return S.Context.getPointerType(Ty->getElementType());
1331     if (ArgTy->isFunctionType()) {
1332       return S.Context.getPointerType(ArgTy);
1333     }
1334     return ArgTy;
1335   }();
1336 
1337   TheCall->setType(ParamTy);
1338 
1339   auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
1340     if (!ParamTy->isPointerType())
1341       return 0;
1342     if (ParamTy->isFunctionPointerType())
1343       return 1;
1344     if (ParamTy->isVoidPointerType())
1345       return 2;
1346     return llvm::Optional<unsigned>{};
1347   }();
1348   if (DiagSelect.hasValue()) {
1349     S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1350         << DiagSelect.getValue() << TheCall->getSourceRange();
1351     return ExprError();
1352   }
1353 
1354   // We either have an incomplete class type, or we have a class template
1355   // whose instantiation has not been forced. Example:
1356   //
1357   //   template <class T> struct Foo { T value; };
1358   //   Foo<int> *p = nullptr;
1359   //   auto *d = __builtin_launder(p);
1360   if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1361                             diag::err_incomplete_type))
1362     return ExprError();
1363 
1364   assert(ParamTy->getPointeeType()->isObjectType() &&
1365          "Unhandled non-object pointer case");
1366 
1367   InitializedEntity Entity =
1368       InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
1369   ExprResult Arg =
1370       S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1371   if (Arg.isInvalid())
1372     return ExprError();
1373   TheCall->setArg(0, Arg.get());
1374 
1375   return TheCall;
1376 }
1377 
1378 // Emit an error and return true if the current architecture is not in the list
1379 // of supported architectures.
1380 static bool
1381 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1382                           ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
1383   llvm::Triple::ArchType CurArch =
1384       S.getASTContext().getTargetInfo().getTriple().getArch();
1385   if (llvm::is_contained(SupportedArchs, CurArch))
1386     return false;
1387   S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1388       << TheCall->getSourceRange();
1389   return true;
1390 }
1391 
1392 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
1393                                  SourceLocation CallSiteLoc);
1394 
1395 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
1396                                       CallExpr *TheCall) {
1397   switch (TI.getTriple().getArch()) {
1398   default:
1399     // Some builtins don't require additional checking, so just consider these
1400     // acceptable.
1401     return false;
1402   case llvm::Triple::arm:
1403   case llvm::Triple::armeb:
1404   case llvm::Triple::thumb:
1405   case llvm::Triple::thumbeb:
1406     return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
1407   case llvm::Triple::aarch64:
1408   case llvm::Triple::aarch64_32:
1409   case llvm::Triple::aarch64_be:
1410     return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
1411   case llvm::Triple::bpfeb:
1412   case llvm::Triple::bpfel:
1413     return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
1414   case llvm::Triple::hexagon:
1415     return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
1416   case llvm::Triple::mips:
1417   case llvm::Triple::mipsel:
1418   case llvm::Triple::mips64:
1419   case llvm::Triple::mips64el:
1420     return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
1421   case llvm::Triple::systemz:
1422     return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
1423   case llvm::Triple::x86:
1424   case llvm::Triple::x86_64:
1425     return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall);
1426   case llvm::Triple::ppc:
1427   case llvm::Triple::ppcle:
1428   case llvm::Triple::ppc64:
1429   case llvm::Triple::ppc64le:
1430     return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
1431   case llvm::Triple::amdgcn:
1432     return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
1433   case llvm::Triple::riscv32:
1434   case llvm::Triple::riscv64:
1435     return CheckRISCVBuiltinFunctionCall(TI, BuiltinID, TheCall);
1436   }
1437 }
1438 
1439 ExprResult
1440 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
1441                                CallExpr *TheCall) {
1442   ExprResult TheCallResult(TheCall);
1443 
1444   // Find out if any arguments are required to be integer constant expressions.
1445   unsigned ICEArguments = 0;
1446   ASTContext::GetBuiltinTypeError Error;
1447   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
1448   if (Error != ASTContext::GE_None)
1449     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
1450 
1451   // If any arguments are required to be ICE's, check and diagnose.
1452   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
1453     // Skip arguments not required to be ICE's.
1454     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
1455 
1456     llvm::APSInt Result;
1457     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
1458       return true;
1459     ICEArguments &= ~(1 << ArgNo);
1460   }
1461 
1462   switch (BuiltinID) {
1463   case Builtin::BI__builtin___CFStringMakeConstantString:
1464     assert(TheCall->getNumArgs() == 1 &&
1465            "Wrong # arguments to builtin CFStringMakeConstantString");
1466     if (CheckObjCString(TheCall->getArg(0)))
1467       return ExprError();
1468     break;
1469   case Builtin::BI__builtin_ms_va_start:
1470   case Builtin::BI__builtin_stdarg_start:
1471   case Builtin::BI__builtin_va_start:
1472     if (SemaBuiltinVAStart(BuiltinID, TheCall))
1473       return ExprError();
1474     break;
1475   case Builtin::BI__va_start: {
1476     switch (Context.getTargetInfo().getTriple().getArch()) {
1477     case llvm::Triple::aarch64:
1478     case llvm::Triple::arm:
1479     case llvm::Triple::thumb:
1480       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
1481         return ExprError();
1482       break;
1483     default:
1484       if (SemaBuiltinVAStart(BuiltinID, TheCall))
1485         return ExprError();
1486       break;
1487     }
1488     break;
1489   }
1490 
1491   // The acquire, release, and no fence variants are ARM and AArch64 only.
1492   case Builtin::BI_interlockedbittestandset_acq:
1493   case Builtin::BI_interlockedbittestandset_rel:
1494   case Builtin::BI_interlockedbittestandset_nf:
1495   case Builtin::BI_interlockedbittestandreset_acq:
1496   case Builtin::BI_interlockedbittestandreset_rel:
1497   case Builtin::BI_interlockedbittestandreset_nf:
1498     if (CheckBuiltinTargetSupport(
1499             *this, BuiltinID, TheCall,
1500             {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
1501       return ExprError();
1502     break;
1503 
1504   // The 64-bit bittest variants are x64, ARM, and AArch64 only.
1505   case Builtin::BI_bittest64:
1506   case Builtin::BI_bittestandcomplement64:
1507   case Builtin::BI_bittestandreset64:
1508   case Builtin::BI_bittestandset64:
1509   case Builtin::BI_interlockedbittestandreset64:
1510   case Builtin::BI_interlockedbittestandset64:
1511     if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
1512                                   {llvm::Triple::x86_64, llvm::Triple::arm,
1513                                    llvm::Triple::thumb, llvm::Triple::aarch64}))
1514       return ExprError();
1515     break;
1516 
1517   case Builtin::BI__builtin_isgreater:
1518   case Builtin::BI__builtin_isgreaterequal:
1519   case Builtin::BI__builtin_isless:
1520   case Builtin::BI__builtin_islessequal:
1521   case Builtin::BI__builtin_islessgreater:
1522   case Builtin::BI__builtin_isunordered:
1523     if (SemaBuiltinUnorderedCompare(TheCall))
1524       return ExprError();
1525     break;
1526   case Builtin::BI__builtin_fpclassify:
1527     if (SemaBuiltinFPClassification(TheCall, 6))
1528       return ExprError();
1529     break;
1530   case Builtin::BI__builtin_isfinite:
1531   case Builtin::BI__builtin_isinf:
1532   case Builtin::BI__builtin_isinf_sign:
1533   case Builtin::BI__builtin_isnan:
1534   case Builtin::BI__builtin_isnormal:
1535   case Builtin::BI__builtin_signbit:
1536   case Builtin::BI__builtin_signbitf:
1537   case Builtin::BI__builtin_signbitl:
1538     if (SemaBuiltinFPClassification(TheCall, 1))
1539       return ExprError();
1540     break;
1541   case Builtin::BI__builtin_shufflevector:
1542     return SemaBuiltinShuffleVector(TheCall);
1543     // TheCall will be freed by the smart pointer here, but that's fine, since
1544     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1545   case Builtin::BI__builtin_prefetch:
1546     if (SemaBuiltinPrefetch(TheCall))
1547       return ExprError();
1548     break;
1549   case Builtin::BI__builtin_alloca_with_align:
1550     if (SemaBuiltinAllocaWithAlign(TheCall))
1551       return ExprError();
1552     LLVM_FALLTHROUGH;
1553   case Builtin::BI__builtin_alloca:
1554     Diag(TheCall->getBeginLoc(), diag::warn_alloca)
1555         << TheCall->getDirectCallee();
1556     break;
1557   case Builtin::BI__assume:
1558   case Builtin::BI__builtin_assume:
1559     if (SemaBuiltinAssume(TheCall))
1560       return ExprError();
1561     break;
1562   case Builtin::BI__builtin_assume_aligned:
1563     if (SemaBuiltinAssumeAligned(TheCall))
1564       return ExprError();
1565     break;
1566   case Builtin::BI__builtin_dynamic_object_size:
1567   case Builtin::BI__builtin_object_size:
1568     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1569       return ExprError();
1570     break;
1571   case Builtin::BI__builtin_longjmp:
1572     if (SemaBuiltinLongjmp(TheCall))
1573       return ExprError();
1574     break;
1575   case Builtin::BI__builtin_setjmp:
1576     if (SemaBuiltinSetjmp(TheCall))
1577       return ExprError();
1578     break;
1579   case Builtin::BI__builtin_classify_type:
1580     if (checkArgCount(*this, TheCall, 1)) return true;
1581     TheCall->setType(Context.IntTy);
1582     break;
1583   case Builtin::BI__builtin_complex:
1584     if (SemaBuiltinComplex(TheCall))
1585       return ExprError();
1586     break;
1587   case Builtin::BI__builtin_constant_p: {
1588     if (checkArgCount(*this, TheCall, 1)) return true;
1589     ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
1590     if (Arg.isInvalid()) return true;
1591     TheCall->setArg(0, Arg.get());
1592     TheCall->setType(Context.IntTy);
1593     break;
1594   }
1595   case Builtin::BI__builtin_launder:
1596     return SemaBuiltinLaunder(*this, TheCall);
1597   case Builtin::BI__sync_fetch_and_add:
1598   case Builtin::BI__sync_fetch_and_add_1:
1599   case Builtin::BI__sync_fetch_and_add_2:
1600   case Builtin::BI__sync_fetch_and_add_4:
1601   case Builtin::BI__sync_fetch_and_add_8:
1602   case Builtin::BI__sync_fetch_and_add_16:
1603   case Builtin::BI__sync_fetch_and_sub:
1604   case Builtin::BI__sync_fetch_and_sub_1:
1605   case Builtin::BI__sync_fetch_and_sub_2:
1606   case Builtin::BI__sync_fetch_and_sub_4:
1607   case Builtin::BI__sync_fetch_and_sub_8:
1608   case Builtin::BI__sync_fetch_and_sub_16:
1609   case Builtin::BI__sync_fetch_and_or:
1610   case Builtin::BI__sync_fetch_and_or_1:
1611   case Builtin::BI__sync_fetch_and_or_2:
1612   case Builtin::BI__sync_fetch_and_or_4:
1613   case Builtin::BI__sync_fetch_and_or_8:
1614   case Builtin::BI__sync_fetch_and_or_16:
1615   case Builtin::BI__sync_fetch_and_and:
1616   case Builtin::BI__sync_fetch_and_and_1:
1617   case Builtin::BI__sync_fetch_and_and_2:
1618   case Builtin::BI__sync_fetch_and_and_4:
1619   case Builtin::BI__sync_fetch_and_and_8:
1620   case Builtin::BI__sync_fetch_and_and_16:
1621   case Builtin::BI__sync_fetch_and_xor:
1622   case Builtin::BI__sync_fetch_and_xor_1:
1623   case Builtin::BI__sync_fetch_and_xor_2:
1624   case Builtin::BI__sync_fetch_and_xor_4:
1625   case Builtin::BI__sync_fetch_and_xor_8:
1626   case Builtin::BI__sync_fetch_and_xor_16:
1627   case Builtin::BI__sync_fetch_and_nand:
1628   case Builtin::BI__sync_fetch_and_nand_1:
1629   case Builtin::BI__sync_fetch_and_nand_2:
1630   case Builtin::BI__sync_fetch_and_nand_4:
1631   case Builtin::BI__sync_fetch_and_nand_8:
1632   case Builtin::BI__sync_fetch_and_nand_16:
1633   case Builtin::BI__sync_add_and_fetch:
1634   case Builtin::BI__sync_add_and_fetch_1:
1635   case Builtin::BI__sync_add_and_fetch_2:
1636   case Builtin::BI__sync_add_and_fetch_4:
1637   case Builtin::BI__sync_add_and_fetch_8:
1638   case Builtin::BI__sync_add_and_fetch_16:
1639   case Builtin::BI__sync_sub_and_fetch:
1640   case Builtin::BI__sync_sub_and_fetch_1:
1641   case Builtin::BI__sync_sub_and_fetch_2:
1642   case Builtin::BI__sync_sub_and_fetch_4:
1643   case Builtin::BI__sync_sub_and_fetch_8:
1644   case Builtin::BI__sync_sub_and_fetch_16:
1645   case Builtin::BI__sync_and_and_fetch:
1646   case Builtin::BI__sync_and_and_fetch_1:
1647   case Builtin::BI__sync_and_and_fetch_2:
1648   case Builtin::BI__sync_and_and_fetch_4:
1649   case Builtin::BI__sync_and_and_fetch_8:
1650   case Builtin::BI__sync_and_and_fetch_16:
1651   case Builtin::BI__sync_or_and_fetch:
1652   case Builtin::BI__sync_or_and_fetch_1:
1653   case Builtin::BI__sync_or_and_fetch_2:
1654   case Builtin::BI__sync_or_and_fetch_4:
1655   case Builtin::BI__sync_or_and_fetch_8:
1656   case Builtin::BI__sync_or_and_fetch_16:
1657   case Builtin::BI__sync_xor_and_fetch:
1658   case Builtin::BI__sync_xor_and_fetch_1:
1659   case Builtin::BI__sync_xor_and_fetch_2:
1660   case Builtin::BI__sync_xor_and_fetch_4:
1661   case Builtin::BI__sync_xor_and_fetch_8:
1662   case Builtin::BI__sync_xor_and_fetch_16:
1663   case Builtin::BI__sync_nand_and_fetch:
1664   case Builtin::BI__sync_nand_and_fetch_1:
1665   case Builtin::BI__sync_nand_and_fetch_2:
1666   case Builtin::BI__sync_nand_and_fetch_4:
1667   case Builtin::BI__sync_nand_and_fetch_8:
1668   case Builtin::BI__sync_nand_and_fetch_16:
1669   case Builtin::BI__sync_val_compare_and_swap:
1670   case Builtin::BI__sync_val_compare_and_swap_1:
1671   case Builtin::BI__sync_val_compare_and_swap_2:
1672   case Builtin::BI__sync_val_compare_and_swap_4:
1673   case Builtin::BI__sync_val_compare_and_swap_8:
1674   case Builtin::BI__sync_val_compare_and_swap_16:
1675   case Builtin::BI__sync_bool_compare_and_swap:
1676   case Builtin::BI__sync_bool_compare_and_swap_1:
1677   case Builtin::BI__sync_bool_compare_and_swap_2:
1678   case Builtin::BI__sync_bool_compare_and_swap_4:
1679   case Builtin::BI__sync_bool_compare_and_swap_8:
1680   case Builtin::BI__sync_bool_compare_and_swap_16:
1681   case Builtin::BI__sync_lock_test_and_set:
1682   case Builtin::BI__sync_lock_test_and_set_1:
1683   case Builtin::BI__sync_lock_test_and_set_2:
1684   case Builtin::BI__sync_lock_test_and_set_4:
1685   case Builtin::BI__sync_lock_test_and_set_8:
1686   case Builtin::BI__sync_lock_test_and_set_16:
1687   case Builtin::BI__sync_lock_release:
1688   case Builtin::BI__sync_lock_release_1:
1689   case Builtin::BI__sync_lock_release_2:
1690   case Builtin::BI__sync_lock_release_4:
1691   case Builtin::BI__sync_lock_release_8:
1692   case Builtin::BI__sync_lock_release_16:
1693   case Builtin::BI__sync_swap:
1694   case Builtin::BI__sync_swap_1:
1695   case Builtin::BI__sync_swap_2:
1696   case Builtin::BI__sync_swap_4:
1697   case Builtin::BI__sync_swap_8:
1698   case Builtin::BI__sync_swap_16:
1699     return SemaBuiltinAtomicOverloaded(TheCallResult);
1700   case Builtin::BI__sync_synchronize:
1701     Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1702         << TheCall->getCallee()->getSourceRange();
1703     break;
1704   case Builtin::BI__builtin_nontemporal_load:
1705   case Builtin::BI__builtin_nontemporal_store:
1706     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1707   case Builtin::BI__builtin_memcpy_inline: {
1708     clang::Expr *SizeOp = TheCall->getArg(2);
1709     // We warn about copying to or from `nullptr` pointers when `size` is
1710     // greater than 0. When `size` is value dependent we cannot evaluate its
1711     // value so we bail out.
1712     if (SizeOp->isValueDependent())
1713       break;
1714     if (!SizeOp->EvaluateKnownConstInt(Context).isNullValue()) {
1715       CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
1716       CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
1717     }
1718     break;
1719   }
1720 #define BUILTIN(ID, TYPE, ATTRS)
1721 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1722   case Builtin::BI##ID: \
1723     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1724 #include "clang/Basic/Builtins.def"
1725   case Builtin::BI__annotation:
1726     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1727       return ExprError();
1728     break;
1729   case Builtin::BI__builtin_annotation:
1730     if (SemaBuiltinAnnotation(*this, TheCall))
1731       return ExprError();
1732     break;
1733   case Builtin::BI__builtin_addressof:
1734     if (SemaBuiltinAddressof(*this, TheCall))
1735       return ExprError();
1736     break;
1737   case Builtin::BI__builtin_is_aligned:
1738   case Builtin::BI__builtin_align_up:
1739   case Builtin::BI__builtin_align_down:
1740     if (SemaBuiltinAlignment(*this, TheCall, BuiltinID))
1741       return ExprError();
1742     break;
1743   case Builtin::BI__builtin_add_overflow:
1744   case Builtin::BI__builtin_sub_overflow:
1745   case Builtin::BI__builtin_mul_overflow:
1746     if (SemaBuiltinOverflow(*this, TheCall, BuiltinID))
1747       return ExprError();
1748     break;
1749   case Builtin::BI__builtin_operator_new:
1750   case Builtin::BI__builtin_operator_delete: {
1751     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1752     ExprResult Res =
1753         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1754     if (Res.isInvalid())
1755       CorrectDelayedTyposInExpr(TheCallResult.get());
1756     return Res;
1757   }
1758   case Builtin::BI__builtin_dump_struct: {
1759     // We first want to ensure we are called with 2 arguments
1760     if (checkArgCount(*this, TheCall, 2))
1761       return ExprError();
1762     // Ensure that the first argument is of type 'struct XX *'
1763     const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1764     const QualType PtrArgType = PtrArg->getType();
1765     if (!PtrArgType->isPointerType() ||
1766         !PtrArgType->getPointeeType()->isRecordType()) {
1767       Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1768           << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1769           << "structure pointer";
1770       return ExprError();
1771     }
1772 
1773     // Ensure that the second argument is of type 'FunctionType'
1774     const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1775     const QualType FnPtrArgType = FnPtrArg->getType();
1776     if (!FnPtrArgType->isPointerType()) {
1777       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1778           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1779           << FnPtrArgType << "'int (*)(const char *, ...)'";
1780       return ExprError();
1781     }
1782 
1783     const auto *FuncType =
1784         FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1785 
1786     if (!FuncType) {
1787       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1788           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1789           << FnPtrArgType << "'int (*)(const char *, ...)'";
1790       return ExprError();
1791     }
1792 
1793     if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1794       if (!FT->getNumParams()) {
1795         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1796             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1797             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1798         return ExprError();
1799       }
1800       QualType PT = FT->getParamType(0);
1801       if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1802           !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1803           !PT->getPointeeType().isConstQualified()) {
1804         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1805             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1806             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1807         return ExprError();
1808       }
1809     }
1810 
1811     TheCall->setType(Context.IntTy);
1812     break;
1813   }
1814   case Builtin::BI__builtin_expect_with_probability: {
1815     // We first want to ensure we are called with 3 arguments
1816     if (checkArgCount(*this, TheCall, 3))
1817       return ExprError();
1818     // then check probability is constant float in range [0.0, 1.0]
1819     const Expr *ProbArg = TheCall->getArg(2);
1820     SmallVector<PartialDiagnosticAt, 8> Notes;
1821     Expr::EvalResult Eval;
1822     Eval.Diag = &Notes;
1823     if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
1824         !Eval.Val.isFloat()) {
1825       Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
1826           << ProbArg->getSourceRange();
1827       for (const PartialDiagnosticAt &PDiag : Notes)
1828         Diag(PDiag.first, PDiag.second);
1829       return ExprError();
1830     }
1831     llvm::APFloat Probability = Eval.Val.getFloat();
1832     bool LoseInfo = false;
1833     Probability.convert(llvm::APFloat::IEEEdouble(),
1834                         llvm::RoundingMode::Dynamic, &LoseInfo);
1835     if (!(Probability >= llvm::APFloat(0.0) &&
1836           Probability <= llvm::APFloat(1.0))) {
1837       Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
1838           << ProbArg->getSourceRange();
1839       return ExprError();
1840     }
1841     break;
1842   }
1843   case Builtin::BI__builtin_preserve_access_index:
1844     if (SemaBuiltinPreserveAI(*this, TheCall))
1845       return ExprError();
1846     break;
1847   case Builtin::BI__builtin_call_with_static_chain:
1848     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1849       return ExprError();
1850     break;
1851   case Builtin::BI__exception_code:
1852   case Builtin::BI_exception_code:
1853     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1854                                  diag::err_seh___except_block))
1855       return ExprError();
1856     break;
1857   case Builtin::BI__exception_info:
1858   case Builtin::BI_exception_info:
1859     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1860                                  diag::err_seh___except_filter))
1861       return ExprError();
1862     break;
1863   case Builtin::BI__GetExceptionInfo:
1864     if (checkArgCount(*this, TheCall, 1))
1865       return ExprError();
1866 
1867     if (CheckCXXThrowOperand(
1868             TheCall->getBeginLoc(),
1869             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1870             TheCall))
1871       return ExprError();
1872 
1873     TheCall->setType(Context.VoidPtrTy);
1874     break;
1875   // OpenCL v2.0, s6.13.16 - Pipe functions
1876   case Builtin::BIread_pipe:
1877   case Builtin::BIwrite_pipe:
1878     // Since those two functions are declared with var args, we need a semantic
1879     // check for the argument.
1880     if (SemaBuiltinRWPipe(*this, TheCall))
1881       return ExprError();
1882     break;
1883   case Builtin::BIreserve_read_pipe:
1884   case Builtin::BIreserve_write_pipe:
1885   case Builtin::BIwork_group_reserve_read_pipe:
1886   case Builtin::BIwork_group_reserve_write_pipe:
1887     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1888       return ExprError();
1889     break;
1890   case Builtin::BIsub_group_reserve_read_pipe:
1891   case Builtin::BIsub_group_reserve_write_pipe:
1892     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1893         SemaBuiltinReserveRWPipe(*this, TheCall))
1894       return ExprError();
1895     break;
1896   case Builtin::BIcommit_read_pipe:
1897   case Builtin::BIcommit_write_pipe:
1898   case Builtin::BIwork_group_commit_read_pipe:
1899   case Builtin::BIwork_group_commit_write_pipe:
1900     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1901       return ExprError();
1902     break;
1903   case Builtin::BIsub_group_commit_read_pipe:
1904   case Builtin::BIsub_group_commit_write_pipe:
1905     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1906         SemaBuiltinCommitRWPipe(*this, TheCall))
1907       return ExprError();
1908     break;
1909   case Builtin::BIget_pipe_num_packets:
1910   case Builtin::BIget_pipe_max_packets:
1911     if (SemaBuiltinPipePackets(*this, TheCall))
1912       return ExprError();
1913     break;
1914   case Builtin::BIto_global:
1915   case Builtin::BIto_local:
1916   case Builtin::BIto_private:
1917     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1918       return ExprError();
1919     break;
1920   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1921   case Builtin::BIenqueue_kernel:
1922     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1923       return ExprError();
1924     break;
1925   case Builtin::BIget_kernel_work_group_size:
1926   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1927     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1928       return ExprError();
1929     break;
1930   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1931   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1932     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1933       return ExprError();
1934     break;
1935   case Builtin::BI__builtin_os_log_format:
1936     Cleanup.setExprNeedsCleanups(true);
1937     LLVM_FALLTHROUGH;
1938   case Builtin::BI__builtin_os_log_format_buffer_size:
1939     if (SemaBuiltinOSLogFormat(TheCall))
1940       return ExprError();
1941     break;
1942   case Builtin::BI__builtin_frame_address:
1943   case Builtin::BI__builtin_return_address: {
1944     if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
1945       return ExprError();
1946 
1947     // -Wframe-address warning if non-zero passed to builtin
1948     // return/frame address.
1949     Expr::EvalResult Result;
1950     if (!TheCall->getArg(0)->isValueDependent() &&
1951         TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
1952         Result.Val.getInt() != 0)
1953       Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
1954           << ((BuiltinID == Builtin::BI__builtin_return_address)
1955                   ? "__builtin_return_address"
1956                   : "__builtin_frame_address")
1957           << TheCall->getSourceRange();
1958     break;
1959   }
1960 
1961   case Builtin::BI__builtin_matrix_transpose:
1962     return SemaBuiltinMatrixTranspose(TheCall, TheCallResult);
1963 
1964   case Builtin::BI__builtin_matrix_column_major_load:
1965     return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
1966 
1967   case Builtin::BI__builtin_matrix_column_major_store:
1968     return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
1969   }
1970 
1971   // Since the target specific builtins for each arch overlap, only check those
1972   // of the arch we are compiling for.
1973   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1974     if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
1975       assert(Context.getAuxTargetInfo() &&
1976              "Aux Target Builtin, but not an aux target?");
1977 
1978       if (CheckTSBuiltinFunctionCall(
1979               *Context.getAuxTargetInfo(),
1980               Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
1981         return ExprError();
1982     } else {
1983       if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
1984                                      TheCall))
1985         return ExprError();
1986     }
1987   }
1988 
1989   return TheCallResult;
1990 }
1991 
1992 // Get the valid immediate range for the specified NEON type code.
1993 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1994   NeonTypeFlags Type(t);
1995   int IsQuad = ForceQuad ? true : Type.isQuad();
1996   switch (Type.getEltType()) {
1997   case NeonTypeFlags::Int8:
1998   case NeonTypeFlags::Poly8:
1999     return shift ? 7 : (8 << IsQuad) - 1;
2000   case NeonTypeFlags::Int16:
2001   case NeonTypeFlags::Poly16:
2002     return shift ? 15 : (4 << IsQuad) - 1;
2003   case NeonTypeFlags::Int32:
2004     return shift ? 31 : (2 << IsQuad) - 1;
2005   case NeonTypeFlags::Int64:
2006   case NeonTypeFlags::Poly64:
2007     return shift ? 63 : (1 << IsQuad) - 1;
2008   case NeonTypeFlags::Poly128:
2009     return shift ? 127 : (1 << IsQuad) - 1;
2010   case NeonTypeFlags::Float16:
2011     assert(!shift && "cannot shift float types!");
2012     return (4 << IsQuad) - 1;
2013   case NeonTypeFlags::Float32:
2014     assert(!shift && "cannot shift float types!");
2015     return (2 << IsQuad) - 1;
2016   case NeonTypeFlags::Float64:
2017     assert(!shift && "cannot shift float types!");
2018     return (1 << IsQuad) - 1;
2019   case NeonTypeFlags::BFloat16:
2020     assert(!shift && "cannot shift float types!");
2021     return (4 << IsQuad) - 1;
2022   }
2023   llvm_unreachable("Invalid NeonTypeFlag!");
2024 }
2025 
2026 /// getNeonEltType - Return the QualType corresponding to the elements of
2027 /// the vector type specified by the NeonTypeFlags.  This is used to check
2028 /// the pointer arguments for Neon load/store intrinsics.
2029 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
2030                                bool IsPolyUnsigned, bool IsInt64Long) {
2031   switch (Flags.getEltType()) {
2032   case NeonTypeFlags::Int8:
2033     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
2034   case NeonTypeFlags::Int16:
2035     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
2036   case NeonTypeFlags::Int32:
2037     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
2038   case NeonTypeFlags::Int64:
2039     if (IsInt64Long)
2040       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
2041     else
2042       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
2043                                 : Context.LongLongTy;
2044   case NeonTypeFlags::Poly8:
2045     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
2046   case NeonTypeFlags::Poly16:
2047     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
2048   case NeonTypeFlags::Poly64:
2049     if (IsInt64Long)
2050       return Context.UnsignedLongTy;
2051     else
2052       return Context.UnsignedLongLongTy;
2053   case NeonTypeFlags::Poly128:
2054     break;
2055   case NeonTypeFlags::Float16:
2056     return Context.HalfTy;
2057   case NeonTypeFlags::Float32:
2058     return Context.FloatTy;
2059   case NeonTypeFlags::Float64:
2060     return Context.DoubleTy;
2061   case NeonTypeFlags::BFloat16:
2062     return Context.BFloat16Ty;
2063   }
2064   llvm_unreachable("Invalid NeonTypeFlag!");
2065 }
2066 
2067 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2068   // Range check SVE intrinsics that take immediate values.
2069   SmallVector<std::tuple<int,int,int>, 3> ImmChecks;
2070 
2071   switch (BuiltinID) {
2072   default:
2073     return false;
2074 #define GET_SVE_IMMEDIATE_CHECK
2075 #include "clang/Basic/arm_sve_sema_rangechecks.inc"
2076 #undef GET_SVE_IMMEDIATE_CHECK
2077   }
2078 
2079   // Perform all the immediate checks for this builtin call.
2080   bool HasError = false;
2081   for (auto &I : ImmChecks) {
2082     int ArgNum, CheckTy, ElementSizeInBits;
2083     std::tie(ArgNum, CheckTy, ElementSizeInBits) = I;
2084 
2085     typedef bool(*OptionSetCheckFnTy)(int64_t Value);
2086 
2087     // Function that checks whether the operand (ArgNum) is an immediate
2088     // that is one of the predefined values.
2089     auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm,
2090                                    int ErrDiag) -> bool {
2091       // We can't check the value of a dependent argument.
2092       Expr *Arg = TheCall->getArg(ArgNum);
2093       if (Arg->isTypeDependent() || Arg->isValueDependent())
2094         return false;
2095 
2096       // Check constant-ness first.
2097       llvm::APSInt Imm;
2098       if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm))
2099         return true;
2100 
2101       if (!CheckImm(Imm.getSExtValue()))
2102         return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange();
2103       return false;
2104     };
2105 
2106     switch ((SVETypeFlags::ImmCheckType)CheckTy) {
2107     case SVETypeFlags::ImmCheck0_31:
2108       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31))
2109         HasError = true;
2110       break;
2111     case SVETypeFlags::ImmCheck0_13:
2112       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13))
2113         HasError = true;
2114       break;
2115     case SVETypeFlags::ImmCheck1_16:
2116       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16))
2117         HasError = true;
2118       break;
2119     case SVETypeFlags::ImmCheck0_7:
2120       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7))
2121         HasError = true;
2122       break;
2123     case SVETypeFlags::ImmCheckExtract:
2124       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2125                                       (2048 / ElementSizeInBits) - 1))
2126         HasError = true;
2127       break;
2128     case SVETypeFlags::ImmCheckShiftRight:
2129       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits))
2130         HasError = true;
2131       break;
2132     case SVETypeFlags::ImmCheckShiftRightNarrow:
2133       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1,
2134                                       ElementSizeInBits / 2))
2135         HasError = true;
2136       break;
2137     case SVETypeFlags::ImmCheckShiftLeft:
2138       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2139                                       ElementSizeInBits - 1))
2140         HasError = true;
2141       break;
2142     case SVETypeFlags::ImmCheckLaneIndex:
2143       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2144                                       (128 / (1 * ElementSizeInBits)) - 1))
2145         HasError = true;
2146       break;
2147     case SVETypeFlags::ImmCheckLaneIndexCompRotate:
2148       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2149                                       (128 / (2 * ElementSizeInBits)) - 1))
2150         HasError = true;
2151       break;
2152     case SVETypeFlags::ImmCheckLaneIndexDot:
2153       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2154                                       (128 / (4 * ElementSizeInBits)) - 1))
2155         HasError = true;
2156       break;
2157     case SVETypeFlags::ImmCheckComplexRot90_270:
2158       if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; },
2159                               diag::err_rotation_argument_to_cadd))
2160         HasError = true;
2161       break;
2162     case SVETypeFlags::ImmCheckComplexRotAll90:
2163       if (CheckImmediateInSet(
2164               [](int64_t V) {
2165                 return V == 0 || V == 90 || V == 180 || V == 270;
2166               },
2167               diag::err_rotation_argument_to_cmla))
2168         HasError = true;
2169       break;
2170     case SVETypeFlags::ImmCheck0_1:
2171       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1))
2172         HasError = true;
2173       break;
2174     case SVETypeFlags::ImmCheck0_2:
2175       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2))
2176         HasError = true;
2177       break;
2178     case SVETypeFlags::ImmCheck0_3:
2179       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3))
2180         HasError = true;
2181       break;
2182     }
2183   }
2184 
2185   return HasError;
2186 }
2187 
2188 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI,
2189                                         unsigned BuiltinID, CallExpr *TheCall) {
2190   llvm::APSInt Result;
2191   uint64_t mask = 0;
2192   unsigned TV = 0;
2193   int PtrArgNum = -1;
2194   bool HasConstPtr = false;
2195   switch (BuiltinID) {
2196 #define GET_NEON_OVERLOAD_CHECK
2197 #include "clang/Basic/arm_neon.inc"
2198 #include "clang/Basic/arm_fp16.inc"
2199 #undef GET_NEON_OVERLOAD_CHECK
2200   }
2201 
2202   // For NEON intrinsics which are overloaded on vector element type, validate
2203   // the immediate which specifies which variant to emit.
2204   unsigned ImmArg = TheCall->getNumArgs()-1;
2205   if (mask) {
2206     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
2207       return true;
2208 
2209     TV = Result.getLimitedValue(64);
2210     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
2211       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
2212              << TheCall->getArg(ImmArg)->getSourceRange();
2213   }
2214 
2215   if (PtrArgNum >= 0) {
2216     // Check that pointer arguments have the specified type.
2217     Expr *Arg = TheCall->getArg(PtrArgNum);
2218     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
2219       Arg = ICE->getSubExpr();
2220     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
2221     QualType RHSTy = RHS.get()->getType();
2222 
2223     llvm::Triple::ArchType Arch = TI.getTriple().getArch();
2224     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
2225                           Arch == llvm::Triple::aarch64_32 ||
2226                           Arch == llvm::Triple::aarch64_be;
2227     bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong;
2228     QualType EltTy =
2229         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
2230     if (HasConstPtr)
2231       EltTy = EltTy.withConst();
2232     QualType LHSTy = Context.getPointerType(EltTy);
2233     AssignConvertType ConvTy;
2234     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
2235     if (RHS.isInvalid())
2236       return true;
2237     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
2238                                  RHS.get(), AA_Assigning))
2239       return true;
2240   }
2241 
2242   // For NEON intrinsics which take an immediate value as part of the
2243   // instruction, range check them here.
2244   unsigned i = 0, l = 0, u = 0;
2245   switch (BuiltinID) {
2246   default:
2247     return false;
2248   #define GET_NEON_IMMEDIATE_CHECK
2249   #include "clang/Basic/arm_neon.inc"
2250   #include "clang/Basic/arm_fp16.inc"
2251   #undef GET_NEON_IMMEDIATE_CHECK
2252   }
2253 
2254   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2255 }
2256 
2257 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2258   switch (BuiltinID) {
2259   default:
2260     return false;
2261   #include "clang/Basic/arm_mve_builtin_sema.inc"
2262   }
2263 }
2264 
2265 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2266                                        CallExpr *TheCall) {
2267   bool Err = false;
2268   switch (BuiltinID) {
2269   default:
2270     return false;
2271 #include "clang/Basic/arm_cde_builtin_sema.inc"
2272   }
2273 
2274   if (Err)
2275     return true;
2276 
2277   return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true);
2278 }
2279 
2280 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI,
2281                                         const Expr *CoprocArg, bool WantCDE) {
2282   if (isConstantEvaluated())
2283     return false;
2284 
2285   // We can't check the value of a dependent argument.
2286   if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent())
2287     return false;
2288 
2289   llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context);
2290   int64_t CoprocNo = CoprocNoAP.getExtValue();
2291   assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative");
2292 
2293   uint32_t CDECoprocMask = TI.getARMCDECoprocMask();
2294   bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo));
2295 
2296   if (IsCDECoproc != WantCDE)
2297     return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc)
2298            << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange();
2299 
2300   return false;
2301 }
2302 
2303 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
2304                                         unsigned MaxWidth) {
2305   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
2306           BuiltinID == ARM::BI__builtin_arm_ldaex ||
2307           BuiltinID == ARM::BI__builtin_arm_strex ||
2308           BuiltinID == ARM::BI__builtin_arm_stlex ||
2309           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2310           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2311           BuiltinID == AArch64::BI__builtin_arm_strex ||
2312           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
2313          "unexpected ARM builtin");
2314   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
2315                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
2316                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2317                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
2318 
2319   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2320 
2321   // Ensure that we have the proper number of arguments.
2322   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
2323     return true;
2324 
2325   // Inspect the pointer argument of the atomic builtin.  This should always be
2326   // a pointer type, whose element is an integral scalar or pointer type.
2327   // Because it is a pointer type, we don't have to worry about any implicit
2328   // casts here.
2329   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
2330   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
2331   if (PointerArgRes.isInvalid())
2332     return true;
2333   PointerArg = PointerArgRes.get();
2334 
2335   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2336   if (!pointerType) {
2337     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
2338         << PointerArg->getType() << PointerArg->getSourceRange();
2339     return true;
2340   }
2341 
2342   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
2343   // task is to insert the appropriate casts into the AST. First work out just
2344   // what the appropriate type is.
2345   QualType ValType = pointerType->getPointeeType();
2346   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
2347   if (IsLdrex)
2348     AddrType.addConst();
2349 
2350   // Issue a warning if the cast is dodgy.
2351   CastKind CastNeeded = CK_NoOp;
2352   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
2353     CastNeeded = CK_BitCast;
2354     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
2355         << PointerArg->getType() << Context.getPointerType(AddrType)
2356         << AA_Passing << PointerArg->getSourceRange();
2357   }
2358 
2359   // Finally, do the cast and replace the argument with the corrected version.
2360   AddrType = Context.getPointerType(AddrType);
2361   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
2362   if (PointerArgRes.isInvalid())
2363     return true;
2364   PointerArg = PointerArgRes.get();
2365 
2366   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
2367 
2368   // In general, we allow ints, floats and pointers to be loaded and stored.
2369   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2370       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
2371     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
2372         << PointerArg->getType() << PointerArg->getSourceRange();
2373     return true;
2374   }
2375 
2376   // But ARM doesn't have instructions to deal with 128-bit versions.
2377   if (Context.getTypeSize(ValType) > MaxWidth) {
2378     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
2379     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
2380         << PointerArg->getType() << PointerArg->getSourceRange();
2381     return true;
2382   }
2383 
2384   switch (ValType.getObjCLifetime()) {
2385   case Qualifiers::OCL_None:
2386   case Qualifiers::OCL_ExplicitNone:
2387     // okay
2388     break;
2389 
2390   case Qualifiers::OCL_Weak:
2391   case Qualifiers::OCL_Strong:
2392   case Qualifiers::OCL_Autoreleasing:
2393     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
2394         << ValType << PointerArg->getSourceRange();
2395     return true;
2396   }
2397 
2398   if (IsLdrex) {
2399     TheCall->setType(ValType);
2400     return false;
2401   }
2402 
2403   // Initialize the argument to be stored.
2404   ExprResult ValArg = TheCall->getArg(0);
2405   InitializedEntity Entity = InitializedEntity::InitializeParameter(
2406       Context, ValType, /*consume*/ false);
2407   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2408   if (ValArg.isInvalid())
2409     return true;
2410   TheCall->setArg(0, ValArg.get());
2411 
2412   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
2413   // but the custom checker bypasses all default analysis.
2414   TheCall->setType(Context.IntTy);
2415   return false;
2416 }
2417 
2418 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2419                                        CallExpr *TheCall) {
2420   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
2421       BuiltinID == ARM::BI__builtin_arm_ldaex ||
2422       BuiltinID == ARM::BI__builtin_arm_strex ||
2423       BuiltinID == ARM::BI__builtin_arm_stlex) {
2424     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
2425   }
2426 
2427   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
2428     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2429       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
2430   }
2431 
2432   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2433       BuiltinID == ARM::BI__builtin_arm_wsr64)
2434     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
2435 
2436   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
2437       BuiltinID == ARM::BI__builtin_arm_rsrp ||
2438       BuiltinID == ARM::BI__builtin_arm_wsr ||
2439       BuiltinID == ARM::BI__builtin_arm_wsrp)
2440     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2441 
2442   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2443     return true;
2444   if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
2445     return true;
2446   if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall))
2447     return true;
2448 
2449   // For intrinsics which take an immediate value as part of the instruction,
2450   // range check them here.
2451   // FIXME: VFP Intrinsics should error if VFP not present.
2452   switch (BuiltinID) {
2453   default: return false;
2454   case ARM::BI__builtin_arm_ssat:
2455     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
2456   case ARM::BI__builtin_arm_usat:
2457     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
2458   case ARM::BI__builtin_arm_ssat16:
2459     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
2460   case ARM::BI__builtin_arm_usat16:
2461     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2462   case ARM::BI__builtin_arm_vcvtr_f:
2463   case ARM::BI__builtin_arm_vcvtr_d:
2464     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
2465   case ARM::BI__builtin_arm_dmb:
2466   case ARM::BI__builtin_arm_dsb:
2467   case ARM::BI__builtin_arm_isb:
2468   case ARM::BI__builtin_arm_dbg:
2469     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
2470   case ARM::BI__builtin_arm_cdp:
2471   case ARM::BI__builtin_arm_cdp2:
2472   case ARM::BI__builtin_arm_mcr:
2473   case ARM::BI__builtin_arm_mcr2:
2474   case ARM::BI__builtin_arm_mrc:
2475   case ARM::BI__builtin_arm_mrc2:
2476   case ARM::BI__builtin_arm_mcrr:
2477   case ARM::BI__builtin_arm_mcrr2:
2478   case ARM::BI__builtin_arm_mrrc:
2479   case ARM::BI__builtin_arm_mrrc2:
2480   case ARM::BI__builtin_arm_ldc:
2481   case ARM::BI__builtin_arm_ldcl:
2482   case ARM::BI__builtin_arm_ldc2:
2483   case ARM::BI__builtin_arm_ldc2l:
2484   case ARM::BI__builtin_arm_stc:
2485   case ARM::BI__builtin_arm_stcl:
2486   case ARM::BI__builtin_arm_stc2:
2487   case ARM::BI__builtin_arm_stc2l:
2488     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) ||
2489            CheckARMCoprocessorImmediate(TI, TheCall->getArg(0),
2490                                         /*WantCDE*/ false);
2491   }
2492 }
2493 
2494 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI,
2495                                            unsigned BuiltinID,
2496                                            CallExpr *TheCall) {
2497   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2498       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2499       BuiltinID == AArch64::BI__builtin_arm_strex ||
2500       BuiltinID == AArch64::BI__builtin_arm_stlex) {
2501     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
2502   }
2503 
2504   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
2505     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2506       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
2507       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
2508       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
2509   }
2510 
2511   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2512       BuiltinID == AArch64::BI__builtin_arm_wsr64)
2513     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2514 
2515   // Memory Tagging Extensions (MTE) Intrinsics
2516   if (BuiltinID == AArch64::BI__builtin_arm_irg ||
2517       BuiltinID == AArch64::BI__builtin_arm_addg ||
2518       BuiltinID == AArch64::BI__builtin_arm_gmi ||
2519       BuiltinID == AArch64::BI__builtin_arm_ldg ||
2520       BuiltinID == AArch64::BI__builtin_arm_stg ||
2521       BuiltinID == AArch64::BI__builtin_arm_subp) {
2522     return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
2523   }
2524 
2525   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
2526       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2527       BuiltinID == AArch64::BI__builtin_arm_wsr ||
2528       BuiltinID == AArch64::BI__builtin_arm_wsrp)
2529     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2530 
2531   // Only check the valid encoding range. Any constant in this range would be
2532   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
2533   // an exception for incorrect registers. This matches MSVC behavior.
2534   if (BuiltinID == AArch64::BI_ReadStatusReg ||
2535       BuiltinID == AArch64::BI_WriteStatusReg)
2536     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
2537 
2538   if (BuiltinID == AArch64::BI__getReg)
2539     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
2540 
2541   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2542     return true;
2543 
2544   if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall))
2545     return true;
2546 
2547   // For intrinsics which take an immediate value as part of the instruction,
2548   // range check them here.
2549   unsigned i = 0, l = 0, u = 0;
2550   switch (BuiltinID) {
2551   default: return false;
2552   case AArch64::BI__builtin_arm_dmb:
2553   case AArch64::BI__builtin_arm_dsb:
2554   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
2555   case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
2556   }
2557 
2558   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2559 }
2560 
2561 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) {
2562   if (Arg->getType()->getAsPlaceholderType())
2563     return false;
2564 
2565   // The first argument needs to be a record field access.
2566   // If it is an array element access, we delay decision
2567   // to BPF backend to check whether the access is a
2568   // field access or not.
2569   return (Arg->IgnoreParens()->getObjectKind() == OK_BitField ||
2570           dyn_cast<MemberExpr>(Arg->IgnoreParens()) ||
2571           dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens()));
2572 }
2573 
2574 static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S,
2575                             QualType VectorTy, QualType EltTy) {
2576   QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType();
2577   if (!Context.hasSameType(VectorEltTy, EltTy)) {
2578     S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types)
2579         << Call->getSourceRange() << VectorEltTy << EltTy;
2580     return false;
2581   }
2582   return true;
2583 }
2584 
2585 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) {
2586   QualType ArgType = Arg->getType();
2587   if (ArgType->getAsPlaceholderType())
2588     return false;
2589 
2590   // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type
2591   // format:
2592   //   1. __builtin_preserve_type_info(*(<type> *)0, flag);
2593   //   2. <type> var;
2594   //      __builtin_preserve_type_info(var, flag);
2595   if (!dyn_cast<DeclRefExpr>(Arg->IgnoreParens()) &&
2596       !dyn_cast<UnaryOperator>(Arg->IgnoreParens()))
2597     return false;
2598 
2599   // Typedef type.
2600   if (ArgType->getAs<TypedefType>())
2601     return true;
2602 
2603   // Record type or Enum type.
2604   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2605   if (const auto *RT = Ty->getAs<RecordType>()) {
2606     if (!RT->getDecl()->getDeclName().isEmpty())
2607       return true;
2608   } else if (const auto *ET = Ty->getAs<EnumType>()) {
2609     if (!ET->getDecl()->getDeclName().isEmpty())
2610       return true;
2611   }
2612 
2613   return false;
2614 }
2615 
2616 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) {
2617   QualType ArgType = Arg->getType();
2618   if (ArgType->getAsPlaceholderType())
2619     return false;
2620 
2621   // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type
2622   // format:
2623   //   __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>,
2624   //                                 flag);
2625   const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens());
2626   if (!UO)
2627     return false;
2628 
2629   const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr());
2630   if (!CE)
2631     return false;
2632   if (CE->getCastKind() != CK_IntegralToPointer &&
2633       CE->getCastKind() != CK_NullToPointer)
2634     return false;
2635 
2636   // The integer must be from an EnumConstantDecl.
2637   const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr());
2638   if (!DR)
2639     return false;
2640 
2641   const EnumConstantDecl *Enumerator =
2642       dyn_cast<EnumConstantDecl>(DR->getDecl());
2643   if (!Enumerator)
2644     return false;
2645 
2646   // The type must be EnumType.
2647   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2648   const auto *ET = Ty->getAs<EnumType>();
2649   if (!ET)
2650     return false;
2651 
2652   // The enum value must be supported.
2653   for (auto *EDI : ET->getDecl()->enumerators()) {
2654     if (EDI == Enumerator)
2655       return true;
2656   }
2657 
2658   return false;
2659 }
2660 
2661 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
2662                                        CallExpr *TheCall) {
2663   assert((BuiltinID == BPF::BI__builtin_preserve_field_info ||
2664           BuiltinID == BPF::BI__builtin_btf_type_id ||
2665           BuiltinID == BPF::BI__builtin_preserve_type_info ||
2666           BuiltinID == BPF::BI__builtin_preserve_enum_value) &&
2667          "unexpected BPF builtin");
2668 
2669   if (checkArgCount(*this, TheCall, 2))
2670     return true;
2671 
2672   // The second argument needs to be a constant int
2673   Expr *Arg = TheCall->getArg(1);
2674   Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context);
2675   diag::kind kind;
2676   if (!Value) {
2677     if (BuiltinID == BPF::BI__builtin_preserve_field_info)
2678       kind = diag::err_preserve_field_info_not_const;
2679     else if (BuiltinID == BPF::BI__builtin_btf_type_id)
2680       kind = diag::err_btf_type_id_not_const;
2681     else if (BuiltinID == BPF::BI__builtin_preserve_type_info)
2682       kind = diag::err_preserve_type_info_not_const;
2683     else
2684       kind = diag::err_preserve_enum_value_not_const;
2685     Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange();
2686     return true;
2687   }
2688 
2689   // The first argument
2690   Arg = TheCall->getArg(0);
2691   bool InvalidArg = false;
2692   bool ReturnUnsignedInt = true;
2693   if (BuiltinID == BPF::BI__builtin_preserve_field_info) {
2694     if (!isValidBPFPreserveFieldInfoArg(Arg)) {
2695       InvalidArg = true;
2696       kind = diag::err_preserve_field_info_not_field;
2697     }
2698   } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) {
2699     if (!isValidBPFPreserveTypeInfoArg(Arg)) {
2700       InvalidArg = true;
2701       kind = diag::err_preserve_type_info_invalid;
2702     }
2703   } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) {
2704     if (!isValidBPFPreserveEnumValueArg(Arg)) {
2705       InvalidArg = true;
2706       kind = diag::err_preserve_enum_value_invalid;
2707     }
2708     ReturnUnsignedInt = false;
2709   } else if (BuiltinID == BPF::BI__builtin_btf_type_id) {
2710     ReturnUnsignedInt = false;
2711   }
2712 
2713   if (InvalidArg) {
2714     Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange();
2715     return true;
2716   }
2717 
2718   if (ReturnUnsignedInt)
2719     TheCall->setType(Context.UnsignedIntTy);
2720   else
2721     TheCall->setType(Context.UnsignedLongTy);
2722   return false;
2723 }
2724 
2725 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2726   struct ArgInfo {
2727     uint8_t OpNum;
2728     bool IsSigned;
2729     uint8_t BitWidth;
2730     uint8_t Align;
2731   };
2732   struct BuiltinInfo {
2733     unsigned BuiltinID;
2734     ArgInfo Infos[2];
2735   };
2736 
2737   static BuiltinInfo Infos[] = {
2738     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
2739     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
2740     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
2741     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  1 }} },
2742     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
2743     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
2744     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
2745     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
2746     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
2747     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
2748     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
2749 
2750     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
2751     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
2752     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
2753     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
2754     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
2755     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
2756     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
2757     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
2758     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
2759     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
2760     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
2761 
2762     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
2763     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
2764     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
2765     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
2766     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
2767     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
2768     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
2769     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
2770     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
2771     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
2772     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
2773     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
2774     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
2775     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
2776     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
2777     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
2778     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
2779     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
2780     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
2781     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
2782     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
2783     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
2784     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
2785     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
2786     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
2787     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
2788     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
2789     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
2790     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
2791     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
2792     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
2793     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
2794     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
2795     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
2796     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
2797     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
2798     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
2799     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
2800     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
2801     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
2802     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
2803     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
2804     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
2805     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
2806     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
2807     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
2808     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
2809     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
2810     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
2811     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
2812     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
2813     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
2814                                                       {{ 1, false, 6,  0 }} },
2815     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
2816     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
2817     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
2818     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
2819     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
2820     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
2821     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
2822                                                       {{ 1, false, 5,  0 }} },
2823     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
2824     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
2825     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
2826     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
2827     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
2828     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
2829                                                        { 2, false, 5,  0 }} },
2830     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
2831                                                        { 2, false, 6,  0 }} },
2832     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
2833                                                        { 3, false, 5,  0 }} },
2834     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
2835                                                        { 3, false, 6,  0 }} },
2836     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
2837     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
2838     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
2839     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
2840     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
2841     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
2842     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
2843     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
2844     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
2845     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
2846     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
2847     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
2848     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
2849     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
2850     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
2851     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
2852                                                       {{ 2, false, 4,  0 },
2853                                                        { 3, false, 5,  0 }} },
2854     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
2855                                                       {{ 2, false, 4,  0 },
2856                                                        { 3, false, 5,  0 }} },
2857     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
2858                                                       {{ 2, false, 4,  0 },
2859                                                        { 3, false, 5,  0 }} },
2860     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
2861                                                       {{ 2, false, 4,  0 },
2862                                                        { 3, false, 5,  0 }} },
2863     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
2864     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
2865     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
2866     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
2867     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
2868     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
2869     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
2870     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
2871     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
2872     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
2873     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
2874                                                        { 2, false, 5,  0 }} },
2875     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
2876                                                        { 2, false, 6,  0 }} },
2877     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
2878     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
2879     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
2880     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
2881     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
2882     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
2883     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
2884     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
2885     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
2886                                                       {{ 1, false, 4,  0 }} },
2887     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
2888     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
2889                                                       {{ 1, false, 4,  0 }} },
2890     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
2891     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
2892     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
2893     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
2894     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
2895     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
2896     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
2897     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
2898     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
2899     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
2900     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
2901     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
2902     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
2903     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
2904     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
2905     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
2906     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
2907     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
2908     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
2909     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
2910                                                       {{ 3, false, 1,  0 }} },
2911     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
2912     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
2913     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
2914     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
2915                                                       {{ 3, false, 1,  0 }} },
2916     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
2917     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
2918     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
2919     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
2920                                                       {{ 3, false, 1,  0 }} },
2921   };
2922 
2923   // Use a dynamically initialized static to sort the table exactly once on
2924   // first run.
2925   static const bool SortOnce =
2926       (llvm::sort(Infos,
2927                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
2928                    return LHS.BuiltinID < RHS.BuiltinID;
2929                  }),
2930        true);
2931   (void)SortOnce;
2932 
2933   const BuiltinInfo *F = llvm::partition_point(
2934       Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
2935   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
2936     return false;
2937 
2938   bool Error = false;
2939 
2940   for (const ArgInfo &A : F->Infos) {
2941     // Ignore empty ArgInfo elements.
2942     if (A.BitWidth == 0)
2943       continue;
2944 
2945     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
2946     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
2947     if (!A.Align) {
2948       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
2949     } else {
2950       unsigned M = 1 << A.Align;
2951       Min *= M;
2952       Max *= M;
2953       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
2954                SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
2955     }
2956   }
2957   return Error;
2958 }
2959 
2960 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
2961                                            CallExpr *TheCall) {
2962   return CheckHexagonBuiltinArgument(BuiltinID, TheCall);
2963 }
2964 
2965 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI,
2966                                         unsigned BuiltinID, CallExpr *TheCall) {
2967   return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) ||
2968          CheckMipsBuiltinArgument(BuiltinID, TheCall);
2969 }
2970 
2971 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
2972                                CallExpr *TheCall) {
2973 
2974   if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
2975       BuiltinID <= Mips::BI__builtin_mips_lwx) {
2976     if (!TI.hasFeature("dsp"))
2977       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
2978   }
2979 
2980   if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
2981       BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
2982     if (!TI.hasFeature("dspr2"))
2983       return Diag(TheCall->getBeginLoc(),
2984                   diag::err_mips_builtin_requires_dspr2);
2985   }
2986 
2987   if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
2988       BuiltinID <= Mips::BI__builtin_msa_xori_b) {
2989     if (!TI.hasFeature("msa"))
2990       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
2991   }
2992 
2993   return false;
2994 }
2995 
2996 // CheckMipsBuiltinArgument - Checks the constant value passed to the
2997 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
2998 // ordering for DSP is unspecified. MSA is ordered by the data format used
2999 // by the underlying instruction i.e., df/m, df/n and then by size.
3000 //
3001 // FIXME: The size tests here should instead be tablegen'd along with the
3002 //        definitions from include/clang/Basic/BuiltinsMips.def.
3003 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
3004 //        be too.
3005 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
3006   unsigned i = 0, l = 0, u = 0, m = 0;
3007   switch (BuiltinID) {
3008   default: return false;
3009   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
3010   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
3011   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
3012   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
3013   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
3014   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
3015   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
3016   // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
3017   // df/m field.
3018   // These intrinsics take an unsigned 3 bit immediate.
3019   case Mips::BI__builtin_msa_bclri_b:
3020   case Mips::BI__builtin_msa_bnegi_b:
3021   case Mips::BI__builtin_msa_bseti_b:
3022   case Mips::BI__builtin_msa_sat_s_b:
3023   case Mips::BI__builtin_msa_sat_u_b:
3024   case Mips::BI__builtin_msa_slli_b:
3025   case Mips::BI__builtin_msa_srai_b:
3026   case Mips::BI__builtin_msa_srari_b:
3027   case Mips::BI__builtin_msa_srli_b:
3028   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
3029   case Mips::BI__builtin_msa_binsli_b:
3030   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
3031   // These intrinsics take an unsigned 4 bit immediate.
3032   case Mips::BI__builtin_msa_bclri_h:
3033   case Mips::BI__builtin_msa_bnegi_h:
3034   case Mips::BI__builtin_msa_bseti_h:
3035   case Mips::BI__builtin_msa_sat_s_h:
3036   case Mips::BI__builtin_msa_sat_u_h:
3037   case Mips::BI__builtin_msa_slli_h:
3038   case Mips::BI__builtin_msa_srai_h:
3039   case Mips::BI__builtin_msa_srari_h:
3040   case Mips::BI__builtin_msa_srli_h:
3041   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
3042   case Mips::BI__builtin_msa_binsli_h:
3043   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
3044   // These intrinsics take an unsigned 5 bit immediate.
3045   // The first block of intrinsics actually have an unsigned 5 bit field,
3046   // not a df/n field.
3047   case Mips::BI__builtin_msa_cfcmsa:
3048   case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
3049   case Mips::BI__builtin_msa_clei_u_b:
3050   case Mips::BI__builtin_msa_clei_u_h:
3051   case Mips::BI__builtin_msa_clei_u_w:
3052   case Mips::BI__builtin_msa_clei_u_d:
3053   case Mips::BI__builtin_msa_clti_u_b:
3054   case Mips::BI__builtin_msa_clti_u_h:
3055   case Mips::BI__builtin_msa_clti_u_w:
3056   case Mips::BI__builtin_msa_clti_u_d:
3057   case Mips::BI__builtin_msa_maxi_u_b:
3058   case Mips::BI__builtin_msa_maxi_u_h:
3059   case Mips::BI__builtin_msa_maxi_u_w:
3060   case Mips::BI__builtin_msa_maxi_u_d:
3061   case Mips::BI__builtin_msa_mini_u_b:
3062   case Mips::BI__builtin_msa_mini_u_h:
3063   case Mips::BI__builtin_msa_mini_u_w:
3064   case Mips::BI__builtin_msa_mini_u_d:
3065   case Mips::BI__builtin_msa_addvi_b:
3066   case Mips::BI__builtin_msa_addvi_h:
3067   case Mips::BI__builtin_msa_addvi_w:
3068   case Mips::BI__builtin_msa_addvi_d:
3069   case Mips::BI__builtin_msa_bclri_w:
3070   case Mips::BI__builtin_msa_bnegi_w:
3071   case Mips::BI__builtin_msa_bseti_w:
3072   case Mips::BI__builtin_msa_sat_s_w:
3073   case Mips::BI__builtin_msa_sat_u_w:
3074   case Mips::BI__builtin_msa_slli_w:
3075   case Mips::BI__builtin_msa_srai_w:
3076   case Mips::BI__builtin_msa_srari_w:
3077   case Mips::BI__builtin_msa_srli_w:
3078   case Mips::BI__builtin_msa_srlri_w:
3079   case Mips::BI__builtin_msa_subvi_b:
3080   case Mips::BI__builtin_msa_subvi_h:
3081   case Mips::BI__builtin_msa_subvi_w:
3082   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
3083   case Mips::BI__builtin_msa_binsli_w:
3084   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
3085   // These intrinsics take an unsigned 6 bit immediate.
3086   case Mips::BI__builtin_msa_bclri_d:
3087   case Mips::BI__builtin_msa_bnegi_d:
3088   case Mips::BI__builtin_msa_bseti_d:
3089   case Mips::BI__builtin_msa_sat_s_d:
3090   case Mips::BI__builtin_msa_sat_u_d:
3091   case Mips::BI__builtin_msa_slli_d:
3092   case Mips::BI__builtin_msa_srai_d:
3093   case Mips::BI__builtin_msa_srari_d:
3094   case Mips::BI__builtin_msa_srli_d:
3095   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
3096   case Mips::BI__builtin_msa_binsli_d:
3097   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
3098   // These intrinsics take a signed 5 bit immediate.
3099   case Mips::BI__builtin_msa_ceqi_b:
3100   case Mips::BI__builtin_msa_ceqi_h:
3101   case Mips::BI__builtin_msa_ceqi_w:
3102   case Mips::BI__builtin_msa_ceqi_d:
3103   case Mips::BI__builtin_msa_clti_s_b:
3104   case Mips::BI__builtin_msa_clti_s_h:
3105   case Mips::BI__builtin_msa_clti_s_w:
3106   case Mips::BI__builtin_msa_clti_s_d:
3107   case Mips::BI__builtin_msa_clei_s_b:
3108   case Mips::BI__builtin_msa_clei_s_h:
3109   case Mips::BI__builtin_msa_clei_s_w:
3110   case Mips::BI__builtin_msa_clei_s_d:
3111   case Mips::BI__builtin_msa_maxi_s_b:
3112   case Mips::BI__builtin_msa_maxi_s_h:
3113   case Mips::BI__builtin_msa_maxi_s_w:
3114   case Mips::BI__builtin_msa_maxi_s_d:
3115   case Mips::BI__builtin_msa_mini_s_b:
3116   case Mips::BI__builtin_msa_mini_s_h:
3117   case Mips::BI__builtin_msa_mini_s_w:
3118   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
3119   // These intrinsics take an unsigned 8 bit immediate.
3120   case Mips::BI__builtin_msa_andi_b:
3121   case Mips::BI__builtin_msa_nori_b:
3122   case Mips::BI__builtin_msa_ori_b:
3123   case Mips::BI__builtin_msa_shf_b:
3124   case Mips::BI__builtin_msa_shf_h:
3125   case Mips::BI__builtin_msa_shf_w:
3126   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
3127   case Mips::BI__builtin_msa_bseli_b:
3128   case Mips::BI__builtin_msa_bmnzi_b:
3129   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
3130   // df/n format
3131   // These intrinsics take an unsigned 4 bit immediate.
3132   case Mips::BI__builtin_msa_copy_s_b:
3133   case Mips::BI__builtin_msa_copy_u_b:
3134   case Mips::BI__builtin_msa_insve_b:
3135   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
3136   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
3137   // These intrinsics take an unsigned 3 bit immediate.
3138   case Mips::BI__builtin_msa_copy_s_h:
3139   case Mips::BI__builtin_msa_copy_u_h:
3140   case Mips::BI__builtin_msa_insve_h:
3141   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
3142   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3143   // These intrinsics take an unsigned 2 bit immediate.
3144   case Mips::BI__builtin_msa_copy_s_w:
3145   case Mips::BI__builtin_msa_copy_u_w:
3146   case Mips::BI__builtin_msa_insve_w:
3147   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
3148   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3149   // These intrinsics take an unsigned 1 bit immediate.
3150   case Mips::BI__builtin_msa_copy_s_d:
3151   case Mips::BI__builtin_msa_copy_u_d:
3152   case Mips::BI__builtin_msa_insve_d:
3153   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
3154   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3155   // Memory offsets and immediate loads.
3156   // These intrinsics take a signed 10 bit immediate.
3157   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
3158   case Mips::BI__builtin_msa_ldi_h:
3159   case Mips::BI__builtin_msa_ldi_w:
3160   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
3161   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3162   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3163   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3164   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3165   case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break;
3166   case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break;
3167   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3168   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3169   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3170   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
3171   case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break;
3172   case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break;
3173   }
3174 
3175   if (!m)
3176     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3177 
3178   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3179          SemaBuiltinConstantArgMultiple(TheCall, i, m);
3180 }
3181 
3182 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str,
3183 /// advancing the pointer over the consumed characters. The decoded type is
3184 /// returned. If the decoded type represents a constant integer with a
3185 /// constraint on its value then Mask is set to that value. The type descriptors
3186 /// used in Str are specific to PPC MMA builtins and are documented in the file
3187 /// defining the PPC builtins.
3188 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str,
3189                                         unsigned &Mask) {
3190   bool RequireICE = false;
3191   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3192   switch (*Str++) {
3193   case 'V':
3194     return Context.getVectorType(Context.UnsignedCharTy, 16,
3195                                  VectorType::VectorKind::AltiVecVector);
3196   case 'i': {
3197     char *End;
3198     unsigned size = strtoul(Str, &End, 10);
3199     assert(End != Str && "Missing constant parameter constraint");
3200     Str = End;
3201     Mask = size;
3202     return Context.IntTy;
3203   }
3204   case 'W': {
3205     char *End;
3206     unsigned size = strtoul(Str, &End, 10);
3207     assert(End != Str && "Missing PowerPC MMA type size");
3208     Str = End;
3209     QualType Type;
3210     switch (size) {
3211   #define PPC_VECTOR_TYPE(typeName, Id, size) \
3212     case size: Type = Context.Id##Ty; break;
3213   #include "clang/Basic/PPCTypes.def"
3214     default: llvm_unreachable("Invalid PowerPC MMA vector type");
3215     }
3216     bool CheckVectorArgs = false;
3217     while (!CheckVectorArgs) {
3218       switch (*Str++) {
3219       case '*':
3220         Type = Context.getPointerType(Type);
3221         break;
3222       case 'C':
3223         Type = Type.withConst();
3224         break;
3225       default:
3226         CheckVectorArgs = true;
3227         --Str;
3228         break;
3229       }
3230     }
3231     return Type;
3232   }
3233   default:
3234     return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true);
3235   }
3236 }
3237 
3238 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3239                                        CallExpr *TheCall) {
3240   unsigned i = 0, l = 0, u = 0;
3241   bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
3242                       BuiltinID == PPC::BI__builtin_divdeu ||
3243                       BuiltinID == PPC::BI__builtin_bpermd;
3244   bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64;
3245   bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
3246                        BuiltinID == PPC::BI__builtin_divweu ||
3247                        BuiltinID == PPC::BI__builtin_divde ||
3248                        BuiltinID == PPC::BI__builtin_divdeu;
3249 
3250   if (Is64BitBltin && !IsTarget64Bit)
3251     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3252            << TheCall->getSourceRange();
3253 
3254   if ((IsBltinExtDiv && !TI.hasFeature("extdiv")) ||
3255       (BuiltinID == PPC::BI__builtin_bpermd && !TI.hasFeature("bpermd")))
3256     return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3257            << TheCall->getSourceRange();
3258 
3259   auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool {
3260     if (!TI.hasFeature("vsx"))
3261       return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3262              << TheCall->getSourceRange();
3263     return false;
3264   };
3265 
3266   switch (BuiltinID) {
3267   default: return false;
3268   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3269   case PPC::BI__builtin_altivec_crypto_vshasigmad:
3270     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3271            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3272   case PPC::BI__builtin_altivec_dss:
3273     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
3274   case PPC::BI__builtin_tbegin:
3275   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
3276   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
3277   case PPC::BI__builtin_tabortwc:
3278   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
3279   case PPC::BI__builtin_tabortwci:
3280   case PPC::BI__builtin_tabortdci:
3281     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3282            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
3283   case PPC::BI__builtin_altivec_dst:
3284   case PPC::BI__builtin_altivec_dstt:
3285   case PPC::BI__builtin_altivec_dstst:
3286   case PPC::BI__builtin_altivec_dststt:
3287     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
3288   case PPC::BI__builtin_vsx_xxpermdi:
3289   case PPC::BI__builtin_vsx_xxsldwi:
3290     return SemaBuiltinVSX(TheCall);
3291   case PPC::BI__builtin_unpack_vector_int128:
3292     return SemaVSXCheck(TheCall) ||
3293            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3294   case PPC::BI__builtin_pack_vector_int128:
3295     return SemaVSXCheck(TheCall);
3296   case PPC::BI__builtin_altivec_vgnb:
3297      return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7);
3298   case PPC::BI__builtin_altivec_vec_replace_elt:
3299   case PPC::BI__builtin_altivec_vec_replace_unaligned: {
3300     QualType VecTy = TheCall->getArg(0)->getType();
3301     QualType EltTy = TheCall->getArg(1)->getType();
3302     unsigned Width = Context.getIntWidth(EltTy);
3303     return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) ||
3304            !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy);
3305   }
3306   case PPC::BI__builtin_vsx_xxeval:
3307      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255);
3308   case PPC::BI__builtin_altivec_vsldbi:
3309      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3310   case PPC::BI__builtin_altivec_vsrdbi:
3311      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3312   case PPC::BI__builtin_vsx_xxpermx:
3313      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7);
3314 #define CUSTOM_BUILTIN(Name, Types, Acc) \
3315   case PPC::BI__builtin_##Name: \
3316     return SemaBuiltinPPCMMACall(TheCall, Types);
3317 #include "clang/Basic/BuiltinsPPC.def"
3318   }
3319   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3320 }
3321 
3322 // Check if the given type is a non-pointer PPC MMA type. This function is used
3323 // in Sema to prevent invalid uses of restricted PPC MMA types.
3324 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) {
3325   if (Type->isPointerType() || Type->isArrayType())
3326     return false;
3327 
3328   QualType CoreType = Type.getCanonicalType().getUnqualifiedType();
3329 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty
3330   if (false
3331 #include "clang/Basic/PPCTypes.def"
3332      ) {
3333     Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type);
3334     return true;
3335   }
3336   return false;
3337 }
3338 
3339 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID,
3340                                           CallExpr *TheCall) {
3341   // position of memory order and scope arguments in the builtin
3342   unsigned OrderIndex, ScopeIndex;
3343   switch (BuiltinID) {
3344   case AMDGPU::BI__builtin_amdgcn_atomic_inc32:
3345   case AMDGPU::BI__builtin_amdgcn_atomic_inc64:
3346   case AMDGPU::BI__builtin_amdgcn_atomic_dec32:
3347   case AMDGPU::BI__builtin_amdgcn_atomic_dec64:
3348     OrderIndex = 2;
3349     ScopeIndex = 3;
3350     break;
3351   case AMDGPU::BI__builtin_amdgcn_fence:
3352     OrderIndex = 0;
3353     ScopeIndex = 1;
3354     break;
3355   default:
3356     return false;
3357   }
3358 
3359   ExprResult Arg = TheCall->getArg(OrderIndex);
3360   auto ArgExpr = Arg.get();
3361   Expr::EvalResult ArgResult;
3362 
3363   if (!ArgExpr->EvaluateAsInt(ArgResult, Context))
3364     return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int)
3365            << ArgExpr->getType();
3366   int ord = ArgResult.Val.getInt().getZExtValue();
3367 
3368   // Check valididty of memory ordering as per C11 / C++11's memody model.
3369   switch (static_cast<llvm::AtomicOrderingCABI>(ord)) {
3370   case llvm::AtomicOrderingCABI::acquire:
3371   case llvm::AtomicOrderingCABI::release:
3372   case llvm::AtomicOrderingCABI::acq_rel:
3373   case llvm::AtomicOrderingCABI::seq_cst:
3374     break;
3375   default: {
3376     return Diag(ArgExpr->getBeginLoc(),
3377                 diag::warn_atomic_op_has_invalid_memory_order)
3378            << ArgExpr->getSourceRange();
3379   }
3380   }
3381 
3382   Arg = TheCall->getArg(ScopeIndex);
3383   ArgExpr = Arg.get();
3384   Expr::EvalResult ArgResult1;
3385   // Check that sync scope is a constant literal
3386   if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context))
3387     return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal)
3388            << ArgExpr->getType();
3389 
3390   return false;
3391 }
3392 
3393 bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI,
3394                                          unsigned BuiltinID,
3395                                          CallExpr *TheCall) {
3396   // CodeGenFunction can also detect this, but this gives a better error
3397   // message.
3398   StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID);
3399   if (Features.find("experimental-v") != StringRef::npos &&
3400       !TI.hasFeature("experimental-v"))
3401     return Diag(TheCall->getBeginLoc(), diag::err_riscvv_builtin_requires_v)
3402            << TheCall->getSourceRange();
3403 
3404   return false;
3405 }
3406 
3407 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3408                                            CallExpr *TheCall) {
3409   if (BuiltinID == SystemZ::BI__builtin_tabort) {
3410     Expr *Arg = TheCall->getArg(0);
3411     if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context))
3412       if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256)
3413         return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
3414                << Arg->getSourceRange();
3415   }
3416 
3417   // For intrinsics which take an immediate value as part of the instruction,
3418   // range check them here.
3419   unsigned i = 0, l = 0, u = 0;
3420   switch (BuiltinID) {
3421   default: return false;
3422   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3423   case SystemZ::BI__builtin_s390_verimb:
3424   case SystemZ::BI__builtin_s390_verimh:
3425   case SystemZ::BI__builtin_s390_verimf:
3426   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
3427   case SystemZ::BI__builtin_s390_vfaeb:
3428   case SystemZ::BI__builtin_s390_vfaeh:
3429   case SystemZ::BI__builtin_s390_vfaef:
3430   case SystemZ::BI__builtin_s390_vfaebs:
3431   case SystemZ::BI__builtin_s390_vfaehs:
3432   case SystemZ::BI__builtin_s390_vfaefs:
3433   case SystemZ::BI__builtin_s390_vfaezb:
3434   case SystemZ::BI__builtin_s390_vfaezh:
3435   case SystemZ::BI__builtin_s390_vfaezf:
3436   case SystemZ::BI__builtin_s390_vfaezbs:
3437   case SystemZ::BI__builtin_s390_vfaezhs:
3438   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
3439   case SystemZ::BI__builtin_s390_vfisb:
3440   case SystemZ::BI__builtin_s390_vfidb:
3441     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3442            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3443   case SystemZ::BI__builtin_s390_vftcisb:
3444   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3445   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3446   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3447   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3448   case SystemZ::BI__builtin_s390_vstrcb:
3449   case SystemZ::BI__builtin_s390_vstrch:
3450   case SystemZ::BI__builtin_s390_vstrcf:
3451   case SystemZ::BI__builtin_s390_vstrczb:
3452   case SystemZ::BI__builtin_s390_vstrczh:
3453   case SystemZ::BI__builtin_s390_vstrczf:
3454   case SystemZ::BI__builtin_s390_vstrcbs:
3455   case SystemZ::BI__builtin_s390_vstrchs:
3456   case SystemZ::BI__builtin_s390_vstrcfs:
3457   case SystemZ::BI__builtin_s390_vstrczbs:
3458   case SystemZ::BI__builtin_s390_vstrczhs:
3459   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
3460   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3461   case SystemZ::BI__builtin_s390_vfminsb:
3462   case SystemZ::BI__builtin_s390_vfmaxsb:
3463   case SystemZ::BI__builtin_s390_vfmindb:
3464   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
3465   case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
3466   case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
3467   }
3468   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3469 }
3470 
3471 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3472 /// This checks that the target supports __builtin_cpu_supports and
3473 /// that the string argument is constant and valid.
3474 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI,
3475                                    CallExpr *TheCall) {
3476   Expr *Arg = TheCall->getArg(0);
3477 
3478   // Check if the argument is a string literal.
3479   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3480     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3481            << Arg->getSourceRange();
3482 
3483   // Check the contents of the string.
3484   StringRef Feature =
3485       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3486   if (!TI.validateCpuSupports(Feature))
3487     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
3488            << Arg->getSourceRange();
3489   return false;
3490 }
3491 
3492 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3493 /// This checks that the target supports __builtin_cpu_is and
3494 /// that the string argument is constant and valid.
3495 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) {
3496   Expr *Arg = TheCall->getArg(0);
3497 
3498   // Check if the argument is a string literal.
3499   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3500     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3501            << Arg->getSourceRange();
3502 
3503   // Check the contents of the string.
3504   StringRef Feature =
3505       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3506   if (!TI.validateCpuIs(Feature))
3507     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
3508            << Arg->getSourceRange();
3509   return false;
3510 }
3511 
3512 // Check if the rounding mode is legal.
3513 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3514   // Indicates if this instruction has rounding control or just SAE.
3515   bool HasRC = false;
3516 
3517   unsigned ArgNum = 0;
3518   switch (BuiltinID) {
3519   default:
3520     return false;
3521   case X86::BI__builtin_ia32_vcvttsd2si32:
3522   case X86::BI__builtin_ia32_vcvttsd2si64:
3523   case X86::BI__builtin_ia32_vcvttsd2usi32:
3524   case X86::BI__builtin_ia32_vcvttsd2usi64:
3525   case X86::BI__builtin_ia32_vcvttss2si32:
3526   case X86::BI__builtin_ia32_vcvttss2si64:
3527   case X86::BI__builtin_ia32_vcvttss2usi32:
3528   case X86::BI__builtin_ia32_vcvttss2usi64:
3529     ArgNum = 1;
3530     break;
3531   case X86::BI__builtin_ia32_maxpd512:
3532   case X86::BI__builtin_ia32_maxps512:
3533   case X86::BI__builtin_ia32_minpd512:
3534   case X86::BI__builtin_ia32_minps512:
3535     ArgNum = 2;
3536     break;
3537   case X86::BI__builtin_ia32_cvtps2pd512_mask:
3538   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
3539   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
3540   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
3541   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
3542   case X86::BI__builtin_ia32_cvttps2dq512_mask:
3543   case X86::BI__builtin_ia32_cvttps2qq512_mask:
3544   case X86::BI__builtin_ia32_cvttps2udq512_mask:
3545   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
3546   case X86::BI__builtin_ia32_exp2pd_mask:
3547   case X86::BI__builtin_ia32_exp2ps_mask:
3548   case X86::BI__builtin_ia32_getexppd512_mask:
3549   case X86::BI__builtin_ia32_getexpps512_mask:
3550   case X86::BI__builtin_ia32_rcp28pd_mask:
3551   case X86::BI__builtin_ia32_rcp28ps_mask:
3552   case X86::BI__builtin_ia32_rsqrt28pd_mask:
3553   case X86::BI__builtin_ia32_rsqrt28ps_mask:
3554   case X86::BI__builtin_ia32_vcomisd:
3555   case X86::BI__builtin_ia32_vcomiss:
3556   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
3557     ArgNum = 3;
3558     break;
3559   case X86::BI__builtin_ia32_cmppd512_mask:
3560   case X86::BI__builtin_ia32_cmpps512_mask:
3561   case X86::BI__builtin_ia32_cmpsd_mask:
3562   case X86::BI__builtin_ia32_cmpss_mask:
3563   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
3564   case X86::BI__builtin_ia32_getexpsd128_round_mask:
3565   case X86::BI__builtin_ia32_getexpss128_round_mask:
3566   case X86::BI__builtin_ia32_getmantpd512_mask:
3567   case X86::BI__builtin_ia32_getmantps512_mask:
3568   case X86::BI__builtin_ia32_maxsd_round_mask:
3569   case X86::BI__builtin_ia32_maxss_round_mask:
3570   case X86::BI__builtin_ia32_minsd_round_mask:
3571   case X86::BI__builtin_ia32_minss_round_mask:
3572   case X86::BI__builtin_ia32_rcp28sd_round_mask:
3573   case X86::BI__builtin_ia32_rcp28ss_round_mask:
3574   case X86::BI__builtin_ia32_reducepd512_mask:
3575   case X86::BI__builtin_ia32_reduceps512_mask:
3576   case X86::BI__builtin_ia32_rndscalepd_mask:
3577   case X86::BI__builtin_ia32_rndscaleps_mask:
3578   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
3579   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
3580     ArgNum = 4;
3581     break;
3582   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3583   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3584   case X86::BI__builtin_ia32_fixupimmps512_mask:
3585   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3586   case X86::BI__builtin_ia32_fixupimmsd_mask:
3587   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3588   case X86::BI__builtin_ia32_fixupimmss_mask:
3589   case X86::BI__builtin_ia32_fixupimmss_maskz:
3590   case X86::BI__builtin_ia32_getmantsd_round_mask:
3591   case X86::BI__builtin_ia32_getmantss_round_mask:
3592   case X86::BI__builtin_ia32_rangepd512_mask:
3593   case X86::BI__builtin_ia32_rangeps512_mask:
3594   case X86::BI__builtin_ia32_rangesd128_round_mask:
3595   case X86::BI__builtin_ia32_rangess128_round_mask:
3596   case X86::BI__builtin_ia32_reducesd_mask:
3597   case X86::BI__builtin_ia32_reducess_mask:
3598   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3599   case X86::BI__builtin_ia32_rndscaless_round_mask:
3600     ArgNum = 5;
3601     break;
3602   case X86::BI__builtin_ia32_vcvtsd2si64:
3603   case X86::BI__builtin_ia32_vcvtsd2si32:
3604   case X86::BI__builtin_ia32_vcvtsd2usi32:
3605   case X86::BI__builtin_ia32_vcvtsd2usi64:
3606   case X86::BI__builtin_ia32_vcvtss2si32:
3607   case X86::BI__builtin_ia32_vcvtss2si64:
3608   case X86::BI__builtin_ia32_vcvtss2usi32:
3609   case X86::BI__builtin_ia32_vcvtss2usi64:
3610   case X86::BI__builtin_ia32_sqrtpd512:
3611   case X86::BI__builtin_ia32_sqrtps512:
3612     ArgNum = 1;
3613     HasRC = true;
3614     break;
3615   case X86::BI__builtin_ia32_addpd512:
3616   case X86::BI__builtin_ia32_addps512:
3617   case X86::BI__builtin_ia32_divpd512:
3618   case X86::BI__builtin_ia32_divps512:
3619   case X86::BI__builtin_ia32_mulpd512:
3620   case X86::BI__builtin_ia32_mulps512:
3621   case X86::BI__builtin_ia32_subpd512:
3622   case X86::BI__builtin_ia32_subps512:
3623   case X86::BI__builtin_ia32_cvtsi2sd64:
3624   case X86::BI__builtin_ia32_cvtsi2ss32:
3625   case X86::BI__builtin_ia32_cvtsi2ss64:
3626   case X86::BI__builtin_ia32_cvtusi2sd64:
3627   case X86::BI__builtin_ia32_cvtusi2ss32:
3628   case X86::BI__builtin_ia32_cvtusi2ss64:
3629     ArgNum = 2;
3630     HasRC = true;
3631     break;
3632   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
3633   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
3634   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
3635   case X86::BI__builtin_ia32_cvtpd2dq512_mask:
3636   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
3637   case X86::BI__builtin_ia32_cvtpd2udq512_mask:
3638   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
3639   case X86::BI__builtin_ia32_cvtps2dq512_mask:
3640   case X86::BI__builtin_ia32_cvtps2qq512_mask:
3641   case X86::BI__builtin_ia32_cvtps2udq512_mask:
3642   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
3643   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
3644   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
3645   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
3646   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
3647     ArgNum = 3;
3648     HasRC = true;
3649     break;
3650   case X86::BI__builtin_ia32_addss_round_mask:
3651   case X86::BI__builtin_ia32_addsd_round_mask:
3652   case X86::BI__builtin_ia32_divss_round_mask:
3653   case X86::BI__builtin_ia32_divsd_round_mask:
3654   case X86::BI__builtin_ia32_mulss_round_mask:
3655   case X86::BI__builtin_ia32_mulsd_round_mask:
3656   case X86::BI__builtin_ia32_subss_round_mask:
3657   case X86::BI__builtin_ia32_subsd_round_mask:
3658   case X86::BI__builtin_ia32_scalefpd512_mask:
3659   case X86::BI__builtin_ia32_scalefps512_mask:
3660   case X86::BI__builtin_ia32_scalefsd_round_mask:
3661   case X86::BI__builtin_ia32_scalefss_round_mask:
3662   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
3663   case X86::BI__builtin_ia32_sqrtsd_round_mask:
3664   case X86::BI__builtin_ia32_sqrtss_round_mask:
3665   case X86::BI__builtin_ia32_vfmaddsd3_mask:
3666   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
3667   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
3668   case X86::BI__builtin_ia32_vfmaddss3_mask:
3669   case X86::BI__builtin_ia32_vfmaddss3_maskz:
3670   case X86::BI__builtin_ia32_vfmaddss3_mask3:
3671   case X86::BI__builtin_ia32_vfmaddpd512_mask:
3672   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
3673   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
3674   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
3675   case X86::BI__builtin_ia32_vfmaddps512_mask:
3676   case X86::BI__builtin_ia32_vfmaddps512_maskz:
3677   case X86::BI__builtin_ia32_vfmaddps512_mask3:
3678   case X86::BI__builtin_ia32_vfmsubps512_mask3:
3679   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
3680   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
3681   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
3682   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
3683   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
3684   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
3685   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
3686   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
3687     ArgNum = 4;
3688     HasRC = true;
3689     break;
3690   }
3691 
3692   llvm::APSInt Result;
3693 
3694   // We can't check the value of a dependent argument.
3695   Expr *Arg = TheCall->getArg(ArgNum);
3696   if (Arg->isTypeDependent() || Arg->isValueDependent())
3697     return false;
3698 
3699   // Check constant-ness first.
3700   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3701     return true;
3702 
3703   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
3704   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
3705   // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
3706   // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
3707   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
3708       Result == 8/*ROUND_NO_EXC*/ ||
3709       (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
3710       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
3711     return false;
3712 
3713   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
3714          << Arg->getSourceRange();
3715 }
3716 
3717 // Check if the gather/scatter scale is legal.
3718 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
3719                                              CallExpr *TheCall) {
3720   unsigned ArgNum = 0;
3721   switch (BuiltinID) {
3722   default:
3723     return false;
3724   case X86::BI__builtin_ia32_gatherpfdpd:
3725   case X86::BI__builtin_ia32_gatherpfdps:
3726   case X86::BI__builtin_ia32_gatherpfqpd:
3727   case X86::BI__builtin_ia32_gatherpfqps:
3728   case X86::BI__builtin_ia32_scatterpfdpd:
3729   case X86::BI__builtin_ia32_scatterpfdps:
3730   case X86::BI__builtin_ia32_scatterpfqpd:
3731   case X86::BI__builtin_ia32_scatterpfqps:
3732     ArgNum = 3;
3733     break;
3734   case X86::BI__builtin_ia32_gatherd_pd:
3735   case X86::BI__builtin_ia32_gatherd_pd256:
3736   case X86::BI__builtin_ia32_gatherq_pd:
3737   case X86::BI__builtin_ia32_gatherq_pd256:
3738   case X86::BI__builtin_ia32_gatherd_ps:
3739   case X86::BI__builtin_ia32_gatherd_ps256:
3740   case X86::BI__builtin_ia32_gatherq_ps:
3741   case X86::BI__builtin_ia32_gatherq_ps256:
3742   case X86::BI__builtin_ia32_gatherd_q:
3743   case X86::BI__builtin_ia32_gatherd_q256:
3744   case X86::BI__builtin_ia32_gatherq_q:
3745   case X86::BI__builtin_ia32_gatherq_q256:
3746   case X86::BI__builtin_ia32_gatherd_d:
3747   case X86::BI__builtin_ia32_gatherd_d256:
3748   case X86::BI__builtin_ia32_gatherq_d:
3749   case X86::BI__builtin_ia32_gatherq_d256:
3750   case X86::BI__builtin_ia32_gather3div2df:
3751   case X86::BI__builtin_ia32_gather3div2di:
3752   case X86::BI__builtin_ia32_gather3div4df:
3753   case X86::BI__builtin_ia32_gather3div4di:
3754   case X86::BI__builtin_ia32_gather3div4sf:
3755   case X86::BI__builtin_ia32_gather3div4si:
3756   case X86::BI__builtin_ia32_gather3div8sf:
3757   case X86::BI__builtin_ia32_gather3div8si:
3758   case X86::BI__builtin_ia32_gather3siv2df:
3759   case X86::BI__builtin_ia32_gather3siv2di:
3760   case X86::BI__builtin_ia32_gather3siv4df:
3761   case X86::BI__builtin_ia32_gather3siv4di:
3762   case X86::BI__builtin_ia32_gather3siv4sf:
3763   case X86::BI__builtin_ia32_gather3siv4si:
3764   case X86::BI__builtin_ia32_gather3siv8sf:
3765   case X86::BI__builtin_ia32_gather3siv8si:
3766   case X86::BI__builtin_ia32_gathersiv8df:
3767   case X86::BI__builtin_ia32_gathersiv16sf:
3768   case X86::BI__builtin_ia32_gatherdiv8df:
3769   case X86::BI__builtin_ia32_gatherdiv16sf:
3770   case X86::BI__builtin_ia32_gathersiv8di:
3771   case X86::BI__builtin_ia32_gathersiv16si:
3772   case X86::BI__builtin_ia32_gatherdiv8di:
3773   case X86::BI__builtin_ia32_gatherdiv16si:
3774   case X86::BI__builtin_ia32_scatterdiv2df:
3775   case X86::BI__builtin_ia32_scatterdiv2di:
3776   case X86::BI__builtin_ia32_scatterdiv4df:
3777   case X86::BI__builtin_ia32_scatterdiv4di:
3778   case X86::BI__builtin_ia32_scatterdiv4sf:
3779   case X86::BI__builtin_ia32_scatterdiv4si:
3780   case X86::BI__builtin_ia32_scatterdiv8sf:
3781   case X86::BI__builtin_ia32_scatterdiv8si:
3782   case X86::BI__builtin_ia32_scattersiv2df:
3783   case X86::BI__builtin_ia32_scattersiv2di:
3784   case X86::BI__builtin_ia32_scattersiv4df:
3785   case X86::BI__builtin_ia32_scattersiv4di:
3786   case X86::BI__builtin_ia32_scattersiv4sf:
3787   case X86::BI__builtin_ia32_scattersiv4si:
3788   case X86::BI__builtin_ia32_scattersiv8sf:
3789   case X86::BI__builtin_ia32_scattersiv8si:
3790   case X86::BI__builtin_ia32_scattersiv8df:
3791   case X86::BI__builtin_ia32_scattersiv16sf:
3792   case X86::BI__builtin_ia32_scatterdiv8df:
3793   case X86::BI__builtin_ia32_scatterdiv16sf:
3794   case X86::BI__builtin_ia32_scattersiv8di:
3795   case X86::BI__builtin_ia32_scattersiv16si:
3796   case X86::BI__builtin_ia32_scatterdiv8di:
3797   case X86::BI__builtin_ia32_scatterdiv16si:
3798     ArgNum = 4;
3799     break;
3800   }
3801 
3802   llvm::APSInt Result;
3803 
3804   // We can't check the value of a dependent argument.
3805   Expr *Arg = TheCall->getArg(ArgNum);
3806   if (Arg->isTypeDependent() || Arg->isValueDependent())
3807     return false;
3808 
3809   // Check constant-ness first.
3810   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3811     return true;
3812 
3813   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
3814     return false;
3815 
3816   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
3817          << Arg->getSourceRange();
3818 }
3819 
3820 enum { TileRegLow = 0, TileRegHigh = 7 };
3821 
3822 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
3823                                              ArrayRef<int> ArgNums) {
3824   for (int ArgNum : ArgNums) {
3825     if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh))
3826       return true;
3827   }
3828   return false;
3829 }
3830 
3831 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall,
3832                                         ArrayRef<int> ArgNums) {
3833   // Because the max number of tile register is TileRegHigh + 1, so here we use
3834   // each bit to represent the usage of them in bitset.
3835   std::bitset<TileRegHigh + 1> ArgValues;
3836   for (int ArgNum : ArgNums) {
3837     Expr *Arg = TheCall->getArg(ArgNum);
3838     if (Arg->isTypeDependent() || Arg->isValueDependent())
3839       continue;
3840 
3841     llvm::APSInt Result;
3842     if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3843       return true;
3844     int ArgExtValue = Result.getExtValue();
3845     assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) &&
3846            "Incorrect tile register num.");
3847     if (ArgValues.test(ArgExtValue))
3848       return Diag(TheCall->getBeginLoc(),
3849                   diag::err_x86_builtin_tile_arg_duplicate)
3850              << TheCall->getArg(ArgNum)->getSourceRange();
3851     ArgValues.set(ArgExtValue);
3852   }
3853   return false;
3854 }
3855 
3856 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
3857                                                 ArrayRef<int> ArgNums) {
3858   return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) ||
3859          CheckX86BuiltinTileDuplicate(TheCall, ArgNums);
3860 }
3861 
3862 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) {
3863   switch (BuiltinID) {
3864   default:
3865     return false;
3866   case X86::BI__builtin_ia32_tileloadd64:
3867   case X86::BI__builtin_ia32_tileloaddt164:
3868   case X86::BI__builtin_ia32_tilestored64:
3869   case X86::BI__builtin_ia32_tilezero:
3870     return CheckX86BuiltinTileArgumentsRange(TheCall, 0);
3871   case X86::BI__builtin_ia32_tdpbssd:
3872   case X86::BI__builtin_ia32_tdpbsud:
3873   case X86::BI__builtin_ia32_tdpbusd:
3874   case X86::BI__builtin_ia32_tdpbuud:
3875   case X86::BI__builtin_ia32_tdpbf16ps:
3876     return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2});
3877   }
3878 }
3879 static bool isX86_32Builtin(unsigned BuiltinID) {
3880   // These builtins only work on x86-32 targets.
3881   switch (BuiltinID) {
3882   case X86::BI__builtin_ia32_readeflags_u32:
3883   case X86::BI__builtin_ia32_writeeflags_u32:
3884     return true;
3885   }
3886 
3887   return false;
3888 }
3889 
3890 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3891                                        CallExpr *TheCall) {
3892   if (BuiltinID == X86::BI__builtin_cpu_supports)
3893     return SemaBuiltinCpuSupports(*this, TI, TheCall);
3894 
3895   if (BuiltinID == X86::BI__builtin_cpu_is)
3896     return SemaBuiltinCpuIs(*this, TI, TheCall);
3897 
3898   // Check for 32-bit only builtins on a 64-bit target.
3899   const llvm::Triple &TT = TI.getTriple();
3900   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
3901     return Diag(TheCall->getCallee()->getBeginLoc(),
3902                 diag::err_32_bit_builtin_64_bit_tgt);
3903 
3904   // If the intrinsic has rounding or SAE make sure its valid.
3905   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
3906     return true;
3907 
3908   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
3909   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
3910     return true;
3911 
3912   // If the intrinsic has a tile arguments, make sure they are valid.
3913   if (CheckX86BuiltinTileArguments(BuiltinID, TheCall))
3914     return true;
3915 
3916   // For intrinsics which take an immediate value as part of the instruction,
3917   // range check them here.
3918   int i = 0, l = 0, u = 0;
3919   switch (BuiltinID) {
3920   default:
3921     return false;
3922   case X86::BI__builtin_ia32_vec_ext_v2si:
3923   case X86::BI__builtin_ia32_vec_ext_v2di:
3924   case X86::BI__builtin_ia32_vextractf128_pd256:
3925   case X86::BI__builtin_ia32_vextractf128_ps256:
3926   case X86::BI__builtin_ia32_vextractf128_si256:
3927   case X86::BI__builtin_ia32_extract128i256:
3928   case X86::BI__builtin_ia32_extractf64x4_mask:
3929   case X86::BI__builtin_ia32_extracti64x4_mask:
3930   case X86::BI__builtin_ia32_extractf32x8_mask:
3931   case X86::BI__builtin_ia32_extracti32x8_mask:
3932   case X86::BI__builtin_ia32_extractf64x2_256_mask:
3933   case X86::BI__builtin_ia32_extracti64x2_256_mask:
3934   case X86::BI__builtin_ia32_extractf32x4_256_mask:
3935   case X86::BI__builtin_ia32_extracti32x4_256_mask:
3936     i = 1; l = 0; u = 1;
3937     break;
3938   case X86::BI__builtin_ia32_vec_set_v2di:
3939   case X86::BI__builtin_ia32_vinsertf128_pd256:
3940   case X86::BI__builtin_ia32_vinsertf128_ps256:
3941   case X86::BI__builtin_ia32_vinsertf128_si256:
3942   case X86::BI__builtin_ia32_insert128i256:
3943   case X86::BI__builtin_ia32_insertf32x8:
3944   case X86::BI__builtin_ia32_inserti32x8:
3945   case X86::BI__builtin_ia32_insertf64x4:
3946   case X86::BI__builtin_ia32_inserti64x4:
3947   case X86::BI__builtin_ia32_insertf64x2_256:
3948   case X86::BI__builtin_ia32_inserti64x2_256:
3949   case X86::BI__builtin_ia32_insertf32x4_256:
3950   case X86::BI__builtin_ia32_inserti32x4_256:
3951     i = 2; l = 0; u = 1;
3952     break;
3953   case X86::BI__builtin_ia32_vpermilpd:
3954   case X86::BI__builtin_ia32_vec_ext_v4hi:
3955   case X86::BI__builtin_ia32_vec_ext_v4si:
3956   case X86::BI__builtin_ia32_vec_ext_v4sf:
3957   case X86::BI__builtin_ia32_vec_ext_v4di:
3958   case X86::BI__builtin_ia32_extractf32x4_mask:
3959   case X86::BI__builtin_ia32_extracti32x4_mask:
3960   case X86::BI__builtin_ia32_extractf64x2_512_mask:
3961   case X86::BI__builtin_ia32_extracti64x2_512_mask:
3962     i = 1; l = 0; u = 3;
3963     break;
3964   case X86::BI_mm_prefetch:
3965   case X86::BI__builtin_ia32_vec_ext_v8hi:
3966   case X86::BI__builtin_ia32_vec_ext_v8si:
3967     i = 1; l = 0; u = 7;
3968     break;
3969   case X86::BI__builtin_ia32_sha1rnds4:
3970   case X86::BI__builtin_ia32_blendpd:
3971   case X86::BI__builtin_ia32_shufpd:
3972   case X86::BI__builtin_ia32_vec_set_v4hi:
3973   case X86::BI__builtin_ia32_vec_set_v4si:
3974   case X86::BI__builtin_ia32_vec_set_v4di:
3975   case X86::BI__builtin_ia32_shuf_f32x4_256:
3976   case X86::BI__builtin_ia32_shuf_f64x2_256:
3977   case X86::BI__builtin_ia32_shuf_i32x4_256:
3978   case X86::BI__builtin_ia32_shuf_i64x2_256:
3979   case X86::BI__builtin_ia32_insertf64x2_512:
3980   case X86::BI__builtin_ia32_inserti64x2_512:
3981   case X86::BI__builtin_ia32_insertf32x4:
3982   case X86::BI__builtin_ia32_inserti32x4:
3983     i = 2; l = 0; u = 3;
3984     break;
3985   case X86::BI__builtin_ia32_vpermil2pd:
3986   case X86::BI__builtin_ia32_vpermil2pd256:
3987   case X86::BI__builtin_ia32_vpermil2ps:
3988   case X86::BI__builtin_ia32_vpermil2ps256:
3989     i = 3; l = 0; u = 3;
3990     break;
3991   case X86::BI__builtin_ia32_cmpb128_mask:
3992   case X86::BI__builtin_ia32_cmpw128_mask:
3993   case X86::BI__builtin_ia32_cmpd128_mask:
3994   case X86::BI__builtin_ia32_cmpq128_mask:
3995   case X86::BI__builtin_ia32_cmpb256_mask:
3996   case X86::BI__builtin_ia32_cmpw256_mask:
3997   case X86::BI__builtin_ia32_cmpd256_mask:
3998   case X86::BI__builtin_ia32_cmpq256_mask:
3999   case X86::BI__builtin_ia32_cmpb512_mask:
4000   case X86::BI__builtin_ia32_cmpw512_mask:
4001   case X86::BI__builtin_ia32_cmpd512_mask:
4002   case X86::BI__builtin_ia32_cmpq512_mask:
4003   case X86::BI__builtin_ia32_ucmpb128_mask:
4004   case X86::BI__builtin_ia32_ucmpw128_mask:
4005   case X86::BI__builtin_ia32_ucmpd128_mask:
4006   case X86::BI__builtin_ia32_ucmpq128_mask:
4007   case X86::BI__builtin_ia32_ucmpb256_mask:
4008   case X86::BI__builtin_ia32_ucmpw256_mask:
4009   case X86::BI__builtin_ia32_ucmpd256_mask:
4010   case X86::BI__builtin_ia32_ucmpq256_mask:
4011   case X86::BI__builtin_ia32_ucmpb512_mask:
4012   case X86::BI__builtin_ia32_ucmpw512_mask:
4013   case X86::BI__builtin_ia32_ucmpd512_mask:
4014   case X86::BI__builtin_ia32_ucmpq512_mask:
4015   case X86::BI__builtin_ia32_vpcomub:
4016   case X86::BI__builtin_ia32_vpcomuw:
4017   case X86::BI__builtin_ia32_vpcomud:
4018   case X86::BI__builtin_ia32_vpcomuq:
4019   case X86::BI__builtin_ia32_vpcomb:
4020   case X86::BI__builtin_ia32_vpcomw:
4021   case X86::BI__builtin_ia32_vpcomd:
4022   case X86::BI__builtin_ia32_vpcomq:
4023   case X86::BI__builtin_ia32_vec_set_v8hi:
4024   case X86::BI__builtin_ia32_vec_set_v8si:
4025     i = 2; l = 0; u = 7;
4026     break;
4027   case X86::BI__builtin_ia32_vpermilpd256:
4028   case X86::BI__builtin_ia32_roundps:
4029   case X86::BI__builtin_ia32_roundpd:
4030   case X86::BI__builtin_ia32_roundps256:
4031   case X86::BI__builtin_ia32_roundpd256:
4032   case X86::BI__builtin_ia32_getmantpd128_mask:
4033   case X86::BI__builtin_ia32_getmantpd256_mask:
4034   case X86::BI__builtin_ia32_getmantps128_mask:
4035   case X86::BI__builtin_ia32_getmantps256_mask:
4036   case X86::BI__builtin_ia32_getmantpd512_mask:
4037   case X86::BI__builtin_ia32_getmantps512_mask:
4038   case X86::BI__builtin_ia32_vec_ext_v16qi:
4039   case X86::BI__builtin_ia32_vec_ext_v16hi:
4040     i = 1; l = 0; u = 15;
4041     break;
4042   case X86::BI__builtin_ia32_pblendd128:
4043   case X86::BI__builtin_ia32_blendps:
4044   case X86::BI__builtin_ia32_blendpd256:
4045   case X86::BI__builtin_ia32_shufpd256:
4046   case X86::BI__builtin_ia32_roundss:
4047   case X86::BI__builtin_ia32_roundsd:
4048   case X86::BI__builtin_ia32_rangepd128_mask:
4049   case X86::BI__builtin_ia32_rangepd256_mask:
4050   case X86::BI__builtin_ia32_rangepd512_mask:
4051   case X86::BI__builtin_ia32_rangeps128_mask:
4052   case X86::BI__builtin_ia32_rangeps256_mask:
4053   case X86::BI__builtin_ia32_rangeps512_mask:
4054   case X86::BI__builtin_ia32_getmantsd_round_mask:
4055   case X86::BI__builtin_ia32_getmantss_round_mask:
4056   case X86::BI__builtin_ia32_vec_set_v16qi:
4057   case X86::BI__builtin_ia32_vec_set_v16hi:
4058     i = 2; l = 0; u = 15;
4059     break;
4060   case X86::BI__builtin_ia32_vec_ext_v32qi:
4061     i = 1; l = 0; u = 31;
4062     break;
4063   case X86::BI__builtin_ia32_cmpps:
4064   case X86::BI__builtin_ia32_cmpss:
4065   case X86::BI__builtin_ia32_cmppd:
4066   case X86::BI__builtin_ia32_cmpsd:
4067   case X86::BI__builtin_ia32_cmpps256:
4068   case X86::BI__builtin_ia32_cmppd256:
4069   case X86::BI__builtin_ia32_cmpps128_mask:
4070   case X86::BI__builtin_ia32_cmppd128_mask:
4071   case X86::BI__builtin_ia32_cmpps256_mask:
4072   case X86::BI__builtin_ia32_cmppd256_mask:
4073   case X86::BI__builtin_ia32_cmpps512_mask:
4074   case X86::BI__builtin_ia32_cmppd512_mask:
4075   case X86::BI__builtin_ia32_cmpsd_mask:
4076   case X86::BI__builtin_ia32_cmpss_mask:
4077   case X86::BI__builtin_ia32_vec_set_v32qi:
4078     i = 2; l = 0; u = 31;
4079     break;
4080   case X86::BI__builtin_ia32_permdf256:
4081   case X86::BI__builtin_ia32_permdi256:
4082   case X86::BI__builtin_ia32_permdf512:
4083   case X86::BI__builtin_ia32_permdi512:
4084   case X86::BI__builtin_ia32_vpermilps:
4085   case X86::BI__builtin_ia32_vpermilps256:
4086   case X86::BI__builtin_ia32_vpermilpd512:
4087   case X86::BI__builtin_ia32_vpermilps512:
4088   case X86::BI__builtin_ia32_pshufd:
4089   case X86::BI__builtin_ia32_pshufd256:
4090   case X86::BI__builtin_ia32_pshufd512:
4091   case X86::BI__builtin_ia32_pshufhw:
4092   case X86::BI__builtin_ia32_pshufhw256:
4093   case X86::BI__builtin_ia32_pshufhw512:
4094   case X86::BI__builtin_ia32_pshuflw:
4095   case X86::BI__builtin_ia32_pshuflw256:
4096   case X86::BI__builtin_ia32_pshuflw512:
4097   case X86::BI__builtin_ia32_vcvtps2ph:
4098   case X86::BI__builtin_ia32_vcvtps2ph_mask:
4099   case X86::BI__builtin_ia32_vcvtps2ph256:
4100   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
4101   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
4102   case X86::BI__builtin_ia32_rndscaleps_128_mask:
4103   case X86::BI__builtin_ia32_rndscalepd_128_mask:
4104   case X86::BI__builtin_ia32_rndscaleps_256_mask:
4105   case X86::BI__builtin_ia32_rndscalepd_256_mask:
4106   case X86::BI__builtin_ia32_rndscaleps_mask:
4107   case X86::BI__builtin_ia32_rndscalepd_mask:
4108   case X86::BI__builtin_ia32_reducepd128_mask:
4109   case X86::BI__builtin_ia32_reducepd256_mask:
4110   case X86::BI__builtin_ia32_reducepd512_mask:
4111   case X86::BI__builtin_ia32_reduceps128_mask:
4112   case X86::BI__builtin_ia32_reduceps256_mask:
4113   case X86::BI__builtin_ia32_reduceps512_mask:
4114   case X86::BI__builtin_ia32_prold512:
4115   case X86::BI__builtin_ia32_prolq512:
4116   case X86::BI__builtin_ia32_prold128:
4117   case X86::BI__builtin_ia32_prold256:
4118   case X86::BI__builtin_ia32_prolq128:
4119   case X86::BI__builtin_ia32_prolq256:
4120   case X86::BI__builtin_ia32_prord512:
4121   case X86::BI__builtin_ia32_prorq512:
4122   case X86::BI__builtin_ia32_prord128:
4123   case X86::BI__builtin_ia32_prord256:
4124   case X86::BI__builtin_ia32_prorq128:
4125   case X86::BI__builtin_ia32_prorq256:
4126   case X86::BI__builtin_ia32_fpclasspd128_mask:
4127   case X86::BI__builtin_ia32_fpclasspd256_mask:
4128   case X86::BI__builtin_ia32_fpclassps128_mask:
4129   case X86::BI__builtin_ia32_fpclassps256_mask:
4130   case X86::BI__builtin_ia32_fpclassps512_mask:
4131   case X86::BI__builtin_ia32_fpclasspd512_mask:
4132   case X86::BI__builtin_ia32_fpclasssd_mask:
4133   case X86::BI__builtin_ia32_fpclassss_mask:
4134   case X86::BI__builtin_ia32_pslldqi128_byteshift:
4135   case X86::BI__builtin_ia32_pslldqi256_byteshift:
4136   case X86::BI__builtin_ia32_pslldqi512_byteshift:
4137   case X86::BI__builtin_ia32_psrldqi128_byteshift:
4138   case X86::BI__builtin_ia32_psrldqi256_byteshift:
4139   case X86::BI__builtin_ia32_psrldqi512_byteshift:
4140   case X86::BI__builtin_ia32_kshiftliqi:
4141   case X86::BI__builtin_ia32_kshiftlihi:
4142   case X86::BI__builtin_ia32_kshiftlisi:
4143   case X86::BI__builtin_ia32_kshiftlidi:
4144   case X86::BI__builtin_ia32_kshiftriqi:
4145   case X86::BI__builtin_ia32_kshiftrihi:
4146   case X86::BI__builtin_ia32_kshiftrisi:
4147   case X86::BI__builtin_ia32_kshiftridi:
4148     i = 1; l = 0; u = 255;
4149     break;
4150   case X86::BI__builtin_ia32_vperm2f128_pd256:
4151   case X86::BI__builtin_ia32_vperm2f128_ps256:
4152   case X86::BI__builtin_ia32_vperm2f128_si256:
4153   case X86::BI__builtin_ia32_permti256:
4154   case X86::BI__builtin_ia32_pblendw128:
4155   case X86::BI__builtin_ia32_pblendw256:
4156   case X86::BI__builtin_ia32_blendps256:
4157   case X86::BI__builtin_ia32_pblendd256:
4158   case X86::BI__builtin_ia32_palignr128:
4159   case X86::BI__builtin_ia32_palignr256:
4160   case X86::BI__builtin_ia32_palignr512:
4161   case X86::BI__builtin_ia32_alignq512:
4162   case X86::BI__builtin_ia32_alignd512:
4163   case X86::BI__builtin_ia32_alignd128:
4164   case X86::BI__builtin_ia32_alignd256:
4165   case X86::BI__builtin_ia32_alignq128:
4166   case X86::BI__builtin_ia32_alignq256:
4167   case X86::BI__builtin_ia32_vcomisd:
4168   case X86::BI__builtin_ia32_vcomiss:
4169   case X86::BI__builtin_ia32_shuf_f32x4:
4170   case X86::BI__builtin_ia32_shuf_f64x2:
4171   case X86::BI__builtin_ia32_shuf_i32x4:
4172   case X86::BI__builtin_ia32_shuf_i64x2:
4173   case X86::BI__builtin_ia32_shufpd512:
4174   case X86::BI__builtin_ia32_shufps:
4175   case X86::BI__builtin_ia32_shufps256:
4176   case X86::BI__builtin_ia32_shufps512:
4177   case X86::BI__builtin_ia32_dbpsadbw128:
4178   case X86::BI__builtin_ia32_dbpsadbw256:
4179   case X86::BI__builtin_ia32_dbpsadbw512:
4180   case X86::BI__builtin_ia32_vpshldd128:
4181   case X86::BI__builtin_ia32_vpshldd256:
4182   case X86::BI__builtin_ia32_vpshldd512:
4183   case X86::BI__builtin_ia32_vpshldq128:
4184   case X86::BI__builtin_ia32_vpshldq256:
4185   case X86::BI__builtin_ia32_vpshldq512:
4186   case X86::BI__builtin_ia32_vpshldw128:
4187   case X86::BI__builtin_ia32_vpshldw256:
4188   case X86::BI__builtin_ia32_vpshldw512:
4189   case X86::BI__builtin_ia32_vpshrdd128:
4190   case X86::BI__builtin_ia32_vpshrdd256:
4191   case X86::BI__builtin_ia32_vpshrdd512:
4192   case X86::BI__builtin_ia32_vpshrdq128:
4193   case X86::BI__builtin_ia32_vpshrdq256:
4194   case X86::BI__builtin_ia32_vpshrdq512:
4195   case X86::BI__builtin_ia32_vpshrdw128:
4196   case X86::BI__builtin_ia32_vpshrdw256:
4197   case X86::BI__builtin_ia32_vpshrdw512:
4198     i = 2; l = 0; u = 255;
4199     break;
4200   case X86::BI__builtin_ia32_fixupimmpd512_mask:
4201   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
4202   case X86::BI__builtin_ia32_fixupimmps512_mask:
4203   case X86::BI__builtin_ia32_fixupimmps512_maskz:
4204   case X86::BI__builtin_ia32_fixupimmsd_mask:
4205   case X86::BI__builtin_ia32_fixupimmsd_maskz:
4206   case X86::BI__builtin_ia32_fixupimmss_mask:
4207   case X86::BI__builtin_ia32_fixupimmss_maskz:
4208   case X86::BI__builtin_ia32_fixupimmpd128_mask:
4209   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
4210   case X86::BI__builtin_ia32_fixupimmpd256_mask:
4211   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
4212   case X86::BI__builtin_ia32_fixupimmps128_mask:
4213   case X86::BI__builtin_ia32_fixupimmps128_maskz:
4214   case X86::BI__builtin_ia32_fixupimmps256_mask:
4215   case X86::BI__builtin_ia32_fixupimmps256_maskz:
4216   case X86::BI__builtin_ia32_pternlogd512_mask:
4217   case X86::BI__builtin_ia32_pternlogd512_maskz:
4218   case X86::BI__builtin_ia32_pternlogq512_mask:
4219   case X86::BI__builtin_ia32_pternlogq512_maskz:
4220   case X86::BI__builtin_ia32_pternlogd128_mask:
4221   case X86::BI__builtin_ia32_pternlogd128_maskz:
4222   case X86::BI__builtin_ia32_pternlogd256_mask:
4223   case X86::BI__builtin_ia32_pternlogd256_maskz:
4224   case X86::BI__builtin_ia32_pternlogq128_mask:
4225   case X86::BI__builtin_ia32_pternlogq128_maskz:
4226   case X86::BI__builtin_ia32_pternlogq256_mask:
4227   case X86::BI__builtin_ia32_pternlogq256_maskz:
4228     i = 3; l = 0; u = 255;
4229     break;
4230   case X86::BI__builtin_ia32_gatherpfdpd:
4231   case X86::BI__builtin_ia32_gatherpfdps:
4232   case X86::BI__builtin_ia32_gatherpfqpd:
4233   case X86::BI__builtin_ia32_gatherpfqps:
4234   case X86::BI__builtin_ia32_scatterpfdpd:
4235   case X86::BI__builtin_ia32_scatterpfdps:
4236   case X86::BI__builtin_ia32_scatterpfqpd:
4237   case X86::BI__builtin_ia32_scatterpfqps:
4238     i = 4; l = 2; u = 3;
4239     break;
4240   case X86::BI__builtin_ia32_reducesd_mask:
4241   case X86::BI__builtin_ia32_reducess_mask:
4242   case X86::BI__builtin_ia32_rndscalesd_round_mask:
4243   case X86::BI__builtin_ia32_rndscaless_round_mask:
4244     i = 4; l = 0; u = 255;
4245     break;
4246   }
4247 
4248   // Note that we don't force a hard error on the range check here, allowing
4249   // template-generated or macro-generated dead code to potentially have out-of-
4250   // range values. These need to code generate, but don't need to necessarily
4251   // make any sense. We use a warning that defaults to an error.
4252   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
4253 }
4254 
4255 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
4256 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
4257 /// Returns true when the format fits the function and the FormatStringInfo has
4258 /// been populated.
4259 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
4260                                FormatStringInfo *FSI) {
4261   FSI->HasVAListArg = Format->getFirstArg() == 0;
4262   FSI->FormatIdx = Format->getFormatIdx() - 1;
4263   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
4264 
4265   // The way the format attribute works in GCC, the implicit this argument
4266   // of member functions is counted. However, it doesn't appear in our own
4267   // lists, so decrement format_idx in that case.
4268   if (IsCXXMember) {
4269     if(FSI->FormatIdx == 0)
4270       return false;
4271     --FSI->FormatIdx;
4272     if (FSI->FirstDataArg != 0)
4273       --FSI->FirstDataArg;
4274   }
4275   return true;
4276 }
4277 
4278 /// Checks if a the given expression evaluates to null.
4279 ///
4280 /// Returns true if the value evaluates to null.
4281 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4282   // If the expression has non-null type, it doesn't evaluate to null.
4283   if (auto nullability
4284         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
4285     if (*nullability == NullabilityKind::NonNull)
4286       return false;
4287   }
4288 
4289   // As a special case, transparent unions initialized with zero are
4290   // considered null for the purposes of the nonnull attribute.
4291   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
4292     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
4293       if (const CompoundLiteralExpr *CLE =
4294           dyn_cast<CompoundLiteralExpr>(Expr))
4295         if (const InitListExpr *ILE =
4296             dyn_cast<InitListExpr>(CLE->getInitializer()))
4297           Expr = ILE->getInit(0);
4298   }
4299 
4300   bool Result;
4301   return (!Expr->isValueDependent() &&
4302           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
4303           !Result);
4304 }
4305 
4306 static void CheckNonNullArgument(Sema &S,
4307                                  const Expr *ArgExpr,
4308                                  SourceLocation CallSiteLoc) {
4309   if (CheckNonNullExpr(S, ArgExpr))
4310     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
4311                           S.PDiag(diag::warn_null_arg)
4312                               << ArgExpr->getSourceRange());
4313 }
4314 
4315 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
4316   FormatStringInfo FSI;
4317   if ((GetFormatStringType(Format) == FST_NSString) &&
4318       getFormatStringInfo(Format, false, &FSI)) {
4319     Idx = FSI.FormatIdx;
4320     return true;
4321   }
4322   return false;
4323 }
4324 
4325 /// Diagnose use of %s directive in an NSString which is being passed
4326 /// as formatting string to formatting method.
4327 static void
4328 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
4329                                         const NamedDecl *FDecl,
4330                                         Expr **Args,
4331                                         unsigned NumArgs) {
4332   unsigned Idx = 0;
4333   bool Format = false;
4334   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
4335   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
4336     Idx = 2;
4337     Format = true;
4338   }
4339   else
4340     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4341       if (S.GetFormatNSStringIdx(I, Idx)) {
4342         Format = true;
4343         break;
4344       }
4345     }
4346   if (!Format || NumArgs <= Idx)
4347     return;
4348   const Expr *FormatExpr = Args[Idx];
4349   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
4350     FormatExpr = CSCE->getSubExpr();
4351   const StringLiteral *FormatString;
4352   if (const ObjCStringLiteral *OSL =
4353       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
4354     FormatString = OSL->getString();
4355   else
4356     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
4357   if (!FormatString)
4358     return;
4359   if (S.FormatStringHasSArg(FormatString)) {
4360     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
4361       << "%s" << 1 << 1;
4362     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
4363       << FDecl->getDeclName();
4364   }
4365 }
4366 
4367 /// Determine whether the given type has a non-null nullability annotation.
4368 static bool isNonNullType(ASTContext &ctx, QualType type) {
4369   if (auto nullability = type->getNullability(ctx))
4370     return *nullability == NullabilityKind::NonNull;
4371 
4372   return false;
4373 }
4374 
4375 static void CheckNonNullArguments(Sema &S,
4376                                   const NamedDecl *FDecl,
4377                                   const FunctionProtoType *Proto,
4378                                   ArrayRef<const Expr *> Args,
4379                                   SourceLocation CallSiteLoc) {
4380   assert((FDecl || Proto) && "Need a function declaration or prototype");
4381 
4382   // Already checked by by constant evaluator.
4383   if (S.isConstantEvaluated())
4384     return;
4385   // Check the attributes attached to the method/function itself.
4386   llvm::SmallBitVector NonNullArgs;
4387   if (FDecl) {
4388     // Handle the nonnull attribute on the function/method declaration itself.
4389     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4390       if (!NonNull->args_size()) {
4391         // Easy case: all pointer arguments are nonnull.
4392         for (const auto *Arg : Args)
4393           if (S.isValidPointerAttrType(Arg->getType()))
4394             CheckNonNullArgument(S, Arg, CallSiteLoc);
4395         return;
4396       }
4397 
4398       for (const ParamIdx &Idx : NonNull->args()) {
4399         unsigned IdxAST = Idx.getASTIndex();
4400         if (IdxAST >= Args.size())
4401           continue;
4402         if (NonNullArgs.empty())
4403           NonNullArgs.resize(Args.size());
4404         NonNullArgs.set(IdxAST);
4405       }
4406     }
4407   }
4408 
4409   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4410     // Handle the nonnull attribute on the parameters of the
4411     // function/method.
4412     ArrayRef<ParmVarDecl*> parms;
4413     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4414       parms = FD->parameters();
4415     else
4416       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4417 
4418     unsigned ParamIndex = 0;
4419     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4420          I != E; ++I, ++ParamIndex) {
4421       const ParmVarDecl *PVD = *I;
4422       if (PVD->hasAttr<NonNullAttr>() ||
4423           isNonNullType(S.Context, PVD->getType())) {
4424         if (NonNullArgs.empty())
4425           NonNullArgs.resize(Args.size());
4426 
4427         NonNullArgs.set(ParamIndex);
4428       }
4429     }
4430   } else {
4431     // If we have a non-function, non-method declaration but no
4432     // function prototype, try to dig out the function prototype.
4433     if (!Proto) {
4434       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4435         QualType type = VD->getType().getNonReferenceType();
4436         if (auto pointerType = type->getAs<PointerType>())
4437           type = pointerType->getPointeeType();
4438         else if (auto blockType = type->getAs<BlockPointerType>())
4439           type = blockType->getPointeeType();
4440         // FIXME: data member pointers?
4441 
4442         // Dig out the function prototype, if there is one.
4443         Proto = type->getAs<FunctionProtoType>();
4444       }
4445     }
4446 
4447     // Fill in non-null argument information from the nullability
4448     // information on the parameter types (if we have them).
4449     if (Proto) {
4450       unsigned Index = 0;
4451       for (auto paramType : Proto->getParamTypes()) {
4452         if (isNonNullType(S.Context, paramType)) {
4453           if (NonNullArgs.empty())
4454             NonNullArgs.resize(Args.size());
4455 
4456           NonNullArgs.set(Index);
4457         }
4458 
4459         ++Index;
4460       }
4461     }
4462   }
4463 
4464   // Check for non-null arguments.
4465   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4466        ArgIndex != ArgIndexEnd; ++ArgIndex) {
4467     if (NonNullArgs[ArgIndex])
4468       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
4469   }
4470 }
4471 
4472 /// Warn if a pointer or reference argument passed to a function points to an
4473 /// object that is less aligned than the parameter. This can happen when
4474 /// creating a typedef with a lower alignment than the original type and then
4475 /// calling functions defined in terms of the original type.
4476 void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
4477                              StringRef ParamName, QualType ArgTy,
4478                              QualType ParamTy) {
4479 
4480   // If a function accepts a pointer or reference type
4481   if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
4482     return;
4483 
4484   // If the parameter is a pointer type, get the pointee type for the
4485   // argument too. If the parameter is a reference type, don't try to get
4486   // the pointee type for the argument.
4487   if (ParamTy->isPointerType())
4488     ArgTy = ArgTy->getPointeeType();
4489 
4490   // Remove reference or pointer
4491   ParamTy = ParamTy->getPointeeType();
4492 
4493   // Find expected alignment, and the actual alignment of the passed object.
4494   // getTypeAlignInChars requires complete types
4495   if (ParamTy->isIncompleteType() || ArgTy->isIncompleteType() ||
4496       ParamTy->isUndeducedType() || ArgTy->isUndeducedType())
4497     return;
4498 
4499   CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
4500   CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
4501 
4502   // If the argument is less aligned than the parameter, there is a
4503   // potential alignment issue.
4504   if (ArgAlign < ParamAlign)
4505     Diag(Loc, diag::warn_param_mismatched_alignment)
4506         << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
4507         << ParamName << FDecl;
4508 }
4509 
4510 /// Handles the checks for format strings, non-POD arguments to vararg
4511 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
4512 /// attributes.
4513 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
4514                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
4515                      bool IsMemberFunction, SourceLocation Loc,
4516                      SourceRange Range, VariadicCallType CallType) {
4517   // FIXME: We should check as much as we can in the template definition.
4518   if (CurContext->isDependentContext())
4519     return;
4520 
4521   // Printf and scanf checking.
4522   llvm::SmallBitVector CheckedVarArgs;
4523   if (FDecl) {
4524     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4525       // Only create vector if there are format attributes.
4526       CheckedVarArgs.resize(Args.size());
4527 
4528       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4529                            CheckedVarArgs);
4530     }
4531   }
4532 
4533   // Refuse POD arguments that weren't caught by the format string
4534   // checks above.
4535   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4536   if (CallType != VariadicDoesNotApply &&
4537       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4538     unsigned NumParams = Proto ? Proto->getNumParams()
4539                        : FDecl && isa<FunctionDecl>(FDecl)
4540                            ? cast<FunctionDecl>(FDecl)->getNumParams()
4541                        : FDecl && isa<ObjCMethodDecl>(FDecl)
4542                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
4543                        : 0;
4544 
4545     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4546       // Args[ArgIdx] can be null in malformed code.
4547       if (const Expr *Arg = Args[ArgIdx]) {
4548         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4549           checkVariadicArgument(Arg, CallType);
4550       }
4551     }
4552   }
4553 
4554   if (FDecl || Proto) {
4555     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4556 
4557     // Type safety checking.
4558     if (FDecl) {
4559       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4560         CheckArgumentWithTypeTag(I, Args, Loc);
4561     }
4562   }
4563 
4564   // Check that passed arguments match the alignment of original arguments.
4565   // Try to get the missing prototype from the declaration.
4566   if (!Proto && FDecl) {
4567     const auto *FT = FDecl->getFunctionType();
4568     if (isa_and_nonnull<FunctionProtoType>(FT))
4569       Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
4570   }
4571   if (Proto) {
4572     // For variadic functions, we may have more args than parameters.
4573     // For some K&R functions, we may have less args than parameters.
4574     const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
4575     for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
4576       // Args[ArgIdx] can be null in malformed code.
4577       if (const Expr *Arg = Args[ArgIdx]) {
4578         QualType ParamTy = Proto->getParamType(ArgIdx);
4579         QualType ArgTy = Arg->getType();
4580         CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
4581                           ArgTy, ParamTy);
4582       }
4583     }
4584   }
4585 
4586   if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
4587     auto *AA = FDecl->getAttr<AllocAlignAttr>();
4588     const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
4589     if (!Arg->isValueDependent()) {
4590       Expr::EvalResult Align;
4591       if (Arg->EvaluateAsInt(Align, Context)) {
4592         const llvm::APSInt &I = Align.Val.getInt();
4593         if (!I.isPowerOf2())
4594           Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
4595               << Arg->getSourceRange();
4596 
4597         if (I > Sema::MaximumAlignment)
4598           Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
4599               << Arg->getSourceRange() << Sema::MaximumAlignment;
4600       }
4601     }
4602   }
4603 
4604   if (FD)
4605     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4606 }
4607 
4608 /// CheckConstructorCall - Check a constructor call for correctness and safety
4609 /// properties not enforced by the C type system.
4610 void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
4611                                 ArrayRef<const Expr *> Args,
4612                                 const FunctionProtoType *Proto,
4613                                 SourceLocation Loc) {
4614   VariadicCallType CallType =
4615       Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4616 
4617   auto *Ctor = cast<CXXConstructorDecl>(FDecl);
4618   CheckArgAlignment(Loc, FDecl, "'this'", Context.getPointerType(ThisType),
4619                     Context.getPointerType(Ctor->getThisObjectType()));
4620 
4621   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4622             Loc, SourceRange(), CallType);
4623 }
4624 
4625 /// CheckFunctionCall - Check a direct function call for various correctness
4626 /// and safety properties not strictly enforced by the C type system.
4627 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
4628                              const FunctionProtoType *Proto) {
4629   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4630                               isa<CXXMethodDecl>(FDecl);
4631   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4632                           IsMemberOperatorCall;
4633   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4634                                                   TheCall->getCallee());
4635   Expr** Args = TheCall->getArgs();
4636   unsigned NumArgs = TheCall->getNumArgs();
4637 
4638   Expr *ImplicitThis = nullptr;
4639   if (IsMemberOperatorCall) {
4640     // If this is a call to a member operator, hide the first argument
4641     // from checkCall.
4642     // FIXME: Our choice of AST representation here is less than ideal.
4643     ImplicitThis = Args[0];
4644     ++Args;
4645     --NumArgs;
4646   } else if (IsMemberFunction)
4647     ImplicitThis =
4648         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4649 
4650   if (ImplicitThis) {
4651     // ImplicitThis may or may not be a pointer, depending on whether . or -> is
4652     // used.
4653     QualType ThisType = ImplicitThis->getType();
4654     if (!ThisType->isPointerType()) {
4655       assert(!ThisType->isReferenceType());
4656       ThisType = Context.getPointerType(ThisType);
4657     }
4658 
4659     QualType ThisTypeFromDecl =
4660         Context.getPointerType(cast<CXXMethodDecl>(FDecl)->getThisObjectType());
4661 
4662     CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
4663                       ThisTypeFromDecl);
4664   }
4665 
4666   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
4667             IsMemberFunction, TheCall->getRParenLoc(),
4668             TheCall->getCallee()->getSourceRange(), CallType);
4669 
4670   IdentifierInfo *FnInfo = FDecl->getIdentifier();
4671   // None of the checks below are needed for functions that don't have
4672   // simple names (e.g., C++ conversion functions).
4673   if (!FnInfo)
4674     return false;
4675 
4676   CheckTCBEnforcement(TheCall, FDecl);
4677 
4678   CheckAbsoluteValueFunction(TheCall, FDecl);
4679   CheckMaxUnsignedZero(TheCall, FDecl);
4680 
4681   if (getLangOpts().ObjC)
4682     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
4683 
4684   unsigned CMId = FDecl->getMemoryFunctionKind();
4685 
4686   // Handle memory setting and copying functions.
4687   switch (CMId) {
4688   case 0:
4689     return false;
4690   case Builtin::BIstrlcpy: // fallthrough
4691   case Builtin::BIstrlcat:
4692     CheckStrlcpycatArguments(TheCall, FnInfo);
4693     break;
4694   case Builtin::BIstrncat:
4695     CheckStrncatArguments(TheCall, FnInfo);
4696     break;
4697   case Builtin::BIfree:
4698     CheckFreeArguments(TheCall);
4699     break;
4700   default:
4701     CheckMemaccessArguments(TheCall, CMId, FnInfo);
4702   }
4703 
4704   return false;
4705 }
4706 
4707 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
4708                                ArrayRef<const Expr *> Args) {
4709   VariadicCallType CallType =
4710       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
4711 
4712   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
4713             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
4714             CallType);
4715 
4716   return false;
4717 }
4718 
4719 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4720                             const FunctionProtoType *Proto) {
4721   QualType Ty;
4722   if (const auto *V = dyn_cast<VarDecl>(NDecl))
4723     Ty = V->getType().getNonReferenceType();
4724   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4725     Ty = F->getType().getNonReferenceType();
4726   else
4727     return false;
4728 
4729   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4730       !Ty->isFunctionProtoType())
4731     return false;
4732 
4733   VariadicCallType CallType;
4734   if (!Proto || !Proto->isVariadic()) {
4735     CallType = VariadicDoesNotApply;
4736   } else if (Ty->isBlockPointerType()) {
4737     CallType = VariadicBlock;
4738   } else { // Ty->isFunctionPointerType()
4739     CallType = VariadicFunction;
4740   }
4741 
4742   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4743             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4744             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4745             TheCall->getCallee()->getSourceRange(), CallType);
4746 
4747   return false;
4748 }
4749 
4750 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
4751 /// such as function pointers returned from functions.
4752 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4753   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4754                                                   TheCall->getCallee());
4755   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4756             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4757             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4758             TheCall->getCallee()->getSourceRange(), CallType);
4759 
4760   return false;
4761 }
4762 
4763 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4764   if (!llvm::isValidAtomicOrderingCABI(Ordering))
4765     return false;
4766 
4767   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4768   switch (Op) {
4769   case AtomicExpr::AO__c11_atomic_init:
4770   case AtomicExpr::AO__opencl_atomic_init:
4771     llvm_unreachable("There is no ordering argument for an init");
4772 
4773   case AtomicExpr::AO__c11_atomic_load:
4774   case AtomicExpr::AO__opencl_atomic_load:
4775   case AtomicExpr::AO__atomic_load_n:
4776   case AtomicExpr::AO__atomic_load:
4777     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4778            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4779 
4780   case AtomicExpr::AO__c11_atomic_store:
4781   case AtomicExpr::AO__opencl_atomic_store:
4782   case AtomicExpr::AO__atomic_store:
4783   case AtomicExpr::AO__atomic_store_n:
4784     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4785            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4786            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4787 
4788   default:
4789     return true;
4790   }
4791 }
4792 
4793 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
4794                                          AtomicExpr::AtomicOp Op) {
4795   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4796   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4797   MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
4798   return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
4799                          DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
4800                          Op);
4801 }
4802 
4803 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
4804                                  SourceLocation RParenLoc, MultiExprArg Args,
4805                                  AtomicExpr::AtomicOp Op,
4806                                  AtomicArgumentOrder ArgOrder) {
4807   // All the non-OpenCL operations take one of the following forms.
4808   // The OpenCL operations take the __c11 forms with one extra argument for
4809   // synchronization scope.
4810   enum {
4811     // C    __c11_atomic_init(A *, C)
4812     Init,
4813 
4814     // C    __c11_atomic_load(A *, int)
4815     Load,
4816 
4817     // void __atomic_load(A *, CP, int)
4818     LoadCopy,
4819 
4820     // void __atomic_store(A *, CP, int)
4821     Copy,
4822 
4823     // C    __c11_atomic_add(A *, M, int)
4824     Arithmetic,
4825 
4826     // C    __atomic_exchange_n(A *, CP, int)
4827     Xchg,
4828 
4829     // void __atomic_exchange(A *, C *, CP, int)
4830     GNUXchg,
4831 
4832     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4833     C11CmpXchg,
4834 
4835     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4836     GNUCmpXchg
4837   } Form = Init;
4838 
4839   const unsigned NumForm = GNUCmpXchg + 1;
4840   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
4841   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
4842   // where:
4843   //   C is an appropriate type,
4844   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4845   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4846   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4847   //   the int parameters are for orderings.
4848 
4849   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4850       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4851       "need to update code for modified forms");
4852   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
4853                     AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
4854                         AtomicExpr::AO__atomic_load,
4855                 "need to update code for modified C11 atomics");
4856   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
4857                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
4858   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
4859                Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
4860                IsOpenCL;
4861   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4862              Op == AtomicExpr::AO__atomic_store_n ||
4863              Op == AtomicExpr::AO__atomic_exchange_n ||
4864              Op == AtomicExpr::AO__atomic_compare_exchange_n;
4865   bool IsAddSub = false;
4866 
4867   switch (Op) {
4868   case AtomicExpr::AO__c11_atomic_init:
4869   case AtomicExpr::AO__opencl_atomic_init:
4870     Form = Init;
4871     break;
4872 
4873   case AtomicExpr::AO__c11_atomic_load:
4874   case AtomicExpr::AO__opencl_atomic_load:
4875   case AtomicExpr::AO__atomic_load_n:
4876     Form = Load;
4877     break;
4878 
4879   case AtomicExpr::AO__atomic_load:
4880     Form = LoadCopy;
4881     break;
4882 
4883   case AtomicExpr::AO__c11_atomic_store:
4884   case AtomicExpr::AO__opencl_atomic_store:
4885   case AtomicExpr::AO__atomic_store:
4886   case AtomicExpr::AO__atomic_store_n:
4887     Form = Copy;
4888     break;
4889 
4890   case AtomicExpr::AO__c11_atomic_fetch_add:
4891   case AtomicExpr::AO__c11_atomic_fetch_sub:
4892   case AtomicExpr::AO__opencl_atomic_fetch_add:
4893   case AtomicExpr::AO__opencl_atomic_fetch_sub:
4894   case AtomicExpr::AO__atomic_fetch_add:
4895   case AtomicExpr::AO__atomic_fetch_sub:
4896   case AtomicExpr::AO__atomic_add_fetch:
4897   case AtomicExpr::AO__atomic_sub_fetch:
4898     IsAddSub = true;
4899     LLVM_FALLTHROUGH;
4900   case AtomicExpr::AO__c11_atomic_fetch_and:
4901   case AtomicExpr::AO__c11_atomic_fetch_or:
4902   case AtomicExpr::AO__c11_atomic_fetch_xor:
4903   case AtomicExpr::AO__opencl_atomic_fetch_and:
4904   case AtomicExpr::AO__opencl_atomic_fetch_or:
4905   case AtomicExpr::AO__opencl_atomic_fetch_xor:
4906   case AtomicExpr::AO__atomic_fetch_and:
4907   case AtomicExpr::AO__atomic_fetch_or:
4908   case AtomicExpr::AO__atomic_fetch_xor:
4909   case AtomicExpr::AO__atomic_fetch_nand:
4910   case AtomicExpr::AO__atomic_and_fetch:
4911   case AtomicExpr::AO__atomic_or_fetch:
4912   case AtomicExpr::AO__atomic_xor_fetch:
4913   case AtomicExpr::AO__atomic_nand_fetch:
4914   case AtomicExpr::AO__c11_atomic_fetch_min:
4915   case AtomicExpr::AO__c11_atomic_fetch_max:
4916   case AtomicExpr::AO__opencl_atomic_fetch_min:
4917   case AtomicExpr::AO__opencl_atomic_fetch_max:
4918   case AtomicExpr::AO__atomic_min_fetch:
4919   case AtomicExpr::AO__atomic_max_fetch:
4920   case AtomicExpr::AO__atomic_fetch_min:
4921   case AtomicExpr::AO__atomic_fetch_max:
4922     Form = Arithmetic;
4923     break;
4924 
4925   case AtomicExpr::AO__c11_atomic_exchange:
4926   case AtomicExpr::AO__opencl_atomic_exchange:
4927   case AtomicExpr::AO__atomic_exchange_n:
4928     Form = Xchg;
4929     break;
4930 
4931   case AtomicExpr::AO__atomic_exchange:
4932     Form = GNUXchg;
4933     break;
4934 
4935   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
4936   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
4937   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
4938   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
4939     Form = C11CmpXchg;
4940     break;
4941 
4942   case AtomicExpr::AO__atomic_compare_exchange:
4943   case AtomicExpr::AO__atomic_compare_exchange_n:
4944     Form = GNUCmpXchg;
4945     break;
4946   }
4947 
4948   unsigned AdjustedNumArgs = NumArgs[Form];
4949   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
4950     ++AdjustedNumArgs;
4951   // Check we have the right number of arguments.
4952   if (Args.size() < AdjustedNumArgs) {
4953     Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
4954         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4955         << ExprRange;
4956     return ExprError();
4957   } else if (Args.size() > AdjustedNumArgs) {
4958     Diag(Args[AdjustedNumArgs]->getBeginLoc(),
4959          diag::err_typecheck_call_too_many_args)
4960         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4961         << ExprRange;
4962     return ExprError();
4963   }
4964 
4965   // Inspect the first argument of the atomic operation.
4966   Expr *Ptr = Args[0];
4967   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
4968   if (ConvertedPtr.isInvalid())
4969     return ExprError();
4970 
4971   Ptr = ConvertedPtr.get();
4972   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
4973   if (!pointerType) {
4974     Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
4975         << Ptr->getType() << Ptr->getSourceRange();
4976     return ExprError();
4977   }
4978 
4979   // For a __c11 builtin, this should be a pointer to an _Atomic type.
4980   QualType AtomTy = pointerType->getPointeeType(); // 'A'
4981   QualType ValType = AtomTy; // 'C'
4982   if (IsC11) {
4983     if (!AtomTy->isAtomicType()) {
4984       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
4985           << Ptr->getType() << Ptr->getSourceRange();
4986       return ExprError();
4987     }
4988     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
4989         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
4990       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
4991           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
4992           << Ptr->getSourceRange();
4993       return ExprError();
4994     }
4995     ValType = AtomTy->castAs<AtomicType>()->getValueType();
4996   } else if (Form != Load && Form != LoadCopy) {
4997     if (ValType.isConstQualified()) {
4998       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
4999           << Ptr->getType() << Ptr->getSourceRange();
5000       return ExprError();
5001     }
5002   }
5003 
5004   // For an arithmetic operation, the implied arithmetic must be well-formed.
5005   if (Form == Arithmetic) {
5006     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
5007     if (IsAddSub && !ValType->isIntegerType()
5008         && !ValType->isPointerType()) {
5009       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
5010           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5011       return ExprError();
5012     }
5013     if (!IsAddSub && !ValType->isIntegerType()) {
5014       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
5015           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5016       return ExprError();
5017     }
5018     if (IsC11 && ValType->isPointerType() &&
5019         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
5020                             diag::err_incomplete_type)) {
5021       return ExprError();
5022     }
5023   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
5024     // For __atomic_*_n operations, the value type must be a scalar integral or
5025     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
5026     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
5027         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5028     return ExprError();
5029   }
5030 
5031   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
5032       !AtomTy->isScalarType()) {
5033     // For GNU atomics, require a trivially-copyable type. This is not part of
5034     // the GNU atomics specification, but we enforce it for sanity.
5035     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
5036         << Ptr->getType() << Ptr->getSourceRange();
5037     return ExprError();
5038   }
5039 
5040   switch (ValType.getObjCLifetime()) {
5041   case Qualifiers::OCL_None:
5042   case Qualifiers::OCL_ExplicitNone:
5043     // okay
5044     break;
5045 
5046   case Qualifiers::OCL_Weak:
5047   case Qualifiers::OCL_Strong:
5048   case Qualifiers::OCL_Autoreleasing:
5049     // FIXME: Can this happen? By this point, ValType should be known
5050     // to be trivially copyable.
5051     Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
5052         << ValType << Ptr->getSourceRange();
5053     return ExprError();
5054   }
5055 
5056   // All atomic operations have an overload which takes a pointer to a volatile
5057   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
5058   // into the result or the other operands. Similarly atomic_load takes a
5059   // pointer to a const 'A'.
5060   ValType.removeLocalVolatile();
5061   ValType.removeLocalConst();
5062   QualType ResultType = ValType;
5063   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
5064       Form == Init)
5065     ResultType = Context.VoidTy;
5066   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
5067     ResultType = Context.BoolTy;
5068 
5069   // The type of a parameter passed 'by value'. In the GNU atomics, such
5070   // arguments are actually passed as pointers.
5071   QualType ByValType = ValType; // 'CP'
5072   bool IsPassedByAddress = false;
5073   if (!IsC11 && !IsN) {
5074     ByValType = Ptr->getType();
5075     IsPassedByAddress = true;
5076   }
5077 
5078   SmallVector<Expr *, 5> APIOrderedArgs;
5079   if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
5080     APIOrderedArgs.push_back(Args[0]);
5081     switch (Form) {
5082     case Init:
5083     case Load:
5084       APIOrderedArgs.push_back(Args[1]); // Val1/Order
5085       break;
5086     case LoadCopy:
5087     case Copy:
5088     case Arithmetic:
5089     case Xchg:
5090       APIOrderedArgs.push_back(Args[2]); // Val1
5091       APIOrderedArgs.push_back(Args[1]); // Order
5092       break;
5093     case GNUXchg:
5094       APIOrderedArgs.push_back(Args[2]); // Val1
5095       APIOrderedArgs.push_back(Args[3]); // Val2
5096       APIOrderedArgs.push_back(Args[1]); // Order
5097       break;
5098     case C11CmpXchg:
5099       APIOrderedArgs.push_back(Args[2]); // Val1
5100       APIOrderedArgs.push_back(Args[4]); // Val2
5101       APIOrderedArgs.push_back(Args[1]); // Order
5102       APIOrderedArgs.push_back(Args[3]); // OrderFail
5103       break;
5104     case GNUCmpXchg:
5105       APIOrderedArgs.push_back(Args[2]); // Val1
5106       APIOrderedArgs.push_back(Args[4]); // Val2
5107       APIOrderedArgs.push_back(Args[5]); // Weak
5108       APIOrderedArgs.push_back(Args[1]); // Order
5109       APIOrderedArgs.push_back(Args[3]); // OrderFail
5110       break;
5111     }
5112   } else
5113     APIOrderedArgs.append(Args.begin(), Args.end());
5114 
5115   // The first argument's non-CV pointer type is used to deduce the type of
5116   // subsequent arguments, except for:
5117   //  - weak flag (always converted to bool)
5118   //  - memory order (always converted to int)
5119   //  - scope  (always converted to int)
5120   for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
5121     QualType Ty;
5122     if (i < NumVals[Form] + 1) {
5123       switch (i) {
5124       case 0:
5125         // The first argument is always a pointer. It has a fixed type.
5126         // It is always dereferenced, a nullptr is undefined.
5127         CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5128         // Nothing else to do: we already know all we want about this pointer.
5129         continue;
5130       case 1:
5131         // The second argument is the non-atomic operand. For arithmetic, this
5132         // is always passed by value, and for a compare_exchange it is always
5133         // passed by address. For the rest, GNU uses by-address and C11 uses
5134         // by-value.
5135         assert(Form != Load);
5136         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
5137           Ty = ValType;
5138         else if (Form == Copy || Form == Xchg) {
5139           if (IsPassedByAddress) {
5140             // The value pointer is always dereferenced, a nullptr is undefined.
5141             CheckNonNullArgument(*this, APIOrderedArgs[i],
5142                                  ExprRange.getBegin());
5143           }
5144           Ty = ByValType;
5145         } else if (Form == Arithmetic)
5146           Ty = Context.getPointerDiffType();
5147         else {
5148           Expr *ValArg = APIOrderedArgs[i];
5149           // The value pointer is always dereferenced, a nullptr is undefined.
5150           CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
5151           LangAS AS = LangAS::Default;
5152           // Keep address space of non-atomic pointer type.
5153           if (const PointerType *PtrTy =
5154                   ValArg->getType()->getAs<PointerType>()) {
5155             AS = PtrTy->getPointeeType().getAddressSpace();
5156           }
5157           Ty = Context.getPointerType(
5158               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
5159         }
5160         break;
5161       case 2:
5162         // The third argument to compare_exchange / GNU exchange is the desired
5163         // value, either by-value (for the C11 and *_n variant) or as a pointer.
5164         if (IsPassedByAddress)
5165           CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5166         Ty = ByValType;
5167         break;
5168       case 3:
5169         // The fourth argument to GNU compare_exchange is a 'weak' flag.
5170         Ty = Context.BoolTy;
5171         break;
5172       }
5173     } else {
5174       // The order(s) and scope are always converted to int.
5175       Ty = Context.IntTy;
5176     }
5177 
5178     InitializedEntity Entity =
5179         InitializedEntity::InitializeParameter(Context, Ty, false);
5180     ExprResult Arg = APIOrderedArgs[i];
5181     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5182     if (Arg.isInvalid())
5183       return true;
5184     APIOrderedArgs[i] = Arg.get();
5185   }
5186 
5187   // Permute the arguments into a 'consistent' order.
5188   SmallVector<Expr*, 5> SubExprs;
5189   SubExprs.push_back(Ptr);
5190   switch (Form) {
5191   case Init:
5192     // Note, AtomicExpr::getVal1() has a special case for this atomic.
5193     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5194     break;
5195   case Load:
5196     SubExprs.push_back(APIOrderedArgs[1]); // Order
5197     break;
5198   case LoadCopy:
5199   case Copy:
5200   case Arithmetic:
5201   case Xchg:
5202     SubExprs.push_back(APIOrderedArgs[2]); // Order
5203     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5204     break;
5205   case GNUXchg:
5206     // Note, AtomicExpr::getVal2() has a special case for this atomic.
5207     SubExprs.push_back(APIOrderedArgs[3]); // Order
5208     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5209     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5210     break;
5211   case C11CmpXchg:
5212     SubExprs.push_back(APIOrderedArgs[3]); // Order
5213     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5214     SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
5215     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5216     break;
5217   case GNUCmpXchg:
5218     SubExprs.push_back(APIOrderedArgs[4]); // Order
5219     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5220     SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
5221     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5222     SubExprs.push_back(APIOrderedArgs[3]); // Weak
5223     break;
5224   }
5225 
5226   if (SubExprs.size() >= 2 && Form != Init) {
5227     if (Optional<llvm::APSInt> Result =
5228             SubExprs[1]->getIntegerConstantExpr(Context))
5229       if (!isValidOrderingForOp(Result->getSExtValue(), Op))
5230         Diag(SubExprs[1]->getBeginLoc(),
5231              diag::warn_atomic_op_has_invalid_memory_order)
5232             << SubExprs[1]->getSourceRange();
5233   }
5234 
5235   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
5236     auto *Scope = Args[Args.size() - 1];
5237     if (Optional<llvm::APSInt> Result =
5238             Scope->getIntegerConstantExpr(Context)) {
5239       if (!ScopeModel->isValid(Result->getZExtValue()))
5240         Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
5241             << Scope->getSourceRange();
5242     }
5243     SubExprs.push_back(Scope);
5244   }
5245 
5246   AtomicExpr *AE = new (Context)
5247       AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
5248 
5249   if ((Op == AtomicExpr::AO__c11_atomic_load ||
5250        Op == AtomicExpr::AO__c11_atomic_store ||
5251        Op == AtomicExpr::AO__opencl_atomic_load ||
5252        Op == AtomicExpr::AO__opencl_atomic_store ) &&
5253       Context.AtomicUsesUnsupportedLibcall(AE))
5254     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
5255         << ((Op == AtomicExpr::AO__c11_atomic_load ||
5256              Op == AtomicExpr::AO__opencl_atomic_load)
5257                 ? 0
5258                 : 1);
5259 
5260   if (ValType->isExtIntType()) {
5261     Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_ext_int_prohibit);
5262     return ExprError();
5263   }
5264 
5265   return AE;
5266 }
5267 
5268 /// checkBuiltinArgument - Given a call to a builtin function, perform
5269 /// normal type-checking on the given argument, updating the call in
5270 /// place.  This is useful when a builtin function requires custom
5271 /// type-checking for some of its arguments but not necessarily all of
5272 /// them.
5273 ///
5274 /// Returns true on error.
5275 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
5276   FunctionDecl *Fn = E->getDirectCallee();
5277   assert(Fn && "builtin call without direct callee!");
5278 
5279   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
5280   InitializedEntity Entity =
5281     InitializedEntity::InitializeParameter(S.Context, Param);
5282 
5283   ExprResult Arg = E->getArg(0);
5284   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
5285   if (Arg.isInvalid())
5286     return true;
5287 
5288   E->setArg(ArgIndex, Arg.get());
5289   return false;
5290 }
5291 
5292 /// We have a call to a function like __sync_fetch_and_add, which is an
5293 /// overloaded function based on the pointer type of its first argument.
5294 /// The main BuildCallExpr routines have already promoted the types of
5295 /// arguments because all of these calls are prototyped as void(...).
5296 ///
5297 /// This function goes through and does final semantic checking for these
5298 /// builtins, as well as generating any warnings.
5299 ExprResult
5300 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
5301   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
5302   Expr *Callee = TheCall->getCallee();
5303   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
5304   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5305 
5306   // Ensure that we have at least one argument to do type inference from.
5307   if (TheCall->getNumArgs() < 1) {
5308     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5309         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
5310     return ExprError();
5311   }
5312 
5313   // Inspect the first argument of the atomic builtin.  This should always be
5314   // a pointer type, whose element is an integral scalar or pointer type.
5315   // Because it is a pointer type, we don't have to worry about any implicit
5316   // casts here.
5317   // FIXME: We don't allow floating point scalars as input.
5318   Expr *FirstArg = TheCall->getArg(0);
5319   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
5320   if (FirstArgResult.isInvalid())
5321     return ExprError();
5322   FirstArg = FirstArgResult.get();
5323   TheCall->setArg(0, FirstArg);
5324 
5325   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5326   if (!pointerType) {
5327     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
5328         << FirstArg->getType() << FirstArg->getSourceRange();
5329     return ExprError();
5330   }
5331 
5332   QualType ValType = pointerType->getPointeeType();
5333   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5334       !ValType->isBlockPointerType()) {
5335     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
5336         << FirstArg->getType() << FirstArg->getSourceRange();
5337     return ExprError();
5338   }
5339 
5340   if (ValType.isConstQualified()) {
5341     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
5342         << FirstArg->getType() << FirstArg->getSourceRange();
5343     return ExprError();
5344   }
5345 
5346   switch (ValType.getObjCLifetime()) {
5347   case Qualifiers::OCL_None:
5348   case Qualifiers::OCL_ExplicitNone:
5349     // okay
5350     break;
5351 
5352   case Qualifiers::OCL_Weak:
5353   case Qualifiers::OCL_Strong:
5354   case Qualifiers::OCL_Autoreleasing:
5355     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
5356         << ValType << FirstArg->getSourceRange();
5357     return ExprError();
5358   }
5359 
5360   // Strip any qualifiers off ValType.
5361   ValType = ValType.getUnqualifiedType();
5362 
5363   // The majority of builtins return a value, but a few have special return
5364   // types, so allow them to override appropriately below.
5365   QualType ResultType = ValType;
5366 
5367   // We need to figure out which concrete builtin this maps onto.  For example,
5368   // __sync_fetch_and_add with a 2 byte object turns into
5369   // __sync_fetch_and_add_2.
5370 #define BUILTIN_ROW(x) \
5371   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5372     Builtin::BI##x##_8, Builtin::BI##x##_16 }
5373 
5374   static const unsigned BuiltinIndices[][5] = {
5375     BUILTIN_ROW(__sync_fetch_and_add),
5376     BUILTIN_ROW(__sync_fetch_and_sub),
5377     BUILTIN_ROW(__sync_fetch_and_or),
5378     BUILTIN_ROW(__sync_fetch_and_and),
5379     BUILTIN_ROW(__sync_fetch_and_xor),
5380     BUILTIN_ROW(__sync_fetch_and_nand),
5381 
5382     BUILTIN_ROW(__sync_add_and_fetch),
5383     BUILTIN_ROW(__sync_sub_and_fetch),
5384     BUILTIN_ROW(__sync_and_and_fetch),
5385     BUILTIN_ROW(__sync_or_and_fetch),
5386     BUILTIN_ROW(__sync_xor_and_fetch),
5387     BUILTIN_ROW(__sync_nand_and_fetch),
5388 
5389     BUILTIN_ROW(__sync_val_compare_and_swap),
5390     BUILTIN_ROW(__sync_bool_compare_and_swap),
5391     BUILTIN_ROW(__sync_lock_test_and_set),
5392     BUILTIN_ROW(__sync_lock_release),
5393     BUILTIN_ROW(__sync_swap)
5394   };
5395 #undef BUILTIN_ROW
5396 
5397   // Determine the index of the size.
5398   unsigned SizeIndex;
5399   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
5400   case 1: SizeIndex = 0; break;
5401   case 2: SizeIndex = 1; break;
5402   case 4: SizeIndex = 2; break;
5403   case 8: SizeIndex = 3; break;
5404   case 16: SizeIndex = 4; break;
5405   default:
5406     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
5407         << FirstArg->getType() << FirstArg->getSourceRange();
5408     return ExprError();
5409   }
5410 
5411   // Each of these builtins has one pointer argument, followed by some number of
5412   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5413   // that we ignore.  Find out which row of BuiltinIndices to read from as well
5414   // as the number of fixed args.
5415   unsigned BuiltinID = FDecl->getBuiltinID();
5416   unsigned BuiltinIndex, NumFixed = 1;
5417   bool WarnAboutSemanticsChange = false;
5418   switch (BuiltinID) {
5419   default: llvm_unreachable("Unknown overloaded atomic builtin!");
5420   case Builtin::BI__sync_fetch_and_add:
5421   case Builtin::BI__sync_fetch_and_add_1:
5422   case Builtin::BI__sync_fetch_and_add_2:
5423   case Builtin::BI__sync_fetch_and_add_4:
5424   case Builtin::BI__sync_fetch_and_add_8:
5425   case Builtin::BI__sync_fetch_and_add_16:
5426     BuiltinIndex = 0;
5427     break;
5428 
5429   case Builtin::BI__sync_fetch_and_sub:
5430   case Builtin::BI__sync_fetch_and_sub_1:
5431   case Builtin::BI__sync_fetch_and_sub_2:
5432   case Builtin::BI__sync_fetch_and_sub_4:
5433   case Builtin::BI__sync_fetch_and_sub_8:
5434   case Builtin::BI__sync_fetch_and_sub_16:
5435     BuiltinIndex = 1;
5436     break;
5437 
5438   case Builtin::BI__sync_fetch_and_or:
5439   case Builtin::BI__sync_fetch_and_or_1:
5440   case Builtin::BI__sync_fetch_and_or_2:
5441   case Builtin::BI__sync_fetch_and_or_4:
5442   case Builtin::BI__sync_fetch_and_or_8:
5443   case Builtin::BI__sync_fetch_and_or_16:
5444     BuiltinIndex = 2;
5445     break;
5446 
5447   case Builtin::BI__sync_fetch_and_and:
5448   case Builtin::BI__sync_fetch_and_and_1:
5449   case Builtin::BI__sync_fetch_and_and_2:
5450   case Builtin::BI__sync_fetch_and_and_4:
5451   case Builtin::BI__sync_fetch_and_and_8:
5452   case Builtin::BI__sync_fetch_and_and_16:
5453     BuiltinIndex = 3;
5454     break;
5455 
5456   case Builtin::BI__sync_fetch_and_xor:
5457   case Builtin::BI__sync_fetch_and_xor_1:
5458   case Builtin::BI__sync_fetch_and_xor_2:
5459   case Builtin::BI__sync_fetch_and_xor_4:
5460   case Builtin::BI__sync_fetch_and_xor_8:
5461   case Builtin::BI__sync_fetch_and_xor_16:
5462     BuiltinIndex = 4;
5463     break;
5464 
5465   case Builtin::BI__sync_fetch_and_nand:
5466   case Builtin::BI__sync_fetch_and_nand_1:
5467   case Builtin::BI__sync_fetch_and_nand_2:
5468   case Builtin::BI__sync_fetch_and_nand_4:
5469   case Builtin::BI__sync_fetch_and_nand_8:
5470   case Builtin::BI__sync_fetch_and_nand_16:
5471     BuiltinIndex = 5;
5472     WarnAboutSemanticsChange = true;
5473     break;
5474 
5475   case Builtin::BI__sync_add_and_fetch:
5476   case Builtin::BI__sync_add_and_fetch_1:
5477   case Builtin::BI__sync_add_and_fetch_2:
5478   case Builtin::BI__sync_add_and_fetch_4:
5479   case Builtin::BI__sync_add_and_fetch_8:
5480   case Builtin::BI__sync_add_and_fetch_16:
5481     BuiltinIndex = 6;
5482     break;
5483 
5484   case Builtin::BI__sync_sub_and_fetch:
5485   case Builtin::BI__sync_sub_and_fetch_1:
5486   case Builtin::BI__sync_sub_and_fetch_2:
5487   case Builtin::BI__sync_sub_and_fetch_4:
5488   case Builtin::BI__sync_sub_and_fetch_8:
5489   case Builtin::BI__sync_sub_and_fetch_16:
5490     BuiltinIndex = 7;
5491     break;
5492 
5493   case Builtin::BI__sync_and_and_fetch:
5494   case Builtin::BI__sync_and_and_fetch_1:
5495   case Builtin::BI__sync_and_and_fetch_2:
5496   case Builtin::BI__sync_and_and_fetch_4:
5497   case Builtin::BI__sync_and_and_fetch_8:
5498   case Builtin::BI__sync_and_and_fetch_16:
5499     BuiltinIndex = 8;
5500     break;
5501 
5502   case Builtin::BI__sync_or_and_fetch:
5503   case Builtin::BI__sync_or_and_fetch_1:
5504   case Builtin::BI__sync_or_and_fetch_2:
5505   case Builtin::BI__sync_or_and_fetch_4:
5506   case Builtin::BI__sync_or_and_fetch_8:
5507   case Builtin::BI__sync_or_and_fetch_16:
5508     BuiltinIndex = 9;
5509     break;
5510 
5511   case Builtin::BI__sync_xor_and_fetch:
5512   case Builtin::BI__sync_xor_and_fetch_1:
5513   case Builtin::BI__sync_xor_and_fetch_2:
5514   case Builtin::BI__sync_xor_and_fetch_4:
5515   case Builtin::BI__sync_xor_and_fetch_8:
5516   case Builtin::BI__sync_xor_and_fetch_16:
5517     BuiltinIndex = 10;
5518     break;
5519 
5520   case Builtin::BI__sync_nand_and_fetch:
5521   case Builtin::BI__sync_nand_and_fetch_1:
5522   case Builtin::BI__sync_nand_and_fetch_2:
5523   case Builtin::BI__sync_nand_and_fetch_4:
5524   case Builtin::BI__sync_nand_and_fetch_8:
5525   case Builtin::BI__sync_nand_and_fetch_16:
5526     BuiltinIndex = 11;
5527     WarnAboutSemanticsChange = true;
5528     break;
5529 
5530   case Builtin::BI__sync_val_compare_and_swap:
5531   case Builtin::BI__sync_val_compare_and_swap_1:
5532   case Builtin::BI__sync_val_compare_and_swap_2:
5533   case Builtin::BI__sync_val_compare_and_swap_4:
5534   case Builtin::BI__sync_val_compare_and_swap_8:
5535   case Builtin::BI__sync_val_compare_and_swap_16:
5536     BuiltinIndex = 12;
5537     NumFixed = 2;
5538     break;
5539 
5540   case Builtin::BI__sync_bool_compare_and_swap:
5541   case Builtin::BI__sync_bool_compare_and_swap_1:
5542   case Builtin::BI__sync_bool_compare_and_swap_2:
5543   case Builtin::BI__sync_bool_compare_and_swap_4:
5544   case Builtin::BI__sync_bool_compare_and_swap_8:
5545   case Builtin::BI__sync_bool_compare_and_swap_16:
5546     BuiltinIndex = 13;
5547     NumFixed = 2;
5548     ResultType = Context.BoolTy;
5549     break;
5550 
5551   case Builtin::BI__sync_lock_test_and_set:
5552   case Builtin::BI__sync_lock_test_and_set_1:
5553   case Builtin::BI__sync_lock_test_and_set_2:
5554   case Builtin::BI__sync_lock_test_and_set_4:
5555   case Builtin::BI__sync_lock_test_and_set_8:
5556   case Builtin::BI__sync_lock_test_and_set_16:
5557     BuiltinIndex = 14;
5558     break;
5559 
5560   case Builtin::BI__sync_lock_release:
5561   case Builtin::BI__sync_lock_release_1:
5562   case Builtin::BI__sync_lock_release_2:
5563   case Builtin::BI__sync_lock_release_4:
5564   case Builtin::BI__sync_lock_release_8:
5565   case Builtin::BI__sync_lock_release_16:
5566     BuiltinIndex = 15;
5567     NumFixed = 0;
5568     ResultType = Context.VoidTy;
5569     break;
5570 
5571   case Builtin::BI__sync_swap:
5572   case Builtin::BI__sync_swap_1:
5573   case Builtin::BI__sync_swap_2:
5574   case Builtin::BI__sync_swap_4:
5575   case Builtin::BI__sync_swap_8:
5576   case Builtin::BI__sync_swap_16:
5577     BuiltinIndex = 16;
5578     break;
5579   }
5580 
5581   // Now that we know how many fixed arguments we expect, first check that we
5582   // have at least that many.
5583   if (TheCall->getNumArgs() < 1+NumFixed) {
5584     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5585         << 0 << 1 + NumFixed << TheCall->getNumArgs()
5586         << Callee->getSourceRange();
5587     return ExprError();
5588   }
5589 
5590   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5591       << Callee->getSourceRange();
5592 
5593   if (WarnAboutSemanticsChange) {
5594     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
5595         << Callee->getSourceRange();
5596   }
5597 
5598   // Get the decl for the concrete builtin from this, we can tell what the
5599   // concrete integer type we should convert to is.
5600   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5601   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
5602   FunctionDecl *NewBuiltinDecl;
5603   if (NewBuiltinID == BuiltinID)
5604     NewBuiltinDecl = FDecl;
5605   else {
5606     // Perform builtin lookup to avoid redeclaring it.
5607     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
5608     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5609     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5610     assert(Res.getFoundDecl());
5611     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
5612     if (!NewBuiltinDecl)
5613       return ExprError();
5614   }
5615 
5616   // The first argument --- the pointer --- has a fixed type; we
5617   // deduce the types of the rest of the arguments accordingly.  Walk
5618   // the remaining arguments, converting them to the deduced value type.
5619   for (unsigned i = 0; i != NumFixed; ++i) {
5620     ExprResult Arg = TheCall->getArg(i+1);
5621 
5622     // GCC does an implicit conversion to the pointer or integer ValType.  This
5623     // can fail in some cases (1i -> int**), check for this error case now.
5624     // Initialize the argument.
5625     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5626                                                    ValType, /*consume*/ false);
5627     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5628     if (Arg.isInvalid())
5629       return ExprError();
5630 
5631     // Okay, we have something that *can* be converted to the right type.  Check
5632     // to see if there is a potentially weird extension going on here.  This can
5633     // happen when you do an atomic operation on something like an char* and
5634     // pass in 42.  The 42 gets converted to char.  This is even more strange
5635     // for things like 45.123 -> char, etc.
5636     // FIXME: Do this check.
5637     TheCall->setArg(i+1, Arg.get());
5638   }
5639 
5640   // Create a new DeclRefExpr to refer to the new decl.
5641   DeclRefExpr *NewDRE = DeclRefExpr::Create(
5642       Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
5643       /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
5644       DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
5645 
5646   // Set the callee in the CallExpr.
5647   // FIXME: This loses syntactic information.
5648   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5649   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5650                                               CK_BuiltinFnToFnPtr);
5651   TheCall->setCallee(PromotedCall.get());
5652 
5653   // Change the result type of the call to match the original value type. This
5654   // is arbitrary, but the codegen for these builtins ins design to handle it
5655   // gracefully.
5656   TheCall->setType(ResultType);
5657 
5658   // Prohibit use of _ExtInt with atomic builtins.
5659   // The arguments would have already been converted to the first argument's
5660   // type, so only need to check the first argument.
5661   const auto *ExtIntValType = ValType->getAs<ExtIntType>();
5662   if (ExtIntValType && !llvm::isPowerOf2_64(ExtIntValType->getNumBits())) {
5663     Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
5664     return ExprError();
5665   }
5666 
5667   return TheCallResult;
5668 }
5669 
5670 /// SemaBuiltinNontemporalOverloaded - We have a call to
5671 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
5672 /// overloaded function based on the pointer type of its last argument.
5673 ///
5674 /// This function goes through and does final semantic checking for these
5675 /// builtins.
5676 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5677   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5678   DeclRefExpr *DRE =
5679       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5680   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5681   unsigned BuiltinID = FDecl->getBuiltinID();
5682   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5683           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5684          "Unexpected nontemporal load/store builtin!");
5685   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5686   unsigned numArgs = isStore ? 2 : 1;
5687 
5688   // Ensure that we have the proper number of arguments.
5689   if (checkArgCount(*this, TheCall, numArgs))
5690     return ExprError();
5691 
5692   // Inspect the last argument of the nontemporal builtin.  This should always
5693   // be a pointer type, from which we imply the type of the memory access.
5694   // Because it is a pointer type, we don't have to worry about any implicit
5695   // casts here.
5696   Expr *PointerArg = TheCall->getArg(numArgs - 1);
5697   ExprResult PointerArgResult =
5698       DefaultFunctionArrayLvalueConversion(PointerArg);
5699 
5700   if (PointerArgResult.isInvalid())
5701     return ExprError();
5702   PointerArg = PointerArgResult.get();
5703   TheCall->setArg(numArgs - 1, PointerArg);
5704 
5705   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5706   if (!pointerType) {
5707     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
5708         << PointerArg->getType() << PointerArg->getSourceRange();
5709     return ExprError();
5710   }
5711 
5712   QualType ValType = pointerType->getPointeeType();
5713 
5714   // Strip any qualifiers off ValType.
5715   ValType = ValType.getUnqualifiedType();
5716   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5717       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5718       !ValType->isVectorType()) {
5719     Diag(DRE->getBeginLoc(),
5720          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5721         << PointerArg->getType() << PointerArg->getSourceRange();
5722     return ExprError();
5723   }
5724 
5725   if (!isStore) {
5726     TheCall->setType(ValType);
5727     return TheCallResult;
5728   }
5729 
5730   ExprResult ValArg = TheCall->getArg(0);
5731   InitializedEntity Entity = InitializedEntity::InitializeParameter(
5732       Context, ValType, /*consume*/ false);
5733   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
5734   if (ValArg.isInvalid())
5735     return ExprError();
5736 
5737   TheCall->setArg(0, ValArg.get());
5738   TheCall->setType(Context.VoidTy);
5739   return TheCallResult;
5740 }
5741 
5742 /// CheckObjCString - Checks that the argument to the builtin
5743 /// CFString constructor is correct
5744 /// Note: It might also make sense to do the UTF-16 conversion here (would
5745 /// simplify the backend).
5746 bool Sema::CheckObjCString(Expr *Arg) {
5747   Arg = Arg->IgnoreParenCasts();
5748   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
5749 
5750   if (!Literal || !Literal->isAscii()) {
5751     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
5752         << Arg->getSourceRange();
5753     return true;
5754   }
5755 
5756   if (Literal->containsNonAsciiOrNull()) {
5757     StringRef String = Literal->getString();
5758     unsigned NumBytes = String.size();
5759     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
5760     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
5761     llvm::UTF16 *ToPtr = &ToBuf[0];
5762 
5763     llvm::ConversionResult Result =
5764         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
5765                                  ToPtr + NumBytes, llvm::strictConversion);
5766     // Check for conversion failure.
5767     if (Result != llvm::conversionOK)
5768       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
5769           << Arg->getSourceRange();
5770   }
5771   return false;
5772 }
5773 
5774 /// CheckObjCString - Checks that the format string argument to the os_log()
5775 /// and os_trace() functions is correct, and converts it to const char *.
5776 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5777   Arg = Arg->IgnoreParenCasts();
5778   auto *Literal = dyn_cast<StringLiteral>(Arg);
5779   if (!Literal) {
5780     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
5781       Literal = ObjcLiteral->getString();
5782     }
5783   }
5784 
5785   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
5786     return ExprError(
5787         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
5788         << Arg->getSourceRange());
5789   }
5790 
5791   ExprResult Result(Literal);
5792   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
5793   InitializedEntity Entity =
5794       InitializedEntity::InitializeParameter(Context, ResultTy, false);
5795   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
5796   return Result;
5797 }
5798 
5799 /// Check that the user is calling the appropriate va_start builtin for the
5800 /// target and calling convention.
5801 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5802   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5803   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
5804   bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
5805                     TT.getArch() == llvm::Triple::aarch64_32);
5806   bool IsWindows = TT.isOSWindows();
5807   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5808   if (IsX64 || IsAArch64) {
5809     CallingConv CC = CC_C;
5810     if (const FunctionDecl *FD = S.getCurFunctionDecl())
5811       CC = FD->getType()->castAs<FunctionType>()->getCallConv();
5812     if (IsMSVAStart) {
5813       // Don't allow this in System V ABI functions.
5814       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
5815         return S.Diag(Fn->getBeginLoc(),
5816                       diag::err_ms_va_start_used_in_sysv_function);
5817     } else {
5818       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
5819       // On x64 Windows, don't allow this in System V ABI functions.
5820       // (Yes, that means there's no corresponding way to support variadic
5821       // System V ABI functions on Windows.)
5822       if ((IsWindows && CC == CC_X86_64SysV) ||
5823           (!IsWindows && CC == CC_Win64))
5824         return S.Diag(Fn->getBeginLoc(),
5825                       diag::err_va_start_used_in_wrong_abi_function)
5826                << !IsWindows;
5827     }
5828     return false;
5829   }
5830 
5831   if (IsMSVAStart)
5832     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
5833   return false;
5834 }
5835 
5836 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
5837                                              ParmVarDecl **LastParam = nullptr) {
5838   // Determine whether the current function, block, or obj-c method is variadic
5839   // and get its parameter list.
5840   bool IsVariadic = false;
5841   ArrayRef<ParmVarDecl *> Params;
5842   DeclContext *Caller = S.CurContext;
5843   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
5844     IsVariadic = Block->isVariadic();
5845     Params = Block->parameters();
5846   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
5847     IsVariadic = FD->isVariadic();
5848     Params = FD->parameters();
5849   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
5850     IsVariadic = MD->isVariadic();
5851     // FIXME: This isn't correct for methods (results in bogus warning).
5852     Params = MD->parameters();
5853   } else if (isa<CapturedDecl>(Caller)) {
5854     // We don't support va_start in a CapturedDecl.
5855     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
5856     return true;
5857   } else {
5858     // This must be some other declcontext that parses exprs.
5859     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
5860     return true;
5861   }
5862 
5863   if (!IsVariadic) {
5864     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
5865     return true;
5866   }
5867 
5868   if (LastParam)
5869     *LastParam = Params.empty() ? nullptr : Params.back();
5870 
5871   return false;
5872 }
5873 
5874 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
5875 /// for validity.  Emit an error and return true on failure; return false
5876 /// on success.
5877 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5878   Expr *Fn = TheCall->getCallee();
5879 
5880   if (checkVAStartABI(*this, BuiltinID, Fn))
5881     return true;
5882 
5883   if (checkArgCount(*this, TheCall, 2))
5884     return true;
5885 
5886   // Type-check the first argument normally.
5887   if (checkBuiltinArgument(*this, TheCall, 0))
5888     return true;
5889 
5890   // Check that the current function is variadic, and get its last parameter.
5891   ParmVarDecl *LastParam;
5892   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
5893     return true;
5894 
5895   // Verify that the second argument to the builtin is the last argument of the
5896   // current function or method.
5897   bool SecondArgIsLastNamedArgument = false;
5898   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
5899 
5900   // These are valid if SecondArgIsLastNamedArgument is false after the next
5901   // block.
5902   QualType Type;
5903   SourceLocation ParamLoc;
5904   bool IsCRegister = false;
5905 
5906   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
5907     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
5908       SecondArgIsLastNamedArgument = PV == LastParam;
5909 
5910       Type = PV->getType();
5911       ParamLoc = PV->getLocation();
5912       IsCRegister =
5913           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
5914     }
5915   }
5916 
5917   if (!SecondArgIsLastNamedArgument)
5918     Diag(TheCall->getArg(1)->getBeginLoc(),
5919          diag::warn_second_arg_of_va_start_not_last_named_param);
5920   else if (IsCRegister || Type->isReferenceType() ||
5921            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
5922              // Promotable integers are UB, but enumerations need a bit of
5923              // extra checking to see what their promotable type actually is.
5924              if (!Type->isPromotableIntegerType())
5925                return false;
5926              if (!Type->isEnumeralType())
5927                return true;
5928              const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
5929              return !(ED &&
5930                       Context.typesAreCompatible(ED->getPromotionType(), Type));
5931            }()) {
5932     unsigned Reason = 0;
5933     if (Type->isReferenceType())  Reason = 1;
5934     else if (IsCRegister)         Reason = 2;
5935     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
5936     Diag(ParamLoc, diag::note_parameter_type) << Type;
5937   }
5938 
5939   TheCall->setType(Context.VoidTy);
5940   return false;
5941 }
5942 
5943 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
5944   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
5945   //                 const char *named_addr);
5946 
5947   Expr *Func = Call->getCallee();
5948 
5949   if (Call->getNumArgs() < 3)
5950     return Diag(Call->getEndLoc(),
5951                 diag::err_typecheck_call_too_few_args_at_least)
5952            << 0 /*function call*/ << 3 << Call->getNumArgs();
5953 
5954   // Type-check the first argument normally.
5955   if (checkBuiltinArgument(*this, Call, 0))
5956     return true;
5957 
5958   // Check that the current function is variadic.
5959   if (checkVAStartIsInVariadicFunction(*this, Func))
5960     return true;
5961 
5962   // __va_start on Windows does not validate the parameter qualifiers
5963 
5964   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
5965   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
5966 
5967   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
5968   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
5969 
5970   const QualType &ConstCharPtrTy =
5971       Context.getPointerType(Context.CharTy.withConst());
5972   if (!Arg1Ty->isPointerType() ||
5973       Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
5974     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5975         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
5976         << 0                                      /* qualifier difference */
5977         << 3                                      /* parameter mismatch */
5978         << 2 << Arg1->getType() << ConstCharPtrTy;
5979 
5980   const QualType SizeTy = Context.getSizeType();
5981   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
5982     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5983         << Arg2->getType() << SizeTy << 1 /* different class */
5984         << 0                              /* qualifier difference */
5985         << 3                              /* parameter mismatch */
5986         << 3 << Arg2->getType() << SizeTy;
5987 
5988   return false;
5989 }
5990 
5991 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
5992 /// friends.  This is declared to take (...), so we have to check everything.
5993 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
5994   if (checkArgCount(*this, TheCall, 2))
5995     return true;
5996 
5997   ExprResult OrigArg0 = TheCall->getArg(0);
5998   ExprResult OrigArg1 = TheCall->getArg(1);
5999 
6000   // Do standard promotions between the two arguments, returning their common
6001   // type.
6002   QualType Res = UsualArithmeticConversions(
6003       OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
6004   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
6005     return true;
6006 
6007   // Make sure any conversions are pushed back into the call; this is
6008   // type safe since unordered compare builtins are declared as "_Bool
6009   // foo(...)".
6010   TheCall->setArg(0, OrigArg0.get());
6011   TheCall->setArg(1, OrigArg1.get());
6012 
6013   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
6014     return false;
6015 
6016   // If the common type isn't a real floating type, then the arguments were
6017   // invalid for this operation.
6018   if (Res.isNull() || !Res->isRealFloatingType())
6019     return Diag(OrigArg0.get()->getBeginLoc(),
6020                 diag::err_typecheck_call_invalid_ordered_compare)
6021            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
6022            << SourceRange(OrigArg0.get()->getBeginLoc(),
6023                           OrigArg1.get()->getEndLoc());
6024 
6025   return false;
6026 }
6027 
6028 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
6029 /// __builtin_isnan and friends.  This is declared to take (...), so we have
6030 /// to check everything. We expect the last argument to be a floating point
6031 /// value.
6032 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
6033   if (checkArgCount(*this, TheCall, NumArgs))
6034     return true;
6035 
6036   // __builtin_fpclassify is the only case where NumArgs != 1, so we can count
6037   // on all preceding parameters just being int.  Try all of those.
6038   for (unsigned i = 0; i < NumArgs - 1; ++i) {
6039     Expr *Arg = TheCall->getArg(i);
6040 
6041     if (Arg->isTypeDependent())
6042       return false;
6043 
6044     ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);
6045 
6046     if (Res.isInvalid())
6047       return true;
6048     TheCall->setArg(i, Res.get());
6049   }
6050 
6051   Expr *OrigArg = TheCall->getArg(NumArgs-1);
6052 
6053   if (OrigArg->isTypeDependent())
6054     return false;
6055 
6056   // Usual Unary Conversions will convert half to float, which we want for
6057   // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
6058   // type how it is, but do normal L->Rvalue conversions.
6059   if (Context.getTargetInfo().useFP16ConversionIntrinsics())
6060     OrigArg = UsualUnaryConversions(OrigArg).get();
6061   else
6062     OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
6063   TheCall->setArg(NumArgs - 1, OrigArg);
6064 
6065   // This operation requires a non-_Complex floating-point number.
6066   if (!OrigArg->getType()->isRealFloatingType())
6067     return Diag(OrigArg->getBeginLoc(),
6068                 diag::err_typecheck_call_invalid_unary_fp)
6069            << OrigArg->getType() << OrigArg->getSourceRange();
6070 
6071   return false;
6072 }
6073 
6074 /// Perform semantic analysis for a call to __builtin_complex.
6075 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) {
6076   if (checkArgCount(*this, TheCall, 2))
6077     return true;
6078 
6079   bool Dependent = false;
6080   for (unsigned I = 0; I != 2; ++I) {
6081     Expr *Arg = TheCall->getArg(I);
6082     QualType T = Arg->getType();
6083     if (T->isDependentType()) {
6084       Dependent = true;
6085       continue;
6086     }
6087 
6088     // Despite supporting _Complex int, GCC requires a real floating point type
6089     // for the operands of __builtin_complex.
6090     if (!T->isRealFloatingType()) {
6091       return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
6092              << Arg->getType() << Arg->getSourceRange();
6093     }
6094 
6095     ExprResult Converted = DefaultLvalueConversion(Arg);
6096     if (Converted.isInvalid())
6097       return true;
6098     TheCall->setArg(I, Converted.get());
6099   }
6100 
6101   if (Dependent) {
6102     TheCall->setType(Context.DependentTy);
6103     return false;
6104   }
6105 
6106   Expr *Real = TheCall->getArg(0);
6107   Expr *Imag = TheCall->getArg(1);
6108   if (!Context.hasSameType(Real->getType(), Imag->getType())) {
6109     return Diag(Real->getBeginLoc(),
6110                 diag::err_typecheck_call_different_arg_types)
6111            << Real->getType() << Imag->getType()
6112            << Real->getSourceRange() << Imag->getSourceRange();
6113   }
6114 
6115   // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers;
6116   // don't allow this builtin to form those types either.
6117   // FIXME: Should we allow these types?
6118   if (Real->getType()->isFloat16Type())
6119     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6120            << "_Float16";
6121   if (Real->getType()->isHalfType())
6122     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6123            << "half";
6124 
6125   TheCall->setType(Context.getComplexType(Real->getType()));
6126   return false;
6127 }
6128 
6129 // Customized Sema Checking for VSX builtins that have the following signature:
6130 // vector [...] builtinName(vector [...], vector [...], const int);
6131 // Which takes the same type of vectors (any legal vector type) for the first
6132 // two arguments and takes compile time constant for the third argument.
6133 // Example builtins are :
6134 // vector double vec_xxpermdi(vector double, vector double, int);
6135 // vector short vec_xxsldwi(vector short, vector short, int);
6136 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
6137   unsigned ExpectedNumArgs = 3;
6138   if (checkArgCount(*this, TheCall, ExpectedNumArgs))
6139     return true;
6140 
6141   // Check the third argument is a compile time constant
6142   if (!TheCall->getArg(2)->isIntegerConstantExpr(Context))
6143     return Diag(TheCall->getBeginLoc(),
6144                 diag::err_vsx_builtin_nonconstant_argument)
6145            << 3 /* argument index */ << TheCall->getDirectCallee()
6146            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
6147                           TheCall->getArg(2)->getEndLoc());
6148 
6149   QualType Arg1Ty = TheCall->getArg(0)->getType();
6150   QualType Arg2Ty = TheCall->getArg(1)->getType();
6151 
6152   // Check the type of argument 1 and argument 2 are vectors.
6153   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
6154   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
6155       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
6156     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
6157            << TheCall->getDirectCallee()
6158            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6159                           TheCall->getArg(1)->getEndLoc());
6160   }
6161 
6162   // Check the first two arguments are the same type.
6163   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
6164     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
6165            << TheCall->getDirectCallee()
6166            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6167                           TheCall->getArg(1)->getEndLoc());
6168   }
6169 
6170   // When default clang type checking is turned off and the customized type
6171   // checking is used, the returning type of the function must be explicitly
6172   // set. Otherwise it is _Bool by default.
6173   TheCall->setType(Arg1Ty);
6174 
6175   return false;
6176 }
6177 
6178 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
6179 // This is declared to take (...), so we have to check everything.
6180 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
6181   if (TheCall->getNumArgs() < 2)
6182     return ExprError(Diag(TheCall->getEndLoc(),
6183                           diag::err_typecheck_call_too_few_args_at_least)
6184                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
6185                      << TheCall->getSourceRange());
6186 
6187   // Determine which of the following types of shufflevector we're checking:
6188   // 1) unary, vector mask: (lhs, mask)
6189   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
6190   QualType resType = TheCall->getArg(0)->getType();
6191   unsigned numElements = 0;
6192 
6193   if (!TheCall->getArg(0)->isTypeDependent() &&
6194       !TheCall->getArg(1)->isTypeDependent()) {
6195     QualType LHSType = TheCall->getArg(0)->getType();
6196     QualType RHSType = TheCall->getArg(1)->getType();
6197 
6198     if (!LHSType->isVectorType() || !RHSType->isVectorType())
6199       return ExprError(
6200           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
6201           << TheCall->getDirectCallee()
6202           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6203                          TheCall->getArg(1)->getEndLoc()));
6204 
6205     numElements = LHSType->castAs<VectorType>()->getNumElements();
6206     unsigned numResElements = TheCall->getNumArgs() - 2;
6207 
6208     // Check to see if we have a call with 2 vector arguments, the unary shuffle
6209     // with mask.  If so, verify that RHS is an integer vector type with the
6210     // same number of elts as lhs.
6211     if (TheCall->getNumArgs() == 2) {
6212       if (!RHSType->hasIntegerRepresentation() ||
6213           RHSType->castAs<VectorType>()->getNumElements() != numElements)
6214         return ExprError(Diag(TheCall->getBeginLoc(),
6215                               diag::err_vec_builtin_incompatible_vector)
6216                          << TheCall->getDirectCallee()
6217                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
6218                                         TheCall->getArg(1)->getEndLoc()));
6219     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
6220       return ExprError(Diag(TheCall->getBeginLoc(),
6221                             diag::err_vec_builtin_incompatible_vector)
6222                        << TheCall->getDirectCallee()
6223                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6224                                       TheCall->getArg(1)->getEndLoc()));
6225     } else if (numElements != numResElements) {
6226       QualType eltType = LHSType->castAs<VectorType>()->getElementType();
6227       resType = Context.getVectorType(eltType, numResElements,
6228                                       VectorType::GenericVector);
6229     }
6230   }
6231 
6232   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
6233     if (TheCall->getArg(i)->isTypeDependent() ||
6234         TheCall->getArg(i)->isValueDependent())
6235       continue;
6236 
6237     Optional<llvm::APSInt> Result;
6238     if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context)))
6239       return ExprError(Diag(TheCall->getBeginLoc(),
6240                             diag::err_shufflevector_nonconstant_argument)
6241                        << TheCall->getArg(i)->getSourceRange());
6242 
6243     // Allow -1 which will be translated to undef in the IR.
6244     if (Result->isSigned() && Result->isAllOnesValue())
6245       continue;
6246 
6247     if (Result->getActiveBits() > 64 ||
6248         Result->getZExtValue() >= numElements * 2)
6249       return ExprError(Diag(TheCall->getBeginLoc(),
6250                             diag::err_shufflevector_argument_too_large)
6251                        << TheCall->getArg(i)->getSourceRange());
6252   }
6253 
6254   SmallVector<Expr*, 32> exprs;
6255 
6256   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
6257     exprs.push_back(TheCall->getArg(i));
6258     TheCall->setArg(i, nullptr);
6259   }
6260 
6261   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
6262                                          TheCall->getCallee()->getBeginLoc(),
6263                                          TheCall->getRParenLoc());
6264 }
6265 
6266 /// SemaConvertVectorExpr - Handle __builtin_convertvector
6267 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
6268                                        SourceLocation BuiltinLoc,
6269                                        SourceLocation RParenLoc) {
6270   ExprValueKind VK = VK_RValue;
6271   ExprObjectKind OK = OK_Ordinary;
6272   QualType DstTy = TInfo->getType();
6273   QualType SrcTy = E->getType();
6274 
6275   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
6276     return ExprError(Diag(BuiltinLoc,
6277                           diag::err_convertvector_non_vector)
6278                      << E->getSourceRange());
6279   if (!DstTy->isVectorType() && !DstTy->isDependentType())
6280     return ExprError(Diag(BuiltinLoc,
6281                           diag::err_convertvector_non_vector_type));
6282 
6283   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
6284     unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
6285     unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
6286     if (SrcElts != DstElts)
6287       return ExprError(Diag(BuiltinLoc,
6288                             diag::err_convertvector_incompatible_vector)
6289                        << E->getSourceRange());
6290   }
6291 
6292   return new (Context)
6293       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
6294 }
6295 
6296 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
6297 // This is declared to take (const void*, ...) and can take two
6298 // optional constant int args.
6299 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
6300   unsigned NumArgs = TheCall->getNumArgs();
6301 
6302   if (NumArgs > 3)
6303     return Diag(TheCall->getEndLoc(),
6304                 diag::err_typecheck_call_too_many_args_at_most)
6305            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6306 
6307   // Argument 0 is checked for us and the remaining arguments must be
6308   // constant integers.
6309   for (unsigned i = 1; i != NumArgs; ++i)
6310     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
6311       return true;
6312 
6313   return false;
6314 }
6315 
6316 /// SemaBuiltinAssume - Handle __assume (MS Extension).
6317 // __assume does not evaluate its arguments, and should warn if its argument
6318 // has side effects.
6319 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
6320   Expr *Arg = TheCall->getArg(0);
6321   if (Arg->isInstantiationDependent()) return false;
6322 
6323   if (Arg->HasSideEffects(Context))
6324     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
6325         << Arg->getSourceRange()
6326         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
6327 
6328   return false;
6329 }
6330 
6331 /// Handle __builtin_alloca_with_align. This is declared
6332 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
6333 /// than 8.
6334 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
6335   // The alignment must be a constant integer.
6336   Expr *Arg = TheCall->getArg(1);
6337 
6338   // We can't check the value of a dependent argument.
6339   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6340     if (const auto *UE =
6341             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
6342       if (UE->getKind() == UETT_AlignOf ||
6343           UE->getKind() == UETT_PreferredAlignOf)
6344         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
6345             << Arg->getSourceRange();
6346 
6347     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
6348 
6349     if (!Result.isPowerOf2())
6350       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6351              << Arg->getSourceRange();
6352 
6353     if (Result < Context.getCharWidth())
6354       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
6355              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6356 
6357     if (Result > std::numeric_limits<int32_t>::max())
6358       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
6359              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6360   }
6361 
6362   return false;
6363 }
6364 
6365 /// Handle __builtin_assume_aligned. This is declared
6366 /// as (const void*, size_t, ...) and can take one optional constant int arg.
6367 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
6368   unsigned NumArgs = TheCall->getNumArgs();
6369 
6370   if (NumArgs > 3)
6371     return Diag(TheCall->getEndLoc(),
6372                 diag::err_typecheck_call_too_many_args_at_most)
6373            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6374 
6375   // The alignment must be a constant integer.
6376   Expr *Arg = TheCall->getArg(1);
6377 
6378   // We can't check the value of a dependent argument.
6379   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6380     llvm::APSInt Result;
6381     if (SemaBuiltinConstantArg(TheCall, 1, Result))
6382       return true;
6383 
6384     if (!Result.isPowerOf2())
6385       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6386              << Arg->getSourceRange();
6387 
6388     if (Result > Sema::MaximumAlignment)
6389       Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
6390           << Arg->getSourceRange() << Sema::MaximumAlignment;
6391   }
6392 
6393   if (NumArgs > 2) {
6394     ExprResult Arg(TheCall->getArg(2));
6395     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6396       Context.getSizeType(), false);
6397     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6398     if (Arg.isInvalid()) return true;
6399     TheCall->setArg(2, Arg.get());
6400   }
6401 
6402   return false;
6403 }
6404 
6405 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
6406   unsigned BuiltinID =
6407       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
6408   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6409 
6410   unsigned NumArgs = TheCall->getNumArgs();
6411   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6412   if (NumArgs < NumRequiredArgs) {
6413     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
6414            << 0 /* function call */ << NumRequiredArgs << NumArgs
6415            << TheCall->getSourceRange();
6416   }
6417   if (NumArgs >= NumRequiredArgs + 0x100) {
6418     return Diag(TheCall->getEndLoc(),
6419                 diag::err_typecheck_call_too_many_args_at_most)
6420            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6421            << TheCall->getSourceRange();
6422   }
6423   unsigned i = 0;
6424 
6425   // For formatting call, check buffer arg.
6426   if (!IsSizeCall) {
6427     ExprResult Arg(TheCall->getArg(i));
6428     InitializedEntity Entity = InitializedEntity::InitializeParameter(
6429         Context, Context.VoidPtrTy, false);
6430     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6431     if (Arg.isInvalid())
6432       return true;
6433     TheCall->setArg(i, Arg.get());
6434     i++;
6435   }
6436 
6437   // Check string literal arg.
6438   unsigned FormatIdx = i;
6439   {
6440     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
6441     if (Arg.isInvalid())
6442       return true;
6443     TheCall->setArg(i, Arg.get());
6444     i++;
6445   }
6446 
6447   // Make sure variadic args are scalar.
6448   unsigned FirstDataArg = i;
6449   while (i < NumArgs) {
6450     ExprResult Arg = DefaultVariadicArgumentPromotion(
6451         TheCall->getArg(i), VariadicFunction, nullptr);
6452     if (Arg.isInvalid())
6453       return true;
6454     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
6455     if (ArgSize.getQuantity() >= 0x100) {
6456       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
6457              << i << (int)ArgSize.getQuantity() << 0xff
6458              << TheCall->getSourceRange();
6459     }
6460     TheCall->setArg(i, Arg.get());
6461     i++;
6462   }
6463 
6464   // Check formatting specifiers. NOTE: We're only doing this for the non-size
6465   // call to avoid duplicate diagnostics.
6466   if (!IsSizeCall) {
6467     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6468     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6469     bool Success = CheckFormatArguments(
6470         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
6471         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
6472         CheckedVarArgs);
6473     if (!Success)
6474       return true;
6475   }
6476 
6477   if (IsSizeCall) {
6478     TheCall->setType(Context.getSizeType());
6479   } else {
6480     TheCall->setType(Context.VoidPtrTy);
6481   }
6482   return false;
6483 }
6484 
6485 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
6486 /// TheCall is a constant expression.
6487 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
6488                                   llvm::APSInt &Result) {
6489   Expr *Arg = TheCall->getArg(ArgNum);
6490   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6491   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6492 
6493   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
6494 
6495   Optional<llvm::APSInt> R;
6496   if (!(R = Arg->getIntegerConstantExpr(Context)))
6497     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6498            << FDecl->getDeclName() << Arg->getSourceRange();
6499   Result = *R;
6500   return false;
6501 }
6502 
6503 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
6504 /// TheCall is a constant expression in the range [Low, High].
6505 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
6506                                        int Low, int High, bool RangeIsError) {
6507   if (isConstantEvaluated())
6508     return false;
6509   llvm::APSInt Result;
6510 
6511   // We can't check the value of a dependent argument.
6512   Expr *Arg = TheCall->getArg(ArgNum);
6513   if (Arg->isTypeDependent() || Arg->isValueDependent())
6514     return false;
6515 
6516   // Check constant-ness first.
6517   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6518     return true;
6519 
6520   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6521     if (RangeIsError)
6522       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
6523              << Result.toString(10) << Low << High << Arg->getSourceRange();
6524     else
6525       // Defer the warning until we know if the code will be emitted so that
6526       // dead code can ignore this.
6527       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6528                           PDiag(diag::warn_argument_invalid_range)
6529                               << Result.toString(10) << Low << High
6530                               << Arg->getSourceRange());
6531   }
6532 
6533   return false;
6534 }
6535 
6536 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
6537 /// TheCall is a constant expression is a multiple of Num..
6538 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
6539                                           unsigned Num) {
6540   llvm::APSInt Result;
6541 
6542   // We can't check the value of a dependent argument.
6543   Expr *Arg = TheCall->getArg(ArgNum);
6544   if (Arg->isTypeDependent() || Arg->isValueDependent())
6545     return false;
6546 
6547   // Check constant-ness first.
6548   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6549     return true;
6550 
6551   if (Result.getSExtValue() % Num != 0)
6552     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6553            << Num << Arg->getSourceRange();
6554 
6555   return false;
6556 }
6557 
6558 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
6559 /// constant expression representing a power of 2.
6560 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
6561   llvm::APSInt Result;
6562 
6563   // We can't check the value of a dependent argument.
6564   Expr *Arg = TheCall->getArg(ArgNum);
6565   if (Arg->isTypeDependent() || Arg->isValueDependent())
6566     return false;
6567 
6568   // Check constant-ness first.
6569   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6570     return true;
6571 
6572   // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
6573   // and only if x is a power of 2.
6574   if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
6575     return false;
6576 
6577   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
6578          << Arg->getSourceRange();
6579 }
6580 
6581 static bool IsShiftedByte(llvm::APSInt Value) {
6582   if (Value.isNegative())
6583     return false;
6584 
6585   // Check if it's a shifted byte, by shifting it down
6586   while (true) {
6587     // If the value fits in the bottom byte, the check passes.
6588     if (Value < 0x100)
6589       return true;
6590 
6591     // Otherwise, if the value has _any_ bits in the bottom byte, the check
6592     // fails.
6593     if ((Value & 0xFF) != 0)
6594       return false;
6595 
6596     // If the bottom 8 bits are all 0, but something above that is nonzero,
6597     // then shifting the value right by 8 bits won't affect whether it's a
6598     // shifted byte or not. So do that, and go round again.
6599     Value >>= 8;
6600   }
6601 }
6602 
6603 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
6604 /// a constant expression representing an arbitrary byte value shifted left by
6605 /// a multiple of 8 bits.
6606 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
6607                                              unsigned ArgBits) {
6608   llvm::APSInt Result;
6609 
6610   // We can't check the value of a dependent argument.
6611   Expr *Arg = TheCall->getArg(ArgNum);
6612   if (Arg->isTypeDependent() || Arg->isValueDependent())
6613     return false;
6614 
6615   // Check constant-ness first.
6616   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6617     return true;
6618 
6619   // Truncate to the given size.
6620   Result = Result.getLoBits(ArgBits);
6621   Result.setIsUnsigned(true);
6622 
6623   if (IsShiftedByte(Result))
6624     return false;
6625 
6626   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
6627          << Arg->getSourceRange();
6628 }
6629 
6630 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
6631 /// TheCall is a constant expression representing either a shifted byte value,
6632 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
6633 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
6634 /// Arm MVE intrinsics.
6635 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
6636                                                    int ArgNum,
6637                                                    unsigned ArgBits) {
6638   llvm::APSInt Result;
6639 
6640   // We can't check the value of a dependent argument.
6641   Expr *Arg = TheCall->getArg(ArgNum);
6642   if (Arg->isTypeDependent() || Arg->isValueDependent())
6643     return false;
6644 
6645   // Check constant-ness first.
6646   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6647     return true;
6648 
6649   // Truncate to the given size.
6650   Result = Result.getLoBits(ArgBits);
6651   Result.setIsUnsigned(true);
6652 
6653   // Check to see if it's in either of the required forms.
6654   if (IsShiftedByte(Result) ||
6655       (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
6656     return false;
6657 
6658   return Diag(TheCall->getBeginLoc(),
6659               diag::err_argument_not_shifted_byte_or_xxff)
6660          << Arg->getSourceRange();
6661 }
6662 
6663 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
6664 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
6665   if (BuiltinID == AArch64::BI__builtin_arm_irg) {
6666     if (checkArgCount(*this, TheCall, 2))
6667       return true;
6668     Expr *Arg0 = TheCall->getArg(0);
6669     Expr *Arg1 = TheCall->getArg(1);
6670 
6671     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6672     if (FirstArg.isInvalid())
6673       return true;
6674     QualType FirstArgType = FirstArg.get()->getType();
6675     if (!FirstArgType->isAnyPointerType())
6676       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6677                << "first" << FirstArgType << Arg0->getSourceRange();
6678     TheCall->setArg(0, FirstArg.get());
6679 
6680     ExprResult SecArg = DefaultLvalueConversion(Arg1);
6681     if (SecArg.isInvalid())
6682       return true;
6683     QualType SecArgType = SecArg.get()->getType();
6684     if (!SecArgType->isIntegerType())
6685       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6686                << "second" << SecArgType << Arg1->getSourceRange();
6687 
6688     // Derive the return type from the pointer argument.
6689     TheCall->setType(FirstArgType);
6690     return false;
6691   }
6692 
6693   if (BuiltinID == AArch64::BI__builtin_arm_addg) {
6694     if (checkArgCount(*this, TheCall, 2))
6695       return true;
6696 
6697     Expr *Arg0 = TheCall->getArg(0);
6698     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6699     if (FirstArg.isInvalid())
6700       return true;
6701     QualType FirstArgType = FirstArg.get()->getType();
6702     if (!FirstArgType->isAnyPointerType())
6703       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6704                << "first" << FirstArgType << Arg0->getSourceRange();
6705     TheCall->setArg(0, FirstArg.get());
6706 
6707     // Derive the return type from the pointer argument.
6708     TheCall->setType(FirstArgType);
6709 
6710     // Second arg must be an constant in range [0,15]
6711     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6712   }
6713 
6714   if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
6715     if (checkArgCount(*this, TheCall, 2))
6716       return true;
6717     Expr *Arg0 = TheCall->getArg(0);
6718     Expr *Arg1 = TheCall->getArg(1);
6719 
6720     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6721     if (FirstArg.isInvalid())
6722       return true;
6723     QualType FirstArgType = FirstArg.get()->getType();
6724     if (!FirstArgType->isAnyPointerType())
6725       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6726                << "first" << FirstArgType << Arg0->getSourceRange();
6727 
6728     QualType SecArgType = Arg1->getType();
6729     if (!SecArgType->isIntegerType())
6730       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6731                << "second" << SecArgType << Arg1->getSourceRange();
6732     TheCall->setType(Context.IntTy);
6733     return false;
6734   }
6735 
6736   if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
6737       BuiltinID == AArch64::BI__builtin_arm_stg) {
6738     if (checkArgCount(*this, TheCall, 1))
6739       return true;
6740     Expr *Arg0 = TheCall->getArg(0);
6741     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6742     if (FirstArg.isInvalid())
6743       return true;
6744 
6745     QualType FirstArgType = FirstArg.get()->getType();
6746     if (!FirstArgType->isAnyPointerType())
6747       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6748                << "first" << FirstArgType << Arg0->getSourceRange();
6749     TheCall->setArg(0, FirstArg.get());
6750 
6751     // Derive the return type from the pointer argument.
6752     if (BuiltinID == AArch64::BI__builtin_arm_ldg)
6753       TheCall->setType(FirstArgType);
6754     return false;
6755   }
6756 
6757   if (BuiltinID == AArch64::BI__builtin_arm_subp) {
6758     Expr *ArgA = TheCall->getArg(0);
6759     Expr *ArgB = TheCall->getArg(1);
6760 
6761     ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
6762     ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
6763 
6764     if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
6765       return true;
6766 
6767     QualType ArgTypeA = ArgExprA.get()->getType();
6768     QualType ArgTypeB = ArgExprB.get()->getType();
6769 
6770     auto isNull = [&] (Expr *E) -> bool {
6771       return E->isNullPointerConstant(
6772                         Context, Expr::NPC_ValueDependentIsNotNull); };
6773 
6774     // argument should be either a pointer or null
6775     if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
6776       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6777         << "first" << ArgTypeA << ArgA->getSourceRange();
6778 
6779     if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
6780       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6781         << "second" << ArgTypeB << ArgB->getSourceRange();
6782 
6783     // Ensure Pointee types are compatible
6784     if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
6785         ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
6786       QualType pointeeA = ArgTypeA->getPointeeType();
6787       QualType pointeeB = ArgTypeB->getPointeeType();
6788       if (!Context.typesAreCompatible(
6789              Context.getCanonicalType(pointeeA).getUnqualifiedType(),
6790              Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
6791         return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
6792           << ArgTypeA <<  ArgTypeB << ArgA->getSourceRange()
6793           << ArgB->getSourceRange();
6794       }
6795     }
6796 
6797     // at least one argument should be pointer type
6798     if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
6799       return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
6800         <<  ArgTypeA << ArgTypeB << ArgA->getSourceRange();
6801 
6802     if (isNull(ArgA)) // adopt type of the other pointer
6803       ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
6804 
6805     if (isNull(ArgB))
6806       ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
6807 
6808     TheCall->setArg(0, ArgExprA.get());
6809     TheCall->setArg(1, ArgExprB.get());
6810     TheCall->setType(Context.LongLongTy);
6811     return false;
6812   }
6813   assert(false && "Unhandled ARM MTE intrinsic");
6814   return true;
6815 }
6816 
6817 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
6818 /// TheCall is an ARM/AArch64 special register string literal.
6819 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
6820                                     int ArgNum, unsigned ExpectedFieldNum,
6821                                     bool AllowName) {
6822   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
6823                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
6824                       BuiltinID == ARM::BI__builtin_arm_rsr ||
6825                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
6826                       BuiltinID == ARM::BI__builtin_arm_wsr ||
6827                       BuiltinID == ARM::BI__builtin_arm_wsrp;
6828   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
6829                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
6830                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
6831                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
6832                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
6833                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
6834   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
6835 
6836   // We can't check the value of a dependent argument.
6837   Expr *Arg = TheCall->getArg(ArgNum);
6838   if (Arg->isTypeDependent() || Arg->isValueDependent())
6839     return false;
6840 
6841   // Check if the argument is a string literal.
6842   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
6843     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
6844            << Arg->getSourceRange();
6845 
6846   // Check the type of special register given.
6847   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
6848   SmallVector<StringRef, 6> Fields;
6849   Reg.split(Fields, ":");
6850 
6851   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
6852     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6853            << Arg->getSourceRange();
6854 
6855   // If the string is the name of a register then we cannot check that it is
6856   // valid here but if the string is of one the forms described in ACLE then we
6857   // can check that the supplied fields are integers and within the valid
6858   // ranges.
6859   if (Fields.size() > 1) {
6860     bool FiveFields = Fields.size() == 5;
6861 
6862     bool ValidString = true;
6863     if (IsARMBuiltin) {
6864       ValidString &= Fields[0].startswith_lower("cp") ||
6865                      Fields[0].startswith_lower("p");
6866       if (ValidString)
6867         Fields[0] =
6868           Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
6869 
6870       ValidString &= Fields[2].startswith_lower("c");
6871       if (ValidString)
6872         Fields[2] = Fields[2].drop_front(1);
6873 
6874       if (FiveFields) {
6875         ValidString &= Fields[3].startswith_lower("c");
6876         if (ValidString)
6877           Fields[3] = Fields[3].drop_front(1);
6878       }
6879     }
6880 
6881     SmallVector<int, 5> Ranges;
6882     if (FiveFields)
6883       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
6884     else
6885       Ranges.append({15, 7, 15});
6886 
6887     for (unsigned i=0; i<Fields.size(); ++i) {
6888       int IntField;
6889       ValidString &= !Fields[i].getAsInteger(10, IntField);
6890       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
6891     }
6892 
6893     if (!ValidString)
6894       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6895              << Arg->getSourceRange();
6896   } else if (IsAArch64Builtin && Fields.size() == 1) {
6897     // If the register name is one of those that appear in the condition below
6898     // and the special register builtin being used is one of the write builtins,
6899     // then we require that the argument provided for writing to the register
6900     // is an integer constant expression. This is because it will be lowered to
6901     // an MSR (immediate) instruction, so we need to know the immediate at
6902     // compile time.
6903     if (TheCall->getNumArgs() != 2)
6904       return false;
6905 
6906     std::string RegLower = Reg.lower();
6907     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
6908         RegLower != "pan" && RegLower != "uao")
6909       return false;
6910 
6911     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6912   }
6913 
6914   return false;
6915 }
6916 
6917 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity.
6918 /// Emit an error and return true on failure; return false on success.
6919 /// TypeStr is a string containing the type descriptor of the value returned by
6920 /// the builtin and the descriptors of the expected type of the arguments.
6921 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, const char *TypeStr) {
6922 
6923   assert((TypeStr[0] != '\0') &&
6924          "Invalid types in PPC MMA builtin declaration");
6925 
6926   unsigned Mask = 0;
6927   unsigned ArgNum = 0;
6928 
6929   // The first type in TypeStr is the type of the value returned by the
6930   // builtin. So we first read that type and change the type of TheCall.
6931   QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
6932   TheCall->setType(type);
6933 
6934   while (*TypeStr != '\0') {
6935     Mask = 0;
6936     QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
6937     if (ArgNum >= TheCall->getNumArgs()) {
6938       ArgNum++;
6939       break;
6940     }
6941 
6942     Expr *Arg = TheCall->getArg(ArgNum);
6943     QualType ArgType = Arg->getType();
6944 
6945     if ((ExpectedType->isVoidPointerType() && !ArgType->isPointerType()) ||
6946         (!ExpectedType->isVoidPointerType() &&
6947            ArgType.getCanonicalType() != ExpectedType))
6948       return Diag(Arg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6949              << ArgType << ExpectedType << 1 << 0 << 0;
6950 
6951     // If the value of the Mask is not 0, we have a constraint in the size of
6952     // the integer argument so here we ensure the argument is a constant that
6953     // is in the valid range.
6954     if (Mask != 0 &&
6955         SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true))
6956       return true;
6957 
6958     ArgNum++;
6959   }
6960 
6961   // In case we exited early from the previous loop, there are other types to
6962   // read from TypeStr. So we need to read them all to ensure we have the right
6963   // number of arguments in TheCall and if it is not the case, to display a
6964   // better error message.
6965   while (*TypeStr != '\0') {
6966     (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
6967     ArgNum++;
6968   }
6969   if (checkArgCount(*this, TheCall, ArgNum))
6970     return true;
6971 
6972   return false;
6973 }
6974 
6975 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
6976 /// This checks that the target supports __builtin_longjmp and
6977 /// that val is a constant 1.
6978 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
6979   if (!Context.getTargetInfo().hasSjLjLowering())
6980     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
6981            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6982 
6983   Expr *Arg = TheCall->getArg(1);
6984   llvm::APSInt Result;
6985 
6986   // TODO: This is less than ideal. Overload this to take a value.
6987   if (SemaBuiltinConstantArg(TheCall, 1, Result))
6988     return true;
6989 
6990   if (Result != 1)
6991     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
6992            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
6993 
6994   return false;
6995 }
6996 
6997 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
6998 /// This checks that the target supports __builtin_setjmp.
6999 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
7000   if (!Context.getTargetInfo().hasSjLjLowering())
7001     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
7002            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7003   return false;
7004 }
7005 
7006 namespace {
7007 
7008 class UncoveredArgHandler {
7009   enum { Unknown = -1, AllCovered = -2 };
7010 
7011   signed FirstUncoveredArg = Unknown;
7012   SmallVector<const Expr *, 4> DiagnosticExprs;
7013 
7014 public:
7015   UncoveredArgHandler() = default;
7016 
7017   bool hasUncoveredArg() const {
7018     return (FirstUncoveredArg >= 0);
7019   }
7020 
7021   unsigned getUncoveredArg() const {
7022     assert(hasUncoveredArg() && "no uncovered argument");
7023     return FirstUncoveredArg;
7024   }
7025 
7026   void setAllCovered() {
7027     // A string has been found with all arguments covered, so clear out
7028     // the diagnostics.
7029     DiagnosticExprs.clear();
7030     FirstUncoveredArg = AllCovered;
7031   }
7032 
7033   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
7034     assert(NewFirstUncoveredArg >= 0 && "Outside range");
7035 
7036     // Don't update if a previous string covers all arguments.
7037     if (FirstUncoveredArg == AllCovered)
7038       return;
7039 
7040     // UncoveredArgHandler tracks the highest uncovered argument index
7041     // and with it all the strings that match this index.
7042     if (NewFirstUncoveredArg == FirstUncoveredArg)
7043       DiagnosticExprs.push_back(StrExpr);
7044     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
7045       DiagnosticExprs.clear();
7046       DiagnosticExprs.push_back(StrExpr);
7047       FirstUncoveredArg = NewFirstUncoveredArg;
7048     }
7049   }
7050 
7051   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
7052 };
7053 
7054 enum StringLiteralCheckType {
7055   SLCT_NotALiteral,
7056   SLCT_UncheckedLiteral,
7057   SLCT_CheckedLiteral
7058 };
7059 
7060 } // namespace
7061 
7062 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
7063                                      BinaryOperatorKind BinOpKind,
7064                                      bool AddendIsRight) {
7065   unsigned BitWidth = Offset.getBitWidth();
7066   unsigned AddendBitWidth = Addend.getBitWidth();
7067   // There might be negative interim results.
7068   if (Addend.isUnsigned()) {
7069     Addend = Addend.zext(++AddendBitWidth);
7070     Addend.setIsSigned(true);
7071   }
7072   // Adjust the bit width of the APSInts.
7073   if (AddendBitWidth > BitWidth) {
7074     Offset = Offset.sext(AddendBitWidth);
7075     BitWidth = AddendBitWidth;
7076   } else if (BitWidth > AddendBitWidth) {
7077     Addend = Addend.sext(BitWidth);
7078   }
7079 
7080   bool Ov = false;
7081   llvm::APSInt ResOffset = Offset;
7082   if (BinOpKind == BO_Add)
7083     ResOffset = Offset.sadd_ov(Addend, Ov);
7084   else {
7085     assert(AddendIsRight && BinOpKind == BO_Sub &&
7086            "operator must be add or sub with addend on the right");
7087     ResOffset = Offset.ssub_ov(Addend, Ov);
7088   }
7089 
7090   // We add an offset to a pointer here so we should support an offset as big as
7091   // possible.
7092   if (Ov) {
7093     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
7094            "index (intermediate) result too big");
7095     Offset = Offset.sext(2 * BitWidth);
7096     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
7097     return;
7098   }
7099 
7100   Offset = ResOffset;
7101 }
7102 
7103 namespace {
7104 
7105 // This is a wrapper class around StringLiteral to support offsetted string
7106 // literals as format strings. It takes the offset into account when returning
7107 // the string and its length or the source locations to display notes correctly.
7108 class FormatStringLiteral {
7109   const StringLiteral *FExpr;
7110   int64_t Offset;
7111 
7112  public:
7113   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
7114       : FExpr(fexpr), Offset(Offset) {}
7115 
7116   StringRef getString() const {
7117     return FExpr->getString().drop_front(Offset);
7118   }
7119 
7120   unsigned getByteLength() const {
7121     return FExpr->getByteLength() - getCharByteWidth() * Offset;
7122   }
7123 
7124   unsigned getLength() const { return FExpr->getLength() - Offset; }
7125   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
7126 
7127   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
7128 
7129   QualType getType() const { return FExpr->getType(); }
7130 
7131   bool isAscii() const { return FExpr->isAscii(); }
7132   bool isWide() const { return FExpr->isWide(); }
7133   bool isUTF8() const { return FExpr->isUTF8(); }
7134   bool isUTF16() const { return FExpr->isUTF16(); }
7135   bool isUTF32() const { return FExpr->isUTF32(); }
7136   bool isPascal() const { return FExpr->isPascal(); }
7137 
7138   SourceLocation getLocationOfByte(
7139       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
7140       const TargetInfo &Target, unsigned *StartToken = nullptr,
7141       unsigned *StartTokenByteOffset = nullptr) const {
7142     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
7143                                     StartToken, StartTokenByteOffset);
7144   }
7145 
7146   SourceLocation getBeginLoc() const LLVM_READONLY {
7147     return FExpr->getBeginLoc().getLocWithOffset(Offset);
7148   }
7149 
7150   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
7151 };
7152 
7153 }  // namespace
7154 
7155 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
7156                               const Expr *OrigFormatExpr,
7157                               ArrayRef<const Expr *> Args,
7158                               bool HasVAListArg, unsigned format_idx,
7159                               unsigned firstDataArg,
7160                               Sema::FormatStringType Type,
7161                               bool inFunctionCall,
7162                               Sema::VariadicCallType CallType,
7163                               llvm::SmallBitVector &CheckedVarArgs,
7164                               UncoveredArgHandler &UncoveredArg,
7165                               bool IgnoreStringsWithoutSpecifiers);
7166 
7167 // Determine if an expression is a string literal or constant string.
7168 // If this function returns false on the arguments to a function expecting a
7169 // format string, we will usually need to emit a warning.
7170 // True string literals are then checked by CheckFormatString.
7171 static StringLiteralCheckType
7172 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
7173                       bool HasVAListArg, unsigned format_idx,
7174                       unsigned firstDataArg, Sema::FormatStringType Type,
7175                       Sema::VariadicCallType CallType, bool InFunctionCall,
7176                       llvm::SmallBitVector &CheckedVarArgs,
7177                       UncoveredArgHandler &UncoveredArg,
7178                       llvm::APSInt Offset,
7179                       bool IgnoreStringsWithoutSpecifiers = false) {
7180   if (S.isConstantEvaluated())
7181     return SLCT_NotALiteral;
7182  tryAgain:
7183   assert(Offset.isSigned() && "invalid offset");
7184 
7185   if (E->isTypeDependent() || E->isValueDependent())
7186     return SLCT_NotALiteral;
7187 
7188   E = E->IgnoreParenCasts();
7189 
7190   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
7191     // Technically -Wformat-nonliteral does not warn about this case.
7192     // The behavior of printf and friends in this case is implementation
7193     // dependent.  Ideally if the format string cannot be null then
7194     // it should have a 'nonnull' attribute in the function prototype.
7195     return SLCT_UncheckedLiteral;
7196 
7197   switch (E->getStmtClass()) {
7198   case Stmt::BinaryConditionalOperatorClass:
7199   case Stmt::ConditionalOperatorClass: {
7200     // The expression is a literal if both sub-expressions were, and it was
7201     // completely checked only if both sub-expressions were checked.
7202     const AbstractConditionalOperator *C =
7203         cast<AbstractConditionalOperator>(E);
7204 
7205     // Determine whether it is necessary to check both sub-expressions, for
7206     // example, because the condition expression is a constant that can be
7207     // evaluated at compile time.
7208     bool CheckLeft = true, CheckRight = true;
7209 
7210     bool Cond;
7211     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
7212                                                  S.isConstantEvaluated())) {
7213       if (Cond)
7214         CheckRight = false;
7215       else
7216         CheckLeft = false;
7217     }
7218 
7219     // We need to maintain the offsets for the right and the left hand side
7220     // separately to check if every possible indexed expression is a valid
7221     // string literal. They might have different offsets for different string
7222     // literals in the end.
7223     StringLiteralCheckType Left;
7224     if (!CheckLeft)
7225       Left = SLCT_UncheckedLiteral;
7226     else {
7227       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
7228                                    HasVAListArg, format_idx, firstDataArg,
7229                                    Type, CallType, InFunctionCall,
7230                                    CheckedVarArgs, UncoveredArg, Offset,
7231                                    IgnoreStringsWithoutSpecifiers);
7232       if (Left == SLCT_NotALiteral || !CheckRight) {
7233         return Left;
7234       }
7235     }
7236 
7237     StringLiteralCheckType Right = checkFormatStringExpr(
7238         S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
7239         Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7240         IgnoreStringsWithoutSpecifiers);
7241 
7242     return (CheckLeft && Left < Right) ? Left : Right;
7243   }
7244 
7245   case Stmt::ImplicitCastExprClass:
7246     E = cast<ImplicitCastExpr>(E)->getSubExpr();
7247     goto tryAgain;
7248 
7249   case Stmt::OpaqueValueExprClass:
7250     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
7251       E = src;
7252       goto tryAgain;
7253     }
7254     return SLCT_NotALiteral;
7255 
7256   case Stmt::PredefinedExprClass:
7257     // While __func__, etc., are technically not string literals, they
7258     // cannot contain format specifiers and thus are not a security
7259     // liability.
7260     return SLCT_UncheckedLiteral;
7261 
7262   case Stmt::DeclRefExprClass: {
7263     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7264 
7265     // As an exception, do not flag errors for variables binding to
7266     // const string literals.
7267     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
7268       bool isConstant = false;
7269       QualType T = DR->getType();
7270 
7271       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
7272         isConstant = AT->getElementType().isConstant(S.Context);
7273       } else if (const PointerType *PT = T->getAs<PointerType>()) {
7274         isConstant = T.isConstant(S.Context) &&
7275                      PT->getPointeeType().isConstant(S.Context);
7276       } else if (T->isObjCObjectPointerType()) {
7277         // In ObjC, there is usually no "const ObjectPointer" type,
7278         // so don't check if the pointee type is constant.
7279         isConstant = T.isConstant(S.Context);
7280       }
7281 
7282       if (isConstant) {
7283         if (const Expr *Init = VD->getAnyInitializer()) {
7284           // Look through initializers like const char c[] = { "foo" }
7285           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
7286             if (InitList->isStringLiteralInit())
7287               Init = InitList->getInit(0)->IgnoreParenImpCasts();
7288           }
7289           return checkFormatStringExpr(S, Init, Args,
7290                                        HasVAListArg, format_idx,
7291                                        firstDataArg, Type, CallType,
7292                                        /*InFunctionCall*/ false, CheckedVarArgs,
7293                                        UncoveredArg, Offset);
7294         }
7295       }
7296 
7297       // For vprintf* functions (i.e., HasVAListArg==true), we add a
7298       // special check to see if the format string is a function parameter
7299       // of the function calling the printf function.  If the function
7300       // has an attribute indicating it is a printf-like function, then we
7301       // should suppress warnings concerning non-literals being used in a call
7302       // to a vprintf function.  For example:
7303       //
7304       // void
7305       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
7306       //      va_list ap;
7307       //      va_start(ap, fmt);
7308       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
7309       //      ...
7310       // }
7311       if (HasVAListArg) {
7312         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
7313           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
7314             int PVIndex = PV->getFunctionScopeIndex() + 1;
7315             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
7316               // adjust for implicit parameter
7317               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
7318                 if (MD->isInstance())
7319                   ++PVIndex;
7320               // We also check if the formats are compatible.
7321               // We can't pass a 'scanf' string to a 'printf' function.
7322               if (PVIndex == PVFormat->getFormatIdx() &&
7323                   Type == S.GetFormatStringType(PVFormat))
7324                 return SLCT_UncheckedLiteral;
7325             }
7326           }
7327         }
7328       }
7329     }
7330 
7331     return SLCT_NotALiteral;
7332   }
7333 
7334   case Stmt::CallExprClass:
7335   case Stmt::CXXMemberCallExprClass: {
7336     const CallExpr *CE = cast<CallExpr>(E);
7337     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
7338       bool IsFirst = true;
7339       StringLiteralCheckType CommonResult;
7340       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
7341         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
7342         StringLiteralCheckType Result = checkFormatStringExpr(
7343             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7344             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7345             IgnoreStringsWithoutSpecifiers);
7346         if (IsFirst) {
7347           CommonResult = Result;
7348           IsFirst = false;
7349         }
7350       }
7351       if (!IsFirst)
7352         return CommonResult;
7353 
7354       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
7355         unsigned BuiltinID = FD->getBuiltinID();
7356         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
7357             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
7358           const Expr *Arg = CE->getArg(0);
7359           return checkFormatStringExpr(S, Arg, Args,
7360                                        HasVAListArg, format_idx,
7361                                        firstDataArg, Type, CallType,
7362                                        InFunctionCall, CheckedVarArgs,
7363                                        UncoveredArg, Offset,
7364                                        IgnoreStringsWithoutSpecifiers);
7365         }
7366       }
7367     }
7368 
7369     return SLCT_NotALiteral;
7370   }
7371   case Stmt::ObjCMessageExprClass: {
7372     const auto *ME = cast<ObjCMessageExpr>(E);
7373     if (const auto *MD = ME->getMethodDecl()) {
7374       if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
7375         // As a special case heuristic, if we're using the method -[NSBundle
7376         // localizedStringForKey:value:table:], ignore any key strings that lack
7377         // format specifiers. The idea is that if the key doesn't have any
7378         // format specifiers then its probably just a key to map to the
7379         // localized strings. If it does have format specifiers though, then its
7380         // likely that the text of the key is the format string in the
7381         // programmer's language, and should be checked.
7382         const ObjCInterfaceDecl *IFace;
7383         if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
7384             IFace->getIdentifier()->isStr("NSBundle") &&
7385             MD->getSelector().isKeywordSelector(
7386                 {"localizedStringForKey", "value", "table"})) {
7387           IgnoreStringsWithoutSpecifiers = true;
7388         }
7389 
7390         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
7391         return checkFormatStringExpr(
7392             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7393             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7394             IgnoreStringsWithoutSpecifiers);
7395       }
7396     }
7397 
7398     return SLCT_NotALiteral;
7399   }
7400   case Stmt::ObjCStringLiteralClass:
7401   case Stmt::StringLiteralClass: {
7402     const StringLiteral *StrE = nullptr;
7403 
7404     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
7405       StrE = ObjCFExpr->getString();
7406     else
7407       StrE = cast<StringLiteral>(E);
7408 
7409     if (StrE) {
7410       if (Offset.isNegative() || Offset > StrE->getLength()) {
7411         // TODO: It would be better to have an explicit warning for out of
7412         // bounds literals.
7413         return SLCT_NotALiteral;
7414       }
7415       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
7416       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
7417                         firstDataArg, Type, InFunctionCall, CallType,
7418                         CheckedVarArgs, UncoveredArg,
7419                         IgnoreStringsWithoutSpecifiers);
7420       return SLCT_CheckedLiteral;
7421     }
7422 
7423     return SLCT_NotALiteral;
7424   }
7425   case Stmt::BinaryOperatorClass: {
7426     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
7427 
7428     // A string literal + an int offset is still a string literal.
7429     if (BinOp->isAdditiveOp()) {
7430       Expr::EvalResult LResult, RResult;
7431 
7432       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
7433           LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7434       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
7435           RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7436 
7437       if (LIsInt != RIsInt) {
7438         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
7439 
7440         if (LIsInt) {
7441           if (BinOpKind == BO_Add) {
7442             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
7443             E = BinOp->getRHS();
7444             goto tryAgain;
7445           }
7446         } else {
7447           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
7448           E = BinOp->getLHS();
7449           goto tryAgain;
7450         }
7451       }
7452     }
7453 
7454     return SLCT_NotALiteral;
7455   }
7456   case Stmt::UnaryOperatorClass: {
7457     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
7458     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
7459     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
7460       Expr::EvalResult IndexResult;
7461       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
7462                                        Expr::SE_NoSideEffects,
7463                                        S.isConstantEvaluated())) {
7464         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
7465                    /*RHS is int*/ true);
7466         E = ASE->getBase();
7467         goto tryAgain;
7468       }
7469     }
7470 
7471     return SLCT_NotALiteral;
7472   }
7473 
7474   default:
7475     return SLCT_NotALiteral;
7476   }
7477 }
7478 
7479 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
7480   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
7481       .Case("scanf", FST_Scanf)
7482       .Cases("printf", "printf0", FST_Printf)
7483       .Cases("NSString", "CFString", FST_NSString)
7484       .Case("strftime", FST_Strftime)
7485       .Case("strfmon", FST_Strfmon)
7486       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
7487       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
7488       .Case("os_trace", FST_OSLog)
7489       .Case("os_log", FST_OSLog)
7490       .Default(FST_Unknown);
7491 }
7492 
7493 /// CheckFormatArguments - Check calls to printf and scanf (and similar
7494 /// functions) for correct use of format strings.
7495 /// Returns true if a format string has been fully checked.
7496 bool Sema::CheckFormatArguments(const FormatAttr *Format,
7497                                 ArrayRef<const Expr *> Args,
7498                                 bool IsCXXMember,
7499                                 VariadicCallType CallType,
7500                                 SourceLocation Loc, SourceRange Range,
7501                                 llvm::SmallBitVector &CheckedVarArgs) {
7502   FormatStringInfo FSI;
7503   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
7504     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
7505                                 FSI.FirstDataArg, GetFormatStringType(Format),
7506                                 CallType, Loc, Range, CheckedVarArgs);
7507   return false;
7508 }
7509 
7510 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
7511                                 bool HasVAListArg, unsigned format_idx,
7512                                 unsigned firstDataArg, FormatStringType Type,
7513                                 VariadicCallType CallType,
7514                                 SourceLocation Loc, SourceRange Range,
7515                                 llvm::SmallBitVector &CheckedVarArgs) {
7516   // CHECK: printf/scanf-like function is called with no format string.
7517   if (format_idx >= Args.size()) {
7518     Diag(Loc, diag::warn_missing_format_string) << Range;
7519     return false;
7520   }
7521 
7522   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
7523 
7524   // CHECK: format string is not a string literal.
7525   //
7526   // Dynamically generated format strings are difficult to
7527   // automatically vet at compile time.  Requiring that format strings
7528   // are string literals: (1) permits the checking of format strings by
7529   // the compiler and thereby (2) can practically remove the source of
7530   // many format string exploits.
7531 
7532   // Format string can be either ObjC string (e.g. @"%d") or
7533   // C string (e.g. "%d")
7534   // ObjC string uses the same format specifiers as C string, so we can use
7535   // the same format string checking logic for both ObjC and C strings.
7536   UncoveredArgHandler UncoveredArg;
7537   StringLiteralCheckType CT =
7538       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
7539                             format_idx, firstDataArg, Type, CallType,
7540                             /*IsFunctionCall*/ true, CheckedVarArgs,
7541                             UncoveredArg,
7542                             /*no string offset*/ llvm::APSInt(64, false) = 0);
7543 
7544   // Generate a diagnostic where an uncovered argument is detected.
7545   if (UncoveredArg.hasUncoveredArg()) {
7546     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
7547     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
7548     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
7549   }
7550 
7551   if (CT != SLCT_NotALiteral)
7552     // Literal format string found, check done!
7553     return CT == SLCT_CheckedLiteral;
7554 
7555   // Strftime is particular as it always uses a single 'time' argument,
7556   // so it is safe to pass a non-literal string.
7557   if (Type == FST_Strftime)
7558     return false;
7559 
7560   // Do not emit diag when the string param is a macro expansion and the
7561   // format is either NSString or CFString. This is a hack to prevent
7562   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
7563   // which are usually used in place of NS and CF string literals.
7564   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
7565   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
7566     return false;
7567 
7568   // If there are no arguments specified, warn with -Wformat-security, otherwise
7569   // warn only with -Wformat-nonliteral.
7570   if (Args.size() == firstDataArg) {
7571     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
7572       << OrigFormatExpr->getSourceRange();
7573     switch (Type) {
7574     default:
7575       break;
7576     case FST_Kprintf:
7577     case FST_FreeBSDKPrintf:
7578     case FST_Printf:
7579       Diag(FormatLoc, diag::note_format_security_fixit)
7580         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
7581       break;
7582     case FST_NSString:
7583       Diag(FormatLoc, diag::note_format_security_fixit)
7584         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
7585       break;
7586     }
7587   } else {
7588     Diag(FormatLoc, diag::warn_format_nonliteral)
7589       << OrigFormatExpr->getSourceRange();
7590   }
7591   return false;
7592 }
7593 
7594 namespace {
7595 
7596 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
7597 protected:
7598   Sema &S;
7599   const FormatStringLiteral *FExpr;
7600   const Expr *OrigFormatExpr;
7601   const Sema::FormatStringType FSType;
7602   const unsigned FirstDataArg;
7603   const unsigned NumDataArgs;
7604   const char *Beg; // Start of format string.
7605   const bool HasVAListArg;
7606   ArrayRef<const Expr *> Args;
7607   unsigned FormatIdx;
7608   llvm::SmallBitVector CoveredArgs;
7609   bool usesPositionalArgs = false;
7610   bool atFirstArg = true;
7611   bool inFunctionCall;
7612   Sema::VariadicCallType CallType;
7613   llvm::SmallBitVector &CheckedVarArgs;
7614   UncoveredArgHandler &UncoveredArg;
7615 
7616 public:
7617   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
7618                      const Expr *origFormatExpr,
7619                      const Sema::FormatStringType type, unsigned firstDataArg,
7620                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
7621                      ArrayRef<const Expr *> Args, unsigned formatIdx,
7622                      bool inFunctionCall, Sema::VariadicCallType callType,
7623                      llvm::SmallBitVector &CheckedVarArgs,
7624                      UncoveredArgHandler &UncoveredArg)
7625       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
7626         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
7627         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
7628         inFunctionCall(inFunctionCall), CallType(callType),
7629         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
7630     CoveredArgs.resize(numDataArgs);
7631     CoveredArgs.reset();
7632   }
7633 
7634   void DoneProcessing();
7635 
7636   void HandleIncompleteSpecifier(const char *startSpecifier,
7637                                  unsigned specifierLen) override;
7638 
7639   void HandleInvalidLengthModifier(
7640                            const analyze_format_string::FormatSpecifier &FS,
7641                            const analyze_format_string::ConversionSpecifier &CS,
7642                            const char *startSpecifier, unsigned specifierLen,
7643                            unsigned DiagID);
7644 
7645   void HandleNonStandardLengthModifier(
7646                     const analyze_format_string::FormatSpecifier &FS,
7647                     const char *startSpecifier, unsigned specifierLen);
7648 
7649   void HandleNonStandardConversionSpecifier(
7650                     const analyze_format_string::ConversionSpecifier &CS,
7651                     const char *startSpecifier, unsigned specifierLen);
7652 
7653   void HandlePosition(const char *startPos, unsigned posLen) override;
7654 
7655   void HandleInvalidPosition(const char *startSpecifier,
7656                              unsigned specifierLen,
7657                              analyze_format_string::PositionContext p) override;
7658 
7659   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
7660 
7661   void HandleNullChar(const char *nullCharacter) override;
7662 
7663   template <typename Range>
7664   static void
7665   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
7666                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
7667                        bool IsStringLocation, Range StringRange,
7668                        ArrayRef<FixItHint> Fixit = None);
7669 
7670 protected:
7671   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
7672                                         const char *startSpec,
7673                                         unsigned specifierLen,
7674                                         const char *csStart, unsigned csLen);
7675 
7676   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
7677                                          const char *startSpec,
7678                                          unsigned specifierLen);
7679 
7680   SourceRange getFormatStringRange();
7681   CharSourceRange getSpecifierRange(const char *startSpecifier,
7682                                     unsigned specifierLen);
7683   SourceLocation getLocationOfByte(const char *x);
7684 
7685   const Expr *getDataArg(unsigned i) const;
7686 
7687   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
7688                     const analyze_format_string::ConversionSpecifier &CS,
7689                     const char *startSpecifier, unsigned specifierLen,
7690                     unsigned argIndex);
7691 
7692   template <typename Range>
7693   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
7694                             bool IsStringLocation, Range StringRange,
7695                             ArrayRef<FixItHint> Fixit = None);
7696 };
7697 
7698 } // namespace
7699 
7700 SourceRange CheckFormatHandler::getFormatStringRange() {
7701   return OrigFormatExpr->getSourceRange();
7702 }
7703 
7704 CharSourceRange CheckFormatHandler::
7705 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
7706   SourceLocation Start = getLocationOfByte(startSpecifier);
7707   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
7708 
7709   // Advance the end SourceLocation by one due to half-open ranges.
7710   End = End.getLocWithOffset(1);
7711 
7712   return CharSourceRange::getCharRange(Start, End);
7713 }
7714 
7715 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
7716   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
7717                                   S.getLangOpts(), S.Context.getTargetInfo());
7718 }
7719 
7720 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
7721                                                    unsigned specifierLen){
7722   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
7723                        getLocationOfByte(startSpecifier),
7724                        /*IsStringLocation*/true,
7725                        getSpecifierRange(startSpecifier, specifierLen));
7726 }
7727 
7728 void CheckFormatHandler::HandleInvalidLengthModifier(
7729     const analyze_format_string::FormatSpecifier &FS,
7730     const analyze_format_string::ConversionSpecifier &CS,
7731     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
7732   using namespace analyze_format_string;
7733 
7734   const LengthModifier &LM = FS.getLengthModifier();
7735   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7736 
7737   // See if we know how to fix this length modifier.
7738   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7739   if (FixedLM) {
7740     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7741                          getLocationOfByte(LM.getStart()),
7742                          /*IsStringLocation*/true,
7743                          getSpecifierRange(startSpecifier, specifierLen));
7744 
7745     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7746       << FixedLM->toString()
7747       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7748 
7749   } else {
7750     FixItHint Hint;
7751     if (DiagID == diag::warn_format_nonsensical_length)
7752       Hint = FixItHint::CreateRemoval(LMRange);
7753 
7754     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7755                          getLocationOfByte(LM.getStart()),
7756                          /*IsStringLocation*/true,
7757                          getSpecifierRange(startSpecifier, specifierLen),
7758                          Hint);
7759   }
7760 }
7761 
7762 void CheckFormatHandler::HandleNonStandardLengthModifier(
7763     const analyze_format_string::FormatSpecifier &FS,
7764     const char *startSpecifier, unsigned specifierLen) {
7765   using namespace analyze_format_string;
7766 
7767   const LengthModifier &LM = FS.getLengthModifier();
7768   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7769 
7770   // See if we know how to fix this length modifier.
7771   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7772   if (FixedLM) {
7773     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7774                            << LM.toString() << 0,
7775                          getLocationOfByte(LM.getStart()),
7776                          /*IsStringLocation*/true,
7777                          getSpecifierRange(startSpecifier, specifierLen));
7778 
7779     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7780       << FixedLM->toString()
7781       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7782 
7783   } else {
7784     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7785                            << LM.toString() << 0,
7786                          getLocationOfByte(LM.getStart()),
7787                          /*IsStringLocation*/true,
7788                          getSpecifierRange(startSpecifier, specifierLen));
7789   }
7790 }
7791 
7792 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
7793     const analyze_format_string::ConversionSpecifier &CS,
7794     const char *startSpecifier, unsigned specifierLen) {
7795   using namespace analyze_format_string;
7796 
7797   // See if we know how to fix this conversion specifier.
7798   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
7799   if (FixedCS) {
7800     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7801                           << CS.toString() << /*conversion specifier*/1,
7802                          getLocationOfByte(CS.getStart()),
7803                          /*IsStringLocation*/true,
7804                          getSpecifierRange(startSpecifier, specifierLen));
7805 
7806     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
7807     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
7808       << FixedCS->toString()
7809       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
7810   } else {
7811     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7812                           << CS.toString() << /*conversion specifier*/1,
7813                          getLocationOfByte(CS.getStart()),
7814                          /*IsStringLocation*/true,
7815                          getSpecifierRange(startSpecifier, specifierLen));
7816   }
7817 }
7818 
7819 void CheckFormatHandler::HandlePosition(const char *startPos,
7820                                         unsigned posLen) {
7821   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
7822                                getLocationOfByte(startPos),
7823                                /*IsStringLocation*/true,
7824                                getSpecifierRange(startPos, posLen));
7825 }
7826 
7827 void
7828 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
7829                                      analyze_format_string::PositionContext p) {
7830   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
7831                          << (unsigned) p,
7832                        getLocationOfByte(startPos), /*IsStringLocation*/true,
7833                        getSpecifierRange(startPos, posLen));
7834 }
7835 
7836 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
7837                                             unsigned posLen) {
7838   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
7839                                getLocationOfByte(startPos),
7840                                /*IsStringLocation*/true,
7841                                getSpecifierRange(startPos, posLen));
7842 }
7843 
7844 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
7845   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
7846     // The presence of a null character is likely an error.
7847     EmitFormatDiagnostic(
7848       S.PDiag(diag::warn_printf_format_string_contains_null_char),
7849       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
7850       getFormatStringRange());
7851   }
7852 }
7853 
7854 // Note that this may return NULL if there was an error parsing or building
7855 // one of the argument expressions.
7856 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
7857   return Args[FirstDataArg + i];
7858 }
7859 
7860 void CheckFormatHandler::DoneProcessing() {
7861   // Does the number of data arguments exceed the number of
7862   // format conversions in the format string?
7863   if (!HasVAListArg) {
7864       // Find any arguments that weren't covered.
7865     CoveredArgs.flip();
7866     signed notCoveredArg = CoveredArgs.find_first();
7867     if (notCoveredArg >= 0) {
7868       assert((unsigned)notCoveredArg < NumDataArgs);
7869       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
7870     } else {
7871       UncoveredArg.setAllCovered();
7872     }
7873   }
7874 }
7875 
7876 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
7877                                    const Expr *ArgExpr) {
7878   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
7879          "Invalid state");
7880 
7881   if (!ArgExpr)
7882     return;
7883 
7884   SourceLocation Loc = ArgExpr->getBeginLoc();
7885 
7886   if (S.getSourceManager().isInSystemMacro(Loc))
7887     return;
7888 
7889   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
7890   for (auto E : DiagnosticExprs)
7891     PDiag << E->getSourceRange();
7892 
7893   CheckFormatHandler::EmitFormatDiagnostic(
7894                                   S, IsFunctionCall, DiagnosticExprs[0],
7895                                   PDiag, Loc, /*IsStringLocation*/false,
7896                                   DiagnosticExprs[0]->getSourceRange());
7897 }
7898 
7899 bool
7900 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
7901                                                      SourceLocation Loc,
7902                                                      const char *startSpec,
7903                                                      unsigned specifierLen,
7904                                                      const char *csStart,
7905                                                      unsigned csLen) {
7906   bool keepGoing = true;
7907   if (argIndex < NumDataArgs) {
7908     // Consider the argument coverered, even though the specifier doesn't
7909     // make sense.
7910     CoveredArgs.set(argIndex);
7911   }
7912   else {
7913     // If argIndex exceeds the number of data arguments we
7914     // don't issue a warning because that is just a cascade of warnings (and
7915     // they may have intended '%%' anyway). We don't want to continue processing
7916     // the format string after this point, however, as we will like just get
7917     // gibberish when trying to match arguments.
7918     keepGoing = false;
7919   }
7920 
7921   StringRef Specifier(csStart, csLen);
7922 
7923   // If the specifier in non-printable, it could be the first byte of a UTF-8
7924   // sequence. In that case, print the UTF-8 code point. If not, print the byte
7925   // hex value.
7926   std::string CodePointStr;
7927   if (!llvm::sys::locale::isPrint(*csStart)) {
7928     llvm::UTF32 CodePoint;
7929     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
7930     const llvm::UTF8 *E =
7931         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
7932     llvm::ConversionResult Result =
7933         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
7934 
7935     if (Result != llvm::conversionOK) {
7936       unsigned char FirstChar = *csStart;
7937       CodePoint = (llvm::UTF32)FirstChar;
7938     }
7939 
7940     llvm::raw_string_ostream OS(CodePointStr);
7941     if (CodePoint < 256)
7942       OS << "\\x" << llvm::format("%02x", CodePoint);
7943     else if (CodePoint <= 0xFFFF)
7944       OS << "\\u" << llvm::format("%04x", CodePoint);
7945     else
7946       OS << "\\U" << llvm::format("%08x", CodePoint);
7947     OS.flush();
7948     Specifier = CodePointStr;
7949   }
7950 
7951   EmitFormatDiagnostic(
7952       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
7953       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
7954 
7955   return keepGoing;
7956 }
7957 
7958 void
7959 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
7960                                                       const char *startSpec,
7961                                                       unsigned specifierLen) {
7962   EmitFormatDiagnostic(
7963     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
7964     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
7965 }
7966 
7967 bool
7968 CheckFormatHandler::CheckNumArgs(
7969   const analyze_format_string::FormatSpecifier &FS,
7970   const analyze_format_string::ConversionSpecifier &CS,
7971   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
7972 
7973   if (argIndex >= NumDataArgs) {
7974     PartialDiagnostic PDiag = FS.usesPositionalArg()
7975       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
7976            << (argIndex+1) << NumDataArgs)
7977       : S.PDiag(diag::warn_printf_insufficient_data_args);
7978     EmitFormatDiagnostic(
7979       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
7980       getSpecifierRange(startSpecifier, specifierLen));
7981 
7982     // Since more arguments than conversion tokens are given, by extension
7983     // all arguments are covered, so mark this as so.
7984     UncoveredArg.setAllCovered();
7985     return false;
7986   }
7987   return true;
7988 }
7989 
7990 template<typename Range>
7991 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
7992                                               SourceLocation Loc,
7993                                               bool IsStringLocation,
7994                                               Range StringRange,
7995                                               ArrayRef<FixItHint> FixIt) {
7996   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
7997                        Loc, IsStringLocation, StringRange, FixIt);
7998 }
7999 
8000 /// If the format string is not within the function call, emit a note
8001 /// so that the function call and string are in diagnostic messages.
8002 ///
8003 /// \param InFunctionCall if true, the format string is within the function
8004 /// call and only one diagnostic message will be produced.  Otherwise, an
8005 /// extra note will be emitted pointing to location of the format string.
8006 ///
8007 /// \param ArgumentExpr the expression that is passed as the format string
8008 /// argument in the function call.  Used for getting locations when two
8009 /// diagnostics are emitted.
8010 ///
8011 /// \param PDiag the callee should already have provided any strings for the
8012 /// diagnostic message.  This function only adds locations and fixits
8013 /// to diagnostics.
8014 ///
8015 /// \param Loc primary location for diagnostic.  If two diagnostics are
8016 /// required, one will be at Loc and a new SourceLocation will be created for
8017 /// the other one.
8018 ///
8019 /// \param IsStringLocation if true, Loc points to the format string should be
8020 /// used for the note.  Otherwise, Loc points to the argument list and will
8021 /// be used with PDiag.
8022 ///
8023 /// \param StringRange some or all of the string to highlight.  This is
8024 /// templated so it can accept either a CharSourceRange or a SourceRange.
8025 ///
8026 /// \param FixIt optional fix it hint for the format string.
8027 template <typename Range>
8028 void CheckFormatHandler::EmitFormatDiagnostic(
8029     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
8030     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
8031     Range StringRange, ArrayRef<FixItHint> FixIt) {
8032   if (InFunctionCall) {
8033     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
8034     D << StringRange;
8035     D << FixIt;
8036   } else {
8037     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
8038       << ArgumentExpr->getSourceRange();
8039 
8040     const Sema::SemaDiagnosticBuilder &Note =
8041       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
8042              diag::note_format_string_defined);
8043 
8044     Note << StringRange;
8045     Note << FixIt;
8046   }
8047 }
8048 
8049 //===--- CHECK: Printf format string checking ------------------------------===//
8050 
8051 namespace {
8052 
8053 class CheckPrintfHandler : public CheckFormatHandler {
8054 public:
8055   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8056                      const Expr *origFormatExpr,
8057                      const Sema::FormatStringType type, unsigned firstDataArg,
8058                      unsigned numDataArgs, bool isObjC, const char *beg,
8059                      bool hasVAListArg, ArrayRef<const Expr *> Args,
8060                      unsigned formatIdx, bool inFunctionCall,
8061                      Sema::VariadicCallType CallType,
8062                      llvm::SmallBitVector &CheckedVarArgs,
8063                      UncoveredArgHandler &UncoveredArg)
8064       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8065                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
8066                            inFunctionCall, CallType, CheckedVarArgs,
8067                            UncoveredArg) {}
8068 
8069   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
8070 
8071   /// Returns true if '%@' specifiers are allowed in the format string.
8072   bool allowsObjCArg() const {
8073     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
8074            FSType == Sema::FST_OSTrace;
8075   }
8076 
8077   bool HandleInvalidPrintfConversionSpecifier(
8078                                       const analyze_printf::PrintfSpecifier &FS,
8079                                       const char *startSpecifier,
8080                                       unsigned specifierLen) override;
8081 
8082   void handleInvalidMaskType(StringRef MaskType) override;
8083 
8084   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8085                              const char *startSpecifier,
8086                              unsigned specifierLen) override;
8087   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8088                        const char *StartSpecifier,
8089                        unsigned SpecifierLen,
8090                        const Expr *E);
8091 
8092   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
8093                     const char *startSpecifier, unsigned specifierLen);
8094   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
8095                            const analyze_printf::OptionalAmount &Amt,
8096                            unsigned type,
8097                            const char *startSpecifier, unsigned specifierLen);
8098   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8099                   const analyze_printf::OptionalFlag &flag,
8100                   const char *startSpecifier, unsigned specifierLen);
8101   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
8102                          const analyze_printf::OptionalFlag &ignoredFlag,
8103                          const analyze_printf::OptionalFlag &flag,
8104                          const char *startSpecifier, unsigned specifierLen);
8105   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
8106                            const Expr *E);
8107 
8108   void HandleEmptyObjCModifierFlag(const char *startFlag,
8109                                    unsigned flagLen) override;
8110 
8111   void HandleInvalidObjCModifierFlag(const char *startFlag,
8112                                             unsigned flagLen) override;
8113 
8114   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
8115                                            const char *flagsEnd,
8116                                            const char *conversionPosition)
8117                                              override;
8118 };
8119 
8120 } // namespace
8121 
8122 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
8123                                       const analyze_printf::PrintfSpecifier &FS,
8124                                       const char *startSpecifier,
8125                                       unsigned specifierLen) {
8126   const analyze_printf::PrintfConversionSpecifier &CS =
8127     FS.getConversionSpecifier();
8128 
8129   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8130                                           getLocationOfByte(CS.getStart()),
8131                                           startSpecifier, specifierLen,
8132                                           CS.getStart(), CS.getLength());
8133 }
8134 
8135 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
8136   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
8137 }
8138 
8139 bool CheckPrintfHandler::HandleAmount(
8140                                const analyze_format_string::OptionalAmount &Amt,
8141                                unsigned k, const char *startSpecifier,
8142                                unsigned specifierLen) {
8143   if (Amt.hasDataArgument()) {
8144     if (!HasVAListArg) {
8145       unsigned argIndex = Amt.getArgIndex();
8146       if (argIndex >= NumDataArgs) {
8147         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
8148                                << k,
8149                              getLocationOfByte(Amt.getStart()),
8150                              /*IsStringLocation*/true,
8151                              getSpecifierRange(startSpecifier, specifierLen));
8152         // Don't do any more checking.  We will just emit
8153         // spurious errors.
8154         return false;
8155       }
8156 
8157       // Type check the data argument.  It should be an 'int'.
8158       // Although not in conformance with C99, we also allow the argument to be
8159       // an 'unsigned int' as that is a reasonably safe case.  GCC also
8160       // doesn't emit a warning for that case.
8161       CoveredArgs.set(argIndex);
8162       const Expr *Arg = getDataArg(argIndex);
8163       if (!Arg)
8164         return false;
8165 
8166       QualType T = Arg->getType();
8167 
8168       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
8169       assert(AT.isValid());
8170 
8171       if (!AT.matchesType(S.Context, T)) {
8172         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
8173                                << k << AT.getRepresentativeTypeName(S.Context)
8174                                << T << Arg->getSourceRange(),
8175                              getLocationOfByte(Amt.getStart()),
8176                              /*IsStringLocation*/true,
8177                              getSpecifierRange(startSpecifier, specifierLen));
8178         // Don't do any more checking.  We will just emit
8179         // spurious errors.
8180         return false;
8181       }
8182     }
8183   }
8184   return true;
8185 }
8186 
8187 void CheckPrintfHandler::HandleInvalidAmount(
8188                                       const analyze_printf::PrintfSpecifier &FS,
8189                                       const analyze_printf::OptionalAmount &Amt,
8190                                       unsigned type,
8191                                       const char *startSpecifier,
8192                                       unsigned specifierLen) {
8193   const analyze_printf::PrintfConversionSpecifier &CS =
8194     FS.getConversionSpecifier();
8195 
8196   FixItHint fixit =
8197     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
8198       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
8199                                  Amt.getConstantLength()))
8200       : FixItHint();
8201 
8202   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
8203                          << type << CS.toString(),
8204                        getLocationOfByte(Amt.getStart()),
8205                        /*IsStringLocation*/true,
8206                        getSpecifierRange(startSpecifier, specifierLen),
8207                        fixit);
8208 }
8209 
8210 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8211                                     const analyze_printf::OptionalFlag &flag,
8212                                     const char *startSpecifier,
8213                                     unsigned specifierLen) {
8214   // Warn about pointless flag with a fixit removal.
8215   const analyze_printf::PrintfConversionSpecifier &CS =
8216     FS.getConversionSpecifier();
8217   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
8218                          << flag.toString() << CS.toString(),
8219                        getLocationOfByte(flag.getPosition()),
8220                        /*IsStringLocation*/true,
8221                        getSpecifierRange(startSpecifier, specifierLen),
8222                        FixItHint::CreateRemoval(
8223                          getSpecifierRange(flag.getPosition(), 1)));
8224 }
8225 
8226 void CheckPrintfHandler::HandleIgnoredFlag(
8227                                 const analyze_printf::PrintfSpecifier &FS,
8228                                 const analyze_printf::OptionalFlag &ignoredFlag,
8229                                 const analyze_printf::OptionalFlag &flag,
8230                                 const char *startSpecifier,
8231                                 unsigned specifierLen) {
8232   // Warn about ignored flag with a fixit removal.
8233   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
8234                          << ignoredFlag.toString() << flag.toString(),
8235                        getLocationOfByte(ignoredFlag.getPosition()),
8236                        /*IsStringLocation*/true,
8237                        getSpecifierRange(startSpecifier, specifierLen),
8238                        FixItHint::CreateRemoval(
8239                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
8240 }
8241 
8242 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
8243                                                      unsigned flagLen) {
8244   // Warn about an empty flag.
8245   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
8246                        getLocationOfByte(startFlag),
8247                        /*IsStringLocation*/true,
8248                        getSpecifierRange(startFlag, flagLen));
8249 }
8250 
8251 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
8252                                                        unsigned flagLen) {
8253   // Warn about an invalid flag.
8254   auto Range = getSpecifierRange(startFlag, flagLen);
8255   StringRef flag(startFlag, flagLen);
8256   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
8257                       getLocationOfByte(startFlag),
8258                       /*IsStringLocation*/true,
8259                       Range, FixItHint::CreateRemoval(Range));
8260 }
8261 
8262 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
8263     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
8264     // Warn about using '[...]' without a '@' conversion.
8265     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
8266     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
8267     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
8268                          getLocationOfByte(conversionPosition),
8269                          /*IsStringLocation*/true,
8270                          Range, FixItHint::CreateRemoval(Range));
8271 }
8272 
8273 // Determines if the specified is a C++ class or struct containing
8274 // a member with the specified name and kind (e.g. a CXXMethodDecl named
8275 // "c_str()").
8276 template<typename MemberKind>
8277 static llvm::SmallPtrSet<MemberKind*, 1>
8278 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
8279   const RecordType *RT = Ty->getAs<RecordType>();
8280   llvm::SmallPtrSet<MemberKind*, 1> Results;
8281 
8282   if (!RT)
8283     return Results;
8284   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
8285   if (!RD || !RD->getDefinition())
8286     return Results;
8287 
8288   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
8289                  Sema::LookupMemberName);
8290   R.suppressDiagnostics();
8291 
8292   // We just need to include all members of the right kind turned up by the
8293   // filter, at this point.
8294   if (S.LookupQualifiedName(R, RT->getDecl()))
8295     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8296       NamedDecl *decl = (*I)->getUnderlyingDecl();
8297       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
8298         Results.insert(FK);
8299     }
8300   return Results;
8301 }
8302 
8303 /// Check if we could call '.c_str()' on an object.
8304 ///
8305 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
8306 /// allow the call, or if it would be ambiguous).
8307 bool Sema::hasCStrMethod(const Expr *E) {
8308   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8309 
8310   MethodSet Results =
8311       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
8312   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8313        MI != ME; ++MI)
8314     if ((*MI)->getMinRequiredArguments() == 0)
8315       return true;
8316   return false;
8317 }
8318 
8319 // Check if a (w)string was passed when a (w)char* was needed, and offer a
8320 // better diagnostic if so. AT is assumed to be valid.
8321 // Returns true when a c_str() conversion method is found.
8322 bool CheckPrintfHandler::checkForCStrMembers(
8323     const analyze_printf::ArgType &AT, const Expr *E) {
8324   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8325 
8326   MethodSet Results =
8327       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
8328 
8329   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8330        MI != ME; ++MI) {
8331     const CXXMethodDecl *Method = *MI;
8332     if (Method->getMinRequiredArguments() == 0 &&
8333         AT.matchesType(S.Context, Method->getReturnType())) {
8334       // FIXME: Suggest parens if the expression needs them.
8335       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
8336       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
8337           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
8338       return true;
8339     }
8340   }
8341 
8342   return false;
8343 }
8344 
8345 bool
8346 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
8347                                             &FS,
8348                                           const char *startSpecifier,
8349                                           unsigned specifierLen) {
8350   using namespace analyze_format_string;
8351   using namespace analyze_printf;
8352 
8353   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
8354 
8355   if (FS.consumesDataArgument()) {
8356     if (atFirstArg) {
8357         atFirstArg = false;
8358         usesPositionalArgs = FS.usesPositionalArg();
8359     }
8360     else if (usesPositionalArgs != FS.usesPositionalArg()) {
8361       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8362                                         startSpecifier, specifierLen);
8363       return false;
8364     }
8365   }
8366 
8367   // First check if the field width, precision, and conversion specifier
8368   // have matching data arguments.
8369   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
8370                     startSpecifier, specifierLen)) {
8371     return false;
8372   }
8373 
8374   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
8375                     startSpecifier, specifierLen)) {
8376     return false;
8377   }
8378 
8379   if (!CS.consumesDataArgument()) {
8380     // FIXME: Technically specifying a precision or field width here
8381     // makes no sense.  Worth issuing a warning at some point.
8382     return true;
8383   }
8384 
8385   // Consume the argument.
8386   unsigned argIndex = FS.getArgIndex();
8387   if (argIndex < NumDataArgs) {
8388     // The check to see if the argIndex is valid will come later.
8389     // We set the bit here because we may exit early from this
8390     // function if we encounter some other error.
8391     CoveredArgs.set(argIndex);
8392   }
8393 
8394   // FreeBSD kernel extensions.
8395   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
8396       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
8397     // We need at least two arguments.
8398     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
8399       return false;
8400 
8401     // Claim the second argument.
8402     CoveredArgs.set(argIndex + 1);
8403 
8404     // Type check the first argument (int for %b, pointer for %D)
8405     const Expr *Ex = getDataArg(argIndex);
8406     const analyze_printf::ArgType &AT =
8407       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
8408         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
8409     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
8410       EmitFormatDiagnostic(
8411           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8412               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
8413               << false << Ex->getSourceRange(),
8414           Ex->getBeginLoc(), /*IsStringLocation*/ false,
8415           getSpecifierRange(startSpecifier, specifierLen));
8416 
8417     // Type check the second argument (char * for both %b and %D)
8418     Ex = getDataArg(argIndex + 1);
8419     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
8420     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
8421       EmitFormatDiagnostic(
8422           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8423               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
8424               << false << Ex->getSourceRange(),
8425           Ex->getBeginLoc(), /*IsStringLocation*/ false,
8426           getSpecifierRange(startSpecifier, specifierLen));
8427 
8428      return true;
8429   }
8430 
8431   // Check for using an Objective-C specific conversion specifier
8432   // in a non-ObjC literal.
8433   if (!allowsObjCArg() && CS.isObjCArg()) {
8434     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8435                                                   specifierLen);
8436   }
8437 
8438   // %P can only be used with os_log.
8439   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
8440     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8441                                                   specifierLen);
8442   }
8443 
8444   // %n is not allowed with os_log.
8445   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
8446     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
8447                          getLocationOfByte(CS.getStart()),
8448                          /*IsStringLocation*/ false,
8449                          getSpecifierRange(startSpecifier, specifierLen));
8450 
8451     return true;
8452   }
8453 
8454   // Only scalars are allowed for os_trace.
8455   if (FSType == Sema::FST_OSTrace &&
8456       (CS.getKind() == ConversionSpecifier::PArg ||
8457        CS.getKind() == ConversionSpecifier::sArg ||
8458        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
8459     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8460                                                   specifierLen);
8461   }
8462 
8463   // Check for use of public/private annotation outside of os_log().
8464   if (FSType != Sema::FST_OSLog) {
8465     if (FS.isPublic().isSet()) {
8466       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8467                                << "public",
8468                            getLocationOfByte(FS.isPublic().getPosition()),
8469                            /*IsStringLocation*/ false,
8470                            getSpecifierRange(startSpecifier, specifierLen));
8471     }
8472     if (FS.isPrivate().isSet()) {
8473       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8474                                << "private",
8475                            getLocationOfByte(FS.isPrivate().getPosition()),
8476                            /*IsStringLocation*/ false,
8477                            getSpecifierRange(startSpecifier, specifierLen));
8478     }
8479   }
8480 
8481   // Check for invalid use of field width
8482   if (!FS.hasValidFieldWidth()) {
8483     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
8484         startSpecifier, specifierLen);
8485   }
8486 
8487   // Check for invalid use of precision
8488   if (!FS.hasValidPrecision()) {
8489     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
8490         startSpecifier, specifierLen);
8491   }
8492 
8493   // Precision is mandatory for %P specifier.
8494   if (CS.getKind() == ConversionSpecifier::PArg &&
8495       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
8496     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
8497                          getLocationOfByte(startSpecifier),
8498                          /*IsStringLocation*/ false,
8499                          getSpecifierRange(startSpecifier, specifierLen));
8500   }
8501 
8502   // Check each flag does not conflict with any other component.
8503   if (!FS.hasValidThousandsGroupingPrefix())
8504     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
8505   if (!FS.hasValidLeadingZeros())
8506     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
8507   if (!FS.hasValidPlusPrefix())
8508     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
8509   if (!FS.hasValidSpacePrefix())
8510     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
8511   if (!FS.hasValidAlternativeForm())
8512     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
8513   if (!FS.hasValidLeftJustified())
8514     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
8515 
8516   // Check that flags are not ignored by another flag
8517   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
8518     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
8519         startSpecifier, specifierLen);
8520   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
8521     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
8522             startSpecifier, specifierLen);
8523 
8524   // Check the length modifier is valid with the given conversion specifier.
8525   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8526                                  S.getLangOpts()))
8527     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8528                                 diag::warn_format_nonsensical_length);
8529   else if (!FS.hasStandardLengthModifier())
8530     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8531   else if (!FS.hasStandardLengthConversionCombination())
8532     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8533                                 diag::warn_format_non_standard_conversion_spec);
8534 
8535   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8536     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8537 
8538   // The remaining checks depend on the data arguments.
8539   if (HasVAListArg)
8540     return true;
8541 
8542   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8543     return false;
8544 
8545   const Expr *Arg = getDataArg(argIndex);
8546   if (!Arg)
8547     return true;
8548 
8549   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
8550 }
8551 
8552 static bool requiresParensToAddCast(const Expr *E) {
8553   // FIXME: We should have a general way to reason about operator
8554   // precedence and whether parens are actually needed here.
8555   // Take care of a few common cases where they aren't.
8556   const Expr *Inside = E->IgnoreImpCasts();
8557   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
8558     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
8559 
8560   switch (Inside->getStmtClass()) {
8561   case Stmt::ArraySubscriptExprClass:
8562   case Stmt::CallExprClass:
8563   case Stmt::CharacterLiteralClass:
8564   case Stmt::CXXBoolLiteralExprClass:
8565   case Stmt::DeclRefExprClass:
8566   case Stmt::FloatingLiteralClass:
8567   case Stmt::IntegerLiteralClass:
8568   case Stmt::MemberExprClass:
8569   case Stmt::ObjCArrayLiteralClass:
8570   case Stmt::ObjCBoolLiteralExprClass:
8571   case Stmt::ObjCBoxedExprClass:
8572   case Stmt::ObjCDictionaryLiteralClass:
8573   case Stmt::ObjCEncodeExprClass:
8574   case Stmt::ObjCIvarRefExprClass:
8575   case Stmt::ObjCMessageExprClass:
8576   case Stmt::ObjCPropertyRefExprClass:
8577   case Stmt::ObjCStringLiteralClass:
8578   case Stmt::ObjCSubscriptRefExprClass:
8579   case Stmt::ParenExprClass:
8580   case Stmt::StringLiteralClass:
8581   case Stmt::UnaryOperatorClass:
8582     return false;
8583   default:
8584     return true;
8585   }
8586 }
8587 
8588 static std::pair<QualType, StringRef>
8589 shouldNotPrintDirectly(const ASTContext &Context,
8590                        QualType IntendedTy,
8591                        const Expr *E) {
8592   // Use a 'while' to peel off layers of typedefs.
8593   QualType TyTy = IntendedTy;
8594   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
8595     StringRef Name = UserTy->getDecl()->getName();
8596     QualType CastTy = llvm::StringSwitch<QualType>(Name)
8597       .Case("CFIndex", Context.getNSIntegerType())
8598       .Case("NSInteger", Context.getNSIntegerType())
8599       .Case("NSUInteger", Context.getNSUIntegerType())
8600       .Case("SInt32", Context.IntTy)
8601       .Case("UInt32", Context.UnsignedIntTy)
8602       .Default(QualType());
8603 
8604     if (!CastTy.isNull())
8605       return std::make_pair(CastTy, Name);
8606 
8607     TyTy = UserTy->desugar();
8608   }
8609 
8610   // Strip parens if necessary.
8611   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
8612     return shouldNotPrintDirectly(Context,
8613                                   PE->getSubExpr()->getType(),
8614                                   PE->getSubExpr());
8615 
8616   // If this is a conditional expression, then its result type is constructed
8617   // via usual arithmetic conversions and thus there might be no necessary
8618   // typedef sugar there.  Recurse to operands to check for NSInteger &
8619   // Co. usage condition.
8620   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8621     QualType TrueTy, FalseTy;
8622     StringRef TrueName, FalseName;
8623 
8624     std::tie(TrueTy, TrueName) =
8625       shouldNotPrintDirectly(Context,
8626                              CO->getTrueExpr()->getType(),
8627                              CO->getTrueExpr());
8628     std::tie(FalseTy, FalseName) =
8629       shouldNotPrintDirectly(Context,
8630                              CO->getFalseExpr()->getType(),
8631                              CO->getFalseExpr());
8632 
8633     if (TrueTy == FalseTy)
8634       return std::make_pair(TrueTy, TrueName);
8635     else if (TrueTy.isNull())
8636       return std::make_pair(FalseTy, FalseName);
8637     else if (FalseTy.isNull())
8638       return std::make_pair(TrueTy, TrueName);
8639   }
8640 
8641   return std::make_pair(QualType(), StringRef());
8642 }
8643 
8644 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
8645 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
8646 /// type do not count.
8647 static bool
8648 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
8649   QualType From = ICE->getSubExpr()->getType();
8650   QualType To = ICE->getType();
8651   // It's an integer promotion if the destination type is the promoted
8652   // source type.
8653   if (ICE->getCastKind() == CK_IntegralCast &&
8654       From->isPromotableIntegerType() &&
8655       S.Context.getPromotedIntegerType(From) == To)
8656     return true;
8657   // Look through vector types, since we do default argument promotion for
8658   // those in OpenCL.
8659   if (const auto *VecTy = From->getAs<ExtVectorType>())
8660     From = VecTy->getElementType();
8661   if (const auto *VecTy = To->getAs<ExtVectorType>())
8662     To = VecTy->getElementType();
8663   // It's a floating promotion if the source type is a lower rank.
8664   return ICE->getCastKind() == CK_FloatingCast &&
8665          S.Context.getFloatingTypeOrder(From, To) < 0;
8666 }
8667 
8668 bool
8669 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8670                                     const char *StartSpecifier,
8671                                     unsigned SpecifierLen,
8672                                     const Expr *E) {
8673   using namespace analyze_format_string;
8674   using namespace analyze_printf;
8675 
8676   // Now type check the data expression that matches the
8677   // format specifier.
8678   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
8679   if (!AT.isValid())
8680     return true;
8681 
8682   QualType ExprTy = E->getType();
8683   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
8684     ExprTy = TET->getUnderlyingExpr()->getType();
8685   }
8686 
8687   // Diagnose attempts to print a boolean value as a character. Unlike other
8688   // -Wformat diagnostics, this is fine from a type perspective, but it still
8689   // doesn't make sense.
8690   if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
8691       E->isKnownToHaveBooleanValue()) {
8692     const CharSourceRange &CSR =
8693         getSpecifierRange(StartSpecifier, SpecifierLen);
8694     SmallString<4> FSString;
8695     llvm::raw_svector_ostream os(FSString);
8696     FS.toString(os);
8697     EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
8698                              << FSString,
8699                          E->getExprLoc(), false, CSR);
8700     return true;
8701   }
8702 
8703   analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
8704   if (Match == analyze_printf::ArgType::Match)
8705     return true;
8706 
8707   // Look through argument promotions for our error message's reported type.
8708   // This includes the integral and floating promotions, but excludes array
8709   // and function pointer decay (seeing that an argument intended to be a
8710   // string has type 'char [6]' is probably more confusing than 'char *') and
8711   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
8712   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8713     if (isArithmeticArgumentPromotion(S, ICE)) {
8714       E = ICE->getSubExpr();
8715       ExprTy = E->getType();
8716 
8717       // Check if we didn't match because of an implicit cast from a 'char'
8718       // or 'short' to an 'int'.  This is done because printf is a varargs
8719       // function.
8720       if (ICE->getType() == S.Context.IntTy ||
8721           ICE->getType() == S.Context.UnsignedIntTy) {
8722         // All further checking is done on the subexpression
8723         const analyze_printf::ArgType::MatchKind ImplicitMatch =
8724             AT.matchesType(S.Context, ExprTy);
8725         if (ImplicitMatch == analyze_printf::ArgType::Match)
8726           return true;
8727         if (ImplicitMatch == ArgType::NoMatchPedantic ||
8728             ImplicitMatch == ArgType::NoMatchTypeConfusion)
8729           Match = ImplicitMatch;
8730       }
8731     }
8732   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
8733     // Special case for 'a', which has type 'int' in C.
8734     // Note, however, that we do /not/ want to treat multibyte constants like
8735     // 'MooV' as characters! This form is deprecated but still exists. In
8736     // addition, don't treat expressions as of type 'char' if one byte length
8737     // modifier is provided.
8738     if (ExprTy == S.Context.IntTy &&
8739         FS.getLengthModifier().getKind() != LengthModifier::AsChar)
8740       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
8741         ExprTy = S.Context.CharTy;
8742   }
8743 
8744   // Look through enums to their underlying type.
8745   bool IsEnum = false;
8746   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
8747     ExprTy = EnumTy->getDecl()->getIntegerType();
8748     IsEnum = true;
8749   }
8750 
8751   // %C in an Objective-C context prints a unichar, not a wchar_t.
8752   // If the argument is an integer of some kind, believe the %C and suggest
8753   // a cast instead of changing the conversion specifier.
8754   QualType IntendedTy = ExprTy;
8755   if (isObjCContext() &&
8756       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
8757     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
8758         !ExprTy->isCharType()) {
8759       // 'unichar' is defined as a typedef of unsigned short, but we should
8760       // prefer using the typedef if it is visible.
8761       IntendedTy = S.Context.UnsignedShortTy;
8762 
8763       // While we are here, check if the value is an IntegerLiteral that happens
8764       // to be within the valid range.
8765       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
8766         const llvm::APInt &V = IL->getValue();
8767         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
8768           return true;
8769       }
8770 
8771       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
8772                           Sema::LookupOrdinaryName);
8773       if (S.LookupName(Result, S.getCurScope())) {
8774         NamedDecl *ND = Result.getFoundDecl();
8775         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
8776           if (TD->getUnderlyingType() == IntendedTy)
8777             IntendedTy = S.Context.getTypedefType(TD);
8778       }
8779     }
8780   }
8781 
8782   // Special-case some of Darwin's platform-independence types by suggesting
8783   // casts to primitive types that are known to be large enough.
8784   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
8785   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
8786     QualType CastTy;
8787     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
8788     if (!CastTy.isNull()) {
8789       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
8790       // (long in ASTContext). Only complain to pedants.
8791       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
8792           (AT.isSizeT() || AT.isPtrdiffT()) &&
8793           AT.matchesType(S.Context, CastTy))
8794         Match = ArgType::NoMatchPedantic;
8795       IntendedTy = CastTy;
8796       ShouldNotPrintDirectly = true;
8797     }
8798   }
8799 
8800   // We may be able to offer a FixItHint if it is a supported type.
8801   PrintfSpecifier fixedFS = FS;
8802   bool Success =
8803       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
8804 
8805   if (Success) {
8806     // Get the fix string from the fixed format specifier
8807     SmallString<16> buf;
8808     llvm::raw_svector_ostream os(buf);
8809     fixedFS.toString(os);
8810 
8811     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
8812 
8813     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
8814       unsigned Diag;
8815       switch (Match) {
8816       case ArgType::Match: llvm_unreachable("expected non-matching");
8817       case ArgType::NoMatchPedantic:
8818         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8819         break;
8820       case ArgType::NoMatchTypeConfusion:
8821         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8822         break;
8823       case ArgType::NoMatch:
8824         Diag = diag::warn_format_conversion_argument_type_mismatch;
8825         break;
8826       }
8827 
8828       // In this case, the specifier is wrong and should be changed to match
8829       // the argument.
8830       EmitFormatDiagnostic(S.PDiag(Diag)
8831                                << AT.getRepresentativeTypeName(S.Context)
8832                                << IntendedTy << IsEnum << E->getSourceRange(),
8833                            E->getBeginLoc(),
8834                            /*IsStringLocation*/ false, SpecRange,
8835                            FixItHint::CreateReplacement(SpecRange, os.str()));
8836     } else {
8837       // The canonical type for formatting this value is different from the
8838       // actual type of the expression. (This occurs, for example, with Darwin's
8839       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
8840       // should be printed as 'long' for 64-bit compatibility.)
8841       // Rather than emitting a normal format/argument mismatch, we want to
8842       // add a cast to the recommended type (and correct the format string
8843       // if necessary).
8844       SmallString<16> CastBuf;
8845       llvm::raw_svector_ostream CastFix(CastBuf);
8846       CastFix << "(";
8847       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
8848       CastFix << ")";
8849 
8850       SmallVector<FixItHint,4> Hints;
8851       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
8852         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
8853 
8854       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
8855         // If there's already a cast present, just replace it.
8856         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
8857         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
8858 
8859       } else if (!requiresParensToAddCast(E)) {
8860         // If the expression has high enough precedence,
8861         // just write the C-style cast.
8862         Hints.push_back(
8863             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8864       } else {
8865         // Otherwise, add parens around the expression as well as the cast.
8866         CastFix << "(";
8867         Hints.push_back(
8868             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8869 
8870         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
8871         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
8872       }
8873 
8874       if (ShouldNotPrintDirectly) {
8875         // The expression has a type that should not be printed directly.
8876         // We extract the name from the typedef because we don't want to show
8877         // the underlying type in the diagnostic.
8878         StringRef Name;
8879         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
8880           Name = TypedefTy->getDecl()->getName();
8881         else
8882           Name = CastTyName;
8883         unsigned Diag = Match == ArgType::NoMatchPedantic
8884                             ? diag::warn_format_argument_needs_cast_pedantic
8885                             : diag::warn_format_argument_needs_cast;
8886         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
8887                                            << E->getSourceRange(),
8888                              E->getBeginLoc(), /*IsStringLocation=*/false,
8889                              SpecRange, Hints);
8890       } else {
8891         // In this case, the expression could be printed using a different
8892         // specifier, but we've decided that the specifier is probably correct
8893         // and we should cast instead. Just use the normal warning message.
8894         EmitFormatDiagnostic(
8895             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8896                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
8897                 << E->getSourceRange(),
8898             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
8899       }
8900     }
8901   } else {
8902     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
8903                                                    SpecifierLen);
8904     // Since the warning for passing non-POD types to variadic functions
8905     // was deferred until now, we emit a warning for non-POD
8906     // arguments here.
8907     switch (S.isValidVarArgType(ExprTy)) {
8908     case Sema::VAK_Valid:
8909     case Sema::VAK_ValidInCXX11: {
8910       unsigned Diag;
8911       switch (Match) {
8912       case ArgType::Match: llvm_unreachable("expected non-matching");
8913       case ArgType::NoMatchPedantic:
8914         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8915         break;
8916       case ArgType::NoMatchTypeConfusion:
8917         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8918         break;
8919       case ArgType::NoMatch:
8920         Diag = diag::warn_format_conversion_argument_type_mismatch;
8921         break;
8922       }
8923 
8924       EmitFormatDiagnostic(
8925           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
8926                         << IsEnum << CSR << E->getSourceRange(),
8927           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8928       break;
8929     }
8930     case Sema::VAK_Undefined:
8931     case Sema::VAK_MSVCUndefined:
8932       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
8933                                << S.getLangOpts().CPlusPlus11 << ExprTy
8934                                << CallType
8935                                << AT.getRepresentativeTypeName(S.Context) << CSR
8936                                << E->getSourceRange(),
8937                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8938       checkForCStrMembers(AT, E);
8939       break;
8940 
8941     case Sema::VAK_Invalid:
8942       if (ExprTy->isObjCObjectType())
8943         EmitFormatDiagnostic(
8944             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
8945                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
8946                 << AT.getRepresentativeTypeName(S.Context) << CSR
8947                 << E->getSourceRange(),
8948             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8949       else
8950         // FIXME: If this is an initializer list, suggest removing the braces
8951         // or inserting a cast to the target type.
8952         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
8953             << isa<InitListExpr>(E) << ExprTy << CallType
8954             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
8955       break;
8956     }
8957 
8958     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
8959            "format string specifier index out of range");
8960     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
8961   }
8962 
8963   return true;
8964 }
8965 
8966 //===--- CHECK: Scanf format string checking ------------------------------===//
8967 
8968 namespace {
8969 
8970 class CheckScanfHandler : public CheckFormatHandler {
8971 public:
8972   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
8973                     const Expr *origFormatExpr, Sema::FormatStringType type,
8974                     unsigned firstDataArg, unsigned numDataArgs,
8975                     const char *beg, bool hasVAListArg,
8976                     ArrayRef<const Expr *> Args, unsigned formatIdx,
8977                     bool inFunctionCall, 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 HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
8986                             const char *startSpecifier,
8987                             unsigned specifierLen) override;
8988 
8989   bool HandleInvalidScanfConversionSpecifier(
8990           const analyze_scanf::ScanfSpecifier &FS,
8991           const char *startSpecifier,
8992           unsigned specifierLen) override;
8993 
8994   void HandleIncompleteScanList(const char *start, const char *end) override;
8995 };
8996 
8997 } // namespace
8998 
8999 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
9000                                                  const char *end) {
9001   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
9002                        getLocationOfByte(end), /*IsStringLocation*/true,
9003                        getSpecifierRange(start, end - start));
9004 }
9005 
9006 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
9007                                         const analyze_scanf::ScanfSpecifier &FS,
9008                                         const char *startSpecifier,
9009                                         unsigned specifierLen) {
9010   const analyze_scanf::ScanfConversionSpecifier &CS =
9011     FS.getConversionSpecifier();
9012 
9013   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
9014                                           getLocationOfByte(CS.getStart()),
9015                                           startSpecifier, specifierLen,
9016                                           CS.getStart(), CS.getLength());
9017 }
9018 
9019 bool CheckScanfHandler::HandleScanfSpecifier(
9020                                        const analyze_scanf::ScanfSpecifier &FS,
9021                                        const char *startSpecifier,
9022                                        unsigned specifierLen) {
9023   using namespace analyze_scanf;
9024   using namespace analyze_format_string;
9025 
9026   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
9027 
9028   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
9029   // be used to decide if we are using positional arguments consistently.
9030   if (FS.consumesDataArgument()) {
9031     if (atFirstArg) {
9032       atFirstArg = false;
9033       usesPositionalArgs = FS.usesPositionalArg();
9034     }
9035     else if (usesPositionalArgs != FS.usesPositionalArg()) {
9036       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9037                                         startSpecifier, specifierLen);
9038       return false;
9039     }
9040   }
9041 
9042   // Check if the field with is non-zero.
9043   const OptionalAmount &Amt = FS.getFieldWidth();
9044   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
9045     if (Amt.getConstantAmount() == 0) {
9046       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
9047                                                    Amt.getConstantLength());
9048       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
9049                            getLocationOfByte(Amt.getStart()),
9050                            /*IsStringLocation*/true, R,
9051                            FixItHint::CreateRemoval(R));
9052     }
9053   }
9054 
9055   if (!FS.consumesDataArgument()) {
9056     // FIXME: Technically specifying a precision or field width here
9057     // makes no sense.  Worth issuing a warning at some point.
9058     return true;
9059   }
9060 
9061   // Consume the argument.
9062   unsigned argIndex = FS.getArgIndex();
9063   if (argIndex < NumDataArgs) {
9064       // The check to see if the argIndex is valid will come later.
9065       // We set the bit here because we may exit early from this
9066       // function if we encounter some other error.
9067     CoveredArgs.set(argIndex);
9068   }
9069 
9070   // Check the length modifier is valid with the given conversion specifier.
9071   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
9072                                  S.getLangOpts()))
9073     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9074                                 diag::warn_format_nonsensical_length);
9075   else if (!FS.hasStandardLengthModifier())
9076     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9077   else if (!FS.hasStandardLengthConversionCombination())
9078     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9079                                 diag::warn_format_non_standard_conversion_spec);
9080 
9081   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
9082     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9083 
9084   // The remaining checks depend on the data arguments.
9085   if (HasVAListArg)
9086     return true;
9087 
9088   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9089     return false;
9090 
9091   // Check that the argument type matches the format specifier.
9092   const Expr *Ex = getDataArg(argIndex);
9093   if (!Ex)
9094     return true;
9095 
9096   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
9097 
9098   if (!AT.isValid()) {
9099     return true;
9100   }
9101 
9102   analyze_format_string::ArgType::MatchKind Match =
9103       AT.matchesType(S.Context, Ex->getType());
9104   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
9105   if (Match == analyze_format_string::ArgType::Match)
9106     return true;
9107 
9108   ScanfSpecifier fixedFS = FS;
9109   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
9110                                  S.getLangOpts(), S.Context);
9111 
9112   unsigned Diag =
9113       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9114                : diag::warn_format_conversion_argument_type_mismatch;
9115 
9116   if (Success) {
9117     // Get the fix string from the fixed format specifier.
9118     SmallString<128> buf;
9119     llvm::raw_svector_ostream os(buf);
9120     fixedFS.toString(os);
9121 
9122     EmitFormatDiagnostic(
9123         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
9124                       << Ex->getType() << false << Ex->getSourceRange(),
9125         Ex->getBeginLoc(),
9126         /*IsStringLocation*/ false,
9127         getSpecifierRange(startSpecifier, specifierLen),
9128         FixItHint::CreateReplacement(
9129             getSpecifierRange(startSpecifier, specifierLen), os.str()));
9130   } else {
9131     EmitFormatDiagnostic(S.PDiag(Diag)
9132                              << AT.getRepresentativeTypeName(S.Context)
9133                              << Ex->getType() << false << Ex->getSourceRange(),
9134                          Ex->getBeginLoc(),
9135                          /*IsStringLocation*/ false,
9136                          getSpecifierRange(startSpecifier, specifierLen));
9137   }
9138 
9139   return true;
9140 }
9141 
9142 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
9143                               const Expr *OrigFormatExpr,
9144                               ArrayRef<const Expr *> Args,
9145                               bool HasVAListArg, unsigned format_idx,
9146                               unsigned firstDataArg,
9147                               Sema::FormatStringType Type,
9148                               bool inFunctionCall,
9149                               Sema::VariadicCallType CallType,
9150                               llvm::SmallBitVector &CheckedVarArgs,
9151                               UncoveredArgHandler &UncoveredArg,
9152                               bool IgnoreStringsWithoutSpecifiers) {
9153   // CHECK: is the format string a wide literal?
9154   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
9155     CheckFormatHandler::EmitFormatDiagnostic(
9156         S, inFunctionCall, Args[format_idx],
9157         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
9158         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9159     return;
9160   }
9161 
9162   // Str - The format string.  NOTE: this is NOT null-terminated!
9163   StringRef StrRef = FExpr->getString();
9164   const char *Str = StrRef.data();
9165   // Account for cases where the string literal is truncated in a declaration.
9166   const ConstantArrayType *T =
9167     S.Context.getAsConstantArrayType(FExpr->getType());
9168   assert(T && "String literal not of constant array type!");
9169   size_t TypeSize = T->getSize().getZExtValue();
9170   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9171   const unsigned numDataArgs = Args.size() - firstDataArg;
9172 
9173   if (IgnoreStringsWithoutSpecifiers &&
9174       !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
9175           Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
9176     return;
9177 
9178   // Emit a warning if the string literal is truncated and does not contain an
9179   // embedded null character.
9180   if (TypeSize <= StrRef.size() &&
9181       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
9182     CheckFormatHandler::EmitFormatDiagnostic(
9183         S, inFunctionCall, Args[format_idx],
9184         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
9185         FExpr->getBeginLoc(),
9186         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
9187     return;
9188   }
9189 
9190   // CHECK: empty format string?
9191   if (StrLen == 0 && numDataArgs > 0) {
9192     CheckFormatHandler::EmitFormatDiagnostic(
9193         S, inFunctionCall, Args[format_idx],
9194         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
9195         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9196     return;
9197   }
9198 
9199   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
9200       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
9201       Type == Sema::FST_OSTrace) {
9202     CheckPrintfHandler H(
9203         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
9204         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
9205         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
9206         CheckedVarArgs, UncoveredArg);
9207 
9208     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
9209                                                   S.getLangOpts(),
9210                                                   S.Context.getTargetInfo(),
9211                                             Type == Sema::FST_FreeBSDKPrintf))
9212       H.DoneProcessing();
9213   } else if (Type == Sema::FST_Scanf) {
9214     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9215                         numDataArgs, Str, HasVAListArg, Args, format_idx,
9216                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
9217 
9218     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
9219                                                  S.getLangOpts(),
9220                                                  S.Context.getTargetInfo()))
9221       H.DoneProcessing();
9222   } // TODO: handle other formats
9223 }
9224 
9225 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
9226   // Str - The format string.  NOTE: this is NOT null-terminated!
9227   StringRef StrRef = FExpr->getString();
9228   const char *Str = StrRef.data();
9229   // Account for cases where the string literal is truncated in a declaration.
9230   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
9231   assert(T && "String literal not of constant array type!");
9232   size_t TypeSize = T->getSize().getZExtValue();
9233   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9234   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
9235                                                          getLangOpts(),
9236                                                          Context.getTargetInfo());
9237 }
9238 
9239 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
9240 
9241 // Returns the related absolute value function that is larger, of 0 if one
9242 // does not exist.
9243 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
9244   switch (AbsFunction) {
9245   default:
9246     return 0;
9247 
9248   case Builtin::BI__builtin_abs:
9249     return Builtin::BI__builtin_labs;
9250   case Builtin::BI__builtin_labs:
9251     return Builtin::BI__builtin_llabs;
9252   case Builtin::BI__builtin_llabs:
9253     return 0;
9254 
9255   case Builtin::BI__builtin_fabsf:
9256     return Builtin::BI__builtin_fabs;
9257   case Builtin::BI__builtin_fabs:
9258     return Builtin::BI__builtin_fabsl;
9259   case Builtin::BI__builtin_fabsl:
9260     return 0;
9261 
9262   case Builtin::BI__builtin_cabsf:
9263     return Builtin::BI__builtin_cabs;
9264   case Builtin::BI__builtin_cabs:
9265     return Builtin::BI__builtin_cabsl;
9266   case Builtin::BI__builtin_cabsl:
9267     return 0;
9268 
9269   case Builtin::BIabs:
9270     return Builtin::BIlabs;
9271   case Builtin::BIlabs:
9272     return Builtin::BIllabs;
9273   case Builtin::BIllabs:
9274     return 0;
9275 
9276   case Builtin::BIfabsf:
9277     return Builtin::BIfabs;
9278   case Builtin::BIfabs:
9279     return Builtin::BIfabsl;
9280   case Builtin::BIfabsl:
9281     return 0;
9282 
9283   case Builtin::BIcabsf:
9284    return Builtin::BIcabs;
9285   case Builtin::BIcabs:
9286     return Builtin::BIcabsl;
9287   case Builtin::BIcabsl:
9288     return 0;
9289   }
9290 }
9291 
9292 // Returns the argument type of the absolute value function.
9293 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
9294                                              unsigned AbsType) {
9295   if (AbsType == 0)
9296     return QualType();
9297 
9298   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
9299   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
9300   if (Error != ASTContext::GE_None)
9301     return QualType();
9302 
9303   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
9304   if (!FT)
9305     return QualType();
9306 
9307   if (FT->getNumParams() != 1)
9308     return QualType();
9309 
9310   return FT->getParamType(0);
9311 }
9312 
9313 // Returns the best absolute value function, or zero, based on type and
9314 // current absolute value function.
9315 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
9316                                    unsigned AbsFunctionKind) {
9317   unsigned BestKind = 0;
9318   uint64_t ArgSize = Context.getTypeSize(ArgType);
9319   for (unsigned Kind = AbsFunctionKind; Kind != 0;
9320        Kind = getLargerAbsoluteValueFunction(Kind)) {
9321     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
9322     if (Context.getTypeSize(ParamType) >= ArgSize) {
9323       if (BestKind == 0)
9324         BestKind = Kind;
9325       else if (Context.hasSameType(ParamType, ArgType)) {
9326         BestKind = Kind;
9327         break;
9328       }
9329     }
9330   }
9331   return BestKind;
9332 }
9333 
9334 enum AbsoluteValueKind {
9335   AVK_Integer,
9336   AVK_Floating,
9337   AVK_Complex
9338 };
9339 
9340 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
9341   if (T->isIntegralOrEnumerationType())
9342     return AVK_Integer;
9343   if (T->isRealFloatingType())
9344     return AVK_Floating;
9345   if (T->isAnyComplexType())
9346     return AVK_Complex;
9347 
9348   llvm_unreachable("Type not integer, floating, or complex");
9349 }
9350 
9351 // Changes the absolute value function to a different type.  Preserves whether
9352 // the function is a builtin.
9353 static unsigned changeAbsFunction(unsigned AbsKind,
9354                                   AbsoluteValueKind ValueKind) {
9355   switch (ValueKind) {
9356   case AVK_Integer:
9357     switch (AbsKind) {
9358     default:
9359       return 0;
9360     case Builtin::BI__builtin_fabsf:
9361     case Builtin::BI__builtin_fabs:
9362     case Builtin::BI__builtin_fabsl:
9363     case Builtin::BI__builtin_cabsf:
9364     case Builtin::BI__builtin_cabs:
9365     case Builtin::BI__builtin_cabsl:
9366       return Builtin::BI__builtin_abs;
9367     case Builtin::BIfabsf:
9368     case Builtin::BIfabs:
9369     case Builtin::BIfabsl:
9370     case Builtin::BIcabsf:
9371     case Builtin::BIcabs:
9372     case Builtin::BIcabsl:
9373       return Builtin::BIabs;
9374     }
9375   case AVK_Floating:
9376     switch (AbsKind) {
9377     default:
9378       return 0;
9379     case Builtin::BI__builtin_abs:
9380     case Builtin::BI__builtin_labs:
9381     case Builtin::BI__builtin_llabs:
9382     case Builtin::BI__builtin_cabsf:
9383     case Builtin::BI__builtin_cabs:
9384     case Builtin::BI__builtin_cabsl:
9385       return Builtin::BI__builtin_fabsf;
9386     case Builtin::BIabs:
9387     case Builtin::BIlabs:
9388     case Builtin::BIllabs:
9389     case Builtin::BIcabsf:
9390     case Builtin::BIcabs:
9391     case Builtin::BIcabsl:
9392       return Builtin::BIfabsf;
9393     }
9394   case AVK_Complex:
9395     switch (AbsKind) {
9396     default:
9397       return 0;
9398     case Builtin::BI__builtin_abs:
9399     case Builtin::BI__builtin_labs:
9400     case Builtin::BI__builtin_llabs:
9401     case Builtin::BI__builtin_fabsf:
9402     case Builtin::BI__builtin_fabs:
9403     case Builtin::BI__builtin_fabsl:
9404       return Builtin::BI__builtin_cabsf;
9405     case Builtin::BIabs:
9406     case Builtin::BIlabs:
9407     case Builtin::BIllabs:
9408     case Builtin::BIfabsf:
9409     case Builtin::BIfabs:
9410     case Builtin::BIfabsl:
9411       return Builtin::BIcabsf;
9412     }
9413   }
9414   llvm_unreachable("Unable to convert function");
9415 }
9416 
9417 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
9418   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
9419   if (!FnInfo)
9420     return 0;
9421 
9422   switch (FDecl->getBuiltinID()) {
9423   default:
9424     return 0;
9425   case Builtin::BI__builtin_abs:
9426   case Builtin::BI__builtin_fabs:
9427   case Builtin::BI__builtin_fabsf:
9428   case Builtin::BI__builtin_fabsl:
9429   case Builtin::BI__builtin_labs:
9430   case Builtin::BI__builtin_llabs:
9431   case Builtin::BI__builtin_cabs:
9432   case Builtin::BI__builtin_cabsf:
9433   case Builtin::BI__builtin_cabsl:
9434   case Builtin::BIabs:
9435   case Builtin::BIlabs:
9436   case Builtin::BIllabs:
9437   case Builtin::BIfabs:
9438   case Builtin::BIfabsf:
9439   case Builtin::BIfabsl:
9440   case Builtin::BIcabs:
9441   case Builtin::BIcabsf:
9442   case Builtin::BIcabsl:
9443     return FDecl->getBuiltinID();
9444   }
9445   llvm_unreachable("Unknown Builtin type");
9446 }
9447 
9448 // If the replacement is valid, emit a note with replacement function.
9449 // Additionally, suggest including the proper header if not already included.
9450 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
9451                             unsigned AbsKind, QualType ArgType) {
9452   bool EmitHeaderHint = true;
9453   const char *HeaderName = nullptr;
9454   const char *FunctionName = nullptr;
9455   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
9456     FunctionName = "std::abs";
9457     if (ArgType->isIntegralOrEnumerationType()) {
9458       HeaderName = "cstdlib";
9459     } else if (ArgType->isRealFloatingType()) {
9460       HeaderName = "cmath";
9461     } else {
9462       llvm_unreachable("Invalid Type");
9463     }
9464 
9465     // Lookup all std::abs
9466     if (NamespaceDecl *Std = S.getStdNamespace()) {
9467       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
9468       R.suppressDiagnostics();
9469       S.LookupQualifiedName(R, Std);
9470 
9471       for (const auto *I : R) {
9472         const FunctionDecl *FDecl = nullptr;
9473         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
9474           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
9475         } else {
9476           FDecl = dyn_cast<FunctionDecl>(I);
9477         }
9478         if (!FDecl)
9479           continue;
9480 
9481         // Found std::abs(), check that they are the right ones.
9482         if (FDecl->getNumParams() != 1)
9483           continue;
9484 
9485         // Check that the parameter type can handle the argument.
9486         QualType ParamType = FDecl->getParamDecl(0)->getType();
9487         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
9488             S.Context.getTypeSize(ArgType) <=
9489                 S.Context.getTypeSize(ParamType)) {
9490           // Found a function, don't need the header hint.
9491           EmitHeaderHint = false;
9492           break;
9493         }
9494       }
9495     }
9496   } else {
9497     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
9498     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
9499 
9500     if (HeaderName) {
9501       DeclarationName DN(&S.Context.Idents.get(FunctionName));
9502       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
9503       R.suppressDiagnostics();
9504       S.LookupName(R, S.getCurScope());
9505 
9506       if (R.isSingleResult()) {
9507         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
9508         if (FD && FD->getBuiltinID() == AbsKind) {
9509           EmitHeaderHint = false;
9510         } else {
9511           return;
9512         }
9513       } else if (!R.empty()) {
9514         return;
9515       }
9516     }
9517   }
9518 
9519   S.Diag(Loc, diag::note_replace_abs_function)
9520       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
9521 
9522   if (!HeaderName)
9523     return;
9524 
9525   if (!EmitHeaderHint)
9526     return;
9527 
9528   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
9529                                                     << FunctionName;
9530 }
9531 
9532 template <std::size_t StrLen>
9533 static bool IsStdFunction(const FunctionDecl *FDecl,
9534                           const char (&Str)[StrLen]) {
9535   if (!FDecl)
9536     return false;
9537   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
9538     return false;
9539   if (!FDecl->isInStdNamespace())
9540     return false;
9541 
9542   return true;
9543 }
9544 
9545 // Warn when using the wrong abs() function.
9546 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
9547                                       const FunctionDecl *FDecl) {
9548   if (Call->getNumArgs() != 1)
9549     return;
9550 
9551   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
9552   bool IsStdAbs = IsStdFunction(FDecl, "abs");
9553   if (AbsKind == 0 && !IsStdAbs)
9554     return;
9555 
9556   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9557   QualType ParamType = Call->getArg(0)->getType();
9558 
9559   // Unsigned types cannot be negative.  Suggest removing the absolute value
9560   // function call.
9561   if (ArgType->isUnsignedIntegerType()) {
9562     const char *FunctionName =
9563         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
9564     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
9565     Diag(Call->getExprLoc(), diag::note_remove_abs)
9566         << FunctionName
9567         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
9568     return;
9569   }
9570 
9571   // Taking the absolute value of a pointer is very suspicious, they probably
9572   // wanted to index into an array, dereference a pointer, call a function, etc.
9573   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
9574     unsigned DiagType = 0;
9575     if (ArgType->isFunctionType())
9576       DiagType = 1;
9577     else if (ArgType->isArrayType())
9578       DiagType = 2;
9579 
9580     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
9581     return;
9582   }
9583 
9584   // std::abs has overloads which prevent most of the absolute value problems
9585   // from occurring.
9586   if (IsStdAbs)
9587     return;
9588 
9589   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
9590   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
9591 
9592   // The argument and parameter are the same kind.  Check if they are the right
9593   // size.
9594   if (ArgValueKind == ParamValueKind) {
9595     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
9596       return;
9597 
9598     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
9599     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
9600         << FDecl << ArgType << ParamType;
9601 
9602     if (NewAbsKind == 0)
9603       return;
9604 
9605     emitReplacement(*this, Call->getExprLoc(),
9606                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9607     return;
9608   }
9609 
9610   // ArgValueKind != ParamValueKind
9611   // The wrong type of absolute value function was used.  Attempt to find the
9612   // proper one.
9613   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
9614   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
9615   if (NewAbsKind == 0)
9616     return;
9617 
9618   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
9619       << FDecl << ParamValueKind << ArgValueKind;
9620 
9621   emitReplacement(*this, Call->getExprLoc(),
9622                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9623 }
9624 
9625 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
9626 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
9627                                 const FunctionDecl *FDecl) {
9628   if (!Call || !FDecl) return;
9629 
9630   // Ignore template specializations and macros.
9631   if (inTemplateInstantiation()) return;
9632   if (Call->getExprLoc().isMacroID()) return;
9633 
9634   // Only care about the one template argument, two function parameter std::max
9635   if (Call->getNumArgs() != 2) return;
9636   if (!IsStdFunction(FDecl, "max")) return;
9637   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
9638   if (!ArgList) return;
9639   if (ArgList->size() != 1) return;
9640 
9641   // Check that template type argument is unsigned integer.
9642   const auto& TA = ArgList->get(0);
9643   if (TA.getKind() != TemplateArgument::Type) return;
9644   QualType ArgType = TA.getAsType();
9645   if (!ArgType->isUnsignedIntegerType()) return;
9646 
9647   // See if either argument is a literal zero.
9648   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
9649     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
9650     if (!MTE) return false;
9651     const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
9652     if (!Num) return false;
9653     if (Num->getValue() != 0) return false;
9654     return true;
9655   };
9656 
9657   const Expr *FirstArg = Call->getArg(0);
9658   const Expr *SecondArg = Call->getArg(1);
9659   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
9660   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
9661 
9662   // Only warn when exactly one argument is zero.
9663   if (IsFirstArgZero == IsSecondArgZero) return;
9664 
9665   SourceRange FirstRange = FirstArg->getSourceRange();
9666   SourceRange SecondRange = SecondArg->getSourceRange();
9667 
9668   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
9669 
9670   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
9671       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
9672 
9673   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
9674   SourceRange RemovalRange;
9675   if (IsFirstArgZero) {
9676     RemovalRange = SourceRange(FirstRange.getBegin(),
9677                                SecondRange.getBegin().getLocWithOffset(-1));
9678   } else {
9679     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
9680                                SecondRange.getEnd());
9681   }
9682 
9683   Diag(Call->getExprLoc(), diag::note_remove_max_call)
9684         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
9685         << FixItHint::CreateRemoval(RemovalRange);
9686 }
9687 
9688 //===--- CHECK: Standard memory functions ---------------------------------===//
9689 
9690 /// Takes the expression passed to the size_t parameter of functions
9691 /// such as memcmp, strncat, etc and warns if it's a comparison.
9692 ///
9693 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
9694 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
9695                                            IdentifierInfo *FnName,
9696                                            SourceLocation FnLoc,
9697                                            SourceLocation RParenLoc) {
9698   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
9699   if (!Size)
9700     return false;
9701 
9702   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
9703   if (!Size->isComparisonOp() && !Size->isLogicalOp())
9704     return false;
9705 
9706   SourceRange SizeRange = Size->getSourceRange();
9707   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
9708       << SizeRange << FnName;
9709   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
9710       << FnName
9711       << FixItHint::CreateInsertion(
9712              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
9713       << FixItHint::CreateRemoval(RParenLoc);
9714   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
9715       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
9716       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
9717                                     ")");
9718 
9719   return true;
9720 }
9721 
9722 /// Determine whether the given type is or contains a dynamic class type
9723 /// (e.g., whether it has a vtable).
9724 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
9725                                                      bool &IsContained) {
9726   // Look through array types while ignoring qualifiers.
9727   const Type *Ty = T->getBaseElementTypeUnsafe();
9728   IsContained = false;
9729 
9730   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
9731   RD = RD ? RD->getDefinition() : nullptr;
9732   if (!RD || RD->isInvalidDecl())
9733     return nullptr;
9734 
9735   if (RD->isDynamicClass())
9736     return RD;
9737 
9738   // Check all the fields.  If any bases were dynamic, the class is dynamic.
9739   // It's impossible for a class to transitively contain itself by value, so
9740   // infinite recursion is impossible.
9741   for (auto *FD : RD->fields()) {
9742     bool SubContained;
9743     if (const CXXRecordDecl *ContainedRD =
9744             getContainedDynamicClass(FD->getType(), SubContained)) {
9745       IsContained = true;
9746       return ContainedRD;
9747     }
9748   }
9749 
9750   return nullptr;
9751 }
9752 
9753 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
9754   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
9755     if (Unary->getKind() == UETT_SizeOf)
9756       return Unary;
9757   return nullptr;
9758 }
9759 
9760 /// If E is a sizeof expression, returns its argument expression,
9761 /// otherwise returns NULL.
9762 static const Expr *getSizeOfExprArg(const Expr *E) {
9763   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9764     if (!SizeOf->isArgumentType())
9765       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
9766   return nullptr;
9767 }
9768 
9769 /// If E is a sizeof expression, returns its argument type.
9770 static QualType getSizeOfArgType(const Expr *E) {
9771   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9772     return SizeOf->getTypeOfArgument();
9773   return QualType();
9774 }
9775 
9776 namespace {
9777 
9778 struct SearchNonTrivialToInitializeField
9779     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
9780   using Super =
9781       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
9782 
9783   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
9784 
9785   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
9786                      SourceLocation SL) {
9787     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9788       asDerived().visitArray(PDIK, AT, SL);
9789       return;
9790     }
9791 
9792     Super::visitWithKind(PDIK, FT, SL);
9793   }
9794 
9795   void visitARCStrong(QualType FT, SourceLocation SL) {
9796     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9797   }
9798   void visitARCWeak(QualType FT, SourceLocation SL) {
9799     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9800   }
9801   void visitStruct(QualType FT, SourceLocation SL) {
9802     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9803       visit(FD->getType(), FD->getLocation());
9804   }
9805   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
9806                   const ArrayType *AT, SourceLocation SL) {
9807     visit(getContext().getBaseElementType(AT), SL);
9808   }
9809   void visitTrivial(QualType FT, SourceLocation SL) {}
9810 
9811   static void diag(QualType RT, const Expr *E, Sema &S) {
9812     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
9813   }
9814 
9815   ASTContext &getContext() { return S.getASTContext(); }
9816 
9817   const Expr *E;
9818   Sema &S;
9819 };
9820 
9821 struct SearchNonTrivialToCopyField
9822     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
9823   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
9824 
9825   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
9826 
9827   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
9828                      SourceLocation SL) {
9829     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9830       asDerived().visitArray(PCK, AT, SL);
9831       return;
9832     }
9833 
9834     Super::visitWithKind(PCK, FT, SL);
9835   }
9836 
9837   void visitARCStrong(QualType FT, SourceLocation SL) {
9838     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9839   }
9840   void visitARCWeak(QualType FT, SourceLocation SL) {
9841     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9842   }
9843   void visitStruct(QualType FT, SourceLocation SL) {
9844     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9845       visit(FD->getType(), FD->getLocation());
9846   }
9847   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
9848                   SourceLocation SL) {
9849     visit(getContext().getBaseElementType(AT), SL);
9850   }
9851   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
9852                 SourceLocation SL) {}
9853   void visitTrivial(QualType FT, SourceLocation SL) {}
9854   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
9855 
9856   static void diag(QualType RT, const Expr *E, Sema &S) {
9857     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
9858   }
9859 
9860   ASTContext &getContext() { return S.getASTContext(); }
9861 
9862   const Expr *E;
9863   Sema &S;
9864 };
9865 
9866 }
9867 
9868 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
9869 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
9870   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
9871 
9872   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
9873     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
9874       return false;
9875 
9876     return doesExprLikelyComputeSize(BO->getLHS()) ||
9877            doesExprLikelyComputeSize(BO->getRHS());
9878   }
9879 
9880   return getAsSizeOfExpr(SizeofExpr) != nullptr;
9881 }
9882 
9883 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
9884 ///
9885 /// \code
9886 ///   #define MACRO 0
9887 ///   foo(MACRO);
9888 ///   foo(0);
9889 /// \endcode
9890 ///
9891 /// This should return true for the first call to foo, but not for the second
9892 /// (regardless of whether foo is a macro or function).
9893 static bool isArgumentExpandedFromMacro(SourceManager &SM,
9894                                         SourceLocation CallLoc,
9895                                         SourceLocation ArgLoc) {
9896   if (!CallLoc.isMacroID())
9897     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
9898 
9899   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
9900          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
9901 }
9902 
9903 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
9904 /// last two arguments transposed.
9905 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
9906   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
9907     return;
9908 
9909   const Expr *SizeArg =
9910     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
9911 
9912   auto isLiteralZero = [](const Expr *E) {
9913     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
9914   };
9915 
9916   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
9917   SourceLocation CallLoc = Call->getRParenLoc();
9918   SourceManager &SM = S.getSourceManager();
9919   if (isLiteralZero(SizeArg) &&
9920       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
9921 
9922     SourceLocation DiagLoc = SizeArg->getExprLoc();
9923 
9924     // Some platforms #define bzero to __builtin_memset. See if this is the
9925     // case, and if so, emit a better diagnostic.
9926     if (BId == Builtin::BIbzero ||
9927         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
9928                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
9929       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
9930       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
9931     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
9932       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
9933       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
9934     }
9935     return;
9936   }
9937 
9938   // If the second argument to a memset is a sizeof expression and the third
9939   // isn't, this is also likely an error. This should catch
9940   // 'memset(buf, sizeof(buf), 0xff)'.
9941   if (BId == Builtin::BImemset &&
9942       doesExprLikelyComputeSize(Call->getArg(1)) &&
9943       !doesExprLikelyComputeSize(Call->getArg(2))) {
9944     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
9945     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
9946     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
9947     return;
9948   }
9949 }
9950 
9951 /// Check for dangerous or invalid arguments to memset().
9952 ///
9953 /// This issues warnings on known problematic, dangerous or unspecified
9954 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
9955 /// function calls.
9956 ///
9957 /// \param Call The call expression to diagnose.
9958 void Sema::CheckMemaccessArguments(const CallExpr *Call,
9959                                    unsigned BId,
9960                                    IdentifierInfo *FnName) {
9961   assert(BId != 0);
9962 
9963   // It is possible to have a non-standard definition of memset.  Validate
9964   // we have enough arguments, and if not, abort further checking.
9965   unsigned ExpectedNumArgs =
9966       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
9967   if (Call->getNumArgs() < ExpectedNumArgs)
9968     return;
9969 
9970   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
9971                       BId == Builtin::BIstrndup ? 1 : 2);
9972   unsigned LenArg =
9973       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
9974   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
9975 
9976   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
9977                                      Call->getBeginLoc(), Call->getRParenLoc()))
9978     return;
9979 
9980   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
9981   CheckMemaccessSize(*this, BId, Call);
9982 
9983   // We have special checking when the length is a sizeof expression.
9984   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
9985   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
9986   llvm::FoldingSetNodeID SizeOfArgID;
9987 
9988   // Although widely used, 'bzero' is not a standard function. Be more strict
9989   // with the argument types before allowing diagnostics and only allow the
9990   // form bzero(ptr, sizeof(...)).
9991   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9992   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
9993     return;
9994 
9995   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
9996     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
9997     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
9998 
9999     QualType DestTy = Dest->getType();
10000     QualType PointeeTy;
10001     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
10002       PointeeTy = DestPtrTy->getPointeeType();
10003 
10004       // Never warn about void type pointers. This can be used to suppress
10005       // false positives.
10006       if (PointeeTy->isVoidType())
10007         continue;
10008 
10009       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
10010       // actually comparing the expressions for equality. Because computing the
10011       // expression IDs can be expensive, we only do this if the diagnostic is
10012       // enabled.
10013       if (SizeOfArg &&
10014           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
10015                            SizeOfArg->getExprLoc())) {
10016         // We only compute IDs for expressions if the warning is enabled, and
10017         // cache the sizeof arg's ID.
10018         if (SizeOfArgID == llvm::FoldingSetNodeID())
10019           SizeOfArg->Profile(SizeOfArgID, Context, true);
10020         llvm::FoldingSetNodeID DestID;
10021         Dest->Profile(DestID, Context, true);
10022         if (DestID == SizeOfArgID) {
10023           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
10024           //       over sizeof(src) as well.
10025           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
10026           StringRef ReadableName = FnName->getName();
10027 
10028           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
10029             if (UnaryOp->getOpcode() == UO_AddrOf)
10030               ActionIdx = 1; // If its an address-of operator, just remove it.
10031           if (!PointeeTy->isIncompleteType() &&
10032               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
10033             ActionIdx = 2; // If the pointee's size is sizeof(char),
10034                            // suggest an explicit length.
10035 
10036           // If the function is defined as a builtin macro, do not show macro
10037           // expansion.
10038           SourceLocation SL = SizeOfArg->getExprLoc();
10039           SourceRange DSR = Dest->getSourceRange();
10040           SourceRange SSR = SizeOfArg->getSourceRange();
10041           SourceManager &SM = getSourceManager();
10042 
10043           if (SM.isMacroArgExpansion(SL)) {
10044             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
10045             SL = SM.getSpellingLoc(SL);
10046             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
10047                              SM.getSpellingLoc(DSR.getEnd()));
10048             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
10049                              SM.getSpellingLoc(SSR.getEnd()));
10050           }
10051 
10052           DiagRuntimeBehavior(SL, SizeOfArg,
10053                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
10054                                 << ReadableName
10055                                 << PointeeTy
10056                                 << DestTy
10057                                 << DSR
10058                                 << SSR);
10059           DiagRuntimeBehavior(SL, SizeOfArg,
10060                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
10061                                 << ActionIdx
10062                                 << SSR);
10063 
10064           break;
10065         }
10066       }
10067 
10068       // Also check for cases where the sizeof argument is the exact same
10069       // type as the memory argument, and where it points to a user-defined
10070       // record type.
10071       if (SizeOfArgTy != QualType()) {
10072         if (PointeeTy->isRecordType() &&
10073             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
10074           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
10075                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
10076                                 << FnName << SizeOfArgTy << ArgIdx
10077                                 << PointeeTy << Dest->getSourceRange()
10078                                 << LenExpr->getSourceRange());
10079           break;
10080         }
10081       }
10082     } else if (DestTy->isArrayType()) {
10083       PointeeTy = DestTy;
10084     }
10085 
10086     if (PointeeTy == QualType())
10087       continue;
10088 
10089     // Always complain about dynamic classes.
10090     bool IsContained;
10091     if (const CXXRecordDecl *ContainedRD =
10092             getContainedDynamicClass(PointeeTy, IsContained)) {
10093 
10094       unsigned OperationType = 0;
10095       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
10096       // "overwritten" if we're warning about the destination for any call
10097       // but memcmp; otherwise a verb appropriate to the call.
10098       if (ArgIdx != 0 || IsCmp) {
10099         if (BId == Builtin::BImemcpy)
10100           OperationType = 1;
10101         else if(BId == Builtin::BImemmove)
10102           OperationType = 2;
10103         else if (IsCmp)
10104           OperationType = 3;
10105       }
10106 
10107       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10108                           PDiag(diag::warn_dyn_class_memaccess)
10109                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
10110                               << IsContained << ContainedRD << OperationType
10111                               << Call->getCallee()->getSourceRange());
10112     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
10113              BId != Builtin::BImemset)
10114       DiagRuntimeBehavior(
10115         Dest->getExprLoc(), Dest,
10116         PDiag(diag::warn_arc_object_memaccess)
10117           << ArgIdx << FnName << PointeeTy
10118           << Call->getCallee()->getSourceRange());
10119     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
10120       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10121           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
10122         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10123                             PDiag(diag::warn_cstruct_memaccess)
10124                                 << ArgIdx << FnName << PointeeTy << 0);
10125         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
10126       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10127                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
10128         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10129                             PDiag(diag::warn_cstruct_memaccess)
10130                                 << ArgIdx << FnName << PointeeTy << 1);
10131         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
10132       } else {
10133         continue;
10134       }
10135     } else
10136       continue;
10137 
10138     DiagRuntimeBehavior(
10139       Dest->getExprLoc(), Dest,
10140       PDiag(diag::note_bad_memaccess_silence)
10141         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
10142     break;
10143   }
10144 }
10145 
10146 // A little helper routine: ignore addition and subtraction of integer literals.
10147 // This intentionally does not ignore all integer constant expressions because
10148 // we don't want to remove sizeof().
10149 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
10150   Ex = Ex->IgnoreParenCasts();
10151 
10152   while (true) {
10153     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
10154     if (!BO || !BO->isAdditiveOp())
10155       break;
10156 
10157     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
10158     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
10159 
10160     if (isa<IntegerLiteral>(RHS))
10161       Ex = LHS;
10162     else if (isa<IntegerLiteral>(LHS))
10163       Ex = RHS;
10164     else
10165       break;
10166   }
10167 
10168   return Ex;
10169 }
10170 
10171 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
10172                                                       ASTContext &Context) {
10173   // Only handle constant-sized or VLAs, but not flexible members.
10174   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
10175     // Only issue the FIXIT for arrays of size > 1.
10176     if (CAT->getSize().getSExtValue() <= 1)
10177       return false;
10178   } else if (!Ty->isVariableArrayType()) {
10179     return false;
10180   }
10181   return true;
10182 }
10183 
10184 // Warn if the user has made the 'size' argument to strlcpy or strlcat
10185 // be the size of the source, instead of the destination.
10186 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
10187                                     IdentifierInfo *FnName) {
10188 
10189   // Don't crash if the user has the wrong number of arguments
10190   unsigned NumArgs = Call->getNumArgs();
10191   if ((NumArgs != 3) && (NumArgs != 4))
10192     return;
10193 
10194   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
10195   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
10196   const Expr *CompareWithSrc = nullptr;
10197 
10198   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
10199                                      Call->getBeginLoc(), Call->getRParenLoc()))
10200     return;
10201 
10202   // Look for 'strlcpy(dst, x, sizeof(x))'
10203   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
10204     CompareWithSrc = Ex;
10205   else {
10206     // Look for 'strlcpy(dst, x, strlen(x))'
10207     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
10208       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
10209           SizeCall->getNumArgs() == 1)
10210         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
10211     }
10212   }
10213 
10214   if (!CompareWithSrc)
10215     return;
10216 
10217   // Determine if the argument to sizeof/strlen is equal to the source
10218   // argument.  In principle there's all kinds of things you could do
10219   // here, for instance creating an == expression and evaluating it with
10220   // EvaluateAsBooleanCondition, but this uses a more direct technique:
10221   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
10222   if (!SrcArgDRE)
10223     return;
10224 
10225   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
10226   if (!CompareWithSrcDRE ||
10227       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
10228     return;
10229 
10230   const Expr *OriginalSizeArg = Call->getArg(2);
10231   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
10232       << OriginalSizeArg->getSourceRange() << FnName;
10233 
10234   // Output a FIXIT hint if the destination is an array (rather than a
10235   // pointer to an array).  This could be enhanced to handle some
10236   // pointers if we know the actual size, like if DstArg is 'array+2'
10237   // we could say 'sizeof(array)-2'.
10238   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
10239   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
10240     return;
10241 
10242   SmallString<128> sizeString;
10243   llvm::raw_svector_ostream OS(sizeString);
10244   OS << "sizeof(";
10245   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10246   OS << ")";
10247 
10248   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
10249       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
10250                                       OS.str());
10251 }
10252 
10253 /// Check if two expressions refer to the same declaration.
10254 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
10255   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
10256     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
10257       return D1->getDecl() == D2->getDecl();
10258   return false;
10259 }
10260 
10261 static const Expr *getStrlenExprArg(const Expr *E) {
10262   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10263     const FunctionDecl *FD = CE->getDirectCallee();
10264     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
10265       return nullptr;
10266     return CE->getArg(0)->IgnoreParenCasts();
10267   }
10268   return nullptr;
10269 }
10270 
10271 // Warn on anti-patterns as the 'size' argument to strncat.
10272 // The correct size argument should look like following:
10273 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
10274 void Sema::CheckStrncatArguments(const CallExpr *CE,
10275                                  IdentifierInfo *FnName) {
10276   // Don't crash if the user has the wrong number of arguments.
10277   if (CE->getNumArgs() < 3)
10278     return;
10279   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
10280   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
10281   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
10282 
10283   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
10284                                      CE->getRParenLoc()))
10285     return;
10286 
10287   // Identify common expressions, which are wrongly used as the size argument
10288   // to strncat and may lead to buffer overflows.
10289   unsigned PatternType = 0;
10290   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
10291     // - sizeof(dst)
10292     if (referToTheSameDecl(SizeOfArg, DstArg))
10293       PatternType = 1;
10294     // - sizeof(src)
10295     else if (referToTheSameDecl(SizeOfArg, SrcArg))
10296       PatternType = 2;
10297   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
10298     if (BE->getOpcode() == BO_Sub) {
10299       const Expr *L = BE->getLHS()->IgnoreParenCasts();
10300       const Expr *R = BE->getRHS()->IgnoreParenCasts();
10301       // - sizeof(dst) - strlen(dst)
10302       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
10303           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
10304         PatternType = 1;
10305       // - sizeof(src) - (anything)
10306       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
10307         PatternType = 2;
10308     }
10309   }
10310 
10311   if (PatternType == 0)
10312     return;
10313 
10314   // Generate the diagnostic.
10315   SourceLocation SL = LenArg->getBeginLoc();
10316   SourceRange SR = LenArg->getSourceRange();
10317   SourceManager &SM = getSourceManager();
10318 
10319   // If the function is defined as a builtin macro, do not show macro expansion.
10320   if (SM.isMacroArgExpansion(SL)) {
10321     SL = SM.getSpellingLoc(SL);
10322     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
10323                      SM.getSpellingLoc(SR.getEnd()));
10324   }
10325 
10326   // Check if the destination is an array (rather than a pointer to an array).
10327   QualType DstTy = DstArg->getType();
10328   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
10329                                                                     Context);
10330   if (!isKnownSizeArray) {
10331     if (PatternType == 1)
10332       Diag(SL, diag::warn_strncat_wrong_size) << SR;
10333     else
10334       Diag(SL, diag::warn_strncat_src_size) << SR;
10335     return;
10336   }
10337 
10338   if (PatternType == 1)
10339     Diag(SL, diag::warn_strncat_large_size) << SR;
10340   else
10341     Diag(SL, diag::warn_strncat_src_size) << SR;
10342 
10343   SmallString<128> sizeString;
10344   llvm::raw_svector_ostream OS(sizeString);
10345   OS << "sizeof(";
10346   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10347   OS << ") - ";
10348   OS << "strlen(";
10349   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10350   OS << ") - 1";
10351 
10352   Diag(SL, diag::note_strncat_wrong_size)
10353     << FixItHint::CreateReplacement(SR, OS.str());
10354 }
10355 
10356 namespace {
10357 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
10358                                 const UnaryOperator *UnaryExpr, const Decl *D) {
10359   if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) {
10360     S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
10361         << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
10362     return;
10363   }
10364 }
10365 
10366 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
10367                                  const UnaryOperator *UnaryExpr) {
10368   if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
10369     const Decl *D = Lvalue->getDecl();
10370     if (isa<VarDecl, FunctionDecl>(D))
10371       return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
10372   }
10373 
10374   if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
10375     return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
10376                                       Lvalue->getMemberDecl());
10377 }
10378 
10379 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
10380                             const UnaryOperator *UnaryExpr) {
10381   const auto *Lambda = dyn_cast<LambdaExpr>(
10382       UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens());
10383   if (!Lambda)
10384     return;
10385 
10386   S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
10387       << CalleeName << 2 /*object: lambda expression*/;
10388 }
10389 
10390 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
10391                                   const DeclRefExpr *Lvalue) {
10392   const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
10393   if (Var == nullptr)
10394     return;
10395 
10396   S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
10397       << CalleeName << 0 /*object: */ << Var;
10398 }
10399 
10400 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
10401                             const CastExpr *Cast) {
10402   SmallString<128> SizeString;
10403   llvm::raw_svector_ostream OS(SizeString);
10404 
10405   clang::CastKind Kind = Cast->getCastKind();
10406   if (Kind == clang::CK_BitCast &&
10407       !Cast->getSubExpr()->getType()->isFunctionPointerType())
10408     return;
10409   if (Kind == clang::CK_IntegralToPointer &&
10410       !isa<IntegerLiteral>(
10411           Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
10412     return;
10413 
10414   switch (Cast->getCastKind()) {
10415   case clang::CK_BitCast:
10416   case clang::CK_IntegralToPointer:
10417   case clang::CK_FunctionToPointerDecay:
10418     OS << '\'';
10419     Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
10420     OS << '\'';
10421     break;
10422   default:
10423     return;
10424   }
10425 
10426   S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
10427       << CalleeName << 0 /*object: */ << OS.str();
10428 }
10429 } // namespace
10430 
10431 /// Alerts the user that they are attempting to free a non-malloc'd object.
10432 void Sema::CheckFreeArguments(const CallExpr *E) {
10433   const std::string CalleeName =
10434       dyn_cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
10435 
10436   { // Prefer something that doesn't involve a cast to make things simpler.
10437     const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
10438     if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
10439       switch (UnaryExpr->getOpcode()) {
10440       case UnaryOperator::Opcode::UO_AddrOf:
10441         return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
10442       case UnaryOperator::Opcode::UO_Plus:
10443         return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
10444       default:
10445         break;
10446       }
10447 
10448     if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
10449       if (Lvalue->getType()->isArrayType())
10450         return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
10451 
10452     if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
10453       Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
10454           << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
10455       return;
10456     }
10457 
10458     if (isa<BlockExpr>(Arg)) {
10459       Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
10460           << CalleeName << 1 /*object: block*/;
10461       return;
10462     }
10463   }
10464   // Maybe the cast was important, check after the other cases.
10465   if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
10466     return CheckFreeArgumentsCast(*this, CalleeName, Cast);
10467 }
10468 
10469 void
10470 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
10471                          SourceLocation ReturnLoc,
10472                          bool isObjCMethod,
10473                          const AttrVec *Attrs,
10474                          const FunctionDecl *FD) {
10475   // Check if the return value is null but should not be.
10476   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
10477        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
10478       CheckNonNullExpr(*this, RetValExp))
10479     Diag(ReturnLoc, diag::warn_null_ret)
10480       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
10481 
10482   // C++11 [basic.stc.dynamic.allocation]p4:
10483   //   If an allocation function declared with a non-throwing
10484   //   exception-specification fails to allocate storage, it shall return
10485   //   a null pointer. Any other allocation function that fails to allocate
10486   //   storage shall indicate failure only by throwing an exception [...]
10487   if (FD) {
10488     OverloadedOperatorKind Op = FD->getOverloadedOperator();
10489     if (Op == OO_New || Op == OO_Array_New) {
10490       const FunctionProtoType *Proto
10491         = FD->getType()->castAs<FunctionProtoType>();
10492       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
10493           CheckNonNullExpr(*this, RetValExp))
10494         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
10495           << FD << getLangOpts().CPlusPlus11;
10496     }
10497   }
10498 
10499   // PPC MMA non-pointer types are not allowed as return type. Checking the type
10500   // here prevent the user from using a PPC MMA type as trailing return type.
10501   if (Context.getTargetInfo().getTriple().isPPC64())
10502     CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
10503 }
10504 
10505 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
10506 
10507 /// Check for comparisons of floating point operands using != and ==.
10508 /// Issue a warning if these are no self-comparisons, as they are not likely
10509 /// to do what the programmer intended.
10510 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
10511   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
10512   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
10513 
10514   // Special case: check for x == x (which is OK).
10515   // Do not emit warnings for such cases.
10516   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
10517     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
10518       if (DRL->getDecl() == DRR->getDecl())
10519         return;
10520 
10521   // Special case: check for comparisons against literals that can be exactly
10522   //  represented by APFloat.  In such cases, do not emit a warning.  This
10523   //  is a heuristic: often comparison against such literals are used to
10524   //  detect if a value in a variable has not changed.  This clearly can
10525   //  lead to false negatives.
10526   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
10527     if (FLL->isExact())
10528       return;
10529   } else
10530     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
10531       if (FLR->isExact())
10532         return;
10533 
10534   // Check for comparisons with builtin types.
10535   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
10536     if (CL->getBuiltinCallee())
10537       return;
10538 
10539   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
10540     if (CR->getBuiltinCallee())
10541       return;
10542 
10543   // Emit the diagnostic.
10544   Diag(Loc, diag::warn_floatingpoint_eq)
10545     << LHS->getSourceRange() << RHS->getSourceRange();
10546 }
10547 
10548 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
10549 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
10550 
10551 namespace {
10552 
10553 /// Structure recording the 'active' range of an integer-valued
10554 /// expression.
10555 struct IntRange {
10556   /// The number of bits active in the int. Note that this includes exactly one
10557   /// sign bit if !NonNegative.
10558   unsigned Width;
10559 
10560   /// True if the int is known not to have negative values. If so, all leading
10561   /// bits before Width are known zero, otherwise they are known to be the
10562   /// same as the MSB within Width.
10563   bool NonNegative;
10564 
10565   IntRange(unsigned Width, bool NonNegative)
10566       : Width(Width), NonNegative(NonNegative) {}
10567 
10568   /// Number of bits excluding the sign bit.
10569   unsigned valueBits() const {
10570     return NonNegative ? Width : Width - 1;
10571   }
10572 
10573   /// Returns the range of the bool type.
10574   static IntRange forBoolType() {
10575     return IntRange(1, true);
10576   }
10577 
10578   /// Returns the range of an opaque value of the given integral type.
10579   static IntRange forValueOfType(ASTContext &C, QualType T) {
10580     return forValueOfCanonicalType(C,
10581                           T->getCanonicalTypeInternal().getTypePtr());
10582   }
10583 
10584   /// Returns the range of an opaque value of a canonical integral type.
10585   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
10586     assert(T->isCanonicalUnqualified());
10587 
10588     if (const VectorType *VT = dyn_cast<VectorType>(T))
10589       T = VT->getElementType().getTypePtr();
10590     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
10591       T = CT->getElementType().getTypePtr();
10592     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
10593       T = AT->getValueType().getTypePtr();
10594 
10595     if (!C.getLangOpts().CPlusPlus) {
10596       // For enum types in C code, use the underlying datatype.
10597       if (const EnumType *ET = dyn_cast<EnumType>(T))
10598         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
10599     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
10600       // For enum types in C++, use the known bit width of the enumerators.
10601       EnumDecl *Enum = ET->getDecl();
10602       // In C++11, enums can have a fixed underlying type. Use this type to
10603       // compute the range.
10604       if (Enum->isFixed()) {
10605         return IntRange(C.getIntWidth(QualType(T, 0)),
10606                         !ET->isSignedIntegerOrEnumerationType());
10607       }
10608 
10609       unsigned NumPositive = Enum->getNumPositiveBits();
10610       unsigned NumNegative = Enum->getNumNegativeBits();
10611 
10612       if (NumNegative == 0)
10613         return IntRange(NumPositive, true/*NonNegative*/);
10614       else
10615         return IntRange(std::max(NumPositive + 1, NumNegative),
10616                         false/*NonNegative*/);
10617     }
10618 
10619     if (const auto *EIT = dyn_cast<ExtIntType>(T))
10620       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
10621 
10622     const BuiltinType *BT = cast<BuiltinType>(T);
10623     assert(BT->isInteger());
10624 
10625     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10626   }
10627 
10628   /// Returns the "target" range of a canonical integral type, i.e.
10629   /// the range of values expressible in the type.
10630   ///
10631   /// This matches forValueOfCanonicalType except that enums have the
10632   /// full range of their type, not the range of their enumerators.
10633   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
10634     assert(T->isCanonicalUnqualified());
10635 
10636     if (const VectorType *VT = dyn_cast<VectorType>(T))
10637       T = VT->getElementType().getTypePtr();
10638     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
10639       T = CT->getElementType().getTypePtr();
10640     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
10641       T = AT->getValueType().getTypePtr();
10642     if (const EnumType *ET = dyn_cast<EnumType>(T))
10643       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
10644 
10645     if (const auto *EIT = dyn_cast<ExtIntType>(T))
10646       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
10647 
10648     const BuiltinType *BT = cast<BuiltinType>(T);
10649     assert(BT->isInteger());
10650 
10651     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10652   }
10653 
10654   /// Returns the supremum of two ranges: i.e. their conservative merge.
10655   static IntRange join(IntRange L, IntRange R) {
10656     bool Unsigned = L.NonNegative && R.NonNegative;
10657     return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
10658                     L.NonNegative && R.NonNegative);
10659   }
10660 
10661   /// Return the range of a bitwise-AND of the two ranges.
10662   static IntRange bit_and(IntRange L, IntRange R) {
10663     unsigned Bits = std::max(L.Width, R.Width);
10664     bool NonNegative = false;
10665     if (L.NonNegative) {
10666       Bits = std::min(Bits, L.Width);
10667       NonNegative = true;
10668     }
10669     if (R.NonNegative) {
10670       Bits = std::min(Bits, R.Width);
10671       NonNegative = true;
10672     }
10673     return IntRange(Bits, NonNegative);
10674   }
10675 
10676   /// Return the range of a sum of the two ranges.
10677   static IntRange sum(IntRange L, IntRange R) {
10678     bool Unsigned = L.NonNegative && R.NonNegative;
10679     return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
10680                     Unsigned);
10681   }
10682 
10683   /// Return the range of a difference of the two ranges.
10684   static IntRange difference(IntRange L, IntRange R) {
10685     // We need a 1-bit-wider range if:
10686     //   1) LHS can be negative: least value can be reduced.
10687     //   2) RHS can be negative: greatest value can be increased.
10688     bool CanWiden = !L.NonNegative || !R.NonNegative;
10689     bool Unsigned = L.NonNegative && R.Width == 0;
10690     return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
10691                         !Unsigned,
10692                     Unsigned);
10693   }
10694 
10695   /// Return the range of a product of the two ranges.
10696   static IntRange product(IntRange L, IntRange R) {
10697     // If both LHS and RHS can be negative, we can form
10698     //   -2^L * -2^R = 2^(L + R)
10699     // which requires L + R + 1 value bits to represent.
10700     bool CanWiden = !L.NonNegative && !R.NonNegative;
10701     bool Unsigned = L.NonNegative && R.NonNegative;
10702     return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
10703                     Unsigned);
10704   }
10705 
10706   /// Return the range of a remainder operation between the two ranges.
10707   static IntRange rem(IntRange L, IntRange R) {
10708     // The result of a remainder can't be larger than the result of
10709     // either side. The sign of the result is the sign of the LHS.
10710     bool Unsigned = L.NonNegative;
10711     return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
10712                     Unsigned);
10713   }
10714 };
10715 
10716 } // namespace
10717 
10718 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
10719                               unsigned MaxWidth) {
10720   if (value.isSigned() && value.isNegative())
10721     return IntRange(value.getMinSignedBits(), false);
10722 
10723   if (value.getBitWidth() > MaxWidth)
10724     value = value.trunc(MaxWidth);
10725 
10726   // isNonNegative() just checks the sign bit without considering
10727   // signedness.
10728   return IntRange(value.getActiveBits(), true);
10729 }
10730 
10731 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
10732                               unsigned MaxWidth) {
10733   if (result.isInt())
10734     return GetValueRange(C, result.getInt(), MaxWidth);
10735 
10736   if (result.isVector()) {
10737     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
10738     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
10739       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
10740       R = IntRange::join(R, El);
10741     }
10742     return R;
10743   }
10744 
10745   if (result.isComplexInt()) {
10746     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
10747     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
10748     return IntRange::join(R, I);
10749   }
10750 
10751   // This can happen with lossless casts to intptr_t of "based" lvalues.
10752   // Assume it might use arbitrary bits.
10753   // FIXME: The only reason we need to pass the type in here is to get
10754   // the sign right on this one case.  It would be nice if APValue
10755   // preserved this.
10756   assert(result.isLValue() || result.isAddrLabelDiff());
10757   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
10758 }
10759 
10760 static QualType GetExprType(const Expr *E) {
10761   QualType Ty = E->getType();
10762   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
10763     Ty = AtomicRHS->getValueType();
10764   return Ty;
10765 }
10766 
10767 /// Pseudo-evaluate the given integer expression, estimating the
10768 /// range of values it might take.
10769 ///
10770 /// \param MaxWidth The width to which the value will be truncated.
10771 /// \param Approximate If \c true, return a likely range for the result: in
10772 ///        particular, assume that aritmetic on narrower types doesn't leave
10773 ///        those types. If \c false, return a range including all possible
10774 ///        result values.
10775 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
10776                              bool InConstantContext, bool Approximate) {
10777   E = E->IgnoreParens();
10778 
10779   // Try a full evaluation first.
10780   Expr::EvalResult result;
10781   if (E->EvaluateAsRValue(result, C, InConstantContext))
10782     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
10783 
10784   // I think we only want to look through implicit casts here; if the
10785   // user has an explicit widening cast, we should treat the value as
10786   // being of the new, wider type.
10787   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
10788     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
10789       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
10790                           Approximate);
10791 
10792     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
10793 
10794     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
10795                          CE->getCastKind() == CK_BooleanToSignedIntegral;
10796 
10797     // Assume that non-integer casts can span the full range of the type.
10798     if (!isIntegerCast)
10799       return OutputTypeRange;
10800 
10801     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
10802                                      std::min(MaxWidth, OutputTypeRange.Width),
10803                                      InConstantContext, Approximate);
10804 
10805     // Bail out if the subexpr's range is as wide as the cast type.
10806     if (SubRange.Width >= OutputTypeRange.Width)
10807       return OutputTypeRange;
10808 
10809     // Otherwise, we take the smaller width, and we're non-negative if
10810     // either the output type or the subexpr is.
10811     return IntRange(SubRange.Width,
10812                     SubRange.NonNegative || OutputTypeRange.NonNegative);
10813   }
10814 
10815   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
10816     // If we can fold the condition, just take that operand.
10817     bool CondResult;
10818     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
10819       return GetExprRange(C,
10820                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
10821                           MaxWidth, InConstantContext, Approximate);
10822 
10823     // Otherwise, conservatively merge.
10824     // GetExprRange requires an integer expression, but a throw expression
10825     // results in a void type.
10826     Expr *E = CO->getTrueExpr();
10827     IntRange L = E->getType()->isVoidType()
10828                      ? IntRange{0, true}
10829                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
10830     E = CO->getFalseExpr();
10831     IntRange R = E->getType()->isVoidType()
10832                      ? IntRange{0, true}
10833                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
10834     return IntRange::join(L, R);
10835   }
10836 
10837   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
10838     IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
10839 
10840     switch (BO->getOpcode()) {
10841     case BO_Cmp:
10842       llvm_unreachable("builtin <=> should have class type");
10843 
10844     // Boolean-valued operations are single-bit and positive.
10845     case BO_LAnd:
10846     case BO_LOr:
10847     case BO_LT:
10848     case BO_GT:
10849     case BO_LE:
10850     case BO_GE:
10851     case BO_EQ:
10852     case BO_NE:
10853       return IntRange::forBoolType();
10854 
10855     // The type of the assignments is the type of the LHS, so the RHS
10856     // is not necessarily the same type.
10857     case BO_MulAssign:
10858     case BO_DivAssign:
10859     case BO_RemAssign:
10860     case BO_AddAssign:
10861     case BO_SubAssign:
10862     case BO_XorAssign:
10863     case BO_OrAssign:
10864       // TODO: bitfields?
10865       return IntRange::forValueOfType(C, GetExprType(E));
10866 
10867     // Simple assignments just pass through the RHS, which will have
10868     // been coerced to the LHS type.
10869     case BO_Assign:
10870       // TODO: bitfields?
10871       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
10872                           Approximate);
10873 
10874     // Operations with opaque sources are black-listed.
10875     case BO_PtrMemD:
10876     case BO_PtrMemI:
10877       return IntRange::forValueOfType(C, GetExprType(E));
10878 
10879     // Bitwise-and uses the *infinum* of the two source ranges.
10880     case BO_And:
10881     case BO_AndAssign:
10882       Combine = IntRange::bit_and;
10883       break;
10884 
10885     // Left shift gets black-listed based on a judgement call.
10886     case BO_Shl:
10887       // ...except that we want to treat '1 << (blah)' as logically
10888       // positive.  It's an important idiom.
10889       if (IntegerLiteral *I
10890             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
10891         if (I->getValue() == 1) {
10892           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
10893           return IntRange(R.Width, /*NonNegative*/ true);
10894         }
10895       }
10896       LLVM_FALLTHROUGH;
10897 
10898     case BO_ShlAssign:
10899       return IntRange::forValueOfType(C, GetExprType(E));
10900 
10901     // Right shift by a constant can narrow its left argument.
10902     case BO_Shr:
10903     case BO_ShrAssign: {
10904       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext,
10905                                 Approximate);
10906 
10907       // If the shift amount is a positive constant, drop the width by
10908       // that much.
10909       if (Optional<llvm::APSInt> shift =
10910               BO->getRHS()->getIntegerConstantExpr(C)) {
10911         if (shift->isNonNegative()) {
10912           unsigned zext = shift->getZExtValue();
10913           if (zext >= L.Width)
10914             L.Width = (L.NonNegative ? 0 : 1);
10915           else
10916             L.Width -= zext;
10917         }
10918       }
10919 
10920       return L;
10921     }
10922 
10923     // Comma acts as its right operand.
10924     case BO_Comma:
10925       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
10926                           Approximate);
10927 
10928     case BO_Add:
10929       if (!Approximate)
10930         Combine = IntRange::sum;
10931       break;
10932 
10933     case BO_Sub:
10934       if (BO->getLHS()->getType()->isPointerType())
10935         return IntRange::forValueOfType(C, GetExprType(E));
10936       if (!Approximate)
10937         Combine = IntRange::difference;
10938       break;
10939 
10940     case BO_Mul:
10941       if (!Approximate)
10942         Combine = IntRange::product;
10943       break;
10944 
10945     // The width of a division result is mostly determined by the size
10946     // of the LHS.
10947     case BO_Div: {
10948       // Don't 'pre-truncate' the operands.
10949       unsigned opWidth = C.getIntWidth(GetExprType(E));
10950       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext,
10951                                 Approximate);
10952 
10953       // If the divisor is constant, use that.
10954       if (Optional<llvm::APSInt> divisor =
10955               BO->getRHS()->getIntegerConstantExpr(C)) {
10956         unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
10957         if (log2 >= L.Width)
10958           L.Width = (L.NonNegative ? 0 : 1);
10959         else
10960           L.Width = std::min(L.Width - log2, MaxWidth);
10961         return L;
10962       }
10963 
10964       // Otherwise, just use the LHS's width.
10965       // FIXME: This is wrong if the LHS could be its minimal value and the RHS
10966       // could be -1.
10967       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext,
10968                                 Approximate);
10969       return IntRange(L.Width, L.NonNegative && R.NonNegative);
10970     }
10971 
10972     case BO_Rem:
10973       Combine = IntRange::rem;
10974       break;
10975 
10976     // The default behavior is okay for these.
10977     case BO_Xor:
10978     case BO_Or:
10979       break;
10980     }
10981 
10982     // Combine the two ranges, but limit the result to the type in which we
10983     // performed the computation.
10984     QualType T = GetExprType(E);
10985     unsigned opWidth = C.getIntWidth(T);
10986     IntRange L =
10987         GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate);
10988     IntRange R =
10989         GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate);
10990     IntRange C = Combine(L, R);
10991     C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
10992     C.Width = std::min(C.Width, MaxWidth);
10993     return C;
10994   }
10995 
10996   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
10997     switch (UO->getOpcode()) {
10998     // Boolean-valued operations are white-listed.
10999     case UO_LNot:
11000       return IntRange::forBoolType();
11001 
11002     // Operations with opaque sources are black-listed.
11003     case UO_Deref:
11004     case UO_AddrOf: // should be impossible
11005       return IntRange::forValueOfType(C, GetExprType(E));
11006 
11007     default:
11008       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11009                           Approximate);
11010     }
11011   }
11012 
11013   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
11014     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
11015                         Approximate);
11016 
11017   if (const auto *BitField = E->getSourceBitField())
11018     return IntRange(BitField->getBitWidthValue(C),
11019                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
11020 
11021   return IntRange::forValueOfType(C, GetExprType(E));
11022 }
11023 
11024 static IntRange GetExprRange(ASTContext &C, const Expr *E,
11025                              bool InConstantContext, bool Approximate) {
11026   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
11027                       Approximate);
11028 }
11029 
11030 /// Checks whether the given value, which currently has the given
11031 /// source semantics, has the same value when coerced through the
11032 /// target semantics.
11033 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
11034                                  const llvm::fltSemantics &Src,
11035                                  const llvm::fltSemantics &Tgt) {
11036   llvm::APFloat truncated = value;
11037 
11038   bool ignored;
11039   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
11040   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
11041 
11042   return truncated.bitwiseIsEqual(value);
11043 }
11044 
11045 /// Checks whether the given value, which currently has the given
11046 /// source semantics, has the same value when coerced through the
11047 /// target semantics.
11048 ///
11049 /// The value might be a vector of floats (or a complex number).
11050 static bool IsSameFloatAfterCast(const APValue &value,
11051                                  const llvm::fltSemantics &Src,
11052                                  const llvm::fltSemantics &Tgt) {
11053   if (value.isFloat())
11054     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
11055 
11056   if (value.isVector()) {
11057     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
11058       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
11059         return false;
11060     return true;
11061   }
11062 
11063   assert(value.isComplexFloat());
11064   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
11065           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
11066 }
11067 
11068 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
11069                                        bool IsListInit = false);
11070 
11071 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
11072   // Suppress cases where we are comparing against an enum constant.
11073   if (const DeclRefExpr *DR =
11074       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
11075     if (isa<EnumConstantDecl>(DR->getDecl()))
11076       return true;
11077 
11078   // Suppress cases where the value is expanded from a macro, unless that macro
11079   // is how a language represents a boolean literal. This is the case in both C
11080   // and Objective-C.
11081   SourceLocation BeginLoc = E->getBeginLoc();
11082   if (BeginLoc.isMacroID()) {
11083     StringRef MacroName = Lexer::getImmediateMacroName(
11084         BeginLoc, S.getSourceManager(), S.getLangOpts());
11085     return MacroName != "YES" && MacroName != "NO" &&
11086            MacroName != "true" && MacroName != "false";
11087   }
11088 
11089   return false;
11090 }
11091 
11092 static bool isKnownToHaveUnsignedValue(Expr *E) {
11093   return E->getType()->isIntegerType() &&
11094          (!E->getType()->isSignedIntegerType() ||
11095           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
11096 }
11097 
11098 namespace {
11099 /// The promoted range of values of a type. In general this has the
11100 /// following structure:
11101 ///
11102 ///     |-----------| . . . |-----------|
11103 ///     ^           ^       ^           ^
11104 ///    Min       HoleMin  HoleMax      Max
11105 ///
11106 /// ... where there is only a hole if a signed type is promoted to unsigned
11107 /// (in which case Min and Max are the smallest and largest representable
11108 /// values).
11109 struct PromotedRange {
11110   // Min, or HoleMax if there is a hole.
11111   llvm::APSInt PromotedMin;
11112   // Max, or HoleMin if there is a hole.
11113   llvm::APSInt PromotedMax;
11114 
11115   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
11116     if (R.Width == 0)
11117       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
11118     else if (R.Width >= BitWidth && !Unsigned) {
11119       // Promotion made the type *narrower*. This happens when promoting
11120       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
11121       // Treat all values of 'signed int' as being in range for now.
11122       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
11123       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
11124     } else {
11125       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
11126                         .extOrTrunc(BitWidth);
11127       PromotedMin.setIsUnsigned(Unsigned);
11128 
11129       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
11130                         .extOrTrunc(BitWidth);
11131       PromotedMax.setIsUnsigned(Unsigned);
11132     }
11133   }
11134 
11135   // Determine whether this range is contiguous (has no hole).
11136   bool isContiguous() const { return PromotedMin <= PromotedMax; }
11137 
11138   // Where a constant value is within the range.
11139   enum ComparisonResult {
11140     LT = 0x1,
11141     LE = 0x2,
11142     GT = 0x4,
11143     GE = 0x8,
11144     EQ = 0x10,
11145     NE = 0x20,
11146     InRangeFlag = 0x40,
11147 
11148     Less = LE | LT | NE,
11149     Min = LE | InRangeFlag,
11150     InRange = InRangeFlag,
11151     Max = GE | InRangeFlag,
11152     Greater = GE | GT | NE,
11153 
11154     OnlyValue = LE | GE | EQ | InRangeFlag,
11155     InHole = NE
11156   };
11157 
11158   ComparisonResult compare(const llvm::APSInt &Value) const {
11159     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
11160            Value.isUnsigned() == PromotedMin.isUnsigned());
11161     if (!isContiguous()) {
11162       assert(Value.isUnsigned() && "discontiguous range for signed compare");
11163       if (Value.isMinValue()) return Min;
11164       if (Value.isMaxValue()) return Max;
11165       if (Value >= PromotedMin) return InRange;
11166       if (Value <= PromotedMax) return InRange;
11167       return InHole;
11168     }
11169 
11170     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
11171     case -1: return Less;
11172     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
11173     case 1:
11174       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
11175       case -1: return InRange;
11176       case 0: return Max;
11177       case 1: return Greater;
11178       }
11179     }
11180 
11181     llvm_unreachable("impossible compare result");
11182   }
11183 
11184   static llvm::Optional<StringRef>
11185   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
11186     if (Op == BO_Cmp) {
11187       ComparisonResult LTFlag = LT, GTFlag = GT;
11188       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
11189 
11190       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
11191       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
11192       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
11193       return llvm::None;
11194     }
11195 
11196     ComparisonResult TrueFlag, FalseFlag;
11197     if (Op == BO_EQ) {
11198       TrueFlag = EQ;
11199       FalseFlag = NE;
11200     } else if (Op == BO_NE) {
11201       TrueFlag = NE;
11202       FalseFlag = EQ;
11203     } else {
11204       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
11205         TrueFlag = LT;
11206         FalseFlag = GE;
11207       } else {
11208         TrueFlag = GT;
11209         FalseFlag = LE;
11210       }
11211       if (Op == BO_GE || Op == BO_LE)
11212         std::swap(TrueFlag, FalseFlag);
11213     }
11214     if (R & TrueFlag)
11215       return StringRef("true");
11216     if (R & FalseFlag)
11217       return StringRef("false");
11218     return llvm::None;
11219   }
11220 };
11221 }
11222 
11223 static bool HasEnumType(Expr *E) {
11224   // Strip off implicit integral promotions.
11225   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
11226     if (ICE->getCastKind() != CK_IntegralCast &&
11227         ICE->getCastKind() != CK_NoOp)
11228       break;
11229     E = ICE->getSubExpr();
11230   }
11231 
11232   return E->getType()->isEnumeralType();
11233 }
11234 
11235 static int classifyConstantValue(Expr *Constant) {
11236   // The values of this enumeration are used in the diagnostics
11237   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
11238   enum ConstantValueKind {
11239     Miscellaneous = 0,
11240     LiteralTrue,
11241     LiteralFalse
11242   };
11243   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
11244     return BL->getValue() ? ConstantValueKind::LiteralTrue
11245                           : ConstantValueKind::LiteralFalse;
11246   return ConstantValueKind::Miscellaneous;
11247 }
11248 
11249 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
11250                                         Expr *Constant, Expr *Other,
11251                                         const llvm::APSInt &Value,
11252                                         bool RhsConstant) {
11253   if (S.inTemplateInstantiation())
11254     return false;
11255 
11256   Expr *OriginalOther = Other;
11257 
11258   Constant = Constant->IgnoreParenImpCasts();
11259   Other = Other->IgnoreParenImpCasts();
11260 
11261   // Suppress warnings on tautological comparisons between values of the same
11262   // enumeration type. There are only two ways we could warn on this:
11263   //  - If the constant is outside the range of representable values of
11264   //    the enumeration. In such a case, we should warn about the cast
11265   //    to enumeration type, not about the comparison.
11266   //  - If the constant is the maximum / minimum in-range value. For an
11267   //    enumeratin type, such comparisons can be meaningful and useful.
11268   if (Constant->getType()->isEnumeralType() &&
11269       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
11270     return false;
11271 
11272   IntRange OtherValueRange = GetExprRange(
11273       S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false);
11274 
11275   QualType OtherT = Other->getType();
11276   if (const auto *AT = OtherT->getAs<AtomicType>())
11277     OtherT = AT->getValueType();
11278   IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
11279 
11280   // Special case for ObjC BOOL on targets where its a typedef for a signed char
11281   // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
11282   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
11283                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
11284                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
11285 
11286   // Whether we're treating Other as being a bool because of the form of
11287   // expression despite it having another type (typically 'int' in C).
11288   bool OtherIsBooleanDespiteType =
11289       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
11290   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
11291     OtherTypeRange = OtherValueRange = IntRange::forBoolType();
11292 
11293   // Check if all values in the range of possible values of this expression
11294   // lead to the same comparison outcome.
11295   PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(),
11296                                         Value.isUnsigned());
11297   auto Cmp = OtherPromotedValueRange.compare(Value);
11298   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
11299   if (!Result)
11300     return false;
11301 
11302   // Also consider the range determined by the type alone. This allows us to
11303   // classify the warning under the proper diagnostic group.
11304   bool TautologicalTypeCompare = false;
11305   {
11306     PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
11307                                          Value.isUnsigned());
11308     auto TypeCmp = OtherPromotedTypeRange.compare(Value);
11309     if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
11310                                                        RhsConstant)) {
11311       TautologicalTypeCompare = true;
11312       Cmp = TypeCmp;
11313       Result = TypeResult;
11314     }
11315   }
11316 
11317   // Don't warn if the non-constant operand actually always evaluates to the
11318   // same value.
11319   if (!TautologicalTypeCompare && OtherValueRange.Width == 0)
11320     return false;
11321 
11322   // Suppress the diagnostic for an in-range comparison if the constant comes
11323   // from a macro or enumerator. We don't want to diagnose
11324   //
11325   //   some_long_value <= INT_MAX
11326   //
11327   // when sizeof(int) == sizeof(long).
11328   bool InRange = Cmp & PromotedRange::InRangeFlag;
11329   if (InRange && IsEnumConstOrFromMacro(S, Constant))
11330     return false;
11331 
11332   // A comparison of an unsigned bit-field against 0 is really a type problem,
11333   // even though at the type level the bit-field might promote to 'signed int'.
11334   if (Other->refersToBitField() && InRange && Value == 0 &&
11335       Other->getType()->isUnsignedIntegerOrEnumerationType())
11336     TautologicalTypeCompare = true;
11337 
11338   // If this is a comparison to an enum constant, include that
11339   // constant in the diagnostic.
11340   const EnumConstantDecl *ED = nullptr;
11341   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
11342     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
11343 
11344   // Should be enough for uint128 (39 decimal digits)
11345   SmallString<64> PrettySourceValue;
11346   llvm::raw_svector_ostream OS(PrettySourceValue);
11347   if (ED) {
11348     OS << '\'' << *ED << "' (" << Value << ")";
11349   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
11350                Constant->IgnoreParenImpCasts())) {
11351     OS << (BL->getValue() ? "YES" : "NO");
11352   } else {
11353     OS << Value;
11354   }
11355 
11356   if (!TautologicalTypeCompare) {
11357     S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
11358         << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative
11359         << E->getOpcodeStr() << OS.str() << *Result
11360         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11361     return true;
11362   }
11363 
11364   if (IsObjCSignedCharBool) {
11365     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
11366                           S.PDiag(diag::warn_tautological_compare_objc_bool)
11367                               << OS.str() << *Result);
11368     return true;
11369   }
11370 
11371   // FIXME: We use a somewhat different formatting for the in-range cases and
11372   // cases involving boolean values for historical reasons. We should pick a
11373   // consistent way of presenting these diagnostics.
11374   if (!InRange || Other->isKnownToHaveBooleanValue()) {
11375 
11376     S.DiagRuntimeBehavior(
11377         E->getOperatorLoc(), E,
11378         S.PDiag(!InRange ? diag::warn_out_of_range_compare
11379                          : diag::warn_tautological_bool_compare)
11380             << OS.str() << classifyConstantValue(Constant) << OtherT
11381             << OtherIsBooleanDespiteType << *Result
11382             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
11383   } else {
11384     unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
11385                         ? (HasEnumType(OriginalOther)
11386                                ? diag::warn_unsigned_enum_always_true_comparison
11387                                : diag::warn_unsigned_always_true_comparison)
11388                         : diag::warn_tautological_constant_compare;
11389 
11390     S.Diag(E->getOperatorLoc(), Diag)
11391         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
11392         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11393   }
11394 
11395   return true;
11396 }
11397 
11398 /// Analyze the operands of the given comparison.  Implements the
11399 /// fallback case from AnalyzeComparison.
11400 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
11401   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11402   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11403 }
11404 
11405 /// Implements -Wsign-compare.
11406 ///
11407 /// \param E the binary operator to check for warnings
11408 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
11409   // The type the comparison is being performed in.
11410   QualType T = E->getLHS()->getType();
11411 
11412   // Only analyze comparison operators where both sides have been converted to
11413   // the same type.
11414   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
11415     return AnalyzeImpConvsInComparison(S, E);
11416 
11417   // Don't analyze value-dependent comparisons directly.
11418   if (E->isValueDependent())
11419     return AnalyzeImpConvsInComparison(S, E);
11420 
11421   Expr *LHS = E->getLHS();
11422   Expr *RHS = E->getRHS();
11423 
11424   if (T->isIntegralType(S.Context)) {
11425     Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context);
11426     Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context);
11427 
11428     // We don't care about expressions whose result is a constant.
11429     if (RHSValue && LHSValue)
11430       return AnalyzeImpConvsInComparison(S, E);
11431 
11432     // We only care about expressions where just one side is literal
11433     if ((bool)RHSValue ^ (bool)LHSValue) {
11434       // Is the constant on the RHS or LHS?
11435       const bool RhsConstant = (bool)RHSValue;
11436       Expr *Const = RhsConstant ? RHS : LHS;
11437       Expr *Other = RhsConstant ? LHS : RHS;
11438       const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
11439 
11440       // Check whether an integer constant comparison results in a value
11441       // of 'true' or 'false'.
11442       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
11443         return AnalyzeImpConvsInComparison(S, E);
11444     }
11445   }
11446 
11447   if (!T->hasUnsignedIntegerRepresentation()) {
11448     // We don't do anything special if this isn't an unsigned integral
11449     // comparison:  we're only interested in integral comparisons, and
11450     // signed comparisons only happen in cases we don't care to warn about.
11451     return AnalyzeImpConvsInComparison(S, E);
11452   }
11453 
11454   LHS = LHS->IgnoreParenImpCasts();
11455   RHS = RHS->IgnoreParenImpCasts();
11456 
11457   if (!S.getLangOpts().CPlusPlus) {
11458     // Avoid warning about comparison of integers with different signs when
11459     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
11460     // the type of `E`.
11461     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
11462       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11463     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
11464       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11465   }
11466 
11467   // Check to see if one of the (unmodified) operands is of different
11468   // signedness.
11469   Expr *signedOperand, *unsignedOperand;
11470   if (LHS->getType()->hasSignedIntegerRepresentation()) {
11471     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
11472            "unsigned comparison between two signed integer expressions?");
11473     signedOperand = LHS;
11474     unsignedOperand = RHS;
11475   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
11476     signedOperand = RHS;
11477     unsignedOperand = LHS;
11478   } else {
11479     return AnalyzeImpConvsInComparison(S, E);
11480   }
11481 
11482   // Otherwise, calculate the effective range of the signed operand.
11483   IntRange signedRange = GetExprRange(
11484       S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true);
11485 
11486   // Go ahead and analyze implicit conversions in the operands.  Note
11487   // that we skip the implicit conversions on both sides.
11488   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
11489   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
11490 
11491   // If the signed range is non-negative, -Wsign-compare won't fire.
11492   if (signedRange.NonNegative)
11493     return;
11494 
11495   // For (in)equality comparisons, if the unsigned operand is a
11496   // constant which cannot collide with a overflowed signed operand,
11497   // then reinterpreting the signed operand as unsigned will not
11498   // change the result of the comparison.
11499   if (E->isEqualityOp()) {
11500     unsigned comparisonWidth = S.Context.getIntWidth(T);
11501     IntRange unsignedRange =
11502         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(),
11503                      /*Approximate*/ true);
11504 
11505     // We should never be unable to prove that the unsigned operand is
11506     // non-negative.
11507     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
11508 
11509     if (unsignedRange.Width < comparisonWidth)
11510       return;
11511   }
11512 
11513   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
11514                         S.PDiag(diag::warn_mixed_sign_comparison)
11515                             << LHS->getType() << RHS->getType()
11516                             << LHS->getSourceRange() << RHS->getSourceRange());
11517 }
11518 
11519 /// Analyzes an attempt to assign the given value to a bitfield.
11520 ///
11521 /// Returns true if there was something fishy about the attempt.
11522 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
11523                                       SourceLocation InitLoc) {
11524   assert(Bitfield->isBitField());
11525   if (Bitfield->isInvalidDecl())
11526     return false;
11527 
11528   // White-list bool bitfields.
11529   QualType BitfieldType = Bitfield->getType();
11530   if (BitfieldType->isBooleanType())
11531      return false;
11532 
11533   if (BitfieldType->isEnumeralType()) {
11534     EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
11535     // If the underlying enum type was not explicitly specified as an unsigned
11536     // type and the enum contain only positive values, MSVC++ will cause an
11537     // inconsistency by storing this as a signed type.
11538     if (S.getLangOpts().CPlusPlus11 &&
11539         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
11540         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
11541         BitfieldEnumDecl->getNumNegativeBits() == 0) {
11542       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
11543           << BitfieldEnumDecl;
11544     }
11545   }
11546 
11547   if (Bitfield->getType()->isBooleanType())
11548     return false;
11549 
11550   // Ignore value- or type-dependent expressions.
11551   if (Bitfield->getBitWidth()->isValueDependent() ||
11552       Bitfield->getBitWidth()->isTypeDependent() ||
11553       Init->isValueDependent() ||
11554       Init->isTypeDependent())
11555     return false;
11556 
11557   Expr *OriginalInit = Init->IgnoreParenImpCasts();
11558   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
11559 
11560   Expr::EvalResult Result;
11561   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
11562                                    Expr::SE_AllowSideEffects)) {
11563     // The RHS is not constant.  If the RHS has an enum type, make sure the
11564     // bitfield is wide enough to hold all the values of the enum without
11565     // truncation.
11566     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
11567       EnumDecl *ED = EnumTy->getDecl();
11568       bool SignedBitfield = BitfieldType->isSignedIntegerType();
11569 
11570       // Enum types are implicitly signed on Windows, so check if there are any
11571       // negative enumerators to see if the enum was intended to be signed or
11572       // not.
11573       bool SignedEnum = ED->getNumNegativeBits() > 0;
11574 
11575       // Check for surprising sign changes when assigning enum values to a
11576       // bitfield of different signedness.  If the bitfield is signed and we
11577       // have exactly the right number of bits to store this unsigned enum,
11578       // suggest changing the enum to an unsigned type. This typically happens
11579       // on Windows where unfixed enums always use an underlying type of 'int'.
11580       unsigned DiagID = 0;
11581       if (SignedEnum && !SignedBitfield) {
11582         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
11583       } else if (SignedBitfield && !SignedEnum &&
11584                  ED->getNumPositiveBits() == FieldWidth) {
11585         DiagID = diag::warn_signed_bitfield_enum_conversion;
11586       }
11587 
11588       if (DiagID) {
11589         S.Diag(InitLoc, DiagID) << Bitfield << ED;
11590         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
11591         SourceRange TypeRange =
11592             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
11593         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
11594             << SignedEnum << TypeRange;
11595       }
11596 
11597       // Compute the required bitwidth. If the enum has negative values, we need
11598       // one more bit than the normal number of positive bits to represent the
11599       // sign bit.
11600       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
11601                                                   ED->getNumNegativeBits())
11602                                        : ED->getNumPositiveBits();
11603 
11604       // Check the bitwidth.
11605       if (BitsNeeded > FieldWidth) {
11606         Expr *WidthExpr = Bitfield->getBitWidth();
11607         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
11608             << Bitfield << ED;
11609         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
11610             << BitsNeeded << ED << WidthExpr->getSourceRange();
11611       }
11612     }
11613 
11614     return false;
11615   }
11616 
11617   llvm::APSInt Value = Result.Val.getInt();
11618 
11619   unsigned OriginalWidth = Value.getBitWidth();
11620 
11621   if (!Value.isSigned() || Value.isNegative())
11622     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
11623       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
11624         OriginalWidth = Value.getMinSignedBits();
11625 
11626   if (OriginalWidth <= FieldWidth)
11627     return false;
11628 
11629   // Compute the value which the bitfield will contain.
11630   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
11631   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
11632 
11633   // Check whether the stored value is equal to the original value.
11634   TruncatedValue = TruncatedValue.extend(OriginalWidth);
11635   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
11636     return false;
11637 
11638   // Special-case bitfields of width 1: booleans are naturally 0/1, and
11639   // therefore don't strictly fit into a signed bitfield of width 1.
11640   if (FieldWidth == 1 && Value == 1)
11641     return false;
11642 
11643   std::string PrettyValue = Value.toString(10);
11644   std::string PrettyTrunc = TruncatedValue.toString(10);
11645 
11646   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
11647     << PrettyValue << PrettyTrunc << OriginalInit->getType()
11648     << Init->getSourceRange();
11649 
11650   return true;
11651 }
11652 
11653 /// Analyze the given simple or compound assignment for warning-worthy
11654 /// operations.
11655 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
11656   // Just recurse on the LHS.
11657   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11658 
11659   // We want to recurse on the RHS as normal unless we're assigning to
11660   // a bitfield.
11661   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
11662     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
11663                                   E->getOperatorLoc())) {
11664       // Recurse, ignoring any implicit conversions on the RHS.
11665       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
11666                                         E->getOperatorLoc());
11667     }
11668   }
11669 
11670   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11671 
11672   // Diagnose implicitly sequentially-consistent atomic assignment.
11673   if (E->getLHS()->getType()->isAtomicType())
11674     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
11675 }
11676 
11677 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
11678 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
11679                             SourceLocation CContext, unsigned diag,
11680                             bool pruneControlFlow = false) {
11681   if (pruneControlFlow) {
11682     S.DiagRuntimeBehavior(E->getExprLoc(), E,
11683                           S.PDiag(diag)
11684                               << SourceType << T << E->getSourceRange()
11685                               << SourceRange(CContext));
11686     return;
11687   }
11688   S.Diag(E->getExprLoc(), diag)
11689     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
11690 }
11691 
11692 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
11693 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
11694                             SourceLocation CContext,
11695                             unsigned diag, bool pruneControlFlow = false) {
11696   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
11697 }
11698 
11699 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
11700   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
11701       S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
11702 }
11703 
11704 static void adornObjCBoolConversionDiagWithTernaryFixit(
11705     Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
11706   Expr *Ignored = SourceExpr->IgnoreImplicit();
11707   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
11708     Ignored = OVE->getSourceExpr();
11709   bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
11710                      isa<BinaryOperator>(Ignored) ||
11711                      isa<CXXOperatorCallExpr>(Ignored);
11712   SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
11713   if (NeedsParens)
11714     Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
11715             << FixItHint::CreateInsertion(EndLoc, ")");
11716   Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
11717 }
11718 
11719 /// Diagnose an implicit cast from a floating point value to an integer value.
11720 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
11721                                     SourceLocation CContext) {
11722   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
11723   const bool PruneWarnings = S.inTemplateInstantiation();
11724 
11725   Expr *InnerE = E->IgnoreParenImpCasts();
11726   // We also want to warn on, e.g., "int i = -1.234"
11727   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
11728     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
11729       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
11730 
11731   const bool IsLiteral =
11732       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
11733 
11734   llvm::APFloat Value(0.0);
11735   bool IsConstant =
11736     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
11737   if (!IsConstant) {
11738     if (isObjCSignedCharBool(S, T)) {
11739       return adornObjCBoolConversionDiagWithTernaryFixit(
11740           S, E,
11741           S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
11742               << E->getType());
11743     }
11744 
11745     return DiagnoseImpCast(S, E, T, CContext,
11746                            diag::warn_impcast_float_integer, PruneWarnings);
11747   }
11748 
11749   bool isExact = false;
11750 
11751   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
11752                             T->hasUnsignedIntegerRepresentation());
11753   llvm::APFloat::opStatus Result = Value.convertToInteger(
11754       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
11755 
11756   // FIXME: Force the precision of the source value down so we don't print
11757   // digits which are usually useless (we don't really care here if we
11758   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
11759   // would automatically print the shortest representation, but it's a bit
11760   // tricky to implement.
11761   SmallString<16> PrettySourceValue;
11762   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
11763   precision = (precision * 59 + 195) / 196;
11764   Value.toString(PrettySourceValue, precision);
11765 
11766   if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
11767     return adornObjCBoolConversionDiagWithTernaryFixit(
11768         S, E,
11769         S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
11770             << PrettySourceValue);
11771   }
11772 
11773   if (Result == llvm::APFloat::opOK && isExact) {
11774     if (IsLiteral) return;
11775     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
11776                            PruneWarnings);
11777   }
11778 
11779   // Conversion of a floating-point value to a non-bool integer where the
11780   // integral part cannot be represented by the integer type is undefined.
11781   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
11782     return DiagnoseImpCast(
11783         S, E, T, CContext,
11784         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
11785                   : diag::warn_impcast_float_to_integer_out_of_range,
11786         PruneWarnings);
11787 
11788   unsigned DiagID = 0;
11789   if (IsLiteral) {
11790     // Warn on floating point literal to integer.
11791     DiagID = diag::warn_impcast_literal_float_to_integer;
11792   } else if (IntegerValue == 0) {
11793     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
11794       return DiagnoseImpCast(S, E, T, CContext,
11795                              diag::warn_impcast_float_integer, PruneWarnings);
11796     }
11797     // Warn on non-zero to zero conversion.
11798     DiagID = diag::warn_impcast_float_to_integer_zero;
11799   } else {
11800     if (IntegerValue.isUnsigned()) {
11801       if (!IntegerValue.isMaxValue()) {
11802         return DiagnoseImpCast(S, E, T, CContext,
11803                                diag::warn_impcast_float_integer, PruneWarnings);
11804       }
11805     } else {  // IntegerValue.isSigned()
11806       if (!IntegerValue.isMaxSignedValue() &&
11807           !IntegerValue.isMinSignedValue()) {
11808         return DiagnoseImpCast(S, E, T, CContext,
11809                                diag::warn_impcast_float_integer, PruneWarnings);
11810       }
11811     }
11812     // Warn on evaluatable floating point expression to integer conversion.
11813     DiagID = diag::warn_impcast_float_to_integer;
11814   }
11815 
11816   SmallString<16> PrettyTargetValue;
11817   if (IsBool)
11818     PrettyTargetValue = Value.isZero() ? "false" : "true";
11819   else
11820     IntegerValue.toString(PrettyTargetValue);
11821 
11822   if (PruneWarnings) {
11823     S.DiagRuntimeBehavior(E->getExprLoc(), E,
11824                           S.PDiag(DiagID)
11825                               << E->getType() << T.getUnqualifiedType()
11826                               << PrettySourceValue << PrettyTargetValue
11827                               << E->getSourceRange() << SourceRange(CContext));
11828   } else {
11829     S.Diag(E->getExprLoc(), DiagID)
11830         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
11831         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
11832   }
11833 }
11834 
11835 /// Analyze the given compound assignment for the possible losing of
11836 /// floating-point precision.
11837 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
11838   assert(isa<CompoundAssignOperator>(E) &&
11839          "Must be compound assignment operation");
11840   // Recurse on the LHS and RHS in here
11841   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11842   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11843 
11844   if (E->getLHS()->getType()->isAtomicType())
11845     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
11846 
11847   // Now check the outermost expression
11848   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
11849   const auto *RBT = cast<CompoundAssignOperator>(E)
11850                         ->getComputationResultType()
11851                         ->getAs<BuiltinType>();
11852 
11853   // The below checks assume source is floating point.
11854   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
11855 
11856   // If source is floating point but target is an integer.
11857   if (ResultBT->isInteger())
11858     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
11859                            E->getExprLoc(), diag::warn_impcast_float_integer);
11860 
11861   if (!ResultBT->isFloatingPoint())
11862     return;
11863 
11864   // If both source and target are floating points, warn about losing precision.
11865   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
11866       QualType(ResultBT, 0), QualType(RBT, 0));
11867   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
11868     // warn about dropping FP rank.
11869     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
11870                     diag::warn_impcast_float_result_precision);
11871 }
11872 
11873 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
11874                                       IntRange Range) {
11875   if (!Range.Width) return "0";
11876 
11877   llvm::APSInt ValueInRange = Value;
11878   ValueInRange.setIsSigned(!Range.NonNegative);
11879   ValueInRange = ValueInRange.trunc(Range.Width);
11880   return ValueInRange.toString(10);
11881 }
11882 
11883 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
11884   if (!isa<ImplicitCastExpr>(Ex))
11885     return false;
11886 
11887   Expr *InnerE = Ex->IgnoreParenImpCasts();
11888   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
11889   const Type *Source =
11890     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
11891   if (Target->isDependentType())
11892     return false;
11893 
11894   const BuiltinType *FloatCandidateBT =
11895     dyn_cast<BuiltinType>(ToBool ? Source : Target);
11896   const Type *BoolCandidateType = ToBool ? Target : Source;
11897 
11898   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
11899           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
11900 }
11901 
11902 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
11903                                              SourceLocation CC) {
11904   unsigned NumArgs = TheCall->getNumArgs();
11905   for (unsigned i = 0; i < NumArgs; ++i) {
11906     Expr *CurrA = TheCall->getArg(i);
11907     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
11908       continue;
11909 
11910     bool IsSwapped = ((i > 0) &&
11911         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
11912     IsSwapped |= ((i < (NumArgs - 1)) &&
11913         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
11914     if (IsSwapped) {
11915       // Warn on this floating-point to bool conversion.
11916       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
11917                       CurrA->getType(), CC,
11918                       diag::warn_impcast_floating_point_to_bool);
11919     }
11920   }
11921 }
11922 
11923 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
11924                                    SourceLocation CC) {
11925   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
11926                         E->getExprLoc()))
11927     return;
11928 
11929   // Don't warn on functions which have return type nullptr_t.
11930   if (isa<CallExpr>(E))
11931     return;
11932 
11933   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
11934   const Expr::NullPointerConstantKind NullKind =
11935       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
11936   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
11937     return;
11938 
11939   // Return if target type is a safe conversion.
11940   if (T->isAnyPointerType() || T->isBlockPointerType() ||
11941       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
11942     return;
11943 
11944   SourceLocation Loc = E->getSourceRange().getBegin();
11945 
11946   // Venture through the macro stacks to get to the source of macro arguments.
11947   // The new location is a better location than the complete location that was
11948   // passed in.
11949   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
11950   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
11951 
11952   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
11953   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
11954     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
11955         Loc, S.SourceMgr, S.getLangOpts());
11956     if (MacroName == "NULL")
11957       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
11958   }
11959 
11960   // Only warn if the null and context location are in the same macro expansion.
11961   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
11962     return;
11963 
11964   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
11965       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
11966       << FixItHint::CreateReplacement(Loc,
11967                                       S.getFixItZeroLiteralForType(T, Loc));
11968 }
11969 
11970 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
11971                                   ObjCArrayLiteral *ArrayLiteral);
11972 
11973 static void
11974 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
11975                            ObjCDictionaryLiteral *DictionaryLiteral);
11976 
11977 /// Check a single element within a collection literal against the
11978 /// target element type.
11979 static void checkObjCCollectionLiteralElement(Sema &S,
11980                                               QualType TargetElementType,
11981                                               Expr *Element,
11982                                               unsigned ElementKind) {
11983   // Skip a bitcast to 'id' or qualified 'id'.
11984   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
11985     if (ICE->getCastKind() == CK_BitCast &&
11986         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
11987       Element = ICE->getSubExpr();
11988   }
11989 
11990   QualType ElementType = Element->getType();
11991   ExprResult ElementResult(Element);
11992   if (ElementType->getAs<ObjCObjectPointerType>() &&
11993       S.CheckSingleAssignmentConstraints(TargetElementType,
11994                                          ElementResult,
11995                                          false, false)
11996         != Sema::Compatible) {
11997     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
11998         << ElementType << ElementKind << TargetElementType
11999         << Element->getSourceRange();
12000   }
12001 
12002   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
12003     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
12004   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
12005     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
12006 }
12007 
12008 /// Check an Objective-C array literal being converted to the given
12009 /// target type.
12010 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12011                                   ObjCArrayLiteral *ArrayLiteral) {
12012   if (!S.NSArrayDecl)
12013     return;
12014 
12015   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12016   if (!TargetObjCPtr)
12017     return;
12018 
12019   if (TargetObjCPtr->isUnspecialized() ||
12020       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12021         != S.NSArrayDecl->getCanonicalDecl())
12022     return;
12023 
12024   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12025   if (TypeArgs.size() != 1)
12026     return;
12027 
12028   QualType TargetElementType = TypeArgs[0];
12029   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
12030     checkObjCCollectionLiteralElement(S, TargetElementType,
12031                                       ArrayLiteral->getElement(I),
12032                                       0);
12033   }
12034 }
12035 
12036 /// Check an Objective-C dictionary literal being converted to the given
12037 /// target type.
12038 static void
12039 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12040                            ObjCDictionaryLiteral *DictionaryLiteral) {
12041   if (!S.NSDictionaryDecl)
12042     return;
12043 
12044   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12045   if (!TargetObjCPtr)
12046     return;
12047 
12048   if (TargetObjCPtr->isUnspecialized() ||
12049       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12050         != S.NSDictionaryDecl->getCanonicalDecl())
12051     return;
12052 
12053   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12054   if (TypeArgs.size() != 2)
12055     return;
12056 
12057   QualType TargetKeyType = TypeArgs[0];
12058   QualType TargetObjectType = TypeArgs[1];
12059   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
12060     auto Element = DictionaryLiteral->getKeyValueElement(I);
12061     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
12062     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
12063   }
12064 }
12065 
12066 // Helper function to filter out cases for constant width constant conversion.
12067 // Don't warn on char array initialization or for non-decimal values.
12068 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
12069                                           SourceLocation CC) {
12070   // If initializing from a constant, and the constant starts with '0',
12071   // then it is a binary, octal, or hexadecimal.  Allow these constants
12072   // to fill all the bits, even if there is a sign change.
12073   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
12074     const char FirstLiteralCharacter =
12075         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
12076     if (FirstLiteralCharacter == '0')
12077       return false;
12078   }
12079 
12080   // If the CC location points to a '{', and the type is char, then assume
12081   // assume it is an array initialization.
12082   if (CC.isValid() && T->isCharType()) {
12083     const char FirstContextCharacter =
12084         S.getSourceManager().getCharacterData(CC)[0];
12085     if (FirstContextCharacter == '{')
12086       return false;
12087   }
12088 
12089   return true;
12090 }
12091 
12092 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
12093   const auto *IL = dyn_cast<IntegerLiteral>(E);
12094   if (!IL) {
12095     if (auto *UO = dyn_cast<UnaryOperator>(E)) {
12096       if (UO->getOpcode() == UO_Minus)
12097         return dyn_cast<IntegerLiteral>(UO->getSubExpr());
12098     }
12099   }
12100 
12101   return IL;
12102 }
12103 
12104 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
12105   E = E->IgnoreParenImpCasts();
12106   SourceLocation ExprLoc = E->getExprLoc();
12107 
12108   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
12109     BinaryOperator::Opcode Opc = BO->getOpcode();
12110     Expr::EvalResult Result;
12111     // Do not diagnose unsigned shifts.
12112     if (Opc == BO_Shl) {
12113       const auto *LHS = getIntegerLiteral(BO->getLHS());
12114       const auto *RHS = getIntegerLiteral(BO->getRHS());
12115       if (LHS && LHS->getValue() == 0)
12116         S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
12117       else if (!E->isValueDependent() && LHS && RHS &&
12118                RHS->getValue().isNonNegative() &&
12119                E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
12120         S.Diag(ExprLoc, diag::warn_left_shift_always)
12121             << (Result.Val.getInt() != 0);
12122       else if (E->getType()->isSignedIntegerType())
12123         S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
12124     }
12125   }
12126 
12127   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
12128     const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
12129     const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
12130     if (!LHS || !RHS)
12131       return;
12132     if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
12133         (RHS->getValue() == 0 || RHS->getValue() == 1))
12134       // Do not diagnose common idioms.
12135       return;
12136     if (LHS->getValue() != 0 && RHS->getValue() != 0)
12137       S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
12138   }
12139 }
12140 
12141 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
12142                                     SourceLocation CC,
12143                                     bool *ICContext = nullptr,
12144                                     bool IsListInit = false) {
12145   if (E->isTypeDependent() || E->isValueDependent()) return;
12146 
12147   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
12148   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
12149   if (Source == Target) return;
12150   if (Target->isDependentType()) return;
12151 
12152   // If the conversion context location is invalid don't complain. We also
12153   // don't want to emit a warning if the issue occurs from the expansion of
12154   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
12155   // delay this check as long as possible. Once we detect we are in that
12156   // scenario, we just return.
12157   if (CC.isInvalid())
12158     return;
12159 
12160   if (Source->isAtomicType())
12161     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
12162 
12163   // Diagnose implicit casts to bool.
12164   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
12165     if (isa<StringLiteral>(E))
12166       // Warn on string literal to bool.  Checks for string literals in logical
12167       // and expressions, for instance, assert(0 && "error here"), are
12168       // prevented by a check in AnalyzeImplicitConversions().
12169       return DiagnoseImpCast(S, E, T, CC,
12170                              diag::warn_impcast_string_literal_to_bool);
12171     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
12172         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
12173       // This covers the literal expressions that evaluate to Objective-C
12174       // objects.
12175       return DiagnoseImpCast(S, E, T, CC,
12176                              diag::warn_impcast_objective_c_literal_to_bool);
12177     }
12178     if (Source->isPointerType() || Source->canDecayToPointerType()) {
12179       // Warn on pointer to bool conversion that is always true.
12180       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
12181                                      SourceRange(CC));
12182     }
12183   }
12184 
12185   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
12186   // is a typedef for signed char (macOS), then that constant value has to be 1
12187   // or 0.
12188   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
12189     Expr::EvalResult Result;
12190     if (E->EvaluateAsInt(Result, S.getASTContext(),
12191                          Expr::SE_AllowSideEffects)) {
12192       if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
12193         adornObjCBoolConversionDiagWithTernaryFixit(
12194             S, E,
12195             S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
12196                 << Result.Val.getInt().toString(10));
12197       }
12198       return;
12199     }
12200   }
12201 
12202   // Check implicit casts from Objective-C collection literals to specialized
12203   // collection types, e.g., NSArray<NSString *> *.
12204   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
12205     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
12206   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
12207     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
12208 
12209   // Strip vector types.
12210   if (const auto *SourceVT = dyn_cast<VectorType>(Source)) {
12211     if (Target->isVLSTBuiltinType()) {
12212       auto SourceVectorKind = SourceVT->getVectorKind();
12213       if (SourceVectorKind == VectorType::SveFixedLengthDataVector ||
12214           SourceVectorKind == VectorType::SveFixedLengthPredicateVector ||
12215           (SourceVectorKind == VectorType::GenericVector &&
12216            S.Context.getTypeSize(Source) == S.getLangOpts().ArmSveVectorBits))
12217         return;
12218     }
12219 
12220     if (!isa<VectorType>(Target)) {
12221       if (S.SourceMgr.isInSystemMacro(CC))
12222         return;
12223       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
12224     }
12225 
12226     // If the vector cast is cast between two vectors of the same size, it is
12227     // a bitcast, not a conversion.
12228     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
12229       return;
12230 
12231     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
12232     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
12233   }
12234   if (auto VecTy = dyn_cast<VectorType>(Target))
12235     Target = VecTy->getElementType().getTypePtr();
12236 
12237   // Strip complex types.
12238   if (isa<ComplexType>(Source)) {
12239     if (!isa<ComplexType>(Target)) {
12240       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
12241         return;
12242 
12243       return DiagnoseImpCast(S, E, T, CC,
12244                              S.getLangOpts().CPlusPlus
12245                                  ? diag::err_impcast_complex_scalar
12246                                  : diag::warn_impcast_complex_scalar);
12247     }
12248 
12249     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
12250     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
12251   }
12252 
12253   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
12254   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
12255 
12256   // If the source is floating point...
12257   if (SourceBT && SourceBT->isFloatingPoint()) {
12258     // ...and the target is floating point...
12259     if (TargetBT && TargetBT->isFloatingPoint()) {
12260       // ...then warn if we're dropping FP rank.
12261 
12262       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12263           QualType(SourceBT, 0), QualType(TargetBT, 0));
12264       if (Order > 0) {
12265         // Don't warn about float constants that are precisely
12266         // representable in the target type.
12267         Expr::EvalResult result;
12268         if (E->EvaluateAsRValue(result, S.Context)) {
12269           // Value might be a float, a float vector, or a float complex.
12270           if (IsSameFloatAfterCast(result.Val,
12271                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
12272                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
12273             return;
12274         }
12275 
12276         if (S.SourceMgr.isInSystemMacro(CC))
12277           return;
12278 
12279         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
12280       }
12281       // ... or possibly if we're increasing rank, too
12282       else if (Order < 0) {
12283         if (S.SourceMgr.isInSystemMacro(CC))
12284           return;
12285 
12286         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
12287       }
12288       return;
12289     }
12290 
12291     // If the target is integral, always warn.
12292     if (TargetBT && TargetBT->isInteger()) {
12293       if (S.SourceMgr.isInSystemMacro(CC))
12294         return;
12295 
12296       DiagnoseFloatingImpCast(S, E, T, CC);
12297     }
12298 
12299     // Detect the case where a call result is converted from floating-point to
12300     // to bool, and the final argument to the call is converted from bool, to
12301     // discover this typo:
12302     //
12303     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
12304     //
12305     // FIXME: This is an incredibly special case; is there some more general
12306     // way to detect this class of misplaced-parentheses bug?
12307     if (Target->isBooleanType() && isa<CallExpr>(E)) {
12308       // Check last argument of function call to see if it is an
12309       // implicit cast from a type matching the type the result
12310       // is being cast to.
12311       CallExpr *CEx = cast<CallExpr>(E);
12312       if (unsigned NumArgs = CEx->getNumArgs()) {
12313         Expr *LastA = CEx->getArg(NumArgs - 1);
12314         Expr *InnerE = LastA->IgnoreParenImpCasts();
12315         if (isa<ImplicitCastExpr>(LastA) &&
12316             InnerE->getType()->isBooleanType()) {
12317           // Warn on this floating-point to bool conversion
12318           DiagnoseImpCast(S, E, T, CC,
12319                           diag::warn_impcast_floating_point_to_bool);
12320         }
12321       }
12322     }
12323     return;
12324   }
12325 
12326   // Valid casts involving fixed point types should be accounted for here.
12327   if (Source->isFixedPointType()) {
12328     if (Target->isUnsaturatedFixedPointType()) {
12329       Expr::EvalResult Result;
12330       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
12331                                   S.isConstantEvaluated())) {
12332         llvm::APFixedPoint Value = Result.Val.getFixedPoint();
12333         llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
12334         llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T);
12335         if (Value > MaxVal || Value < MinVal) {
12336           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12337                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12338                                     << Value.toString() << T
12339                                     << E->getSourceRange()
12340                                     << clang::SourceRange(CC));
12341           return;
12342         }
12343       }
12344     } else if (Target->isIntegerType()) {
12345       Expr::EvalResult Result;
12346       if (!S.isConstantEvaluated() &&
12347           E->EvaluateAsFixedPoint(Result, S.Context,
12348                                   Expr::SE_AllowSideEffects)) {
12349         llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
12350 
12351         bool Overflowed;
12352         llvm::APSInt IntResult = FXResult.convertToInt(
12353             S.Context.getIntWidth(T),
12354             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
12355 
12356         if (Overflowed) {
12357           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12358                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12359                                     << FXResult.toString() << T
12360                                     << E->getSourceRange()
12361                                     << clang::SourceRange(CC));
12362           return;
12363         }
12364       }
12365     }
12366   } else if (Target->isUnsaturatedFixedPointType()) {
12367     if (Source->isIntegerType()) {
12368       Expr::EvalResult Result;
12369       if (!S.isConstantEvaluated() &&
12370           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
12371         llvm::APSInt Value = Result.Val.getInt();
12372 
12373         bool Overflowed;
12374         llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
12375             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
12376 
12377         if (Overflowed) {
12378           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12379                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12380                                     << Value.toString(/*Radix=*/10) << T
12381                                     << E->getSourceRange()
12382                                     << clang::SourceRange(CC));
12383           return;
12384         }
12385       }
12386     }
12387   }
12388 
12389   // If we are casting an integer type to a floating point type without
12390   // initialization-list syntax, we might lose accuracy if the floating
12391   // point type has a narrower significand than the integer type.
12392   if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
12393       TargetBT->isFloatingType() && !IsListInit) {
12394     // Determine the number of precision bits in the source integer type.
12395     IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(),
12396                                         /*Approximate*/ true);
12397     unsigned int SourcePrecision = SourceRange.Width;
12398 
12399     // Determine the number of precision bits in the
12400     // target floating point type.
12401     unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
12402         S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12403 
12404     if (SourcePrecision > 0 && TargetPrecision > 0 &&
12405         SourcePrecision > TargetPrecision) {
12406 
12407       if (Optional<llvm::APSInt> SourceInt =
12408               E->getIntegerConstantExpr(S.Context)) {
12409         // If the source integer is a constant, convert it to the target
12410         // floating point type. Issue a warning if the value changes
12411         // during the whole conversion.
12412         llvm::APFloat TargetFloatValue(
12413             S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12414         llvm::APFloat::opStatus ConversionStatus =
12415             TargetFloatValue.convertFromAPInt(
12416                 *SourceInt, SourceBT->isSignedInteger(),
12417                 llvm::APFloat::rmNearestTiesToEven);
12418 
12419         if (ConversionStatus != llvm::APFloat::opOK) {
12420           std::string PrettySourceValue = SourceInt->toString(10);
12421           SmallString<32> PrettyTargetValue;
12422           TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
12423 
12424           S.DiagRuntimeBehavior(
12425               E->getExprLoc(), E,
12426               S.PDiag(diag::warn_impcast_integer_float_precision_constant)
12427                   << PrettySourceValue << PrettyTargetValue << E->getType() << T
12428                   << E->getSourceRange() << clang::SourceRange(CC));
12429         }
12430       } else {
12431         // Otherwise, the implicit conversion may lose precision.
12432         DiagnoseImpCast(S, E, T, CC,
12433                         diag::warn_impcast_integer_float_precision);
12434       }
12435     }
12436   }
12437 
12438   DiagnoseNullConversion(S, E, T, CC);
12439 
12440   S.DiscardMisalignedMemberAddress(Target, E);
12441 
12442   if (Target->isBooleanType())
12443     DiagnoseIntInBoolContext(S, E);
12444 
12445   if (!Source->isIntegerType() || !Target->isIntegerType())
12446     return;
12447 
12448   // TODO: remove this early return once the false positives for constant->bool
12449   // in templates, macros, etc, are reduced or removed.
12450   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
12451     return;
12452 
12453   if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
12454       !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
12455     return adornObjCBoolConversionDiagWithTernaryFixit(
12456         S, E,
12457         S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
12458             << E->getType());
12459   }
12460 
12461   IntRange SourceTypeRange =
12462       IntRange::forTargetOfCanonicalType(S.Context, Source);
12463   IntRange LikelySourceRange =
12464       GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true);
12465   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
12466 
12467   if (LikelySourceRange.Width > TargetRange.Width) {
12468     // If the source is a constant, use a default-on diagnostic.
12469     // TODO: this should happen for bitfield stores, too.
12470     Expr::EvalResult Result;
12471     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
12472                          S.isConstantEvaluated())) {
12473       llvm::APSInt Value(32);
12474       Value = Result.Val.getInt();
12475 
12476       if (S.SourceMgr.isInSystemMacro(CC))
12477         return;
12478 
12479       std::string PrettySourceValue = Value.toString(10);
12480       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
12481 
12482       S.DiagRuntimeBehavior(
12483           E->getExprLoc(), E,
12484           S.PDiag(diag::warn_impcast_integer_precision_constant)
12485               << PrettySourceValue << PrettyTargetValue << E->getType() << T
12486               << E->getSourceRange() << SourceRange(CC));
12487       return;
12488     }
12489 
12490     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
12491     if (S.SourceMgr.isInSystemMacro(CC))
12492       return;
12493 
12494     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
12495       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
12496                              /* pruneControlFlow */ true);
12497     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
12498   }
12499 
12500   if (TargetRange.Width > SourceTypeRange.Width) {
12501     if (auto *UO = dyn_cast<UnaryOperator>(E))
12502       if (UO->getOpcode() == UO_Minus)
12503         if (Source->isUnsignedIntegerType()) {
12504           if (Target->isUnsignedIntegerType())
12505             return DiagnoseImpCast(S, E, T, CC,
12506                                    diag::warn_impcast_high_order_zero_bits);
12507           if (Target->isSignedIntegerType())
12508             return DiagnoseImpCast(S, E, T, CC,
12509                                    diag::warn_impcast_nonnegative_result);
12510         }
12511   }
12512 
12513   if (TargetRange.Width == LikelySourceRange.Width &&
12514       !TargetRange.NonNegative && LikelySourceRange.NonNegative &&
12515       Source->isSignedIntegerType()) {
12516     // Warn when doing a signed to signed conversion, warn if the positive
12517     // source value is exactly the width of the target type, which will
12518     // cause a negative value to be stored.
12519 
12520     Expr::EvalResult Result;
12521     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
12522         !S.SourceMgr.isInSystemMacro(CC)) {
12523       llvm::APSInt Value = Result.Val.getInt();
12524       if (isSameWidthConstantConversion(S, E, T, CC)) {
12525         std::string PrettySourceValue = Value.toString(10);
12526         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
12527 
12528         S.DiagRuntimeBehavior(
12529             E->getExprLoc(), E,
12530             S.PDiag(diag::warn_impcast_integer_precision_constant)
12531                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
12532                 << E->getSourceRange() << SourceRange(CC));
12533         return;
12534       }
12535     }
12536 
12537     // Fall through for non-constants to give a sign conversion warning.
12538   }
12539 
12540   if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) ||
12541       (!TargetRange.NonNegative && LikelySourceRange.NonNegative &&
12542        LikelySourceRange.Width == TargetRange.Width)) {
12543     if (S.SourceMgr.isInSystemMacro(CC))
12544       return;
12545 
12546     unsigned DiagID = diag::warn_impcast_integer_sign;
12547 
12548     // Traditionally, gcc has warned about this under -Wsign-compare.
12549     // We also want to warn about it in -Wconversion.
12550     // So if -Wconversion is off, use a completely identical diagnostic
12551     // in the sign-compare group.
12552     // The conditional-checking code will
12553     if (ICContext) {
12554       DiagID = diag::warn_impcast_integer_sign_conditional;
12555       *ICContext = true;
12556     }
12557 
12558     return DiagnoseImpCast(S, E, T, CC, DiagID);
12559   }
12560 
12561   // Diagnose conversions between different enumeration types.
12562   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
12563   // type, to give us better diagnostics.
12564   QualType SourceType = E->getType();
12565   if (!S.getLangOpts().CPlusPlus) {
12566     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12567       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
12568         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
12569         SourceType = S.Context.getTypeDeclType(Enum);
12570         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
12571       }
12572   }
12573 
12574   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
12575     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
12576       if (SourceEnum->getDecl()->hasNameForLinkage() &&
12577           TargetEnum->getDecl()->hasNameForLinkage() &&
12578           SourceEnum != TargetEnum) {
12579         if (S.SourceMgr.isInSystemMacro(CC))
12580           return;
12581 
12582         return DiagnoseImpCast(S, E, SourceType, T, CC,
12583                                diag::warn_impcast_different_enum_types);
12584       }
12585 }
12586 
12587 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
12588                                      SourceLocation CC, QualType T);
12589 
12590 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
12591                                     SourceLocation CC, bool &ICContext) {
12592   E = E->IgnoreParenImpCasts();
12593 
12594   if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
12595     return CheckConditionalOperator(S, CO, CC, T);
12596 
12597   AnalyzeImplicitConversions(S, E, CC);
12598   if (E->getType() != T)
12599     return CheckImplicitConversion(S, E, T, CC, &ICContext);
12600 }
12601 
12602 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
12603                                      SourceLocation CC, QualType T) {
12604   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
12605 
12606   Expr *TrueExpr = E->getTrueExpr();
12607   if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
12608     TrueExpr = BCO->getCommon();
12609 
12610   bool Suspicious = false;
12611   CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
12612   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
12613 
12614   if (T->isBooleanType())
12615     DiagnoseIntInBoolContext(S, E);
12616 
12617   // If -Wconversion would have warned about either of the candidates
12618   // for a signedness conversion to the context type...
12619   if (!Suspicious) return;
12620 
12621   // ...but it's currently ignored...
12622   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
12623     return;
12624 
12625   // ...then check whether it would have warned about either of the
12626   // candidates for a signedness conversion to the condition type.
12627   if (E->getType() == T) return;
12628 
12629   Suspicious = false;
12630   CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(),
12631                           E->getType(), CC, &Suspicious);
12632   if (!Suspicious)
12633     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
12634                             E->getType(), CC, &Suspicious);
12635 }
12636 
12637 /// Check conversion of given expression to boolean.
12638 /// Input argument E is a logical expression.
12639 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
12640   if (S.getLangOpts().Bool)
12641     return;
12642   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
12643     return;
12644   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
12645 }
12646 
12647 namespace {
12648 struct AnalyzeImplicitConversionsWorkItem {
12649   Expr *E;
12650   SourceLocation CC;
12651   bool IsListInit;
12652 };
12653 }
12654 
12655 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
12656 /// that should be visited are added to WorkList.
12657 static void AnalyzeImplicitConversions(
12658     Sema &S, AnalyzeImplicitConversionsWorkItem Item,
12659     llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
12660   Expr *OrigE = Item.E;
12661   SourceLocation CC = Item.CC;
12662 
12663   QualType T = OrigE->getType();
12664   Expr *E = OrigE->IgnoreParenImpCasts();
12665 
12666   // Propagate whether we are in a C++ list initialization expression.
12667   // If so, we do not issue warnings for implicit int-float conversion
12668   // precision loss, because C++11 narrowing already handles it.
12669   bool IsListInit = Item.IsListInit ||
12670                     (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
12671 
12672   if (E->isTypeDependent() || E->isValueDependent())
12673     return;
12674 
12675   Expr *SourceExpr = E;
12676   // Examine, but don't traverse into the source expression of an
12677   // OpaqueValueExpr, since it may have multiple parents and we don't want to
12678   // emit duplicate diagnostics. Its fine to examine the form or attempt to
12679   // evaluate it in the context of checking the specific conversion to T though.
12680   if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
12681     if (auto *Src = OVE->getSourceExpr())
12682       SourceExpr = Src;
12683 
12684   if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
12685     if (UO->getOpcode() == UO_Not &&
12686         UO->getSubExpr()->isKnownToHaveBooleanValue())
12687       S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
12688           << OrigE->getSourceRange() << T->isBooleanType()
12689           << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
12690 
12691   // For conditional operators, we analyze the arguments as if they
12692   // were being fed directly into the output.
12693   if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
12694     CheckConditionalOperator(S, CO, CC, T);
12695     return;
12696   }
12697 
12698   // Check implicit argument conversions for function calls.
12699   if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
12700     CheckImplicitArgumentConversions(S, Call, CC);
12701 
12702   // Go ahead and check any implicit conversions we might have skipped.
12703   // The non-canonical typecheck is just an optimization;
12704   // CheckImplicitConversion will filter out dead implicit conversions.
12705   if (SourceExpr->getType() != T)
12706     CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit);
12707 
12708   // Now continue drilling into this expression.
12709 
12710   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
12711     // The bound subexpressions in a PseudoObjectExpr are not reachable
12712     // as transitive children.
12713     // FIXME: Use a more uniform representation for this.
12714     for (auto *SE : POE->semantics())
12715       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
12716         WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
12717   }
12718 
12719   // Skip past explicit casts.
12720   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
12721     E = CE->getSubExpr()->IgnoreParenImpCasts();
12722     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
12723       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12724     WorkList.push_back({E, CC, IsListInit});
12725     return;
12726   }
12727 
12728   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12729     // Do a somewhat different check with comparison operators.
12730     if (BO->isComparisonOp())
12731       return AnalyzeComparison(S, BO);
12732 
12733     // And with simple assignments.
12734     if (BO->getOpcode() == BO_Assign)
12735       return AnalyzeAssignment(S, BO);
12736     // And with compound assignments.
12737     if (BO->isAssignmentOp())
12738       return AnalyzeCompoundAssignment(S, BO);
12739   }
12740 
12741   // These break the otherwise-useful invariant below.  Fortunately,
12742   // we don't really need to recurse into them, because any internal
12743   // expressions should have been analyzed already when they were
12744   // built into statements.
12745   if (isa<StmtExpr>(E)) return;
12746 
12747   // Don't descend into unevaluated contexts.
12748   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
12749 
12750   // Now just recurse over the expression's children.
12751   CC = E->getExprLoc();
12752   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
12753   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
12754   for (Stmt *SubStmt : E->children()) {
12755     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
12756     if (!ChildExpr)
12757       continue;
12758 
12759     if (IsLogicalAndOperator &&
12760         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
12761       // Ignore checking string literals that are in logical and operators.
12762       // This is a common pattern for asserts.
12763       continue;
12764     WorkList.push_back({ChildExpr, CC, IsListInit});
12765   }
12766 
12767   if (BO && BO->isLogicalOp()) {
12768     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
12769     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
12770       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
12771 
12772     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
12773     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
12774       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
12775   }
12776 
12777   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
12778     if (U->getOpcode() == UO_LNot) {
12779       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
12780     } else if (U->getOpcode() != UO_AddrOf) {
12781       if (U->getSubExpr()->getType()->isAtomicType())
12782         S.Diag(U->getSubExpr()->getBeginLoc(),
12783                diag::warn_atomic_implicit_seq_cst);
12784     }
12785   }
12786 }
12787 
12788 /// AnalyzeImplicitConversions - Find and report any interesting
12789 /// implicit conversions in the given expression.  There are a couple
12790 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
12791 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
12792                                        bool IsListInit/*= false*/) {
12793   llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
12794   WorkList.push_back({OrigE, CC, IsListInit});
12795   while (!WorkList.empty())
12796     AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
12797 }
12798 
12799 /// Diagnose integer type and any valid implicit conversion to it.
12800 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
12801   // Taking into account implicit conversions,
12802   // allow any integer.
12803   if (!E->getType()->isIntegerType()) {
12804     S.Diag(E->getBeginLoc(),
12805            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
12806     return true;
12807   }
12808   // Potentially emit standard warnings for implicit conversions if enabled
12809   // using -Wconversion.
12810   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
12811   return false;
12812 }
12813 
12814 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
12815 // Returns true when emitting a warning about taking the address of a reference.
12816 static bool CheckForReference(Sema &SemaRef, const Expr *E,
12817                               const PartialDiagnostic &PD) {
12818   E = E->IgnoreParenImpCasts();
12819 
12820   const FunctionDecl *FD = nullptr;
12821 
12822   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12823     if (!DRE->getDecl()->getType()->isReferenceType())
12824       return false;
12825   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
12826     if (!M->getMemberDecl()->getType()->isReferenceType())
12827       return false;
12828   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
12829     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
12830       return false;
12831     FD = Call->getDirectCallee();
12832   } else {
12833     return false;
12834   }
12835 
12836   SemaRef.Diag(E->getExprLoc(), PD);
12837 
12838   // If possible, point to location of function.
12839   if (FD) {
12840     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
12841   }
12842 
12843   return true;
12844 }
12845 
12846 // Returns true if the SourceLocation is expanded from any macro body.
12847 // Returns false if the SourceLocation is invalid, is from not in a macro
12848 // expansion, or is from expanded from a top-level macro argument.
12849 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
12850   if (Loc.isInvalid())
12851     return false;
12852 
12853   while (Loc.isMacroID()) {
12854     if (SM.isMacroBodyExpansion(Loc))
12855       return true;
12856     Loc = SM.getImmediateMacroCallerLoc(Loc);
12857   }
12858 
12859   return false;
12860 }
12861 
12862 /// Diagnose pointers that are always non-null.
12863 /// \param E the expression containing the pointer
12864 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
12865 /// compared to a null pointer
12866 /// \param IsEqual True when the comparison is equal to a null pointer
12867 /// \param Range Extra SourceRange to highlight in the diagnostic
12868 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
12869                                         Expr::NullPointerConstantKind NullKind,
12870                                         bool IsEqual, SourceRange Range) {
12871   if (!E)
12872     return;
12873 
12874   // Don't warn inside macros.
12875   if (E->getExprLoc().isMacroID()) {
12876     const SourceManager &SM = getSourceManager();
12877     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
12878         IsInAnyMacroBody(SM, Range.getBegin()))
12879       return;
12880   }
12881   E = E->IgnoreImpCasts();
12882 
12883   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
12884 
12885   if (isa<CXXThisExpr>(E)) {
12886     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
12887                                 : diag::warn_this_bool_conversion;
12888     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
12889     return;
12890   }
12891 
12892   bool IsAddressOf = false;
12893 
12894   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
12895     if (UO->getOpcode() != UO_AddrOf)
12896       return;
12897     IsAddressOf = true;
12898     E = UO->getSubExpr();
12899   }
12900 
12901   if (IsAddressOf) {
12902     unsigned DiagID = IsCompare
12903                           ? diag::warn_address_of_reference_null_compare
12904                           : diag::warn_address_of_reference_bool_conversion;
12905     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
12906                                          << IsEqual;
12907     if (CheckForReference(*this, E, PD)) {
12908       return;
12909     }
12910   }
12911 
12912   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
12913     bool IsParam = isa<NonNullAttr>(NonnullAttr);
12914     std::string Str;
12915     llvm::raw_string_ostream S(Str);
12916     E->printPretty(S, nullptr, getPrintingPolicy());
12917     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
12918                                 : diag::warn_cast_nonnull_to_bool;
12919     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
12920       << E->getSourceRange() << Range << IsEqual;
12921     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
12922   };
12923 
12924   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
12925   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
12926     if (auto *Callee = Call->getDirectCallee()) {
12927       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
12928         ComplainAboutNonnullParamOrCall(A);
12929         return;
12930       }
12931     }
12932   }
12933 
12934   // Expect to find a single Decl.  Skip anything more complicated.
12935   ValueDecl *D = nullptr;
12936   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
12937     D = R->getDecl();
12938   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
12939     D = M->getMemberDecl();
12940   }
12941 
12942   // Weak Decls can be null.
12943   if (!D || D->isWeak())
12944     return;
12945 
12946   // Check for parameter decl with nonnull attribute
12947   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
12948     if (getCurFunction() &&
12949         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
12950       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
12951         ComplainAboutNonnullParamOrCall(A);
12952         return;
12953       }
12954 
12955       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
12956         // Skip function template not specialized yet.
12957         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
12958           return;
12959         auto ParamIter = llvm::find(FD->parameters(), PV);
12960         assert(ParamIter != FD->param_end());
12961         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
12962 
12963         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
12964           if (!NonNull->args_size()) {
12965               ComplainAboutNonnullParamOrCall(NonNull);
12966               return;
12967           }
12968 
12969           for (const ParamIdx &ArgNo : NonNull->args()) {
12970             if (ArgNo.getASTIndex() == ParamNo) {
12971               ComplainAboutNonnullParamOrCall(NonNull);
12972               return;
12973             }
12974           }
12975         }
12976       }
12977     }
12978   }
12979 
12980   QualType T = D->getType();
12981   const bool IsArray = T->isArrayType();
12982   const bool IsFunction = T->isFunctionType();
12983 
12984   // Address of function is used to silence the function warning.
12985   if (IsAddressOf && IsFunction) {
12986     return;
12987   }
12988 
12989   // Found nothing.
12990   if (!IsAddressOf && !IsFunction && !IsArray)
12991     return;
12992 
12993   // Pretty print the expression for the diagnostic.
12994   std::string Str;
12995   llvm::raw_string_ostream S(Str);
12996   E->printPretty(S, nullptr, getPrintingPolicy());
12997 
12998   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
12999                               : diag::warn_impcast_pointer_to_bool;
13000   enum {
13001     AddressOf,
13002     FunctionPointer,
13003     ArrayPointer
13004   } DiagType;
13005   if (IsAddressOf)
13006     DiagType = AddressOf;
13007   else if (IsFunction)
13008     DiagType = FunctionPointer;
13009   else if (IsArray)
13010     DiagType = ArrayPointer;
13011   else
13012     llvm_unreachable("Could not determine diagnostic.");
13013   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
13014                                 << Range << IsEqual;
13015 
13016   if (!IsFunction)
13017     return;
13018 
13019   // Suggest '&' to silence the function warning.
13020   Diag(E->getExprLoc(), diag::note_function_warning_silence)
13021       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
13022 
13023   // Check to see if '()' fixit should be emitted.
13024   QualType ReturnType;
13025   UnresolvedSet<4> NonTemplateOverloads;
13026   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
13027   if (ReturnType.isNull())
13028     return;
13029 
13030   if (IsCompare) {
13031     // There are two cases here.  If there is null constant, the only suggest
13032     // for a pointer return type.  If the null is 0, then suggest if the return
13033     // type is a pointer or an integer type.
13034     if (!ReturnType->isPointerType()) {
13035       if (NullKind == Expr::NPCK_ZeroExpression ||
13036           NullKind == Expr::NPCK_ZeroLiteral) {
13037         if (!ReturnType->isIntegerType())
13038           return;
13039       } else {
13040         return;
13041       }
13042     }
13043   } else { // !IsCompare
13044     // For function to bool, only suggest if the function pointer has bool
13045     // return type.
13046     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
13047       return;
13048   }
13049   Diag(E->getExprLoc(), diag::note_function_to_function_call)
13050       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
13051 }
13052 
13053 /// Diagnoses "dangerous" implicit conversions within the given
13054 /// expression (which is a full expression).  Implements -Wconversion
13055 /// and -Wsign-compare.
13056 ///
13057 /// \param CC the "context" location of the implicit conversion, i.e.
13058 ///   the most location of the syntactic entity requiring the implicit
13059 ///   conversion
13060 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
13061   // Don't diagnose in unevaluated contexts.
13062   if (isUnevaluatedContext())
13063     return;
13064 
13065   // Don't diagnose for value- or type-dependent expressions.
13066   if (E->isTypeDependent() || E->isValueDependent())
13067     return;
13068 
13069   // Check for array bounds violations in cases where the check isn't triggered
13070   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
13071   // ArraySubscriptExpr is on the RHS of a variable initialization.
13072   CheckArrayAccess(E);
13073 
13074   // This is not the right CC for (e.g.) a variable initialization.
13075   AnalyzeImplicitConversions(*this, E, CC);
13076 }
13077 
13078 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
13079 /// Input argument E is a logical expression.
13080 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
13081   ::CheckBoolLikeConversion(*this, E, CC);
13082 }
13083 
13084 /// Diagnose when expression is an integer constant expression and its evaluation
13085 /// results in integer overflow
13086 void Sema::CheckForIntOverflow (Expr *E) {
13087   // Use a work list to deal with nested struct initializers.
13088   SmallVector<Expr *, 2> Exprs(1, E);
13089 
13090   do {
13091     Expr *OriginalE = Exprs.pop_back_val();
13092     Expr *E = OriginalE->IgnoreParenCasts();
13093 
13094     if (isa<BinaryOperator>(E)) {
13095       E->EvaluateForOverflow(Context);
13096       continue;
13097     }
13098 
13099     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
13100       Exprs.append(InitList->inits().begin(), InitList->inits().end());
13101     else if (isa<ObjCBoxedExpr>(OriginalE))
13102       E->EvaluateForOverflow(Context);
13103     else if (auto Call = dyn_cast<CallExpr>(E))
13104       Exprs.append(Call->arg_begin(), Call->arg_end());
13105     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
13106       Exprs.append(Message->arg_begin(), Message->arg_end());
13107   } while (!Exprs.empty());
13108 }
13109 
13110 namespace {
13111 
13112 /// Visitor for expressions which looks for unsequenced operations on the
13113 /// same object.
13114 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
13115   using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
13116 
13117   /// A tree of sequenced regions within an expression. Two regions are
13118   /// unsequenced if one is an ancestor or a descendent of the other. When we
13119   /// finish processing an expression with sequencing, such as a comma
13120   /// expression, we fold its tree nodes into its parent, since they are
13121   /// unsequenced with respect to nodes we will visit later.
13122   class SequenceTree {
13123     struct Value {
13124       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
13125       unsigned Parent : 31;
13126       unsigned Merged : 1;
13127     };
13128     SmallVector<Value, 8> Values;
13129 
13130   public:
13131     /// A region within an expression which may be sequenced with respect
13132     /// to some other region.
13133     class Seq {
13134       friend class SequenceTree;
13135 
13136       unsigned Index;
13137 
13138       explicit Seq(unsigned N) : Index(N) {}
13139 
13140     public:
13141       Seq() : Index(0) {}
13142     };
13143 
13144     SequenceTree() { Values.push_back(Value(0)); }
13145     Seq root() const { return Seq(0); }
13146 
13147     /// Create a new sequence of operations, which is an unsequenced
13148     /// subset of \p Parent. This sequence of operations is sequenced with
13149     /// respect to other children of \p Parent.
13150     Seq allocate(Seq Parent) {
13151       Values.push_back(Value(Parent.Index));
13152       return Seq(Values.size() - 1);
13153     }
13154 
13155     /// Merge a sequence of operations into its parent.
13156     void merge(Seq S) {
13157       Values[S.Index].Merged = true;
13158     }
13159 
13160     /// Determine whether two operations are unsequenced. This operation
13161     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
13162     /// should have been merged into its parent as appropriate.
13163     bool isUnsequenced(Seq Cur, Seq Old) {
13164       unsigned C = representative(Cur.Index);
13165       unsigned Target = representative(Old.Index);
13166       while (C >= Target) {
13167         if (C == Target)
13168           return true;
13169         C = Values[C].Parent;
13170       }
13171       return false;
13172     }
13173 
13174   private:
13175     /// Pick a representative for a sequence.
13176     unsigned representative(unsigned K) {
13177       if (Values[K].Merged)
13178         // Perform path compression as we go.
13179         return Values[K].Parent = representative(Values[K].Parent);
13180       return K;
13181     }
13182   };
13183 
13184   /// An object for which we can track unsequenced uses.
13185   using Object = const NamedDecl *;
13186 
13187   /// Different flavors of object usage which we track. We only track the
13188   /// least-sequenced usage of each kind.
13189   enum UsageKind {
13190     /// A read of an object. Multiple unsequenced reads are OK.
13191     UK_Use,
13192 
13193     /// A modification of an object which is sequenced before the value
13194     /// computation of the expression, such as ++n in C++.
13195     UK_ModAsValue,
13196 
13197     /// A modification of an object which is not sequenced before the value
13198     /// computation of the expression, such as n++.
13199     UK_ModAsSideEffect,
13200 
13201     UK_Count = UK_ModAsSideEffect + 1
13202   };
13203 
13204   /// Bundle together a sequencing region and the expression corresponding
13205   /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
13206   struct Usage {
13207     const Expr *UsageExpr;
13208     SequenceTree::Seq Seq;
13209 
13210     Usage() : UsageExpr(nullptr), Seq() {}
13211   };
13212 
13213   struct UsageInfo {
13214     Usage Uses[UK_Count];
13215 
13216     /// Have we issued a diagnostic for this object already?
13217     bool Diagnosed;
13218 
13219     UsageInfo() : Uses(), Diagnosed(false) {}
13220   };
13221   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
13222 
13223   Sema &SemaRef;
13224 
13225   /// Sequenced regions within the expression.
13226   SequenceTree Tree;
13227 
13228   /// Declaration modifications and references which we have seen.
13229   UsageInfoMap UsageMap;
13230 
13231   /// The region we are currently within.
13232   SequenceTree::Seq Region;
13233 
13234   /// Filled in with declarations which were modified as a side-effect
13235   /// (that is, post-increment operations).
13236   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
13237 
13238   /// Expressions to check later. We defer checking these to reduce
13239   /// stack usage.
13240   SmallVectorImpl<const Expr *> &WorkList;
13241 
13242   /// RAII object wrapping the visitation of a sequenced subexpression of an
13243   /// expression. At the end of this process, the side-effects of the evaluation
13244   /// become sequenced with respect to the value computation of the result, so
13245   /// we downgrade any UK_ModAsSideEffect within the evaluation to
13246   /// UK_ModAsValue.
13247   struct SequencedSubexpression {
13248     SequencedSubexpression(SequenceChecker &Self)
13249       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
13250       Self.ModAsSideEffect = &ModAsSideEffect;
13251     }
13252 
13253     ~SequencedSubexpression() {
13254       for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
13255         // Add a new usage with usage kind UK_ModAsValue, and then restore
13256         // the previous usage with UK_ModAsSideEffect (thus clearing it if
13257         // the previous one was empty).
13258         UsageInfo &UI = Self.UsageMap[M.first];
13259         auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
13260         Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
13261         SideEffectUsage = M.second;
13262       }
13263       Self.ModAsSideEffect = OldModAsSideEffect;
13264     }
13265 
13266     SequenceChecker &Self;
13267     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
13268     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
13269   };
13270 
13271   /// RAII object wrapping the visitation of a subexpression which we might
13272   /// choose to evaluate as a constant. If any subexpression is evaluated and
13273   /// found to be non-constant, this allows us to suppress the evaluation of
13274   /// the outer expression.
13275   class EvaluationTracker {
13276   public:
13277     EvaluationTracker(SequenceChecker &Self)
13278         : Self(Self), Prev(Self.EvalTracker) {
13279       Self.EvalTracker = this;
13280     }
13281 
13282     ~EvaluationTracker() {
13283       Self.EvalTracker = Prev;
13284       if (Prev)
13285         Prev->EvalOK &= EvalOK;
13286     }
13287 
13288     bool evaluate(const Expr *E, bool &Result) {
13289       if (!EvalOK || E->isValueDependent())
13290         return false;
13291       EvalOK = E->EvaluateAsBooleanCondition(
13292           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
13293       return EvalOK;
13294     }
13295 
13296   private:
13297     SequenceChecker &Self;
13298     EvaluationTracker *Prev;
13299     bool EvalOK = true;
13300   } *EvalTracker = nullptr;
13301 
13302   /// Find the object which is produced by the specified expression,
13303   /// if any.
13304   Object getObject(const Expr *E, bool Mod) const {
13305     E = E->IgnoreParenCasts();
13306     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13307       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
13308         return getObject(UO->getSubExpr(), Mod);
13309     } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13310       if (BO->getOpcode() == BO_Comma)
13311         return getObject(BO->getRHS(), Mod);
13312       if (Mod && BO->isAssignmentOp())
13313         return getObject(BO->getLHS(), Mod);
13314     } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13315       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
13316       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
13317         return ME->getMemberDecl();
13318     } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13319       // FIXME: If this is a reference, map through to its value.
13320       return DRE->getDecl();
13321     return nullptr;
13322   }
13323 
13324   /// Note that an object \p O was modified or used by an expression
13325   /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
13326   /// the object \p O as obtained via the \p UsageMap.
13327   void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
13328     // Get the old usage for the given object and usage kind.
13329     Usage &U = UI.Uses[UK];
13330     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
13331       // If we have a modification as side effect and are in a sequenced
13332       // subexpression, save the old Usage so that we can restore it later
13333       // in SequencedSubexpression::~SequencedSubexpression.
13334       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
13335         ModAsSideEffect->push_back(std::make_pair(O, U));
13336       // Then record the new usage with the current sequencing region.
13337       U.UsageExpr = UsageExpr;
13338       U.Seq = Region;
13339     }
13340   }
13341 
13342   /// Check whether a modification or use of an object \p O in an expression
13343   /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
13344   /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
13345   /// \p IsModMod is true when we are checking for a mod-mod unsequenced
13346   /// usage and false we are checking for a mod-use unsequenced usage.
13347   void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
13348                   UsageKind OtherKind, bool IsModMod) {
13349     if (UI.Diagnosed)
13350       return;
13351 
13352     const Usage &U = UI.Uses[OtherKind];
13353     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
13354       return;
13355 
13356     const Expr *Mod = U.UsageExpr;
13357     const Expr *ModOrUse = UsageExpr;
13358     if (OtherKind == UK_Use)
13359       std::swap(Mod, ModOrUse);
13360 
13361     SemaRef.DiagRuntimeBehavior(
13362         Mod->getExprLoc(), {Mod, ModOrUse},
13363         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
13364                                : diag::warn_unsequenced_mod_use)
13365             << O << SourceRange(ModOrUse->getExprLoc()));
13366     UI.Diagnosed = true;
13367   }
13368 
13369   // A note on note{Pre, Post}{Use, Mod}:
13370   //
13371   // (It helps to follow the algorithm with an expression such as
13372   //  "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
13373   //  operations before C++17 and both are well-defined in C++17).
13374   //
13375   // When visiting a node which uses/modify an object we first call notePreUse
13376   // or notePreMod before visiting its sub-expression(s). At this point the
13377   // children of the current node have not yet been visited and so the eventual
13378   // uses/modifications resulting from the children of the current node have not
13379   // been recorded yet.
13380   //
13381   // We then visit the children of the current node. After that notePostUse or
13382   // notePostMod is called. These will 1) detect an unsequenced modification
13383   // as side effect (as in "k++ + k") and 2) add a new usage with the
13384   // appropriate usage kind.
13385   //
13386   // We also have to be careful that some operation sequences modification as
13387   // side effect as well (for example: || or ,). To account for this we wrap
13388   // the visitation of such a sub-expression (for example: the LHS of || or ,)
13389   // with SequencedSubexpression. SequencedSubexpression is an RAII object
13390   // which record usages which are modifications as side effect, and then
13391   // downgrade them (or more accurately restore the previous usage which was a
13392   // modification as side effect) when exiting the scope of the sequenced
13393   // subexpression.
13394 
13395   void notePreUse(Object O, const Expr *UseExpr) {
13396     UsageInfo &UI = UsageMap[O];
13397     // Uses conflict with other modifications.
13398     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
13399   }
13400 
13401   void notePostUse(Object O, const Expr *UseExpr) {
13402     UsageInfo &UI = UsageMap[O];
13403     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
13404                /*IsModMod=*/false);
13405     addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
13406   }
13407 
13408   void notePreMod(Object O, const Expr *ModExpr) {
13409     UsageInfo &UI = UsageMap[O];
13410     // Modifications conflict with other modifications and with uses.
13411     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
13412     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
13413   }
13414 
13415   void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
13416     UsageInfo &UI = UsageMap[O];
13417     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
13418                /*IsModMod=*/true);
13419     addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
13420   }
13421 
13422 public:
13423   SequenceChecker(Sema &S, const Expr *E,
13424                   SmallVectorImpl<const Expr *> &WorkList)
13425       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
13426     Visit(E);
13427     // Silence a -Wunused-private-field since WorkList is now unused.
13428     // TODO: Evaluate if it can be used, and if not remove it.
13429     (void)this->WorkList;
13430   }
13431 
13432   void VisitStmt(const Stmt *S) {
13433     // Skip all statements which aren't expressions for now.
13434   }
13435 
13436   void VisitExpr(const Expr *E) {
13437     // By default, just recurse to evaluated subexpressions.
13438     Base::VisitStmt(E);
13439   }
13440 
13441   void VisitCastExpr(const CastExpr *E) {
13442     Object O = Object();
13443     if (E->getCastKind() == CK_LValueToRValue)
13444       O = getObject(E->getSubExpr(), false);
13445 
13446     if (O)
13447       notePreUse(O, E);
13448     VisitExpr(E);
13449     if (O)
13450       notePostUse(O, E);
13451   }
13452 
13453   void VisitSequencedExpressions(const Expr *SequencedBefore,
13454                                  const Expr *SequencedAfter) {
13455     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
13456     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
13457     SequenceTree::Seq OldRegion = Region;
13458 
13459     {
13460       SequencedSubexpression SeqBefore(*this);
13461       Region = BeforeRegion;
13462       Visit(SequencedBefore);
13463     }
13464 
13465     Region = AfterRegion;
13466     Visit(SequencedAfter);
13467 
13468     Region = OldRegion;
13469 
13470     Tree.merge(BeforeRegion);
13471     Tree.merge(AfterRegion);
13472   }
13473 
13474   void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
13475     // C++17 [expr.sub]p1:
13476     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
13477     //   expression E1 is sequenced before the expression E2.
13478     if (SemaRef.getLangOpts().CPlusPlus17)
13479       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
13480     else {
13481       Visit(ASE->getLHS());
13482       Visit(ASE->getRHS());
13483     }
13484   }
13485 
13486   void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
13487   void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
13488   void VisitBinPtrMem(const BinaryOperator *BO) {
13489     // C++17 [expr.mptr.oper]p4:
13490     //  Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
13491     //  the expression E1 is sequenced before the expression E2.
13492     if (SemaRef.getLangOpts().CPlusPlus17)
13493       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13494     else {
13495       Visit(BO->getLHS());
13496       Visit(BO->getRHS());
13497     }
13498   }
13499 
13500   void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
13501   void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
13502   void VisitBinShlShr(const BinaryOperator *BO) {
13503     // C++17 [expr.shift]p4:
13504     //  The expression E1 is sequenced before the expression E2.
13505     if (SemaRef.getLangOpts().CPlusPlus17)
13506       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13507     else {
13508       Visit(BO->getLHS());
13509       Visit(BO->getRHS());
13510     }
13511   }
13512 
13513   void VisitBinComma(const BinaryOperator *BO) {
13514     // C++11 [expr.comma]p1:
13515     //   Every value computation and side effect associated with the left
13516     //   expression is sequenced before every value computation and side
13517     //   effect associated with the right expression.
13518     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13519   }
13520 
13521   void VisitBinAssign(const BinaryOperator *BO) {
13522     SequenceTree::Seq RHSRegion;
13523     SequenceTree::Seq LHSRegion;
13524     if (SemaRef.getLangOpts().CPlusPlus17) {
13525       RHSRegion = Tree.allocate(Region);
13526       LHSRegion = Tree.allocate(Region);
13527     } else {
13528       RHSRegion = Region;
13529       LHSRegion = Region;
13530     }
13531     SequenceTree::Seq OldRegion = Region;
13532 
13533     // C++11 [expr.ass]p1:
13534     //  [...] the assignment is sequenced after the value computation
13535     //  of the right and left operands, [...]
13536     //
13537     // so check it before inspecting the operands and update the
13538     // map afterwards.
13539     Object O = getObject(BO->getLHS(), /*Mod=*/true);
13540     if (O)
13541       notePreMod(O, BO);
13542 
13543     if (SemaRef.getLangOpts().CPlusPlus17) {
13544       // C++17 [expr.ass]p1:
13545       //  [...] The right operand is sequenced before the left operand. [...]
13546       {
13547         SequencedSubexpression SeqBefore(*this);
13548         Region = RHSRegion;
13549         Visit(BO->getRHS());
13550       }
13551 
13552       Region = LHSRegion;
13553       Visit(BO->getLHS());
13554 
13555       if (O && isa<CompoundAssignOperator>(BO))
13556         notePostUse(O, BO);
13557 
13558     } else {
13559       // C++11 does not specify any sequencing between the LHS and RHS.
13560       Region = LHSRegion;
13561       Visit(BO->getLHS());
13562 
13563       if (O && isa<CompoundAssignOperator>(BO))
13564         notePostUse(O, BO);
13565 
13566       Region = RHSRegion;
13567       Visit(BO->getRHS());
13568     }
13569 
13570     // C++11 [expr.ass]p1:
13571     //  the assignment is sequenced [...] before the value computation of the
13572     //  assignment expression.
13573     // C11 6.5.16/3 has no such rule.
13574     Region = OldRegion;
13575     if (O)
13576       notePostMod(O, BO,
13577                   SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
13578                                                   : UK_ModAsSideEffect);
13579     if (SemaRef.getLangOpts().CPlusPlus17) {
13580       Tree.merge(RHSRegion);
13581       Tree.merge(LHSRegion);
13582     }
13583   }
13584 
13585   void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
13586     VisitBinAssign(CAO);
13587   }
13588 
13589   void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
13590   void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
13591   void VisitUnaryPreIncDec(const UnaryOperator *UO) {
13592     Object O = getObject(UO->getSubExpr(), true);
13593     if (!O)
13594       return VisitExpr(UO);
13595 
13596     notePreMod(O, UO);
13597     Visit(UO->getSubExpr());
13598     // C++11 [expr.pre.incr]p1:
13599     //   the expression ++x is equivalent to x+=1
13600     notePostMod(O, UO,
13601                 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
13602                                                 : UK_ModAsSideEffect);
13603   }
13604 
13605   void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
13606   void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
13607   void VisitUnaryPostIncDec(const UnaryOperator *UO) {
13608     Object O = getObject(UO->getSubExpr(), true);
13609     if (!O)
13610       return VisitExpr(UO);
13611 
13612     notePreMod(O, UO);
13613     Visit(UO->getSubExpr());
13614     notePostMod(O, UO, UK_ModAsSideEffect);
13615   }
13616 
13617   void VisitBinLOr(const BinaryOperator *BO) {
13618     // C++11 [expr.log.or]p2:
13619     //  If the second expression is evaluated, every value computation and
13620     //  side effect associated with the first expression is sequenced before
13621     //  every value computation and side effect associated with the
13622     //  second expression.
13623     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
13624     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
13625     SequenceTree::Seq OldRegion = Region;
13626 
13627     EvaluationTracker Eval(*this);
13628     {
13629       SequencedSubexpression Sequenced(*this);
13630       Region = LHSRegion;
13631       Visit(BO->getLHS());
13632     }
13633 
13634     // C++11 [expr.log.or]p1:
13635     //  [...] the second operand is not evaluated if the first operand
13636     //  evaluates to true.
13637     bool EvalResult = false;
13638     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
13639     bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
13640     if (ShouldVisitRHS) {
13641       Region = RHSRegion;
13642       Visit(BO->getRHS());
13643     }
13644 
13645     Region = OldRegion;
13646     Tree.merge(LHSRegion);
13647     Tree.merge(RHSRegion);
13648   }
13649 
13650   void VisitBinLAnd(const BinaryOperator *BO) {
13651     // C++11 [expr.log.and]p2:
13652     //  If the second expression is evaluated, every value computation and
13653     //  side effect associated with the first expression is sequenced before
13654     //  every value computation and side effect associated with the
13655     //  second expression.
13656     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
13657     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
13658     SequenceTree::Seq OldRegion = Region;
13659 
13660     EvaluationTracker Eval(*this);
13661     {
13662       SequencedSubexpression Sequenced(*this);
13663       Region = LHSRegion;
13664       Visit(BO->getLHS());
13665     }
13666 
13667     // C++11 [expr.log.and]p1:
13668     //  [...] the second operand is not evaluated if the first operand is false.
13669     bool EvalResult = false;
13670     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
13671     bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
13672     if (ShouldVisitRHS) {
13673       Region = RHSRegion;
13674       Visit(BO->getRHS());
13675     }
13676 
13677     Region = OldRegion;
13678     Tree.merge(LHSRegion);
13679     Tree.merge(RHSRegion);
13680   }
13681 
13682   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
13683     // C++11 [expr.cond]p1:
13684     //  [...] Every value computation and side effect associated with the first
13685     //  expression is sequenced before every value computation and side effect
13686     //  associated with the second or third expression.
13687     SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
13688 
13689     // No sequencing is specified between the true and false expression.
13690     // However since exactly one of both is going to be evaluated we can
13691     // consider them to be sequenced. This is needed to avoid warning on
13692     // something like "x ? y+= 1 : y += 2;" in the case where we will visit
13693     // both the true and false expressions because we can't evaluate x.
13694     // This will still allow us to detect an expression like (pre C++17)
13695     // "(x ? y += 1 : y += 2) = y".
13696     //
13697     // We don't wrap the visitation of the true and false expression with
13698     // SequencedSubexpression because we don't want to downgrade modifications
13699     // as side effect in the true and false expressions after the visition
13700     // is done. (for example in the expression "(x ? y++ : y++) + y" we should
13701     // not warn between the two "y++", but we should warn between the "y++"
13702     // and the "y".
13703     SequenceTree::Seq TrueRegion = Tree.allocate(Region);
13704     SequenceTree::Seq FalseRegion = Tree.allocate(Region);
13705     SequenceTree::Seq OldRegion = Region;
13706 
13707     EvaluationTracker Eval(*this);
13708     {
13709       SequencedSubexpression Sequenced(*this);
13710       Region = ConditionRegion;
13711       Visit(CO->getCond());
13712     }
13713 
13714     // C++11 [expr.cond]p1:
13715     // [...] The first expression is contextually converted to bool (Clause 4).
13716     // It is evaluated and if it is true, the result of the conditional
13717     // expression is the value of the second expression, otherwise that of the
13718     // third expression. Only one of the second and third expressions is
13719     // evaluated. [...]
13720     bool EvalResult = false;
13721     bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
13722     bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
13723     bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
13724     if (ShouldVisitTrueExpr) {
13725       Region = TrueRegion;
13726       Visit(CO->getTrueExpr());
13727     }
13728     if (ShouldVisitFalseExpr) {
13729       Region = FalseRegion;
13730       Visit(CO->getFalseExpr());
13731     }
13732 
13733     Region = OldRegion;
13734     Tree.merge(ConditionRegion);
13735     Tree.merge(TrueRegion);
13736     Tree.merge(FalseRegion);
13737   }
13738 
13739   void VisitCallExpr(const CallExpr *CE) {
13740     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
13741 
13742     if (CE->isUnevaluatedBuiltinCall(Context))
13743       return;
13744 
13745     // C++11 [intro.execution]p15:
13746     //   When calling a function [...], every value computation and side effect
13747     //   associated with any argument expression, or with the postfix expression
13748     //   designating the called function, is sequenced before execution of every
13749     //   expression or statement in the body of the function [and thus before
13750     //   the value computation of its result].
13751     SequencedSubexpression Sequenced(*this);
13752     SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
13753       // C++17 [expr.call]p5
13754       //   The postfix-expression is sequenced before each expression in the
13755       //   expression-list and any default argument. [...]
13756       SequenceTree::Seq CalleeRegion;
13757       SequenceTree::Seq OtherRegion;
13758       if (SemaRef.getLangOpts().CPlusPlus17) {
13759         CalleeRegion = Tree.allocate(Region);
13760         OtherRegion = Tree.allocate(Region);
13761       } else {
13762         CalleeRegion = Region;
13763         OtherRegion = Region;
13764       }
13765       SequenceTree::Seq OldRegion = Region;
13766 
13767       // Visit the callee expression first.
13768       Region = CalleeRegion;
13769       if (SemaRef.getLangOpts().CPlusPlus17) {
13770         SequencedSubexpression Sequenced(*this);
13771         Visit(CE->getCallee());
13772       } else {
13773         Visit(CE->getCallee());
13774       }
13775 
13776       // Then visit the argument expressions.
13777       Region = OtherRegion;
13778       for (const Expr *Argument : CE->arguments())
13779         Visit(Argument);
13780 
13781       Region = OldRegion;
13782       if (SemaRef.getLangOpts().CPlusPlus17) {
13783         Tree.merge(CalleeRegion);
13784         Tree.merge(OtherRegion);
13785       }
13786     });
13787   }
13788 
13789   void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
13790     // C++17 [over.match.oper]p2:
13791     //   [...] the operator notation is first transformed to the equivalent
13792     //   function-call notation as summarized in Table 12 (where @ denotes one
13793     //   of the operators covered in the specified subclause). However, the
13794     //   operands are sequenced in the order prescribed for the built-in
13795     //   operator (Clause 8).
13796     //
13797     // From the above only overloaded binary operators and overloaded call
13798     // operators have sequencing rules in C++17 that we need to handle
13799     // separately.
13800     if (!SemaRef.getLangOpts().CPlusPlus17 ||
13801         (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
13802       return VisitCallExpr(CXXOCE);
13803 
13804     enum {
13805       NoSequencing,
13806       LHSBeforeRHS,
13807       RHSBeforeLHS,
13808       LHSBeforeRest
13809     } SequencingKind;
13810     switch (CXXOCE->getOperator()) {
13811     case OO_Equal:
13812     case OO_PlusEqual:
13813     case OO_MinusEqual:
13814     case OO_StarEqual:
13815     case OO_SlashEqual:
13816     case OO_PercentEqual:
13817     case OO_CaretEqual:
13818     case OO_AmpEqual:
13819     case OO_PipeEqual:
13820     case OO_LessLessEqual:
13821     case OO_GreaterGreaterEqual:
13822       SequencingKind = RHSBeforeLHS;
13823       break;
13824 
13825     case OO_LessLess:
13826     case OO_GreaterGreater:
13827     case OO_AmpAmp:
13828     case OO_PipePipe:
13829     case OO_Comma:
13830     case OO_ArrowStar:
13831     case OO_Subscript:
13832       SequencingKind = LHSBeforeRHS;
13833       break;
13834 
13835     case OO_Call:
13836       SequencingKind = LHSBeforeRest;
13837       break;
13838 
13839     default:
13840       SequencingKind = NoSequencing;
13841       break;
13842     }
13843 
13844     if (SequencingKind == NoSequencing)
13845       return VisitCallExpr(CXXOCE);
13846 
13847     // This is a call, so all subexpressions are sequenced before the result.
13848     SequencedSubexpression Sequenced(*this);
13849 
13850     SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
13851       assert(SemaRef.getLangOpts().CPlusPlus17 &&
13852              "Should only get there with C++17 and above!");
13853       assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
13854              "Should only get there with an overloaded binary operator"
13855              " or an overloaded call operator!");
13856 
13857       if (SequencingKind == LHSBeforeRest) {
13858         assert(CXXOCE->getOperator() == OO_Call &&
13859                "We should only have an overloaded call operator here!");
13860 
13861         // This is very similar to VisitCallExpr, except that we only have the
13862         // C++17 case. The postfix-expression is the first argument of the
13863         // CXXOperatorCallExpr. The expressions in the expression-list, if any,
13864         // are in the following arguments.
13865         //
13866         // Note that we intentionally do not visit the callee expression since
13867         // it is just a decayed reference to a function.
13868         SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
13869         SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
13870         SequenceTree::Seq OldRegion = Region;
13871 
13872         assert(CXXOCE->getNumArgs() >= 1 &&
13873                "An overloaded call operator must have at least one argument"
13874                " for the postfix-expression!");
13875         const Expr *PostfixExpr = CXXOCE->getArgs()[0];
13876         llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
13877                                           CXXOCE->getNumArgs() - 1);
13878 
13879         // Visit the postfix-expression first.
13880         {
13881           Region = PostfixExprRegion;
13882           SequencedSubexpression Sequenced(*this);
13883           Visit(PostfixExpr);
13884         }
13885 
13886         // Then visit the argument expressions.
13887         Region = ArgsRegion;
13888         for (const Expr *Arg : Args)
13889           Visit(Arg);
13890 
13891         Region = OldRegion;
13892         Tree.merge(PostfixExprRegion);
13893         Tree.merge(ArgsRegion);
13894       } else {
13895         assert(CXXOCE->getNumArgs() == 2 &&
13896                "Should only have two arguments here!");
13897         assert((SequencingKind == LHSBeforeRHS ||
13898                 SequencingKind == RHSBeforeLHS) &&
13899                "Unexpected sequencing kind!");
13900 
13901         // We do not visit the callee expression since it is just a decayed
13902         // reference to a function.
13903         const Expr *E1 = CXXOCE->getArg(0);
13904         const Expr *E2 = CXXOCE->getArg(1);
13905         if (SequencingKind == RHSBeforeLHS)
13906           std::swap(E1, E2);
13907 
13908         return VisitSequencedExpressions(E1, E2);
13909       }
13910     });
13911   }
13912 
13913   void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
13914     // This is a call, so all subexpressions are sequenced before the result.
13915     SequencedSubexpression Sequenced(*this);
13916 
13917     if (!CCE->isListInitialization())
13918       return VisitExpr(CCE);
13919 
13920     // In C++11, list initializations are sequenced.
13921     SmallVector<SequenceTree::Seq, 32> Elts;
13922     SequenceTree::Seq Parent = Region;
13923     for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
13924                                               E = CCE->arg_end();
13925          I != E; ++I) {
13926       Region = Tree.allocate(Parent);
13927       Elts.push_back(Region);
13928       Visit(*I);
13929     }
13930 
13931     // Forget that the initializers are sequenced.
13932     Region = Parent;
13933     for (unsigned I = 0; I < Elts.size(); ++I)
13934       Tree.merge(Elts[I]);
13935   }
13936 
13937   void VisitInitListExpr(const InitListExpr *ILE) {
13938     if (!SemaRef.getLangOpts().CPlusPlus11)
13939       return VisitExpr(ILE);
13940 
13941     // In C++11, list initializations are sequenced.
13942     SmallVector<SequenceTree::Seq, 32> Elts;
13943     SequenceTree::Seq Parent = Region;
13944     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
13945       const Expr *E = ILE->getInit(I);
13946       if (!E)
13947         continue;
13948       Region = Tree.allocate(Parent);
13949       Elts.push_back(Region);
13950       Visit(E);
13951     }
13952 
13953     // Forget that the initializers are sequenced.
13954     Region = Parent;
13955     for (unsigned I = 0; I < Elts.size(); ++I)
13956       Tree.merge(Elts[I]);
13957   }
13958 };
13959 
13960 } // namespace
13961 
13962 void Sema::CheckUnsequencedOperations(const Expr *E) {
13963   SmallVector<const Expr *, 8> WorkList;
13964   WorkList.push_back(E);
13965   while (!WorkList.empty()) {
13966     const Expr *Item = WorkList.pop_back_val();
13967     SequenceChecker(*this, Item, WorkList);
13968   }
13969 }
13970 
13971 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
13972                               bool IsConstexpr) {
13973   llvm::SaveAndRestore<bool> ConstantContext(
13974       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
13975   CheckImplicitConversions(E, CheckLoc);
13976   if (!E->isInstantiationDependent())
13977     CheckUnsequencedOperations(E);
13978   if (!IsConstexpr && !E->isValueDependent())
13979     CheckForIntOverflow(E);
13980   DiagnoseMisalignedMembers();
13981 }
13982 
13983 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
13984                                        FieldDecl *BitField,
13985                                        Expr *Init) {
13986   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
13987 }
13988 
13989 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
13990                                          SourceLocation Loc) {
13991   if (!PType->isVariablyModifiedType())
13992     return;
13993   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
13994     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
13995     return;
13996   }
13997   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
13998     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
13999     return;
14000   }
14001   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
14002     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
14003     return;
14004   }
14005 
14006   const ArrayType *AT = S.Context.getAsArrayType(PType);
14007   if (!AT)
14008     return;
14009 
14010   if (AT->getSizeModifier() != ArrayType::Star) {
14011     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
14012     return;
14013   }
14014 
14015   S.Diag(Loc, diag::err_array_star_in_function_definition);
14016 }
14017 
14018 /// CheckParmsForFunctionDef - Check that the parameters of the given
14019 /// function are appropriate for the definition of a function. This
14020 /// takes care of any checks that cannot be performed on the
14021 /// declaration itself, e.g., that the types of each of the function
14022 /// parameters are complete.
14023 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
14024                                     bool CheckParameterNames) {
14025   bool HasInvalidParm = false;
14026   for (ParmVarDecl *Param : Parameters) {
14027     // C99 6.7.5.3p4: the parameters in a parameter type list in a
14028     // function declarator that is part of a function definition of
14029     // that function shall not have incomplete type.
14030     //
14031     // This is also C++ [dcl.fct]p6.
14032     if (!Param->isInvalidDecl() &&
14033         RequireCompleteType(Param->getLocation(), Param->getType(),
14034                             diag::err_typecheck_decl_incomplete_type)) {
14035       Param->setInvalidDecl();
14036       HasInvalidParm = true;
14037     }
14038 
14039     // C99 6.9.1p5: If the declarator includes a parameter type list, the
14040     // declaration of each parameter shall include an identifier.
14041     if (CheckParameterNames && Param->getIdentifier() == nullptr &&
14042         !Param->isImplicit() && !getLangOpts().CPlusPlus) {
14043       // Diagnose this as an extension in C17 and earlier.
14044       if (!getLangOpts().C2x)
14045         Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
14046     }
14047 
14048     // C99 6.7.5.3p12:
14049     //   If the function declarator is not part of a definition of that
14050     //   function, parameters may have incomplete type and may use the [*]
14051     //   notation in their sequences of declarator specifiers to specify
14052     //   variable length array types.
14053     QualType PType = Param->getOriginalType();
14054     // FIXME: This diagnostic should point the '[*]' if source-location
14055     // information is added for it.
14056     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
14057 
14058     // If the parameter is a c++ class type and it has to be destructed in the
14059     // callee function, declare the destructor so that it can be called by the
14060     // callee function. Do not perform any direct access check on the dtor here.
14061     if (!Param->isInvalidDecl()) {
14062       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
14063         if (!ClassDecl->isInvalidDecl() &&
14064             !ClassDecl->hasIrrelevantDestructor() &&
14065             !ClassDecl->isDependentContext() &&
14066             ClassDecl->isParamDestroyedInCallee()) {
14067           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
14068           MarkFunctionReferenced(Param->getLocation(), Destructor);
14069           DiagnoseUseOfDecl(Destructor, Param->getLocation());
14070         }
14071       }
14072     }
14073 
14074     // Parameters with the pass_object_size attribute only need to be marked
14075     // constant at function definitions. Because we lack information about
14076     // whether we're on a declaration or definition when we're instantiating the
14077     // attribute, we need to check for constness here.
14078     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
14079       if (!Param->getType().isConstQualified())
14080         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
14081             << Attr->getSpelling() << 1;
14082 
14083     // Check for parameter names shadowing fields from the class.
14084     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
14085       // The owning context for the parameter should be the function, but we
14086       // want to see if this function's declaration context is a record.
14087       DeclContext *DC = Param->getDeclContext();
14088       if (DC && DC->isFunctionOrMethod()) {
14089         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
14090           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
14091                                      RD, /*DeclIsField*/ false);
14092       }
14093     }
14094   }
14095 
14096   return HasInvalidParm;
14097 }
14098 
14099 Optional<std::pair<CharUnits, CharUnits>>
14100 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx);
14101 
14102 /// Compute the alignment and offset of the base class object given the
14103 /// derived-to-base cast expression and the alignment and offset of the derived
14104 /// class object.
14105 static std::pair<CharUnits, CharUnits>
14106 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
14107                                    CharUnits BaseAlignment, CharUnits Offset,
14108                                    ASTContext &Ctx) {
14109   for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
14110        ++PathI) {
14111     const CXXBaseSpecifier *Base = *PathI;
14112     const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
14113     if (Base->isVirtual()) {
14114       // The complete object may have a lower alignment than the non-virtual
14115       // alignment of the base, in which case the base may be misaligned. Choose
14116       // the smaller of the non-virtual alignment and BaseAlignment, which is a
14117       // conservative lower bound of the complete object alignment.
14118       CharUnits NonVirtualAlignment =
14119           Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment();
14120       BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
14121       Offset = CharUnits::Zero();
14122     } else {
14123       const ASTRecordLayout &RL =
14124           Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
14125       Offset += RL.getBaseClassOffset(BaseDecl);
14126     }
14127     DerivedType = Base->getType();
14128   }
14129 
14130   return std::make_pair(BaseAlignment, Offset);
14131 }
14132 
14133 /// Compute the alignment and offset of a binary additive operator.
14134 static Optional<std::pair<CharUnits, CharUnits>>
14135 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
14136                                      bool IsSub, ASTContext &Ctx) {
14137   QualType PointeeType = PtrE->getType()->getPointeeType();
14138 
14139   if (!PointeeType->isConstantSizeType())
14140     return llvm::None;
14141 
14142   auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
14143 
14144   if (!P)
14145     return llvm::None;
14146 
14147   CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
14148   if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
14149     CharUnits Offset = EltSize * IdxRes->getExtValue();
14150     if (IsSub)
14151       Offset = -Offset;
14152     return std::make_pair(P->first, P->second + Offset);
14153   }
14154 
14155   // If the integer expression isn't a constant expression, compute the lower
14156   // bound of the alignment using the alignment and offset of the pointer
14157   // expression and the element size.
14158   return std::make_pair(
14159       P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
14160       CharUnits::Zero());
14161 }
14162 
14163 /// This helper function takes an lvalue expression and returns the alignment of
14164 /// a VarDecl and a constant offset from the VarDecl.
14165 Optional<std::pair<CharUnits, CharUnits>>
14166 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) {
14167   E = E->IgnoreParens();
14168   switch (E->getStmtClass()) {
14169   default:
14170     break;
14171   case Stmt::CStyleCastExprClass:
14172   case Stmt::CXXStaticCastExprClass:
14173   case Stmt::ImplicitCastExprClass: {
14174     auto *CE = cast<CastExpr>(E);
14175     const Expr *From = CE->getSubExpr();
14176     switch (CE->getCastKind()) {
14177     default:
14178       break;
14179     case CK_NoOp:
14180       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14181     case CK_UncheckedDerivedToBase:
14182     case CK_DerivedToBase: {
14183       auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14184       if (!P)
14185         break;
14186       return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
14187                                                 P->second, Ctx);
14188     }
14189     }
14190     break;
14191   }
14192   case Stmt::ArraySubscriptExprClass: {
14193     auto *ASE = cast<ArraySubscriptExpr>(E);
14194     return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(),
14195                                                 false, Ctx);
14196   }
14197   case Stmt::DeclRefExprClass: {
14198     if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
14199       // FIXME: If VD is captured by copy or is an escaping __block variable,
14200       // use the alignment of VD's type.
14201       if (!VD->getType()->isReferenceType())
14202         return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
14203       if (VD->hasInit())
14204         return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
14205     }
14206     break;
14207   }
14208   case Stmt::MemberExprClass: {
14209     auto *ME = cast<MemberExpr>(E);
14210     auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
14211     if (!FD || FD->getType()->isReferenceType())
14212       break;
14213     Optional<std::pair<CharUnits, CharUnits>> P;
14214     if (ME->isArrow())
14215       P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
14216     else
14217       P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
14218     if (!P)
14219       break;
14220     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
14221     uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
14222     return std::make_pair(P->first,
14223                           P->second + CharUnits::fromQuantity(Offset));
14224   }
14225   case Stmt::UnaryOperatorClass: {
14226     auto *UO = cast<UnaryOperator>(E);
14227     switch (UO->getOpcode()) {
14228     default:
14229       break;
14230     case UO_Deref:
14231       return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx);
14232     }
14233     break;
14234   }
14235   case Stmt::BinaryOperatorClass: {
14236     auto *BO = cast<BinaryOperator>(E);
14237     auto Opcode = BO->getOpcode();
14238     switch (Opcode) {
14239     default:
14240       break;
14241     case BO_Comma:
14242       return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx);
14243     }
14244     break;
14245   }
14246   }
14247   return llvm::None;
14248 }
14249 
14250 /// This helper function takes a pointer expression and returns the alignment of
14251 /// a VarDecl and a constant offset from the VarDecl.
14252 Optional<std::pair<CharUnits, CharUnits>>
14253 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) {
14254   E = E->IgnoreParens();
14255   switch (E->getStmtClass()) {
14256   default:
14257     break;
14258   case Stmt::CStyleCastExprClass:
14259   case Stmt::CXXStaticCastExprClass:
14260   case Stmt::ImplicitCastExprClass: {
14261     auto *CE = cast<CastExpr>(E);
14262     const Expr *From = CE->getSubExpr();
14263     switch (CE->getCastKind()) {
14264     default:
14265       break;
14266     case CK_NoOp:
14267       return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14268     case CK_ArrayToPointerDecay:
14269       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14270     case CK_UncheckedDerivedToBase:
14271     case CK_DerivedToBase: {
14272       auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14273       if (!P)
14274         break;
14275       return getDerivedToBaseAlignmentAndOffset(
14276           CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
14277     }
14278     }
14279     break;
14280   }
14281   case Stmt::CXXThisExprClass: {
14282     auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
14283     CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment();
14284     return std::make_pair(Alignment, CharUnits::Zero());
14285   }
14286   case Stmt::UnaryOperatorClass: {
14287     auto *UO = cast<UnaryOperator>(E);
14288     if (UO->getOpcode() == UO_AddrOf)
14289       return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx);
14290     break;
14291   }
14292   case Stmt::BinaryOperatorClass: {
14293     auto *BO = cast<BinaryOperator>(E);
14294     auto Opcode = BO->getOpcode();
14295     switch (Opcode) {
14296     default:
14297       break;
14298     case BO_Add:
14299     case BO_Sub: {
14300       const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
14301       if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
14302         std::swap(LHS, RHS);
14303       return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
14304                                                   Ctx);
14305     }
14306     case BO_Comma:
14307       return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
14308     }
14309     break;
14310   }
14311   }
14312   return llvm::None;
14313 }
14314 
14315 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
14316   // See if we can compute the alignment of a VarDecl and an offset from it.
14317   Optional<std::pair<CharUnits, CharUnits>> P =
14318       getBaseAlignmentAndOffsetFromPtr(E, S.Context);
14319 
14320   if (P)
14321     return P->first.alignmentAtOffset(P->second);
14322 
14323   // If that failed, return the type's alignment.
14324   return S.Context.getTypeAlignInChars(E->getType()->getPointeeType());
14325 }
14326 
14327 /// CheckCastAlign - Implements -Wcast-align, which warns when a
14328 /// pointer cast increases the alignment requirements.
14329 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
14330   // This is actually a lot of work to potentially be doing on every
14331   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
14332   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
14333     return;
14334 
14335   // Ignore dependent types.
14336   if (T->isDependentType() || Op->getType()->isDependentType())
14337     return;
14338 
14339   // Require that the destination be a pointer type.
14340   const PointerType *DestPtr = T->getAs<PointerType>();
14341   if (!DestPtr) return;
14342 
14343   // If the destination has alignment 1, we're done.
14344   QualType DestPointee = DestPtr->getPointeeType();
14345   if (DestPointee->isIncompleteType()) return;
14346   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
14347   if (DestAlign.isOne()) return;
14348 
14349   // Require that the source be a pointer type.
14350   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
14351   if (!SrcPtr) return;
14352   QualType SrcPointee = SrcPtr->getPointeeType();
14353 
14354   // Explicitly allow casts from cv void*.  We already implicitly
14355   // allowed casts to cv void*, since they have alignment 1.
14356   // Also allow casts involving incomplete types, which implicitly
14357   // includes 'void'.
14358   if (SrcPointee->isIncompleteType()) return;
14359 
14360   CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
14361 
14362   if (SrcAlign >= DestAlign) return;
14363 
14364   Diag(TRange.getBegin(), diag::warn_cast_align)
14365     << Op->getType() << T
14366     << static_cast<unsigned>(SrcAlign.getQuantity())
14367     << static_cast<unsigned>(DestAlign.getQuantity())
14368     << TRange << Op->getSourceRange();
14369 }
14370 
14371 /// Check whether this array fits the idiom of a size-one tail padded
14372 /// array member of a struct.
14373 ///
14374 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
14375 /// commonly used to emulate flexible arrays in C89 code.
14376 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
14377                                     const NamedDecl *ND) {
14378   if (Size != 1 || !ND) return false;
14379 
14380   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
14381   if (!FD) return false;
14382 
14383   // Don't consider sizes resulting from macro expansions or template argument
14384   // substitution to form C89 tail-padded arrays.
14385 
14386   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
14387   while (TInfo) {
14388     TypeLoc TL = TInfo->getTypeLoc();
14389     // Look through typedefs.
14390     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
14391       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
14392       TInfo = TDL->getTypeSourceInfo();
14393       continue;
14394     }
14395     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
14396       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
14397       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
14398         return false;
14399     }
14400     break;
14401   }
14402 
14403   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
14404   if (!RD) return false;
14405   if (RD->isUnion()) return false;
14406   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
14407     if (!CRD->isStandardLayout()) return false;
14408   }
14409 
14410   // See if this is the last field decl in the record.
14411   const Decl *D = FD;
14412   while ((D = D->getNextDeclInContext()))
14413     if (isa<FieldDecl>(D))
14414       return false;
14415   return true;
14416 }
14417 
14418 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
14419                             const ArraySubscriptExpr *ASE,
14420                             bool AllowOnePastEnd, bool IndexNegated) {
14421   // Already diagnosed by the constant evaluator.
14422   if (isConstantEvaluated())
14423     return;
14424 
14425   IndexExpr = IndexExpr->IgnoreParenImpCasts();
14426   if (IndexExpr->isValueDependent())
14427     return;
14428 
14429   const Type *EffectiveType =
14430       BaseExpr->getType()->getPointeeOrArrayElementType();
14431   BaseExpr = BaseExpr->IgnoreParenCasts();
14432   const ConstantArrayType *ArrayTy =
14433       Context.getAsConstantArrayType(BaseExpr->getType());
14434 
14435   if (!ArrayTy)
14436     return;
14437 
14438   const Type *BaseType = ArrayTy->getElementType().getTypePtr();
14439   if (EffectiveType->isDependentType() || BaseType->isDependentType())
14440     return;
14441 
14442   Expr::EvalResult Result;
14443   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
14444     return;
14445 
14446   llvm::APSInt index = Result.Val.getInt();
14447   if (IndexNegated)
14448     index = -index;
14449 
14450   const NamedDecl *ND = nullptr;
14451   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14452     ND = DRE->getDecl();
14453   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
14454     ND = ME->getMemberDecl();
14455 
14456   if (index.isUnsigned() || !index.isNegative()) {
14457     // It is possible that the type of the base expression after
14458     // IgnoreParenCasts is incomplete, even though the type of the base
14459     // expression before IgnoreParenCasts is complete (see PR39746 for an
14460     // example). In this case we have no information about whether the array
14461     // access exceeds the array bounds. However we can still diagnose an array
14462     // access which precedes the array bounds.
14463     if (BaseType->isIncompleteType())
14464       return;
14465 
14466     llvm::APInt size = ArrayTy->getSize();
14467     if (!size.isStrictlyPositive())
14468       return;
14469 
14470     if (BaseType != EffectiveType) {
14471       // Make sure we're comparing apples to apples when comparing index to size
14472       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
14473       uint64_t array_typesize = Context.getTypeSize(BaseType);
14474       // Handle ptrarith_typesize being zero, such as when casting to void*
14475       if (!ptrarith_typesize) ptrarith_typesize = 1;
14476       if (ptrarith_typesize != array_typesize) {
14477         // There's a cast to a different size type involved
14478         uint64_t ratio = array_typesize / ptrarith_typesize;
14479         // TODO: Be smarter about handling cases where array_typesize is not a
14480         // multiple of ptrarith_typesize
14481         if (ptrarith_typesize * ratio == array_typesize)
14482           size *= llvm::APInt(size.getBitWidth(), ratio);
14483       }
14484     }
14485 
14486     if (size.getBitWidth() > index.getBitWidth())
14487       index = index.zext(size.getBitWidth());
14488     else if (size.getBitWidth() < index.getBitWidth())
14489       size = size.zext(index.getBitWidth());
14490 
14491     // For array subscripting the index must be less than size, but for pointer
14492     // arithmetic also allow the index (offset) to be equal to size since
14493     // computing the next address after the end of the array is legal and
14494     // commonly done e.g. in C++ iterators and range-based for loops.
14495     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
14496       return;
14497 
14498     // Also don't warn for arrays of size 1 which are members of some
14499     // structure. These are often used to approximate flexible arrays in C89
14500     // code.
14501     if (IsTailPaddedMemberArray(*this, size, ND))
14502       return;
14503 
14504     // Suppress the warning if the subscript expression (as identified by the
14505     // ']' location) and the index expression are both from macro expansions
14506     // within a system header.
14507     if (ASE) {
14508       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
14509           ASE->getRBracketLoc());
14510       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
14511         SourceLocation IndexLoc =
14512             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
14513         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
14514           return;
14515       }
14516     }
14517 
14518     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
14519     if (ASE)
14520       DiagID = diag::warn_array_index_exceeds_bounds;
14521 
14522     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
14523                         PDiag(DiagID) << index.toString(10, true)
14524                                       << size.toString(10, true)
14525                                       << (unsigned)size.getLimitedValue(~0U)
14526                                       << IndexExpr->getSourceRange());
14527   } else {
14528     unsigned DiagID = diag::warn_array_index_precedes_bounds;
14529     if (!ASE) {
14530       DiagID = diag::warn_ptr_arith_precedes_bounds;
14531       if (index.isNegative()) index = -index;
14532     }
14533 
14534     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
14535                         PDiag(DiagID) << index.toString(10, true)
14536                                       << IndexExpr->getSourceRange());
14537   }
14538 
14539   if (!ND) {
14540     // Try harder to find a NamedDecl to point at in the note.
14541     while (const ArraySubscriptExpr *ASE =
14542            dyn_cast<ArraySubscriptExpr>(BaseExpr))
14543       BaseExpr = ASE->getBase()->IgnoreParenCasts();
14544     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14545       ND = DRE->getDecl();
14546     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
14547       ND = ME->getMemberDecl();
14548   }
14549 
14550   if (ND)
14551     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
14552                         PDiag(diag::note_array_declared_here) << ND);
14553 }
14554 
14555 void Sema::CheckArrayAccess(const Expr *expr) {
14556   int AllowOnePastEnd = 0;
14557   while (expr) {
14558     expr = expr->IgnoreParenImpCasts();
14559     switch (expr->getStmtClass()) {
14560       case Stmt::ArraySubscriptExprClass: {
14561         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
14562         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
14563                          AllowOnePastEnd > 0);
14564         expr = ASE->getBase();
14565         break;
14566       }
14567       case Stmt::MemberExprClass: {
14568         expr = cast<MemberExpr>(expr)->getBase();
14569         break;
14570       }
14571       case Stmt::OMPArraySectionExprClass: {
14572         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
14573         if (ASE->getLowerBound())
14574           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
14575                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
14576         return;
14577       }
14578       case Stmt::UnaryOperatorClass: {
14579         // Only unwrap the * and & unary operators
14580         const UnaryOperator *UO = cast<UnaryOperator>(expr);
14581         expr = UO->getSubExpr();
14582         switch (UO->getOpcode()) {
14583           case UO_AddrOf:
14584             AllowOnePastEnd++;
14585             break;
14586           case UO_Deref:
14587             AllowOnePastEnd--;
14588             break;
14589           default:
14590             return;
14591         }
14592         break;
14593       }
14594       case Stmt::ConditionalOperatorClass: {
14595         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
14596         if (const Expr *lhs = cond->getLHS())
14597           CheckArrayAccess(lhs);
14598         if (const Expr *rhs = cond->getRHS())
14599           CheckArrayAccess(rhs);
14600         return;
14601       }
14602       case Stmt::CXXOperatorCallExprClass: {
14603         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
14604         for (const auto *Arg : OCE->arguments())
14605           CheckArrayAccess(Arg);
14606         return;
14607       }
14608       default:
14609         return;
14610     }
14611   }
14612 }
14613 
14614 //===--- CHECK: Objective-C retain cycles ----------------------------------//
14615 
14616 namespace {
14617 
14618 struct RetainCycleOwner {
14619   VarDecl *Variable = nullptr;
14620   SourceRange Range;
14621   SourceLocation Loc;
14622   bool Indirect = false;
14623 
14624   RetainCycleOwner() = default;
14625 
14626   void setLocsFrom(Expr *e) {
14627     Loc = e->getExprLoc();
14628     Range = e->getSourceRange();
14629   }
14630 };
14631 
14632 } // namespace
14633 
14634 /// Consider whether capturing the given variable can possibly lead to
14635 /// a retain cycle.
14636 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
14637   // In ARC, it's captured strongly iff the variable has __strong
14638   // lifetime.  In MRR, it's captured strongly if the variable is
14639   // __block and has an appropriate type.
14640   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
14641     return false;
14642 
14643   owner.Variable = var;
14644   if (ref)
14645     owner.setLocsFrom(ref);
14646   return true;
14647 }
14648 
14649 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
14650   while (true) {
14651     e = e->IgnoreParens();
14652     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
14653       switch (cast->getCastKind()) {
14654       case CK_BitCast:
14655       case CK_LValueBitCast:
14656       case CK_LValueToRValue:
14657       case CK_ARCReclaimReturnedObject:
14658         e = cast->getSubExpr();
14659         continue;
14660 
14661       default:
14662         return false;
14663       }
14664     }
14665 
14666     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
14667       ObjCIvarDecl *ivar = ref->getDecl();
14668       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
14669         return false;
14670 
14671       // Try to find a retain cycle in the base.
14672       if (!findRetainCycleOwner(S, ref->getBase(), owner))
14673         return false;
14674 
14675       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
14676       owner.Indirect = true;
14677       return true;
14678     }
14679 
14680     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
14681       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
14682       if (!var) return false;
14683       return considerVariable(var, ref, owner);
14684     }
14685 
14686     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
14687       if (member->isArrow()) return false;
14688 
14689       // Don't count this as an indirect ownership.
14690       e = member->getBase();
14691       continue;
14692     }
14693 
14694     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
14695       // Only pay attention to pseudo-objects on property references.
14696       ObjCPropertyRefExpr *pre
14697         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
14698                                               ->IgnoreParens());
14699       if (!pre) return false;
14700       if (pre->isImplicitProperty()) return false;
14701       ObjCPropertyDecl *property = pre->getExplicitProperty();
14702       if (!property->isRetaining() &&
14703           !(property->getPropertyIvarDecl() &&
14704             property->getPropertyIvarDecl()->getType()
14705               .getObjCLifetime() == Qualifiers::OCL_Strong))
14706           return false;
14707 
14708       owner.Indirect = true;
14709       if (pre->isSuperReceiver()) {
14710         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
14711         if (!owner.Variable)
14712           return false;
14713         owner.Loc = pre->getLocation();
14714         owner.Range = pre->getSourceRange();
14715         return true;
14716       }
14717       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
14718                               ->getSourceExpr());
14719       continue;
14720     }
14721 
14722     // Array ivars?
14723 
14724     return false;
14725   }
14726 }
14727 
14728 namespace {
14729 
14730   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
14731     ASTContext &Context;
14732     VarDecl *Variable;
14733     Expr *Capturer = nullptr;
14734     bool VarWillBeReased = false;
14735 
14736     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
14737         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
14738           Context(Context), Variable(variable) {}
14739 
14740     void VisitDeclRefExpr(DeclRefExpr *ref) {
14741       if (ref->getDecl() == Variable && !Capturer)
14742         Capturer = ref;
14743     }
14744 
14745     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
14746       if (Capturer) return;
14747       Visit(ref->getBase());
14748       if (Capturer && ref->isFreeIvar())
14749         Capturer = ref;
14750     }
14751 
14752     void VisitBlockExpr(BlockExpr *block) {
14753       // Look inside nested blocks
14754       if (block->getBlockDecl()->capturesVariable(Variable))
14755         Visit(block->getBlockDecl()->getBody());
14756     }
14757 
14758     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
14759       if (Capturer) return;
14760       if (OVE->getSourceExpr())
14761         Visit(OVE->getSourceExpr());
14762     }
14763 
14764     void VisitBinaryOperator(BinaryOperator *BinOp) {
14765       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
14766         return;
14767       Expr *LHS = BinOp->getLHS();
14768       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
14769         if (DRE->getDecl() != Variable)
14770           return;
14771         if (Expr *RHS = BinOp->getRHS()) {
14772           RHS = RHS->IgnoreParenCasts();
14773           Optional<llvm::APSInt> Value;
14774           VarWillBeReased =
14775               (RHS && (Value = RHS->getIntegerConstantExpr(Context)) &&
14776                *Value == 0);
14777         }
14778       }
14779     }
14780   };
14781 
14782 } // namespace
14783 
14784 /// Check whether the given argument is a block which captures a
14785 /// variable.
14786 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
14787   assert(owner.Variable && owner.Loc.isValid());
14788 
14789   e = e->IgnoreParenCasts();
14790 
14791   // Look through [^{...} copy] and Block_copy(^{...}).
14792   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
14793     Selector Cmd = ME->getSelector();
14794     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
14795       e = ME->getInstanceReceiver();
14796       if (!e)
14797         return nullptr;
14798       e = e->IgnoreParenCasts();
14799     }
14800   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
14801     if (CE->getNumArgs() == 1) {
14802       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
14803       if (Fn) {
14804         const IdentifierInfo *FnI = Fn->getIdentifier();
14805         if (FnI && FnI->isStr("_Block_copy")) {
14806           e = CE->getArg(0)->IgnoreParenCasts();
14807         }
14808       }
14809     }
14810   }
14811 
14812   BlockExpr *block = dyn_cast<BlockExpr>(e);
14813   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
14814     return nullptr;
14815 
14816   FindCaptureVisitor visitor(S.Context, owner.Variable);
14817   visitor.Visit(block->getBlockDecl()->getBody());
14818   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
14819 }
14820 
14821 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
14822                                 RetainCycleOwner &owner) {
14823   assert(capturer);
14824   assert(owner.Variable && owner.Loc.isValid());
14825 
14826   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
14827     << owner.Variable << capturer->getSourceRange();
14828   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
14829     << owner.Indirect << owner.Range;
14830 }
14831 
14832 /// Check for a keyword selector that starts with the word 'add' or
14833 /// 'set'.
14834 static bool isSetterLikeSelector(Selector sel) {
14835   if (sel.isUnarySelector()) return false;
14836 
14837   StringRef str = sel.getNameForSlot(0);
14838   while (!str.empty() && str.front() == '_') str = str.substr(1);
14839   if (str.startswith("set"))
14840     str = str.substr(3);
14841   else if (str.startswith("add")) {
14842     // Specially allow 'addOperationWithBlock:'.
14843     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
14844       return false;
14845     str = str.substr(3);
14846   }
14847   else
14848     return false;
14849 
14850   if (str.empty()) return true;
14851   return !isLowercase(str.front());
14852 }
14853 
14854 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
14855                                                     ObjCMessageExpr *Message) {
14856   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
14857                                                 Message->getReceiverInterface(),
14858                                                 NSAPI::ClassId_NSMutableArray);
14859   if (!IsMutableArray) {
14860     return None;
14861   }
14862 
14863   Selector Sel = Message->getSelector();
14864 
14865   Optional<NSAPI::NSArrayMethodKind> MKOpt =
14866     S.NSAPIObj->getNSArrayMethodKind(Sel);
14867   if (!MKOpt) {
14868     return None;
14869   }
14870 
14871   NSAPI::NSArrayMethodKind MK = *MKOpt;
14872 
14873   switch (MK) {
14874     case NSAPI::NSMutableArr_addObject:
14875     case NSAPI::NSMutableArr_insertObjectAtIndex:
14876     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
14877       return 0;
14878     case NSAPI::NSMutableArr_replaceObjectAtIndex:
14879       return 1;
14880 
14881     default:
14882       return None;
14883   }
14884 
14885   return None;
14886 }
14887 
14888 static
14889 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
14890                                                   ObjCMessageExpr *Message) {
14891   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
14892                                             Message->getReceiverInterface(),
14893                                             NSAPI::ClassId_NSMutableDictionary);
14894   if (!IsMutableDictionary) {
14895     return None;
14896   }
14897 
14898   Selector Sel = Message->getSelector();
14899 
14900   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
14901     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
14902   if (!MKOpt) {
14903     return None;
14904   }
14905 
14906   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
14907 
14908   switch (MK) {
14909     case NSAPI::NSMutableDict_setObjectForKey:
14910     case NSAPI::NSMutableDict_setValueForKey:
14911     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
14912       return 0;
14913 
14914     default:
14915       return None;
14916   }
14917 
14918   return None;
14919 }
14920 
14921 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
14922   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
14923                                                 Message->getReceiverInterface(),
14924                                                 NSAPI::ClassId_NSMutableSet);
14925 
14926   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
14927                                             Message->getReceiverInterface(),
14928                                             NSAPI::ClassId_NSMutableOrderedSet);
14929   if (!IsMutableSet && !IsMutableOrderedSet) {
14930     return None;
14931   }
14932 
14933   Selector Sel = Message->getSelector();
14934 
14935   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
14936   if (!MKOpt) {
14937     return None;
14938   }
14939 
14940   NSAPI::NSSetMethodKind MK = *MKOpt;
14941 
14942   switch (MK) {
14943     case NSAPI::NSMutableSet_addObject:
14944     case NSAPI::NSOrderedSet_setObjectAtIndex:
14945     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
14946     case NSAPI::NSOrderedSet_insertObjectAtIndex:
14947       return 0;
14948     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
14949       return 1;
14950   }
14951 
14952   return None;
14953 }
14954 
14955 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
14956   if (!Message->isInstanceMessage()) {
14957     return;
14958   }
14959 
14960   Optional<int> ArgOpt;
14961 
14962   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
14963       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
14964       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
14965     return;
14966   }
14967 
14968   int ArgIndex = *ArgOpt;
14969 
14970   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
14971   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
14972     Arg = OE->getSourceExpr()->IgnoreImpCasts();
14973   }
14974 
14975   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
14976     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
14977       if (ArgRE->isObjCSelfExpr()) {
14978         Diag(Message->getSourceRange().getBegin(),
14979              diag::warn_objc_circular_container)
14980           << ArgRE->getDecl() << StringRef("'super'");
14981       }
14982     }
14983   } else {
14984     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
14985 
14986     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
14987       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
14988     }
14989 
14990     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
14991       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
14992         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
14993           ValueDecl *Decl = ReceiverRE->getDecl();
14994           Diag(Message->getSourceRange().getBegin(),
14995                diag::warn_objc_circular_container)
14996             << Decl << Decl;
14997           if (!ArgRE->isObjCSelfExpr()) {
14998             Diag(Decl->getLocation(),
14999                  diag::note_objc_circular_container_declared_here)
15000               << Decl;
15001           }
15002         }
15003       }
15004     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
15005       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
15006         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
15007           ObjCIvarDecl *Decl = IvarRE->getDecl();
15008           Diag(Message->getSourceRange().getBegin(),
15009                diag::warn_objc_circular_container)
15010             << Decl << Decl;
15011           Diag(Decl->getLocation(),
15012                diag::note_objc_circular_container_declared_here)
15013             << Decl;
15014         }
15015       }
15016     }
15017   }
15018 }
15019 
15020 /// Check a message send to see if it's likely to cause a retain cycle.
15021 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
15022   // Only check instance methods whose selector looks like a setter.
15023   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
15024     return;
15025 
15026   // Try to find a variable that the receiver is strongly owned by.
15027   RetainCycleOwner owner;
15028   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
15029     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
15030       return;
15031   } else {
15032     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
15033     owner.Variable = getCurMethodDecl()->getSelfDecl();
15034     owner.Loc = msg->getSuperLoc();
15035     owner.Range = msg->getSuperLoc();
15036   }
15037 
15038   // Check whether the receiver is captured by any of the arguments.
15039   const ObjCMethodDecl *MD = msg->getMethodDecl();
15040   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
15041     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
15042       // noescape blocks should not be retained by the method.
15043       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
15044         continue;
15045       return diagnoseRetainCycle(*this, capturer, owner);
15046     }
15047   }
15048 }
15049 
15050 /// Check a property assign to see if it's likely to cause a retain cycle.
15051 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
15052   RetainCycleOwner owner;
15053   if (!findRetainCycleOwner(*this, receiver, owner))
15054     return;
15055 
15056   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
15057     diagnoseRetainCycle(*this, capturer, owner);
15058 }
15059 
15060 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
15061   RetainCycleOwner Owner;
15062   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
15063     return;
15064 
15065   // Because we don't have an expression for the variable, we have to set the
15066   // location explicitly here.
15067   Owner.Loc = Var->getLocation();
15068   Owner.Range = Var->getSourceRange();
15069 
15070   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
15071     diagnoseRetainCycle(*this, Capturer, Owner);
15072 }
15073 
15074 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
15075                                      Expr *RHS, bool isProperty) {
15076   // Check if RHS is an Objective-C object literal, which also can get
15077   // immediately zapped in a weak reference.  Note that we explicitly
15078   // allow ObjCStringLiterals, since those are designed to never really die.
15079   RHS = RHS->IgnoreParenImpCasts();
15080 
15081   // This enum needs to match with the 'select' in
15082   // warn_objc_arc_literal_assign (off-by-1).
15083   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
15084   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
15085     return false;
15086 
15087   S.Diag(Loc, diag::warn_arc_literal_assign)
15088     << (unsigned) Kind
15089     << (isProperty ? 0 : 1)
15090     << RHS->getSourceRange();
15091 
15092   return true;
15093 }
15094 
15095 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
15096                                     Qualifiers::ObjCLifetime LT,
15097                                     Expr *RHS, bool isProperty) {
15098   // Strip off any implicit cast added to get to the one ARC-specific.
15099   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15100     if (cast->getCastKind() == CK_ARCConsumeObject) {
15101       S.Diag(Loc, diag::warn_arc_retained_assign)
15102         << (LT == Qualifiers::OCL_ExplicitNone)
15103         << (isProperty ? 0 : 1)
15104         << RHS->getSourceRange();
15105       return true;
15106     }
15107     RHS = cast->getSubExpr();
15108   }
15109 
15110   if (LT == Qualifiers::OCL_Weak &&
15111       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
15112     return true;
15113 
15114   return false;
15115 }
15116 
15117 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
15118                               QualType LHS, Expr *RHS) {
15119   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
15120 
15121   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
15122     return false;
15123 
15124   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
15125     return true;
15126 
15127   return false;
15128 }
15129 
15130 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
15131                               Expr *LHS, Expr *RHS) {
15132   QualType LHSType;
15133   // PropertyRef on LHS type need be directly obtained from
15134   // its declaration as it has a PseudoType.
15135   ObjCPropertyRefExpr *PRE
15136     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
15137   if (PRE && !PRE->isImplicitProperty()) {
15138     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15139     if (PD)
15140       LHSType = PD->getType();
15141   }
15142 
15143   if (LHSType.isNull())
15144     LHSType = LHS->getType();
15145 
15146   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
15147 
15148   if (LT == Qualifiers::OCL_Weak) {
15149     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
15150       getCurFunction()->markSafeWeakUse(LHS);
15151   }
15152 
15153   if (checkUnsafeAssigns(Loc, LHSType, RHS))
15154     return;
15155 
15156   // FIXME. Check for other life times.
15157   if (LT != Qualifiers::OCL_None)
15158     return;
15159 
15160   if (PRE) {
15161     if (PRE->isImplicitProperty())
15162       return;
15163     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15164     if (!PD)
15165       return;
15166 
15167     unsigned Attributes = PD->getPropertyAttributes();
15168     if (Attributes & ObjCPropertyAttribute::kind_assign) {
15169       // when 'assign' attribute was not explicitly specified
15170       // by user, ignore it and rely on property type itself
15171       // for lifetime info.
15172       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
15173       if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
15174           LHSType->isObjCRetainableType())
15175         return;
15176 
15177       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15178         if (cast->getCastKind() == CK_ARCConsumeObject) {
15179           Diag(Loc, diag::warn_arc_retained_property_assign)
15180           << RHS->getSourceRange();
15181           return;
15182         }
15183         RHS = cast->getSubExpr();
15184       }
15185     } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
15186       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
15187         return;
15188     }
15189   }
15190 }
15191 
15192 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
15193 
15194 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
15195                                         SourceLocation StmtLoc,
15196                                         const NullStmt *Body) {
15197   // Do not warn if the body is a macro that expands to nothing, e.g:
15198   //
15199   // #define CALL(x)
15200   // if (condition)
15201   //   CALL(0);
15202   if (Body->hasLeadingEmptyMacro())
15203     return false;
15204 
15205   // Get line numbers of statement and body.
15206   bool StmtLineInvalid;
15207   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
15208                                                       &StmtLineInvalid);
15209   if (StmtLineInvalid)
15210     return false;
15211 
15212   bool BodyLineInvalid;
15213   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
15214                                                       &BodyLineInvalid);
15215   if (BodyLineInvalid)
15216     return false;
15217 
15218   // Warn if null statement and body are on the same line.
15219   if (StmtLine != BodyLine)
15220     return false;
15221 
15222   return true;
15223 }
15224 
15225 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
15226                                  const Stmt *Body,
15227                                  unsigned DiagID) {
15228   // Since this is a syntactic check, don't emit diagnostic for template
15229   // instantiations, this just adds noise.
15230   if (CurrentInstantiationScope)
15231     return;
15232 
15233   // The body should be a null statement.
15234   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15235   if (!NBody)
15236     return;
15237 
15238   // Do the usual checks.
15239   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15240     return;
15241 
15242   Diag(NBody->getSemiLoc(), DiagID);
15243   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15244 }
15245 
15246 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
15247                                  const Stmt *PossibleBody) {
15248   assert(!CurrentInstantiationScope); // Ensured by caller
15249 
15250   SourceLocation StmtLoc;
15251   const Stmt *Body;
15252   unsigned DiagID;
15253   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
15254     StmtLoc = FS->getRParenLoc();
15255     Body = FS->getBody();
15256     DiagID = diag::warn_empty_for_body;
15257   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
15258     StmtLoc = WS->getCond()->getSourceRange().getEnd();
15259     Body = WS->getBody();
15260     DiagID = diag::warn_empty_while_body;
15261   } else
15262     return; // Neither `for' nor `while'.
15263 
15264   // The body should be a null statement.
15265   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15266   if (!NBody)
15267     return;
15268 
15269   // Skip expensive checks if diagnostic is disabled.
15270   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
15271     return;
15272 
15273   // Do the usual checks.
15274   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15275     return;
15276 
15277   // `for(...);' and `while(...);' are popular idioms, so in order to keep
15278   // noise level low, emit diagnostics only if for/while is followed by a
15279   // CompoundStmt, e.g.:
15280   //    for (int i = 0; i < n; i++);
15281   //    {
15282   //      a(i);
15283   //    }
15284   // or if for/while is followed by a statement with more indentation
15285   // than for/while itself:
15286   //    for (int i = 0; i < n; i++);
15287   //      a(i);
15288   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
15289   if (!ProbableTypo) {
15290     bool BodyColInvalid;
15291     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
15292         PossibleBody->getBeginLoc(), &BodyColInvalid);
15293     if (BodyColInvalid)
15294       return;
15295 
15296     bool StmtColInvalid;
15297     unsigned StmtCol =
15298         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
15299     if (StmtColInvalid)
15300       return;
15301 
15302     if (BodyCol > StmtCol)
15303       ProbableTypo = true;
15304   }
15305 
15306   if (ProbableTypo) {
15307     Diag(NBody->getSemiLoc(), DiagID);
15308     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15309   }
15310 }
15311 
15312 //===--- CHECK: Warn on self move with std::move. -------------------------===//
15313 
15314 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
15315 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
15316                              SourceLocation OpLoc) {
15317   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
15318     return;
15319 
15320   if (inTemplateInstantiation())
15321     return;
15322 
15323   // Strip parens and casts away.
15324   LHSExpr = LHSExpr->IgnoreParenImpCasts();
15325   RHSExpr = RHSExpr->IgnoreParenImpCasts();
15326 
15327   // Check for a call expression
15328   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
15329   if (!CE || CE->getNumArgs() != 1)
15330     return;
15331 
15332   // Check for a call to std::move
15333   if (!CE->isCallToStdMove())
15334     return;
15335 
15336   // Get argument from std::move
15337   RHSExpr = CE->getArg(0);
15338 
15339   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
15340   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
15341 
15342   // Two DeclRefExpr's, check that the decls are the same.
15343   if (LHSDeclRef && RHSDeclRef) {
15344     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15345       return;
15346     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15347         RHSDeclRef->getDecl()->getCanonicalDecl())
15348       return;
15349 
15350     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15351                                         << LHSExpr->getSourceRange()
15352                                         << RHSExpr->getSourceRange();
15353     return;
15354   }
15355 
15356   // Member variables require a different approach to check for self moves.
15357   // MemberExpr's are the same if every nested MemberExpr refers to the same
15358   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
15359   // the base Expr's are CXXThisExpr's.
15360   const Expr *LHSBase = LHSExpr;
15361   const Expr *RHSBase = RHSExpr;
15362   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
15363   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
15364   if (!LHSME || !RHSME)
15365     return;
15366 
15367   while (LHSME && RHSME) {
15368     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
15369         RHSME->getMemberDecl()->getCanonicalDecl())
15370       return;
15371 
15372     LHSBase = LHSME->getBase();
15373     RHSBase = RHSME->getBase();
15374     LHSME = dyn_cast<MemberExpr>(LHSBase);
15375     RHSME = dyn_cast<MemberExpr>(RHSBase);
15376   }
15377 
15378   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
15379   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
15380   if (LHSDeclRef && RHSDeclRef) {
15381     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15382       return;
15383     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15384         RHSDeclRef->getDecl()->getCanonicalDecl())
15385       return;
15386 
15387     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15388                                         << LHSExpr->getSourceRange()
15389                                         << RHSExpr->getSourceRange();
15390     return;
15391   }
15392 
15393   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
15394     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15395                                         << LHSExpr->getSourceRange()
15396                                         << RHSExpr->getSourceRange();
15397 }
15398 
15399 //===--- Layout compatibility ----------------------------------------------//
15400 
15401 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
15402 
15403 /// Check if two enumeration types are layout-compatible.
15404 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
15405   // C++11 [dcl.enum] p8:
15406   // Two enumeration types are layout-compatible if they have the same
15407   // underlying type.
15408   return ED1->isComplete() && ED2->isComplete() &&
15409          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
15410 }
15411 
15412 /// Check if two fields are layout-compatible.
15413 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
15414                                FieldDecl *Field2) {
15415   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
15416     return false;
15417 
15418   if (Field1->isBitField() != Field2->isBitField())
15419     return false;
15420 
15421   if (Field1->isBitField()) {
15422     // Make sure that the bit-fields are the same length.
15423     unsigned Bits1 = Field1->getBitWidthValue(C);
15424     unsigned Bits2 = Field2->getBitWidthValue(C);
15425 
15426     if (Bits1 != Bits2)
15427       return false;
15428   }
15429 
15430   return true;
15431 }
15432 
15433 /// Check if two standard-layout structs are layout-compatible.
15434 /// (C++11 [class.mem] p17)
15435 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
15436                                      RecordDecl *RD2) {
15437   // If both records are C++ classes, check that base classes match.
15438   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
15439     // If one of records is a CXXRecordDecl we are in C++ mode,
15440     // thus the other one is a CXXRecordDecl, too.
15441     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
15442     // Check number of base classes.
15443     if (D1CXX->getNumBases() != D2CXX->getNumBases())
15444       return false;
15445 
15446     // Check the base classes.
15447     for (CXXRecordDecl::base_class_const_iterator
15448                Base1 = D1CXX->bases_begin(),
15449            BaseEnd1 = D1CXX->bases_end(),
15450               Base2 = D2CXX->bases_begin();
15451          Base1 != BaseEnd1;
15452          ++Base1, ++Base2) {
15453       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
15454         return false;
15455     }
15456   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
15457     // If only RD2 is a C++ class, it should have zero base classes.
15458     if (D2CXX->getNumBases() > 0)
15459       return false;
15460   }
15461 
15462   // Check the fields.
15463   RecordDecl::field_iterator Field2 = RD2->field_begin(),
15464                              Field2End = RD2->field_end(),
15465                              Field1 = RD1->field_begin(),
15466                              Field1End = RD1->field_end();
15467   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
15468     if (!isLayoutCompatible(C, *Field1, *Field2))
15469       return false;
15470   }
15471   if (Field1 != Field1End || Field2 != Field2End)
15472     return false;
15473 
15474   return true;
15475 }
15476 
15477 /// Check if two standard-layout unions are layout-compatible.
15478 /// (C++11 [class.mem] p18)
15479 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
15480                                     RecordDecl *RD2) {
15481   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
15482   for (auto *Field2 : RD2->fields())
15483     UnmatchedFields.insert(Field2);
15484 
15485   for (auto *Field1 : RD1->fields()) {
15486     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
15487         I = UnmatchedFields.begin(),
15488         E = UnmatchedFields.end();
15489 
15490     for ( ; I != E; ++I) {
15491       if (isLayoutCompatible(C, Field1, *I)) {
15492         bool Result = UnmatchedFields.erase(*I);
15493         (void) Result;
15494         assert(Result);
15495         break;
15496       }
15497     }
15498     if (I == E)
15499       return false;
15500   }
15501 
15502   return UnmatchedFields.empty();
15503 }
15504 
15505 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
15506                                RecordDecl *RD2) {
15507   if (RD1->isUnion() != RD2->isUnion())
15508     return false;
15509 
15510   if (RD1->isUnion())
15511     return isLayoutCompatibleUnion(C, RD1, RD2);
15512   else
15513     return isLayoutCompatibleStruct(C, RD1, RD2);
15514 }
15515 
15516 /// Check if two types are layout-compatible in C++11 sense.
15517 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
15518   if (T1.isNull() || T2.isNull())
15519     return false;
15520 
15521   // C++11 [basic.types] p11:
15522   // If two types T1 and T2 are the same type, then T1 and T2 are
15523   // layout-compatible types.
15524   if (C.hasSameType(T1, T2))
15525     return true;
15526 
15527   T1 = T1.getCanonicalType().getUnqualifiedType();
15528   T2 = T2.getCanonicalType().getUnqualifiedType();
15529 
15530   const Type::TypeClass TC1 = T1->getTypeClass();
15531   const Type::TypeClass TC2 = T2->getTypeClass();
15532 
15533   if (TC1 != TC2)
15534     return false;
15535 
15536   if (TC1 == Type::Enum) {
15537     return isLayoutCompatible(C,
15538                               cast<EnumType>(T1)->getDecl(),
15539                               cast<EnumType>(T2)->getDecl());
15540   } else if (TC1 == Type::Record) {
15541     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
15542       return false;
15543 
15544     return isLayoutCompatible(C,
15545                               cast<RecordType>(T1)->getDecl(),
15546                               cast<RecordType>(T2)->getDecl());
15547   }
15548 
15549   return false;
15550 }
15551 
15552 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
15553 
15554 /// Given a type tag expression find the type tag itself.
15555 ///
15556 /// \param TypeExpr Type tag expression, as it appears in user's code.
15557 ///
15558 /// \param VD Declaration of an identifier that appears in a type tag.
15559 ///
15560 /// \param MagicValue Type tag magic value.
15561 ///
15562 /// \param isConstantEvaluated wether the evalaution should be performed in
15563 
15564 /// constant context.
15565 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
15566                             const ValueDecl **VD, uint64_t *MagicValue,
15567                             bool isConstantEvaluated) {
15568   while(true) {
15569     if (!TypeExpr)
15570       return false;
15571 
15572     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
15573 
15574     switch (TypeExpr->getStmtClass()) {
15575     case Stmt::UnaryOperatorClass: {
15576       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
15577       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
15578         TypeExpr = UO->getSubExpr();
15579         continue;
15580       }
15581       return false;
15582     }
15583 
15584     case Stmt::DeclRefExprClass: {
15585       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
15586       *VD = DRE->getDecl();
15587       return true;
15588     }
15589 
15590     case Stmt::IntegerLiteralClass: {
15591       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
15592       llvm::APInt MagicValueAPInt = IL->getValue();
15593       if (MagicValueAPInt.getActiveBits() <= 64) {
15594         *MagicValue = MagicValueAPInt.getZExtValue();
15595         return true;
15596       } else
15597         return false;
15598     }
15599 
15600     case Stmt::BinaryConditionalOperatorClass:
15601     case Stmt::ConditionalOperatorClass: {
15602       const AbstractConditionalOperator *ACO =
15603           cast<AbstractConditionalOperator>(TypeExpr);
15604       bool Result;
15605       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
15606                                                      isConstantEvaluated)) {
15607         if (Result)
15608           TypeExpr = ACO->getTrueExpr();
15609         else
15610           TypeExpr = ACO->getFalseExpr();
15611         continue;
15612       }
15613       return false;
15614     }
15615 
15616     case Stmt::BinaryOperatorClass: {
15617       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
15618       if (BO->getOpcode() == BO_Comma) {
15619         TypeExpr = BO->getRHS();
15620         continue;
15621       }
15622       return false;
15623     }
15624 
15625     default:
15626       return false;
15627     }
15628   }
15629 }
15630 
15631 /// Retrieve the C type corresponding to type tag TypeExpr.
15632 ///
15633 /// \param TypeExpr Expression that specifies a type tag.
15634 ///
15635 /// \param MagicValues Registered magic values.
15636 ///
15637 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
15638 ///        kind.
15639 ///
15640 /// \param TypeInfo Information about the corresponding C type.
15641 ///
15642 /// \param isConstantEvaluated wether the evalaution should be performed in
15643 /// constant context.
15644 ///
15645 /// \returns true if the corresponding C type was found.
15646 static bool GetMatchingCType(
15647     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
15648     const ASTContext &Ctx,
15649     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
15650         *MagicValues,
15651     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
15652     bool isConstantEvaluated) {
15653   FoundWrongKind = false;
15654 
15655   // Variable declaration that has type_tag_for_datatype attribute.
15656   const ValueDecl *VD = nullptr;
15657 
15658   uint64_t MagicValue;
15659 
15660   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
15661     return false;
15662 
15663   if (VD) {
15664     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
15665       if (I->getArgumentKind() != ArgumentKind) {
15666         FoundWrongKind = true;
15667         return false;
15668       }
15669       TypeInfo.Type = I->getMatchingCType();
15670       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
15671       TypeInfo.MustBeNull = I->getMustBeNull();
15672       return true;
15673     }
15674     return false;
15675   }
15676 
15677   if (!MagicValues)
15678     return false;
15679 
15680   llvm::DenseMap<Sema::TypeTagMagicValue,
15681                  Sema::TypeTagData>::const_iterator I =
15682       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
15683   if (I == MagicValues->end())
15684     return false;
15685 
15686   TypeInfo = I->second;
15687   return true;
15688 }
15689 
15690 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
15691                                       uint64_t MagicValue, QualType Type,
15692                                       bool LayoutCompatible,
15693                                       bool MustBeNull) {
15694   if (!TypeTagForDatatypeMagicValues)
15695     TypeTagForDatatypeMagicValues.reset(
15696         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
15697 
15698   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
15699   (*TypeTagForDatatypeMagicValues)[Magic] =
15700       TypeTagData(Type, LayoutCompatible, MustBeNull);
15701 }
15702 
15703 static bool IsSameCharType(QualType T1, QualType T2) {
15704   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
15705   if (!BT1)
15706     return false;
15707 
15708   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
15709   if (!BT2)
15710     return false;
15711 
15712   BuiltinType::Kind T1Kind = BT1->getKind();
15713   BuiltinType::Kind T2Kind = BT2->getKind();
15714 
15715   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
15716          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
15717          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
15718          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
15719 }
15720 
15721 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
15722                                     const ArrayRef<const Expr *> ExprArgs,
15723                                     SourceLocation CallSiteLoc) {
15724   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
15725   bool IsPointerAttr = Attr->getIsPointer();
15726 
15727   // Retrieve the argument representing the 'type_tag'.
15728   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
15729   if (TypeTagIdxAST >= ExprArgs.size()) {
15730     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
15731         << 0 << Attr->getTypeTagIdx().getSourceIndex();
15732     return;
15733   }
15734   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
15735   bool FoundWrongKind;
15736   TypeTagData TypeInfo;
15737   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
15738                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
15739                         TypeInfo, isConstantEvaluated())) {
15740     if (FoundWrongKind)
15741       Diag(TypeTagExpr->getExprLoc(),
15742            diag::warn_type_tag_for_datatype_wrong_kind)
15743         << TypeTagExpr->getSourceRange();
15744     return;
15745   }
15746 
15747   // Retrieve the argument representing the 'arg_idx'.
15748   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
15749   if (ArgumentIdxAST >= ExprArgs.size()) {
15750     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
15751         << 1 << Attr->getArgumentIdx().getSourceIndex();
15752     return;
15753   }
15754   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
15755   if (IsPointerAttr) {
15756     // Skip implicit cast of pointer to `void *' (as a function argument).
15757     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
15758       if (ICE->getType()->isVoidPointerType() &&
15759           ICE->getCastKind() == CK_BitCast)
15760         ArgumentExpr = ICE->getSubExpr();
15761   }
15762   QualType ArgumentType = ArgumentExpr->getType();
15763 
15764   // Passing a `void*' pointer shouldn't trigger a warning.
15765   if (IsPointerAttr && ArgumentType->isVoidPointerType())
15766     return;
15767 
15768   if (TypeInfo.MustBeNull) {
15769     // Type tag with matching void type requires a null pointer.
15770     if (!ArgumentExpr->isNullPointerConstant(Context,
15771                                              Expr::NPC_ValueDependentIsNotNull)) {
15772       Diag(ArgumentExpr->getExprLoc(),
15773            diag::warn_type_safety_null_pointer_required)
15774           << ArgumentKind->getName()
15775           << ArgumentExpr->getSourceRange()
15776           << TypeTagExpr->getSourceRange();
15777     }
15778     return;
15779   }
15780 
15781   QualType RequiredType = TypeInfo.Type;
15782   if (IsPointerAttr)
15783     RequiredType = Context.getPointerType(RequiredType);
15784 
15785   bool mismatch = false;
15786   if (!TypeInfo.LayoutCompatible) {
15787     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
15788 
15789     // C++11 [basic.fundamental] p1:
15790     // Plain char, signed char, and unsigned char are three distinct types.
15791     //
15792     // But we treat plain `char' as equivalent to `signed char' or `unsigned
15793     // char' depending on the current char signedness mode.
15794     if (mismatch)
15795       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
15796                                            RequiredType->getPointeeType())) ||
15797           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
15798         mismatch = false;
15799   } else
15800     if (IsPointerAttr)
15801       mismatch = !isLayoutCompatible(Context,
15802                                      ArgumentType->getPointeeType(),
15803                                      RequiredType->getPointeeType());
15804     else
15805       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
15806 
15807   if (mismatch)
15808     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
15809         << ArgumentType << ArgumentKind
15810         << TypeInfo.LayoutCompatible << RequiredType
15811         << ArgumentExpr->getSourceRange()
15812         << TypeTagExpr->getSourceRange();
15813 }
15814 
15815 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
15816                                          CharUnits Alignment) {
15817   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
15818 }
15819 
15820 void Sema::DiagnoseMisalignedMembers() {
15821   for (MisalignedMember &m : MisalignedMembers) {
15822     const NamedDecl *ND = m.RD;
15823     if (ND->getName().empty()) {
15824       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
15825         ND = TD;
15826     }
15827     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
15828         << m.MD << ND << m.E->getSourceRange();
15829   }
15830   MisalignedMembers.clear();
15831 }
15832 
15833 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
15834   E = E->IgnoreParens();
15835   if (!T->isPointerType() && !T->isIntegerType())
15836     return;
15837   if (isa<UnaryOperator>(E) &&
15838       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
15839     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
15840     if (isa<MemberExpr>(Op)) {
15841       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
15842       if (MA != MisalignedMembers.end() &&
15843           (T->isIntegerType() ||
15844            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
15845                                    Context.getTypeAlignInChars(
15846                                        T->getPointeeType()) <= MA->Alignment))))
15847         MisalignedMembers.erase(MA);
15848     }
15849   }
15850 }
15851 
15852 void Sema::RefersToMemberWithReducedAlignment(
15853     Expr *E,
15854     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
15855         Action) {
15856   const auto *ME = dyn_cast<MemberExpr>(E);
15857   if (!ME)
15858     return;
15859 
15860   // No need to check expressions with an __unaligned-qualified type.
15861   if (E->getType().getQualifiers().hasUnaligned())
15862     return;
15863 
15864   // For a chain of MemberExpr like "a.b.c.d" this list
15865   // will keep FieldDecl's like [d, c, b].
15866   SmallVector<FieldDecl *, 4> ReverseMemberChain;
15867   const MemberExpr *TopME = nullptr;
15868   bool AnyIsPacked = false;
15869   do {
15870     QualType BaseType = ME->getBase()->getType();
15871     if (BaseType->isDependentType())
15872       return;
15873     if (ME->isArrow())
15874       BaseType = BaseType->getPointeeType();
15875     RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
15876     if (RD->isInvalidDecl())
15877       return;
15878 
15879     ValueDecl *MD = ME->getMemberDecl();
15880     auto *FD = dyn_cast<FieldDecl>(MD);
15881     // We do not care about non-data members.
15882     if (!FD || FD->isInvalidDecl())
15883       return;
15884 
15885     AnyIsPacked =
15886         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
15887     ReverseMemberChain.push_back(FD);
15888 
15889     TopME = ME;
15890     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
15891   } while (ME);
15892   assert(TopME && "We did not compute a topmost MemberExpr!");
15893 
15894   // Not the scope of this diagnostic.
15895   if (!AnyIsPacked)
15896     return;
15897 
15898   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
15899   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
15900   // TODO: The innermost base of the member expression may be too complicated.
15901   // For now, just disregard these cases. This is left for future
15902   // improvement.
15903   if (!DRE && !isa<CXXThisExpr>(TopBase))
15904       return;
15905 
15906   // Alignment expected by the whole expression.
15907   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
15908 
15909   // No need to do anything else with this case.
15910   if (ExpectedAlignment.isOne())
15911     return;
15912 
15913   // Synthesize offset of the whole access.
15914   CharUnits Offset;
15915   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
15916        I++) {
15917     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
15918   }
15919 
15920   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
15921   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
15922       ReverseMemberChain.back()->getParent()->getTypeForDecl());
15923 
15924   // The base expression of the innermost MemberExpr may give
15925   // stronger guarantees than the class containing the member.
15926   if (DRE && !TopME->isArrow()) {
15927     const ValueDecl *VD = DRE->getDecl();
15928     if (!VD->getType()->isReferenceType())
15929       CompleteObjectAlignment =
15930           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
15931   }
15932 
15933   // Check if the synthesized offset fulfills the alignment.
15934   if (Offset % ExpectedAlignment != 0 ||
15935       // It may fulfill the offset it but the effective alignment may still be
15936       // lower than the expected expression alignment.
15937       CompleteObjectAlignment < ExpectedAlignment) {
15938     // If this happens, we want to determine a sensible culprit of this.
15939     // Intuitively, watching the chain of member expressions from right to
15940     // left, we start with the required alignment (as required by the field
15941     // type) but some packed attribute in that chain has reduced the alignment.
15942     // It may happen that another packed structure increases it again. But if
15943     // we are here such increase has not been enough. So pointing the first
15944     // FieldDecl that either is packed or else its RecordDecl is,
15945     // seems reasonable.
15946     FieldDecl *FD = nullptr;
15947     CharUnits Alignment;
15948     for (FieldDecl *FDI : ReverseMemberChain) {
15949       if (FDI->hasAttr<PackedAttr>() ||
15950           FDI->getParent()->hasAttr<PackedAttr>()) {
15951         FD = FDI;
15952         Alignment = std::min(
15953             Context.getTypeAlignInChars(FD->getType()),
15954             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
15955         break;
15956       }
15957     }
15958     assert(FD && "We did not find a packed FieldDecl!");
15959     Action(E, FD->getParent(), FD, Alignment);
15960   }
15961 }
15962 
15963 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
15964   using namespace std::placeholders;
15965 
15966   RefersToMemberWithReducedAlignment(
15967       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
15968                      _2, _3, _4));
15969 }
15970 
15971 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall,
15972                                             ExprResult CallResult) {
15973   if (checkArgCount(*this, TheCall, 1))
15974     return ExprError();
15975 
15976   ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
15977   if (MatrixArg.isInvalid())
15978     return MatrixArg;
15979   Expr *Matrix = MatrixArg.get();
15980 
15981   auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
15982   if (!MType) {
15983     Diag(Matrix->getBeginLoc(), diag::err_builtin_matrix_arg);
15984     return ExprError();
15985   }
15986 
15987   // Create returned matrix type by swapping rows and columns of the argument
15988   // matrix type.
15989   QualType ResultType = Context.getConstantMatrixType(
15990       MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
15991 
15992   // Change the return type to the type of the returned matrix.
15993   TheCall->setType(ResultType);
15994 
15995   // Update call argument to use the possibly converted matrix argument.
15996   TheCall->setArg(0, Matrix);
15997   return CallResult;
15998 }
15999 
16000 // Get and verify the matrix dimensions.
16001 static llvm::Optional<unsigned>
16002 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {
16003   SourceLocation ErrorPos;
16004   Optional<llvm::APSInt> Value =
16005       Expr->getIntegerConstantExpr(S.Context, &ErrorPos);
16006   if (!Value) {
16007     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
16008         << Name;
16009     return {};
16010   }
16011   uint64_t Dim = Value->getZExtValue();
16012   if (!ConstantMatrixType::isDimensionValid(Dim)) {
16013     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
16014         << Name << ConstantMatrixType::getMaxElementsPerDimension();
16015     return {};
16016   }
16017   return Dim;
16018 }
16019 
16020 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
16021                                                   ExprResult CallResult) {
16022   if (!getLangOpts().MatrixTypes) {
16023     Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
16024     return ExprError();
16025   }
16026 
16027   if (checkArgCount(*this, TheCall, 4))
16028     return ExprError();
16029 
16030   unsigned PtrArgIdx = 0;
16031   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16032   Expr *RowsExpr = TheCall->getArg(1);
16033   Expr *ColumnsExpr = TheCall->getArg(2);
16034   Expr *StrideExpr = TheCall->getArg(3);
16035 
16036   bool ArgError = false;
16037 
16038   // Check pointer argument.
16039   {
16040     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
16041     if (PtrConv.isInvalid())
16042       return PtrConv;
16043     PtrExpr = PtrConv.get();
16044     TheCall->setArg(0, PtrExpr);
16045     if (PtrExpr->isTypeDependent()) {
16046       TheCall->setType(Context.DependentTy);
16047       return TheCall;
16048     }
16049   }
16050 
16051   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16052   QualType ElementTy;
16053   if (!PtrTy) {
16054     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
16055         << PtrArgIdx + 1;
16056     ArgError = true;
16057   } else {
16058     ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
16059 
16060     if (!ConstantMatrixType::isValidElementType(ElementTy)) {
16061       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
16062           << PtrArgIdx + 1;
16063       ArgError = true;
16064     }
16065   }
16066 
16067   // Apply default Lvalue conversions and convert the expression to size_t.
16068   auto ApplyArgumentConversions = [this](Expr *E) {
16069     ExprResult Conv = DefaultLvalueConversion(E);
16070     if (Conv.isInvalid())
16071       return Conv;
16072 
16073     return tryConvertExprToType(Conv.get(), Context.getSizeType());
16074   };
16075 
16076   // Apply conversion to row and column expressions.
16077   ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
16078   if (!RowsConv.isInvalid()) {
16079     RowsExpr = RowsConv.get();
16080     TheCall->setArg(1, RowsExpr);
16081   } else
16082     RowsExpr = nullptr;
16083 
16084   ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
16085   if (!ColumnsConv.isInvalid()) {
16086     ColumnsExpr = ColumnsConv.get();
16087     TheCall->setArg(2, ColumnsExpr);
16088   } else
16089     ColumnsExpr = nullptr;
16090 
16091   // If any any part of the result matrix type is still pending, just use
16092   // Context.DependentTy, until all parts are resolved.
16093   if ((RowsExpr && RowsExpr->isTypeDependent()) ||
16094       (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
16095     TheCall->setType(Context.DependentTy);
16096     return CallResult;
16097   }
16098 
16099   // Check row and column dimenions.
16100   llvm::Optional<unsigned> MaybeRows;
16101   if (RowsExpr)
16102     MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
16103 
16104   llvm::Optional<unsigned> MaybeColumns;
16105   if (ColumnsExpr)
16106     MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
16107 
16108   // Check stride argument.
16109   ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
16110   if (StrideConv.isInvalid())
16111     return ExprError();
16112   StrideExpr = StrideConv.get();
16113   TheCall->setArg(3, StrideExpr);
16114 
16115   if (MaybeRows) {
16116     if (Optional<llvm::APSInt> Value =
16117             StrideExpr->getIntegerConstantExpr(Context)) {
16118       uint64_t Stride = Value->getZExtValue();
16119       if (Stride < *MaybeRows) {
16120         Diag(StrideExpr->getBeginLoc(),
16121              diag::err_builtin_matrix_stride_too_small);
16122         ArgError = true;
16123       }
16124     }
16125   }
16126 
16127   if (ArgError || !MaybeRows || !MaybeColumns)
16128     return ExprError();
16129 
16130   TheCall->setType(
16131       Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
16132   return CallResult;
16133 }
16134 
16135 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
16136                                                    ExprResult CallResult) {
16137   if (checkArgCount(*this, TheCall, 3))
16138     return ExprError();
16139 
16140   unsigned PtrArgIdx = 1;
16141   Expr *MatrixExpr = TheCall->getArg(0);
16142   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16143   Expr *StrideExpr = TheCall->getArg(2);
16144 
16145   bool ArgError = false;
16146 
16147   {
16148     ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
16149     if (MatrixConv.isInvalid())
16150       return MatrixConv;
16151     MatrixExpr = MatrixConv.get();
16152     TheCall->setArg(0, MatrixExpr);
16153   }
16154   if (MatrixExpr->isTypeDependent()) {
16155     TheCall->setType(Context.DependentTy);
16156     return TheCall;
16157   }
16158 
16159   auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
16160   if (!MatrixTy) {
16161     Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_matrix_arg) << 0;
16162     ArgError = true;
16163   }
16164 
16165   {
16166     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
16167     if (PtrConv.isInvalid())
16168       return PtrConv;
16169     PtrExpr = PtrConv.get();
16170     TheCall->setArg(1, PtrExpr);
16171     if (PtrExpr->isTypeDependent()) {
16172       TheCall->setType(Context.DependentTy);
16173       return TheCall;
16174     }
16175   }
16176 
16177   // Check pointer argument.
16178   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16179   if (!PtrTy) {
16180     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
16181         << PtrArgIdx + 1;
16182     ArgError = true;
16183   } else {
16184     QualType ElementTy = PtrTy->getPointeeType();
16185     if (ElementTy.isConstQualified()) {
16186       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
16187       ArgError = true;
16188     }
16189     ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
16190     if (MatrixTy &&
16191         !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
16192       Diag(PtrExpr->getBeginLoc(),
16193            diag::err_builtin_matrix_pointer_arg_mismatch)
16194           << ElementTy << MatrixTy->getElementType();
16195       ArgError = true;
16196     }
16197   }
16198 
16199   // Apply default Lvalue conversions and convert the stride expression to
16200   // size_t.
16201   {
16202     ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
16203     if (StrideConv.isInvalid())
16204       return StrideConv;
16205 
16206     StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
16207     if (StrideConv.isInvalid())
16208       return StrideConv;
16209     StrideExpr = StrideConv.get();
16210     TheCall->setArg(2, StrideExpr);
16211   }
16212 
16213   // Check stride argument.
16214   if (MatrixTy) {
16215     if (Optional<llvm::APSInt> Value =
16216             StrideExpr->getIntegerConstantExpr(Context)) {
16217       uint64_t Stride = Value->getZExtValue();
16218       if (Stride < MatrixTy->getNumRows()) {
16219         Diag(StrideExpr->getBeginLoc(),
16220              diag::err_builtin_matrix_stride_too_small);
16221         ArgError = true;
16222       }
16223     }
16224   }
16225 
16226   if (ArgError)
16227     return ExprError();
16228 
16229   return CallResult;
16230 }
16231 
16232 /// \brief Enforce the bounds of a TCB
16233 /// CheckTCBEnforcement - Enforces that every function in a named TCB only
16234 /// directly calls other functions in the same TCB as marked by the enforce_tcb
16235 /// and enforce_tcb_leaf attributes.
16236 void Sema::CheckTCBEnforcement(const CallExpr *TheCall,
16237                                const FunctionDecl *Callee) {
16238   const FunctionDecl *Caller = getCurFunctionDecl();
16239 
16240   // Calls to builtins are not enforced.
16241   if (!Caller || !Caller->hasAttr<EnforceTCBAttr>() ||
16242       Callee->getBuiltinID() != 0)
16243     return;
16244 
16245   // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
16246   // all TCBs the callee is a part of.
16247   llvm::StringSet<> CalleeTCBs;
16248   for_each(Callee->specific_attrs<EnforceTCBAttr>(),
16249            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
16250   for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(),
16251            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
16252 
16253   // Go through the TCBs the caller is a part of and emit warnings if Caller
16254   // is in a TCB that the Callee is not.
16255   for_each(
16256       Caller->specific_attrs<EnforceTCBAttr>(),
16257       [&](const auto *A) {
16258         StringRef CallerTCB = A->getTCBName();
16259         if (CalleeTCBs.count(CallerTCB) == 0) {
16260           this->Diag(TheCall->getExprLoc(),
16261                      diag::warn_tcb_enforcement_violation) << Callee
16262                                                            << CallerTCB;
16263         }
16264       });
16265 }
16266