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   case Builtin::BI__builtin_get_device_side_mangled_name: {
1971     auto Check = [](CallExpr *TheCall) {
1972       if (TheCall->getNumArgs() != 1)
1973         return false;
1974       auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());
1975       if (!DRE)
1976         return false;
1977       auto *D = DRE->getDecl();
1978       if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D))
1979         return false;
1980       return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
1981              D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
1982     };
1983     if (!Check(TheCall)) {
1984       Diag(TheCall->getBeginLoc(),
1985            diag::err_hip_invalid_args_builtin_mangled_name);
1986       return ExprError();
1987     }
1988   }
1989   }
1990 
1991   // Since the target specific builtins for each arch overlap, only check those
1992   // of the arch we are compiling for.
1993   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1994     if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
1995       assert(Context.getAuxTargetInfo() &&
1996              "Aux Target Builtin, but not an aux target?");
1997 
1998       if (CheckTSBuiltinFunctionCall(
1999               *Context.getAuxTargetInfo(),
2000               Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
2001         return ExprError();
2002     } else {
2003       if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
2004                                      TheCall))
2005         return ExprError();
2006     }
2007   }
2008 
2009   return TheCallResult;
2010 }
2011 
2012 // Get the valid immediate range for the specified NEON type code.
2013 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
2014   NeonTypeFlags Type(t);
2015   int IsQuad = ForceQuad ? true : Type.isQuad();
2016   switch (Type.getEltType()) {
2017   case NeonTypeFlags::Int8:
2018   case NeonTypeFlags::Poly8:
2019     return shift ? 7 : (8 << IsQuad) - 1;
2020   case NeonTypeFlags::Int16:
2021   case NeonTypeFlags::Poly16:
2022     return shift ? 15 : (4 << IsQuad) - 1;
2023   case NeonTypeFlags::Int32:
2024     return shift ? 31 : (2 << IsQuad) - 1;
2025   case NeonTypeFlags::Int64:
2026   case NeonTypeFlags::Poly64:
2027     return shift ? 63 : (1 << IsQuad) - 1;
2028   case NeonTypeFlags::Poly128:
2029     return shift ? 127 : (1 << IsQuad) - 1;
2030   case NeonTypeFlags::Float16:
2031     assert(!shift && "cannot shift float types!");
2032     return (4 << IsQuad) - 1;
2033   case NeonTypeFlags::Float32:
2034     assert(!shift && "cannot shift float types!");
2035     return (2 << IsQuad) - 1;
2036   case NeonTypeFlags::Float64:
2037     assert(!shift && "cannot shift float types!");
2038     return (1 << IsQuad) - 1;
2039   case NeonTypeFlags::BFloat16:
2040     assert(!shift && "cannot shift float types!");
2041     return (4 << IsQuad) - 1;
2042   }
2043   llvm_unreachable("Invalid NeonTypeFlag!");
2044 }
2045 
2046 /// getNeonEltType - Return the QualType corresponding to the elements of
2047 /// the vector type specified by the NeonTypeFlags.  This is used to check
2048 /// the pointer arguments for Neon load/store intrinsics.
2049 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
2050                                bool IsPolyUnsigned, bool IsInt64Long) {
2051   switch (Flags.getEltType()) {
2052   case NeonTypeFlags::Int8:
2053     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
2054   case NeonTypeFlags::Int16:
2055     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
2056   case NeonTypeFlags::Int32:
2057     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
2058   case NeonTypeFlags::Int64:
2059     if (IsInt64Long)
2060       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
2061     else
2062       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
2063                                 : Context.LongLongTy;
2064   case NeonTypeFlags::Poly8:
2065     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
2066   case NeonTypeFlags::Poly16:
2067     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
2068   case NeonTypeFlags::Poly64:
2069     if (IsInt64Long)
2070       return Context.UnsignedLongTy;
2071     else
2072       return Context.UnsignedLongLongTy;
2073   case NeonTypeFlags::Poly128:
2074     break;
2075   case NeonTypeFlags::Float16:
2076     return Context.HalfTy;
2077   case NeonTypeFlags::Float32:
2078     return Context.FloatTy;
2079   case NeonTypeFlags::Float64:
2080     return Context.DoubleTy;
2081   case NeonTypeFlags::BFloat16:
2082     return Context.BFloat16Ty;
2083   }
2084   llvm_unreachable("Invalid NeonTypeFlag!");
2085 }
2086 
2087 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2088   // Range check SVE intrinsics that take immediate values.
2089   SmallVector<std::tuple<int,int,int>, 3> ImmChecks;
2090 
2091   switch (BuiltinID) {
2092   default:
2093     return false;
2094 #define GET_SVE_IMMEDIATE_CHECK
2095 #include "clang/Basic/arm_sve_sema_rangechecks.inc"
2096 #undef GET_SVE_IMMEDIATE_CHECK
2097   }
2098 
2099   // Perform all the immediate checks for this builtin call.
2100   bool HasError = false;
2101   for (auto &I : ImmChecks) {
2102     int ArgNum, CheckTy, ElementSizeInBits;
2103     std::tie(ArgNum, CheckTy, ElementSizeInBits) = I;
2104 
2105     typedef bool(*OptionSetCheckFnTy)(int64_t Value);
2106 
2107     // Function that checks whether the operand (ArgNum) is an immediate
2108     // that is one of the predefined values.
2109     auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm,
2110                                    int ErrDiag) -> bool {
2111       // We can't check the value of a dependent argument.
2112       Expr *Arg = TheCall->getArg(ArgNum);
2113       if (Arg->isTypeDependent() || Arg->isValueDependent())
2114         return false;
2115 
2116       // Check constant-ness first.
2117       llvm::APSInt Imm;
2118       if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm))
2119         return true;
2120 
2121       if (!CheckImm(Imm.getSExtValue()))
2122         return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange();
2123       return false;
2124     };
2125 
2126     switch ((SVETypeFlags::ImmCheckType)CheckTy) {
2127     case SVETypeFlags::ImmCheck0_31:
2128       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31))
2129         HasError = true;
2130       break;
2131     case SVETypeFlags::ImmCheck0_13:
2132       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13))
2133         HasError = true;
2134       break;
2135     case SVETypeFlags::ImmCheck1_16:
2136       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16))
2137         HasError = true;
2138       break;
2139     case SVETypeFlags::ImmCheck0_7:
2140       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7))
2141         HasError = true;
2142       break;
2143     case SVETypeFlags::ImmCheckExtract:
2144       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2145                                       (2048 / ElementSizeInBits) - 1))
2146         HasError = true;
2147       break;
2148     case SVETypeFlags::ImmCheckShiftRight:
2149       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits))
2150         HasError = true;
2151       break;
2152     case SVETypeFlags::ImmCheckShiftRightNarrow:
2153       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1,
2154                                       ElementSizeInBits / 2))
2155         HasError = true;
2156       break;
2157     case SVETypeFlags::ImmCheckShiftLeft:
2158       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2159                                       ElementSizeInBits - 1))
2160         HasError = true;
2161       break;
2162     case SVETypeFlags::ImmCheckLaneIndex:
2163       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2164                                       (128 / (1 * ElementSizeInBits)) - 1))
2165         HasError = true;
2166       break;
2167     case SVETypeFlags::ImmCheckLaneIndexCompRotate:
2168       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2169                                       (128 / (2 * ElementSizeInBits)) - 1))
2170         HasError = true;
2171       break;
2172     case SVETypeFlags::ImmCheckLaneIndexDot:
2173       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2174                                       (128 / (4 * ElementSizeInBits)) - 1))
2175         HasError = true;
2176       break;
2177     case SVETypeFlags::ImmCheckComplexRot90_270:
2178       if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; },
2179                               diag::err_rotation_argument_to_cadd))
2180         HasError = true;
2181       break;
2182     case SVETypeFlags::ImmCheckComplexRotAll90:
2183       if (CheckImmediateInSet(
2184               [](int64_t V) {
2185                 return V == 0 || V == 90 || V == 180 || V == 270;
2186               },
2187               diag::err_rotation_argument_to_cmla))
2188         HasError = true;
2189       break;
2190     case SVETypeFlags::ImmCheck0_1:
2191       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1))
2192         HasError = true;
2193       break;
2194     case SVETypeFlags::ImmCheck0_2:
2195       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2))
2196         HasError = true;
2197       break;
2198     case SVETypeFlags::ImmCheck0_3:
2199       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3))
2200         HasError = true;
2201       break;
2202     }
2203   }
2204 
2205   return HasError;
2206 }
2207 
2208 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI,
2209                                         unsigned BuiltinID, CallExpr *TheCall) {
2210   llvm::APSInt Result;
2211   uint64_t mask = 0;
2212   unsigned TV = 0;
2213   int PtrArgNum = -1;
2214   bool HasConstPtr = false;
2215   switch (BuiltinID) {
2216 #define GET_NEON_OVERLOAD_CHECK
2217 #include "clang/Basic/arm_neon.inc"
2218 #include "clang/Basic/arm_fp16.inc"
2219 #undef GET_NEON_OVERLOAD_CHECK
2220   }
2221 
2222   // For NEON intrinsics which are overloaded on vector element type, validate
2223   // the immediate which specifies which variant to emit.
2224   unsigned ImmArg = TheCall->getNumArgs()-1;
2225   if (mask) {
2226     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
2227       return true;
2228 
2229     TV = Result.getLimitedValue(64);
2230     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
2231       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
2232              << TheCall->getArg(ImmArg)->getSourceRange();
2233   }
2234 
2235   if (PtrArgNum >= 0) {
2236     // Check that pointer arguments have the specified type.
2237     Expr *Arg = TheCall->getArg(PtrArgNum);
2238     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
2239       Arg = ICE->getSubExpr();
2240     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
2241     QualType RHSTy = RHS.get()->getType();
2242 
2243     llvm::Triple::ArchType Arch = TI.getTriple().getArch();
2244     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
2245                           Arch == llvm::Triple::aarch64_32 ||
2246                           Arch == llvm::Triple::aarch64_be;
2247     bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong;
2248     QualType EltTy =
2249         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
2250     if (HasConstPtr)
2251       EltTy = EltTy.withConst();
2252     QualType LHSTy = Context.getPointerType(EltTy);
2253     AssignConvertType ConvTy;
2254     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
2255     if (RHS.isInvalid())
2256       return true;
2257     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
2258                                  RHS.get(), AA_Assigning))
2259       return true;
2260   }
2261 
2262   // For NEON intrinsics which take an immediate value as part of the
2263   // instruction, range check them here.
2264   unsigned i = 0, l = 0, u = 0;
2265   switch (BuiltinID) {
2266   default:
2267     return false;
2268   #define GET_NEON_IMMEDIATE_CHECK
2269   #include "clang/Basic/arm_neon.inc"
2270   #include "clang/Basic/arm_fp16.inc"
2271   #undef GET_NEON_IMMEDIATE_CHECK
2272   }
2273 
2274   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2275 }
2276 
2277 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2278   switch (BuiltinID) {
2279   default:
2280     return false;
2281   #include "clang/Basic/arm_mve_builtin_sema.inc"
2282   }
2283 }
2284 
2285 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2286                                        CallExpr *TheCall) {
2287   bool Err = false;
2288   switch (BuiltinID) {
2289   default:
2290     return false;
2291 #include "clang/Basic/arm_cde_builtin_sema.inc"
2292   }
2293 
2294   if (Err)
2295     return true;
2296 
2297   return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true);
2298 }
2299 
2300 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI,
2301                                         const Expr *CoprocArg, bool WantCDE) {
2302   if (isConstantEvaluated())
2303     return false;
2304 
2305   // We can't check the value of a dependent argument.
2306   if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent())
2307     return false;
2308 
2309   llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context);
2310   int64_t CoprocNo = CoprocNoAP.getExtValue();
2311   assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative");
2312 
2313   uint32_t CDECoprocMask = TI.getARMCDECoprocMask();
2314   bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo));
2315 
2316   if (IsCDECoproc != WantCDE)
2317     return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc)
2318            << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange();
2319 
2320   return false;
2321 }
2322 
2323 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
2324                                         unsigned MaxWidth) {
2325   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
2326           BuiltinID == ARM::BI__builtin_arm_ldaex ||
2327           BuiltinID == ARM::BI__builtin_arm_strex ||
2328           BuiltinID == ARM::BI__builtin_arm_stlex ||
2329           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2330           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2331           BuiltinID == AArch64::BI__builtin_arm_strex ||
2332           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
2333          "unexpected ARM builtin");
2334   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
2335                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
2336                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2337                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
2338 
2339   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2340 
2341   // Ensure that we have the proper number of arguments.
2342   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
2343     return true;
2344 
2345   // Inspect the pointer argument of the atomic builtin.  This should always be
2346   // a pointer type, whose element is an integral scalar or pointer type.
2347   // Because it is a pointer type, we don't have to worry about any implicit
2348   // casts here.
2349   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
2350   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
2351   if (PointerArgRes.isInvalid())
2352     return true;
2353   PointerArg = PointerArgRes.get();
2354 
2355   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2356   if (!pointerType) {
2357     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
2358         << PointerArg->getType() << PointerArg->getSourceRange();
2359     return true;
2360   }
2361 
2362   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
2363   // task is to insert the appropriate casts into the AST. First work out just
2364   // what the appropriate type is.
2365   QualType ValType = pointerType->getPointeeType();
2366   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
2367   if (IsLdrex)
2368     AddrType.addConst();
2369 
2370   // Issue a warning if the cast is dodgy.
2371   CastKind CastNeeded = CK_NoOp;
2372   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
2373     CastNeeded = CK_BitCast;
2374     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
2375         << PointerArg->getType() << Context.getPointerType(AddrType)
2376         << AA_Passing << PointerArg->getSourceRange();
2377   }
2378 
2379   // Finally, do the cast and replace the argument with the corrected version.
2380   AddrType = Context.getPointerType(AddrType);
2381   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
2382   if (PointerArgRes.isInvalid())
2383     return true;
2384   PointerArg = PointerArgRes.get();
2385 
2386   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
2387 
2388   // In general, we allow ints, floats and pointers to be loaded and stored.
2389   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2390       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
2391     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
2392         << PointerArg->getType() << PointerArg->getSourceRange();
2393     return true;
2394   }
2395 
2396   // But ARM doesn't have instructions to deal with 128-bit versions.
2397   if (Context.getTypeSize(ValType) > MaxWidth) {
2398     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
2399     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
2400         << PointerArg->getType() << PointerArg->getSourceRange();
2401     return true;
2402   }
2403 
2404   switch (ValType.getObjCLifetime()) {
2405   case Qualifiers::OCL_None:
2406   case Qualifiers::OCL_ExplicitNone:
2407     // okay
2408     break;
2409 
2410   case Qualifiers::OCL_Weak:
2411   case Qualifiers::OCL_Strong:
2412   case Qualifiers::OCL_Autoreleasing:
2413     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
2414         << ValType << PointerArg->getSourceRange();
2415     return true;
2416   }
2417 
2418   if (IsLdrex) {
2419     TheCall->setType(ValType);
2420     return false;
2421   }
2422 
2423   // Initialize the argument to be stored.
2424   ExprResult ValArg = TheCall->getArg(0);
2425   InitializedEntity Entity = InitializedEntity::InitializeParameter(
2426       Context, ValType, /*consume*/ false);
2427   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2428   if (ValArg.isInvalid())
2429     return true;
2430   TheCall->setArg(0, ValArg.get());
2431 
2432   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
2433   // but the custom checker bypasses all default analysis.
2434   TheCall->setType(Context.IntTy);
2435   return false;
2436 }
2437 
2438 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2439                                        CallExpr *TheCall) {
2440   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
2441       BuiltinID == ARM::BI__builtin_arm_ldaex ||
2442       BuiltinID == ARM::BI__builtin_arm_strex ||
2443       BuiltinID == ARM::BI__builtin_arm_stlex) {
2444     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
2445   }
2446 
2447   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
2448     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2449       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
2450   }
2451 
2452   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2453       BuiltinID == ARM::BI__builtin_arm_wsr64)
2454     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
2455 
2456   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
2457       BuiltinID == ARM::BI__builtin_arm_rsrp ||
2458       BuiltinID == ARM::BI__builtin_arm_wsr ||
2459       BuiltinID == ARM::BI__builtin_arm_wsrp)
2460     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2461 
2462   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2463     return true;
2464   if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
2465     return true;
2466   if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall))
2467     return true;
2468 
2469   // For intrinsics which take an immediate value as part of the instruction,
2470   // range check them here.
2471   // FIXME: VFP Intrinsics should error if VFP not present.
2472   switch (BuiltinID) {
2473   default: return false;
2474   case ARM::BI__builtin_arm_ssat:
2475     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
2476   case ARM::BI__builtin_arm_usat:
2477     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
2478   case ARM::BI__builtin_arm_ssat16:
2479     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
2480   case ARM::BI__builtin_arm_usat16:
2481     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2482   case ARM::BI__builtin_arm_vcvtr_f:
2483   case ARM::BI__builtin_arm_vcvtr_d:
2484     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
2485   case ARM::BI__builtin_arm_dmb:
2486   case ARM::BI__builtin_arm_dsb:
2487   case ARM::BI__builtin_arm_isb:
2488   case ARM::BI__builtin_arm_dbg:
2489     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
2490   case ARM::BI__builtin_arm_cdp:
2491   case ARM::BI__builtin_arm_cdp2:
2492   case ARM::BI__builtin_arm_mcr:
2493   case ARM::BI__builtin_arm_mcr2:
2494   case ARM::BI__builtin_arm_mrc:
2495   case ARM::BI__builtin_arm_mrc2:
2496   case ARM::BI__builtin_arm_mcrr:
2497   case ARM::BI__builtin_arm_mcrr2:
2498   case ARM::BI__builtin_arm_mrrc:
2499   case ARM::BI__builtin_arm_mrrc2:
2500   case ARM::BI__builtin_arm_ldc:
2501   case ARM::BI__builtin_arm_ldcl:
2502   case ARM::BI__builtin_arm_ldc2:
2503   case ARM::BI__builtin_arm_ldc2l:
2504   case ARM::BI__builtin_arm_stc:
2505   case ARM::BI__builtin_arm_stcl:
2506   case ARM::BI__builtin_arm_stc2:
2507   case ARM::BI__builtin_arm_stc2l:
2508     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) ||
2509            CheckARMCoprocessorImmediate(TI, TheCall->getArg(0),
2510                                         /*WantCDE*/ false);
2511   }
2512 }
2513 
2514 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI,
2515                                            unsigned BuiltinID,
2516                                            CallExpr *TheCall) {
2517   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2518       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2519       BuiltinID == AArch64::BI__builtin_arm_strex ||
2520       BuiltinID == AArch64::BI__builtin_arm_stlex) {
2521     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
2522   }
2523 
2524   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
2525     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2526       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
2527       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
2528       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
2529   }
2530 
2531   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2532       BuiltinID == AArch64::BI__builtin_arm_wsr64)
2533     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2534 
2535   // Memory Tagging Extensions (MTE) Intrinsics
2536   if (BuiltinID == AArch64::BI__builtin_arm_irg ||
2537       BuiltinID == AArch64::BI__builtin_arm_addg ||
2538       BuiltinID == AArch64::BI__builtin_arm_gmi ||
2539       BuiltinID == AArch64::BI__builtin_arm_ldg ||
2540       BuiltinID == AArch64::BI__builtin_arm_stg ||
2541       BuiltinID == AArch64::BI__builtin_arm_subp) {
2542     return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
2543   }
2544 
2545   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
2546       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2547       BuiltinID == AArch64::BI__builtin_arm_wsr ||
2548       BuiltinID == AArch64::BI__builtin_arm_wsrp)
2549     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2550 
2551   // Only check the valid encoding range. Any constant in this range would be
2552   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
2553   // an exception for incorrect registers. This matches MSVC behavior.
2554   if (BuiltinID == AArch64::BI_ReadStatusReg ||
2555       BuiltinID == AArch64::BI_WriteStatusReg)
2556     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
2557 
2558   if (BuiltinID == AArch64::BI__getReg)
2559     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
2560 
2561   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2562     return true;
2563 
2564   if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall))
2565     return true;
2566 
2567   // For intrinsics which take an immediate value as part of the instruction,
2568   // range check them here.
2569   unsigned i = 0, l = 0, u = 0;
2570   switch (BuiltinID) {
2571   default: return false;
2572   case AArch64::BI__builtin_arm_dmb:
2573   case AArch64::BI__builtin_arm_dsb:
2574   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
2575   case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
2576   }
2577 
2578   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2579 }
2580 
2581 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) {
2582   if (Arg->getType()->getAsPlaceholderType())
2583     return false;
2584 
2585   // The first argument needs to be a record field access.
2586   // If it is an array element access, we delay decision
2587   // to BPF backend to check whether the access is a
2588   // field access or not.
2589   return (Arg->IgnoreParens()->getObjectKind() == OK_BitField ||
2590           dyn_cast<MemberExpr>(Arg->IgnoreParens()) ||
2591           dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens()));
2592 }
2593 
2594 static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S,
2595                             QualType VectorTy, QualType EltTy) {
2596   QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType();
2597   if (!Context.hasSameType(VectorEltTy, EltTy)) {
2598     S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types)
2599         << Call->getSourceRange() << VectorEltTy << EltTy;
2600     return false;
2601   }
2602   return true;
2603 }
2604 
2605 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) {
2606   QualType ArgType = Arg->getType();
2607   if (ArgType->getAsPlaceholderType())
2608     return false;
2609 
2610   // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type
2611   // format:
2612   //   1. __builtin_preserve_type_info(*(<type> *)0, flag);
2613   //   2. <type> var;
2614   //      __builtin_preserve_type_info(var, flag);
2615   if (!dyn_cast<DeclRefExpr>(Arg->IgnoreParens()) &&
2616       !dyn_cast<UnaryOperator>(Arg->IgnoreParens()))
2617     return false;
2618 
2619   // Typedef type.
2620   if (ArgType->getAs<TypedefType>())
2621     return true;
2622 
2623   // Record type or Enum type.
2624   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2625   if (const auto *RT = Ty->getAs<RecordType>()) {
2626     if (!RT->getDecl()->getDeclName().isEmpty())
2627       return true;
2628   } else if (const auto *ET = Ty->getAs<EnumType>()) {
2629     if (!ET->getDecl()->getDeclName().isEmpty())
2630       return true;
2631   }
2632 
2633   return false;
2634 }
2635 
2636 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) {
2637   QualType ArgType = Arg->getType();
2638   if (ArgType->getAsPlaceholderType())
2639     return false;
2640 
2641   // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type
2642   // format:
2643   //   __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>,
2644   //                                 flag);
2645   const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens());
2646   if (!UO)
2647     return false;
2648 
2649   const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr());
2650   if (!CE)
2651     return false;
2652   if (CE->getCastKind() != CK_IntegralToPointer &&
2653       CE->getCastKind() != CK_NullToPointer)
2654     return false;
2655 
2656   // The integer must be from an EnumConstantDecl.
2657   const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr());
2658   if (!DR)
2659     return false;
2660 
2661   const EnumConstantDecl *Enumerator =
2662       dyn_cast<EnumConstantDecl>(DR->getDecl());
2663   if (!Enumerator)
2664     return false;
2665 
2666   // The type must be EnumType.
2667   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2668   const auto *ET = Ty->getAs<EnumType>();
2669   if (!ET)
2670     return false;
2671 
2672   // The enum value must be supported.
2673   for (auto *EDI : ET->getDecl()->enumerators()) {
2674     if (EDI == Enumerator)
2675       return true;
2676   }
2677 
2678   return false;
2679 }
2680 
2681 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
2682                                        CallExpr *TheCall) {
2683   assert((BuiltinID == BPF::BI__builtin_preserve_field_info ||
2684           BuiltinID == BPF::BI__builtin_btf_type_id ||
2685           BuiltinID == BPF::BI__builtin_preserve_type_info ||
2686           BuiltinID == BPF::BI__builtin_preserve_enum_value) &&
2687          "unexpected BPF builtin");
2688 
2689   if (checkArgCount(*this, TheCall, 2))
2690     return true;
2691 
2692   // The second argument needs to be a constant int
2693   Expr *Arg = TheCall->getArg(1);
2694   Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context);
2695   diag::kind kind;
2696   if (!Value) {
2697     if (BuiltinID == BPF::BI__builtin_preserve_field_info)
2698       kind = diag::err_preserve_field_info_not_const;
2699     else if (BuiltinID == BPF::BI__builtin_btf_type_id)
2700       kind = diag::err_btf_type_id_not_const;
2701     else if (BuiltinID == BPF::BI__builtin_preserve_type_info)
2702       kind = diag::err_preserve_type_info_not_const;
2703     else
2704       kind = diag::err_preserve_enum_value_not_const;
2705     Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange();
2706     return true;
2707   }
2708 
2709   // The first argument
2710   Arg = TheCall->getArg(0);
2711   bool InvalidArg = false;
2712   bool ReturnUnsignedInt = true;
2713   if (BuiltinID == BPF::BI__builtin_preserve_field_info) {
2714     if (!isValidBPFPreserveFieldInfoArg(Arg)) {
2715       InvalidArg = true;
2716       kind = diag::err_preserve_field_info_not_field;
2717     }
2718   } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) {
2719     if (!isValidBPFPreserveTypeInfoArg(Arg)) {
2720       InvalidArg = true;
2721       kind = diag::err_preserve_type_info_invalid;
2722     }
2723   } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) {
2724     if (!isValidBPFPreserveEnumValueArg(Arg)) {
2725       InvalidArg = true;
2726       kind = diag::err_preserve_enum_value_invalid;
2727     }
2728     ReturnUnsignedInt = false;
2729   } else if (BuiltinID == BPF::BI__builtin_btf_type_id) {
2730     ReturnUnsignedInt = false;
2731   }
2732 
2733   if (InvalidArg) {
2734     Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange();
2735     return true;
2736   }
2737 
2738   if (ReturnUnsignedInt)
2739     TheCall->setType(Context.UnsignedIntTy);
2740   else
2741     TheCall->setType(Context.UnsignedLongTy);
2742   return false;
2743 }
2744 
2745 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2746   struct ArgInfo {
2747     uint8_t OpNum;
2748     bool IsSigned;
2749     uint8_t BitWidth;
2750     uint8_t Align;
2751   };
2752   struct BuiltinInfo {
2753     unsigned BuiltinID;
2754     ArgInfo Infos[2];
2755   };
2756 
2757   static BuiltinInfo Infos[] = {
2758     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
2759     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
2760     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
2761     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  1 }} },
2762     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
2763     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
2764     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
2765     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
2766     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
2767     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
2768     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
2769 
2770     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
2771     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
2772     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
2773     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
2774     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
2775     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
2776     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
2777     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
2778     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
2779     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
2780     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
2781 
2782     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
2783     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
2784     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
2785     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
2786     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
2787     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
2788     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
2789     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
2790     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
2791     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
2792     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
2793     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
2794     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
2795     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
2796     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
2797     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
2798     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
2799     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
2800     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
2801     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
2802     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
2803     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
2804     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
2805     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
2806     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
2807     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
2808     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
2809     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
2810     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
2811     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
2812     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
2813     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
2814     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
2815     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
2816     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
2817     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
2818     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
2819     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
2820     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
2821     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
2822     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
2823     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
2824     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
2825     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
2826     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
2827     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
2828     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
2829     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
2830     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
2831     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
2832     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
2833     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
2834                                                       {{ 1, false, 6,  0 }} },
2835     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
2836     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
2837     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
2838     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
2839     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
2840     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
2841     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
2842                                                       {{ 1, false, 5,  0 }} },
2843     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
2844     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
2845     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
2846     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
2847     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
2848     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
2849                                                        { 2, false, 5,  0 }} },
2850     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
2851                                                        { 2, false, 6,  0 }} },
2852     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
2853                                                        { 3, false, 5,  0 }} },
2854     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
2855                                                        { 3, false, 6,  0 }} },
2856     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
2857     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
2858     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
2859     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
2860     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
2861     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
2862     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
2863     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
2864     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
2865     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
2866     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
2867     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
2868     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
2869     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
2870     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
2871     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
2872                                                       {{ 2, false, 4,  0 },
2873                                                        { 3, false, 5,  0 }} },
2874     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
2875                                                       {{ 2, false, 4,  0 },
2876                                                        { 3, false, 5,  0 }} },
2877     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
2878                                                       {{ 2, false, 4,  0 },
2879                                                        { 3, false, 5,  0 }} },
2880     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
2881                                                       {{ 2, false, 4,  0 },
2882                                                        { 3, false, 5,  0 }} },
2883     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
2884     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
2885     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
2886     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
2887     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
2888     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
2889     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
2890     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
2891     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
2892     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
2893     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
2894                                                        { 2, false, 5,  0 }} },
2895     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
2896                                                        { 2, false, 6,  0 }} },
2897     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
2898     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
2899     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
2900     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
2901     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
2902     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
2903     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
2904     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
2905     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
2906                                                       {{ 1, false, 4,  0 }} },
2907     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
2908     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
2909                                                       {{ 1, false, 4,  0 }} },
2910     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
2911     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
2912     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
2913     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
2914     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
2915     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
2916     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
2917     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
2918     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
2919     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
2920     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
2921     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
2922     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
2923     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
2924     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
2925     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
2926     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
2927     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
2928     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
2929     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
2930                                                       {{ 3, false, 1,  0 }} },
2931     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
2932     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
2933     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
2934     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
2935                                                       {{ 3, false, 1,  0 }} },
2936     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
2937     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
2938     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
2939     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
2940                                                       {{ 3, false, 1,  0 }} },
2941   };
2942 
2943   // Use a dynamically initialized static to sort the table exactly once on
2944   // first run.
2945   static const bool SortOnce =
2946       (llvm::sort(Infos,
2947                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
2948                    return LHS.BuiltinID < RHS.BuiltinID;
2949                  }),
2950        true);
2951   (void)SortOnce;
2952 
2953   const BuiltinInfo *F = llvm::partition_point(
2954       Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
2955   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
2956     return false;
2957 
2958   bool Error = false;
2959 
2960   for (const ArgInfo &A : F->Infos) {
2961     // Ignore empty ArgInfo elements.
2962     if (A.BitWidth == 0)
2963       continue;
2964 
2965     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
2966     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
2967     if (!A.Align) {
2968       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
2969     } else {
2970       unsigned M = 1 << A.Align;
2971       Min *= M;
2972       Max *= M;
2973       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
2974                SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
2975     }
2976   }
2977   return Error;
2978 }
2979 
2980 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
2981                                            CallExpr *TheCall) {
2982   return CheckHexagonBuiltinArgument(BuiltinID, TheCall);
2983 }
2984 
2985 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI,
2986                                         unsigned BuiltinID, CallExpr *TheCall) {
2987   return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) ||
2988          CheckMipsBuiltinArgument(BuiltinID, TheCall);
2989 }
2990 
2991 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
2992                                CallExpr *TheCall) {
2993 
2994   if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
2995       BuiltinID <= Mips::BI__builtin_mips_lwx) {
2996     if (!TI.hasFeature("dsp"))
2997       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
2998   }
2999 
3000   if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
3001       BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
3002     if (!TI.hasFeature("dspr2"))
3003       return Diag(TheCall->getBeginLoc(),
3004                   diag::err_mips_builtin_requires_dspr2);
3005   }
3006 
3007   if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
3008       BuiltinID <= Mips::BI__builtin_msa_xori_b) {
3009     if (!TI.hasFeature("msa"))
3010       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
3011   }
3012 
3013   return false;
3014 }
3015 
3016 // CheckMipsBuiltinArgument - Checks the constant value passed to the
3017 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
3018 // ordering for DSP is unspecified. MSA is ordered by the data format used
3019 // by the underlying instruction i.e., df/m, df/n and then by size.
3020 //
3021 // FIXME: The size tests here should instead be tablegen'd along with the
3022 //        definitions from include/clang/Basic/BuiltinsMips.def.
3023 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
3024 //        be too.
3025 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
3026   unsigned i = 0, l = 0, u = 0, m = 0;
3027   switch (BuiltinID) {
3028   default: return false;
3029   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
3030   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
3031   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
3032   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
3033   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
3034   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
3035   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
3036   // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
3037   // df/m field.
3038   // These intrinsics take an unsigned 3 bit immediate.
3039   case Mips::BI__builtin_msa_bclri_b:
3040   case Mips::BI__builtin_msa_bnegi_b:
3041   case Mips::BI__builtin_msa_bseti_b:
3042   case Mips::BI__builtin_msa_sat_s_b:
3043   case Mips::BI__builtin_msa_sat_u_b:
3044   case Mips::BI__builtin_msa_slli_b:
3045   case Mips::BI__builtin_msa_srai_b:
3046   case Mips::BI__builtin_msa_srari_b:
3047   case Mips::BI__builtin_msa_srli_b:
3048   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
3049   case Mips::BI__builtin_msa_binsli_b:
3050   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
3051   // These intrinsics take an unsigned 4 bit immediate.
3052   case Mips::BI__builtin_msa_bclri_h:
3053   case Mips::BI__builtin_msa_bnegi_h:
3054   case Mips::BI__builtin_msa_bseti_h:
3055   case Mips::BI__builtin_msa_sat_s_h:
3056   case Mips::BI__builtin_msa_sat_u_h:
3057   case Mips::BI__builtin_msa_slli_h:
3058   case Mips::BI__builtin_msa_srai_h:
3059   case Mips::BI__builtin_msa_srari_h:
3060   case Mips::BI__builtin_msa_srli_h:
3061   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
3062   case Mips::BI__builtin_msa_binsli_h:
3063   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
3064   // These intrinsics take an unsigned 5 bit immediate.
3065   // The first block of intrinsics actually have an unsigned 5 bit field,
3066   // not a df/n field.
3067   case Mips::BI__builtin_msa_cfcmsa:
3068   case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
3069   case Mips::BI__builtin_msa_clei_u_b:
3070   case Mips::BI__builtin_msa_clei_u_h:
3071   case Mips::BI__builtin_msa_clei_u_w:
3072   case Mips::BI__builtin_msa_clei_u_d:
3073   case Mips::BI__builtin_msa_clti_u_b:
3074   case Mips::BI__builtin_msa_clti_u_h:
3075   case Mips::BI__builtin_msa_clti_u_w:
3076   case Mips::BI__builtin_msa_clti_u_d:
3077   case Mips::BI__builtin_msa_maxi_u_b:
3078   case Mips::BI__builtin_msa_maxi_u_h:
3079   case Mips::BI__builtin_msa_maxi_u_w:
3080   case Mips::BI__builtin_msa_maxi_u_d:
3081   case Mips::BI__builtin_msa_mini_u_b:
3082   case Mips::BI__builtin_msa_mini_u_h:
3083   case Mips::BI__builtin_msa_mini_u_w:
3084   case Mips::BI__builtin_msa_mini_u_d:
3085   case Mips::BI__builtin_msa_addvi_b:
3086   case Mips::BI__builtin_msa_addvi_h:
3087   case Mips::BI__builtin_msa_addvi_w:
3088   case Mips::BI__builtin_msa_addvi_d:
3089   case Mips::BI__builtin_msa_bclri_w:
3090   case Mips::BI__builtin_msa_bnegi_w:
3091   case Mips::BI__builtin_msa_bseti_w:
3092   case Mips::BI__builtin_msa_sat_s_w:
3093   case Mips::BI__builtin_msa_sat_u_w:
3094   case Mips::BI__builtin_msa_slli_w:
3095   case Mips::BI__builtin_msa_srai_w:
3096   case Mips::BI__builtin_msa_srari_w:
3097   case Mips::BI__builtin_msa_srli_w:
3098   case Mips::BI__builtin_msa_srlri_w:
3099   case Mips::BI__builtin_msa_subvi_b:
3100   case Mips::BI__builtin_msa_subvi_h:
3101   case Mips::BI__builtin_msa_subvi_w:
3102   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
3103   case Mips::BI__builtin_msa_binsli_w:
3104   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
3105   // These intrinsics take an unsigned 6 bit immediate.
3106   case Mips::BI__builtin_msa_bclri_d:
3107   case Mips::BI__builtin_msa_bnegi_d:
3108   case Mips::BI__builtin_msa_bseti_d:
3109   case Mips::BI__builtin_msa_sat_s_d:
3110   case Mips::BI__builtin_msa_sat_u_d:
3111   case Mips::BI__builtin_msa_slli_d:
3112   case Mips::BI__builtin_msa_srai_d:
3113   case Mips::BI__builtin_msa_srari_d:
3114   case Mips::BI__builtin_msa_srli_d:
3115   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
3116   case Mips::BI__builtin_msa_binsli_d:
3117   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
3118   // These intrinsics take a signed 5 bit immediate.
3119   case Mips::BI__builtin_msa_ceqi_b:
3120   case Mips::BI__builtin_msa_ceqi_h:
3121   case Mips::BI__builtin_msa_ceqi_w:
3122   case Mips::BI__builtin_msa_ceqi_d:
3123   case Mips::BI__builtin_msa_clti_s_b:
3124   case Mips::BI__builtin_msa_clti_s_h:
3125   case Mips::BI__builtin_msa_clti_s_w:
3126   case Mips::BI__builtin_msa_clti_s_d:
3127   case Mips::BI__builtin_msa_clei_s_b:
3128   case Mips::BI__builtin_msa_clei_s_h:
3129   case Mips::BI__builtin_msa_clei_s_w:
3130   case Mips::BI__builtin_msa_clei_s_d:
3131   case Mips::BI__builtin_msa_maxi_s_b:
3132   case Mips::BI__builtin_msa_maxi_s_h:
3133   case Mips::BI__builtin_msa_maxi_s_w:
3134   case Mips::BI__builtin_msa_maxi_s_d:
3135   case Mips::BI__builtin_msa_mini_s_b:
3136   case Mips::BI__builtin_msa_mini_s_h:
3137   case Mips::BI__builtin_msa_mini_s_w:
3138   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
3139   // These intrinsics take an unsigned 8 bit immediate.
3140   case Mips::BI__builtin_msa_andi_b:
3141   case Mips::BI__builtin_msa_nori_b:
3142   case Mips::BI__builtin_msa_ori_b:
3143   case Mips::BI__builtin_msa_shf_b:
3144   case Mips::BI__builtin_msa_shf_h:
3145   case Mips::BI__builtin_msa_shf_w:
3146   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
3147   case Mips::BI__builtin_msa_bseli_b:
3148   case Mips::BI__builtin_msa_bmnzi_b:
3149   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
3150   // df/n format
3151   // These intrinsics take an unsigned 4 bit immediate.
3152   case Mips::BI__builtin_msa_copy_s_b:
3153   case Mips::BI__builtin_msa_copy_u_b:
3154   case Mips::BI__builtin_msa_insve_b:
3155   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
3156   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
3157   // These intrinsics take an unsigned 3 bit immediate.
3158   case Mips::BI__builtin_msa_copy_s_h:
3159   case Mips::BI__builtin_msa_copy_u_h:
3160   case Mips::BI__builtin_msa_insve_h:
3161   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
3162   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3163   // These intrinsics take an unsigned 2 bit immediate.
3164   case Mips::BI__builtin_msa_copy_s_w:
3165   case Mips::BI__builtin_msa_copy_u_w:
3166   case Mips::BI__builtin_msa_insve_w:
3167   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
3168   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3169   // These intrinsics take an unsigned 1 bit immediate.
3170   case Mips::BI__builtin_msa_copy_s_d:
3171   case Mips::BI__builtin_msa_copy_u_d:
3172   case Mips::BI__builtin_msa_insve_d:
3173   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
3174   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3175   // Memory offsets and immediate loads.
3176   // These intrinsics take a signed 10 bit immediate.
3177   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
3178   case Mips::BI__builtin_msa_ldi_h:
3179   case Mips::BI__builtin_msa_ldi_w:
3180   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
3181   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3182   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3183   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3184   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3185   case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break;
3186   case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break;
3187   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3188   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3189   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3190   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
3191   case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break;
3192   case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break;
3193   }
3194 
3195   if (!m)
3196     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3197 
3198   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3199          SemaBuiltinConstantArgMultiple(TheCall, i, m);
3200 }
3201 
3202 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str,
3203 /// advancing the pointer over the consumed characters. The decoded type is
3204 /// returned. If the decoded type represents a constant integer with a
3205 /// constraint on its value then Mask is set to that value. The type descriptors
3206 /// used in Str are specific to PPC MMA builtins and are documented in the file
3207 /// defining the PPC builtins.
3208 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str,
3209                                         unsigned &Mask) {
3210   bool RequireICE = false;
3211   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3212   switch (*Str++) {
3213   case 'V':
3214     return Context.getVectorType(Context.UnsignedCharTy, 16,
3215                                  VectorType::VectorKind::AltiVecVector);
3216   case 'i': {
3217     char *End;
3218     unsigned size = strtoul(Str, &End, 10);
3219     assert(End != Str && "Missing constant parameter constraint");
3220     Str = End;
3221     Mask = size;
3222     return Context.IntTy;
3223   }
3224   case 'W': {
3225     char *End;
3226     unsigned size = strtoul(Str, &End, 10);
3227     assert(End != Str && "Missing PowerPC MMA type size");
3228     Str = End;
3229     QualType Type;
3230     switch (size) {
3231   #define PPC_VECTOR_TYPE(typeName, Id, size) \
3232     case size: Type = Context.Id##Ty; break;
3233   #include "clang/Basic/PPCTypes.def"
3234     default: llvm_unreachable("Invalid PowerPC MMA vector type");
3235     }
3236     bool CheckVectorArgs = false;
3237     while (!CheckVectorArgs) {
3238       switch (*Str++) {
3239       case '*':
3240         Type = Context.getPointerType(Type);
3241         break;
3242       case 'C':
3243         Type = Type.withConst();
3244         break;
3245       default:
3246         CheckVectorArgs = true;
3247         --Str;
3248         break;
3249       }
3250     }
3251     return Type;
3252   }
3253   default:
3254     return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true);
3255   }
3256 }
3257 
3258 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3259                                        CallExpr *TheCall) {
3260   unsigned i = 0, l = 0, u = 0;
3261   bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
3262                       BuiltinID == PPC::BI__builtin_divdeu ||
3263                       BuiltinID == PPC::BI__builtin_bpermd;
3264   bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64;
3265   bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
3266                        BuiltinID == PPC::BI__builtin_divweu ||
3267                        BuiltinID == PPC::BI__builtin_divde ||
3268                        BuiltinID == PPC::BI__builtin_divdeu;
3269 
3270   if (Is64BitBltin && !IsTarget64Bit)
3271     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3272            << TheCall->getSourceRange();
3273 
3274   if ((IsBltinExtDiv && !TI.hasFeature("extdiv")) ||
3275       (BuiltinID == PPC::BI__builtin_bpermd && !TI.hasFeature("bpermd")))
3276     return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3277            << TheCall->getSourceRange();
3278 
3279   auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool {
3280     if (!TI.hasFeature("vsx"))
3281       return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3282              << TheCall->getSourceRange();
3283     return false;
3284   };
3285 
3286   switch (BuiltinID) {
3287   default: return false;
3288   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3289   case PPC::BI__builtin_altivec_crypto_vshasigmad:
3290     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3291            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3292   case PPC::BI__builtin_altivec_dss:
3293     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
3294   case PPC::BI__builtin_tbegin:
3295   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
3296   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
3297   case PPC::BI__builtin_tabortwc:
3298   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
3299   case PPC::BI__builtin_tabortwci:
3300   case PPC::BI__builtin_tabortdci:
3301     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3302            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
3303   case PPC::BI__builtin_altivec_dst:
3304   case PPC::BI__builtin_altivec_dstt:
3305   case PPC::BI__builtin_altivec_dstst:
3306   case PPC::BI__builtin_altivec_dststt:
3307     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
3308   case PPC::BI__builtin_vsx_xxpermdi:
3309   case PPC::BI__builtin_vsx_xxsldwi:
3310     return SemaBuiltinVSX(TheCall);
3311   case PPC::BI__builtin_unpack_vector_int128:
3312     return SemaVSXCheck(TheCall) ||
3313            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3314   case PPC::BI__builtin_pack_vector_int128:
3315     return SemaVSXCheck(TheCall);
3316   case PPC::BI__builtin_altivec_vgnb:
3317      return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7);
3318   case PPC::BI__builtin_altivec_vec_replace_elt:
3319   case PPC::BI__builtin_altivec_vec_replace_unaligned: {
3320     QualType VecTy = TheCall->getArg(0)->getType();
3321     QualType EltTy = TheCall->getArg(1)->getType();
3322     unsigned Width = Context.getIntWidth(EltTy);
3323     return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) ||
3324            !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy);
3325   }
3326   case PPC::BI__builtin_vsx_xxeval:
3327      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255);
3328   case PPC::BI__builtin_altivec_vsldbi:
3329      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3330   case PPC::BI__builtin_altivec_vsrdbi:
3331      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3332   case PPC::BI__builtin_vsx_xxpermx:
3333      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7);
3334 #define CUSTOM_BUILTIN(Name, Types, Acc) \
3335   case PPC::BI__builtin_##Name: \
3336     return SemaBuiltinPPCMMACall(TheCall, Types);
3337 #include "clang/Basic/BuiltinsPPC.def"
3338   }
3339   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3340 }
3341 
3342 // Check if the given type is a non-pointer PPC MMA type. This function is used
3343 // in Sema to prevent invalid uses of restricted PPC MMA types.
3344 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) {
3345   if (Type->isPointerType() || Type->isArrayType())
3346     return false;
3347 
3348   QualType CoreType = Type.getCanonicalType().getUnqualifiedType();
3349 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty
3350   if (false
3351 #include "clang/Basic/PPCTypes.def"
3352      ) {
3353     Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type);
3354     return true;
3355   }
3356   return false;
3357 }
3358 
3359 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID,
3360                                           CallExpr *TheCall) {
3361   // position of memory order and scope arguments in the builtin
3362   unsigned OrderIndex, ScopeIndex;
3363   switch (BuiltinID) {
3364   case AMDGPU::BI__builtin_amdgcn_atomic_inc32:
3365   case AMDGPU::BI__builtin_amdgcn_atomic_inc64:
3366   case AMDGPU::BI__builtin_amdgcn_atomic_dec32:
3367   case AMDGPU::BI__builtin_amdgcn_atomic_dec64:
3368     OrderIndex = 2;
3369     ScopeIndex = 3;
3370     break;
3371   case AMDGPU::BI__builtin_amdgcn_fence:
3372     OrderIndex = 0;
3373     ScopeIndex = 1;
3374     break;
3375   default:
3376     return false;
3377   }
3378 
3379   ExprResult Arg = TheCall->getArg(OrderIndex);
3380   auto ArgExpr = Arg.get();
3381   Expr::EvalResult ArgResult;
3382 
3383   if (!ArgExpr->EvaluateAsInt(ArgResult, Context))
3384     return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int)
3385            << ArgExpr->getType();
3386   int ord = ArgResult.Val.getInt().getZExtValue();
3387 
3388   // Check valididty of memory ordering as per C11 / C++11's memody model.
3389   switch (static_cast<llvm::AtomicOrderingCABI>(ord)) {
3390   case llvm::AtomicOrderingCABI::acquire:
3391   case llvm::AtomicOrderingCABI::release:
3392   case llvm::AtomicOrderingCABI::acq_rel:
3393   case llvm::AtomicOrderingCABI::seq_cst:
3394     break;
3395   default: {
3396     return Diag(ArgExpr->getBeginLoc(),
3397                 diag::warn_atomic_op_has_invalid_memory_order)
3398            << ArgExpr->getSourceRange();
3399   }
3400   }
3401 
3402   Arg = TheCall->getArg(ScopeIndex);
3403   ArgExpr = Arg.get();
3404   Expr::EvalResult ArgResult1;
3405   // Check that sync scope is a constant literal
3406   if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context))
3407     return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal)
3408            << ArgExpr->getType();
3409 
3410   return false;
3411 }
3412 
3413 bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI,
3414                                          unsigned BuiltinID,
3415                                          CallExpr *TheCall) {
3416   // CodeGenFunction can also detect this, but this gives a better error
3417   // message.
3418   StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID);
3419   if (Features.find("experimental-v") != StringRef::npos &&
3420       !TI.hasFeature("experimental-v"))
3421     return Diag(TheCall->getBeginLoc(), diag::err_riscvv_builtin_requires_v)
3422            << TheCall->getSourceRange();
3423 
3424   return false;
3425 }
3426 
3427 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3428                                            CallExpr *TheCall) {
3429   if (BuiltinID == SystemZ::BI__builtin_tabort) {
3430     Expr *Arg = TheCall->getArg(0);
3431     if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context))
3432       if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256)
3433         return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
3434                << Arg->getSourceRange();
3435   }
3436 
3437   // For intrinsics which take an immediate value as part of the instruction,
3438   // range check them here.
3439   unsigned i = 0, l = 0, u = 0;
3440   switch (BuiltinID) {
3441   default: return false;
3442   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3443   case SystemZ::BI__builtin_s390_verimb:
3444   case SystemZ::BI__builtin_s390_verimh:
3445   case SystemZ::BI__builtin_s390_verimf:
3446   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
3447   case SystemZ::BI__builtin_s390_vfaeb:
3448   case SystemZ::BI__builtin_s390_vfaeh:
3449   case SystemZ::BI__builtin_s390_vfaef:
3450   case SystemZ::BI__builtin_s390_vfaebs:
3451   case SystemZ::BI__builtin_s390_vfaehs:
3452   case SystemZ::BI__builtin_s390_vfaefs:
3453   case SystemZ::BI__builtin_s390_vfaezb:
3454   case SystemZ::BI__builtin_s390_vfaezh:
3455   case SystemZ::BI__builtin_s390_vfaezf:
3456   case SystemZ::BI__builtin_s390_vfaezbs:
3457   case SystemZ::BI__builtin_s390_vfaezhs:
3458   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
3459   case SystemZ::BI__builtin_s390_vfisb:
3460   case SystemZ::BI__builtin_s390_vfidb:
3461     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3462            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3463   case SystemZ::BI__builtin_s390_vftcisb:
3464   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3465   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3466   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3467   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3468   case SystemZ::BI__builtin_s390_vstrcb:
3469   case SystemZ::BI__builtin_s390_vstrch:
3470   case SystemZ::BI__builtin_s390_vstrcf:
3471   case SystemZ::BI__builtin_s390_vstrczb:
3472   case SystemZ::BI__builtin_s390_vstrczh:
3473   case SystemZ::BI__builtin_s390_vstrczf:
3474   case SystemZ::BI__builtin_s390_vstrcbs:
3475   case SystemZ::BI__builtin_s390_vstrchs:
3476   case SystemZ::BI__builtin_s390_vstrcfs:
3477   case SystemZ::BI__builtin_s390_vstrczbs:
3478   case SystemZ::BI__builtin_s390_vstrczhs:
3479   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
3480   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3481   case SystemZ::BI__builtin_s390_vfminsb:
3482   case SystemZ::BI__builtin_s390_vfmaxsb:
3483   case SystemZ::BI__builtin_s390_vfmindb:
3484   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
3485   case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
3486   case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
3487   }
3488   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3489 }
3490 
3491 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3492 /// This checks that the target supports __builtin_cpu_supports and
3493 /// that the string argument is constant and valid.
3494 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI,
3495                                    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.validateCpuSupports(Feature))
3507     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
3508            << Arg->getSourceRange();
3509   return false;
3510 }
3511 
3512 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3513 /// This checks that the target supports __builtin_cpu_is and
3514 /// that the string argument is constant and valid.
3515 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) {
3516   Expr *Arg = TheCall->getArg(0);
3517 
3518   // Check if the argument is a string literal.
3519   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3520     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3521            << Arg->getSourceRange();
3522 
3523   // Check the contents of the string.
3524   StringRef Feature =
3525       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3526   if (!TI.validateCpuIs(Feature))
3527     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
3528            << Arg->getSourceRange();
3529   return false;
3530 }
3531 
3532 // Check if the rounding mode is legal.
3533 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3534   // Indicates if this instruction has rounding control or just SAE.
3535   bool HasRC = false;
3536 
3537   unsigned ArgNum = 0;
3538   switch (BuiltinID) {
3539   default:
3540     return false;
3541   case X86::BI__builtin_ia32_vcvttsd2si32:
3542   case X86::BI__builtin_ia32_vcvttsd2si64:
3543   case X86::BI__builtin_ia32_vcvttsd2usi32:
3544   case X86::BI__builtin_ia32_vcvttsd2usi64:
3545   case X86::BI__builtin_ia32_vcvttss2si32:
3546   case X86::BI__builtin_ia32_vcvttss2si64:
3547   case X86::BI__builtin_ia32_vcvttss2usi32:
3548   case X86::BI__builtin_ia32_vcvttss2usi64:
3549     ArgNum = 1;
3550     break;
3551   case X86::BI__builtin_ia32_maxpd512:
3552   case X86::BI__builtin_ia32_maxps512:
3553   case X86::BI__builtin_ia32_minpd512:
3554   case X86::BI__builtin_ia32_minps512:
3555     ArgNum = 2;
3556     break;
3557   case X86::BI__builtin_ia32_cvtps2pd512_mask:
3558   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
3559   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
3560   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
3561   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
3562   case X86::BI__builtin_ia32_cvttps2dq512_mask:
3563   case X86::BI__builtin_ia32_cvttps2qq512_mask:
3564   case X86::BI__builtin_ia32_cvttps2udq512_mask:
3565   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
3566   case X86::BI__builtin_ia32_exp2pd_mask:
3567   case X86::BI__builtin_ia32_exp2ps_mask:
3568   case X86::BI__builtin_ia32_getexppd512_mask:
3569   case X86::BI__builtin_ia32_getexpps512_mask:
3570   case X86::BI__builtin_ia32_rcp28pd_mask:
3571   case X86::BI__builtin_ia32_rcp28ps_mask:
3572   case X86::BI__builtin_ia32_rsqrt28pd_mask:
3573   case X86::BI__builtin_ia32_rsqrt28ps_mask:
3574   case X86::BI__builtin_ia32_vcomisd:
3575   case X86::BI__builtin_ia32_vcomiss:
3576   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
3577     ArgNum = 3;
3578     break;
3579   case X86::BI__builtin_ia32_cmppd512_mask:
3580   case X86::BI__builtin_ia32_cmpps512_mask:
3581   case X86::BI__builtin_ia32_cmpsd_mask:
3582   case X86::BI__builtin_ia32_cmpss_mask:
3583   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
3584   case X86::BI__builtin_ia32_getexpsd128_round_mask:
3585   case X86::BI__builtin_ia32_getexpss128_round_mask:
3586   case X86::BI__builtin_ia32_getmantpd512_mask:
3587   case X86::BI__builtin_ia32_getmantps512_mask:
3588   case X86::BI__builtin_ia32_maxsd_round_mask:
3589   case X86::BI__builtin_ia32_maxss_round_mask:
3590   case X86::BI__builtin_ia32_minsd_round_mask:
3591   case X86::BI__builtin_ia32_minss_round_mask:
3592   case X86::BI__builtin_ia32_rcp28sd_round_mask:
3593   case X86::BI__builtin_ia32_rcp28ss_round_mask:
3594   case X86::BI__builtin_ia32_reducepd512_mask:
3595   case X86::BI__builtin_ia32_reduceps512_mask:
3596   case X86::BI__builtin_ia32_rndscalepd_mask:
3597   case X86::BI__builtin_ia32_rndscaleps_mask:
3598   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
3599   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
3600     ArgNum = 4;
3601     break;
3602   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3603   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3604   case X86::BI__builtin_ia32_fixupimmps512_mask:
3605   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3606   case X86::BI__builtin_ia32_fixupimmsd_mask:
3607   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3608   case X86::BI__builtin_ia32_fixupimmss_mask:
3609   case X86::BI__builtin_ia32_fixupimmss_maskz:
3610   case X86::BI__builtin_ia32_getmantsd_round_mask:
3611   case X86::BI__builtin_ia32_getmantss_round_mask:
3612   case X86::BI__builtin_ia32_rangepd512_mask:
3613   case X86::BI__builtin_ia32_rangeps512_mask:
3614   case X86::BI__builtin_ia32_rangesd128_round_mask:
3615   case X86::BI__builtin_ia32_rangess128_round_mask:
3616   case X86::BI__builtin_ia32_reducesd_mask:
3617   case X86::BI__builtin_ia32_reducess_mask:
3618   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3619   case X86::BI__builtin_ia32_rndscaless_round_mask:
3620     ArgNum = 5;
3621     break;
3622   case X86::BI__builtin_ia32_vcvtsd2si64:
3623   case X86::BI__builtin_ia32_vcvtsd2si32:
3624   case X86::BI__builtin_ia32_vcvtsd2usi32:
3625   case X86::BI__builtin_ia32_vcvtsd2usi64:
3626   case X86::BI__builtin_ia32_vcvtss2si32:
3627   case X86::BI__builtin_ia32_vcvtss2si64:
3628   case X86::BI__builtin_ia32_vcvtss2usi32:
3629   case X86::BI__builtin_ia32_vcvtss2usi64:
3630   case X86::BI__builtin_ia32_sqrtpd512:
3631   case X86::BI__builtin_ia32_sqrtps512:
3632     ArgNum = 1;
3633     HasRC = true;
3634     break;
3635   case X86::BI__builtin_ia32_addpd512:
3636   case X86::BI__builtin_ia32_addps512:
3637   case X86::BI__builtin_ia32_divpd512:
3638   case X86::BI__builtin_ia32_divps512:
3639   case X86::BI__builtin_ia32_mulpd512:
3640   case X86::BI__builtin_ia32_mulps512:
3641   case X86::BI__builtin_ia32_subpd512:
3642   case X86::BI__builtin_ia32_subps512:
3643   case X86::BI__builtin_ia32_cvtsi2sd64:
3644   case X86::BI__builtin_ia32_cvtsi2ss32:
3645   case X86::BI__builtin_ia32_cvtsi2ss64:
3646   case X86::BI__builtin_ia32_cvtusi2sd64:
3647   case X86::BI__builtin_ia32_cvtusi2ss32:
3648   case X86::BI__builtin_ia32_cvtusi2ss64:
3649     ArgNum = 2;
3650     HasRC = true;
3651     break;
3652   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
3653   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
3654   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
3655   case X86::BI__builtin_ia32_cvtpd2dq512_mask:
3656   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
3657   case X86::BI__builtin_ia32_cvtpd2udq512_mask:
3658   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
3659   case X86::BI__builtin_ia32_cvtps2dq512_mask:
3660   case X86::BI__builtin_ia32_cvtps2qq512_mask:
3661   case X86::BI__builtin_ia32_cvtps2udq512_mask:
3662   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
3663   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
3664   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
3665   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
3666   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
3667     ArgNum = 3;
3668     HasRC = true;
3669     break;
3670   case X86::BI__builtin_ia32_addss_round_mask:
3671   case X86::BI__builtin_ia32_addsd_round_mask:
3672   case X86::BI__builtin_ia32_divss_round_mask:
3673   case X86::BI__builtin_ia32_divsd_round_mask:
3674   case X86::BI__builtin_ia32_mulss_round_mask:
3675   case X86::BI__builtin_ia32_mulsd_round_mask:
3676   case X86::BI__builtin_ia32_subss_round_mask:
3677   case X86::BI__builtin_ia32_subsd_round_mask:
3678   case X86::BI__builtin_ia32_scalefpd512_mask:
3679   case X86::BI__builtin_ia32_scalefps512_mask:
3680   case X86::BI__builtin_ia32_scalefsd_round_mask:
3681   case X86::BI__builtin_ia32_scalefss_round_mask:
3682   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
3683   case X86::BI__builtin_ia32_sqrtsd_round_mask:
3684   case X86::BI__builtin_ia32_sqrtss_round_mask:
3685   case X86::BI__builtin_ia32_vfmaddsd3_mask:
3686   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
3687   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
3688   case X86::BI__builtin_ia32_vfmaddss3_mask:
3689   case X86::BI__builtin_ia32_vfmaddss3_maskz:
3690   case X86::BI__builtin_ia32_vfmaddss3_mask3:
3691   case X86::BI__builtin_ia32_vfmaddpd512_mask:
3692   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
3693   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
3694   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
3695   case X86::BI__builtin_ia32_vfmaddps512_mask:
3696   case X86::BI__builtin_ia32_vfmaddps512_maskz:
3697   case X86::BI__builtin_ia32_vfmaddps512_mask3:
3698   case X86::BI__builtin_ia32_vfmsubps512_mask3:
3699   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
3700   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
3701   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
3702   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
3703   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
3704   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
3705   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
3706   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
3707     ArgNum = 4;
3708     HasRC = true;
3709     break;
3710   }
3711 
3712   llvm::APSInt Result;
3713 
3714   // We can't check the value of a dependent argument.
3715   Expr *Arg = TheCall->getArg(ArgNum);
3716   if (Arg->isTypeDependent() || Arg->isValueDependent())
3717     return false;
3718 
3719   // Check constant-ness first.
3720   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3721     return true;
3722 
3723   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
3724   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
3725   // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
3726   // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
3727   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
3728       Result == 8/*ROUND_NO_EXC*/ ||
3729       (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
3730       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
3731     return false;
3732 
3733   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
3734          << Arg->getSourceRange();
3735 }
3736 
3737 // Check if the gather/scatter scale is legal.
3738 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
3739                                              CallExpr *TheCall) {
3740   unsigned ArgNum = 0;
3741   switch (BuiltinID) {
3742   default:
3743     return false;
3744   case X86::BI__builtin_ia32_gatherpfdpd:
3745   case X86::BI__builtin_ia32_gatherpfdps:
3746   case X86::BI__builtin_ia32_gatherpfqpd:
3747   case X86::BI__builtin_ia32_gatherpfqps:
3748   case X86::BI__builtin_ia32_scatterpfdpd:
3749   case X86::BI__builtin_ia32_scatterpfdps:
3750   case X86::BI__builtin_ia32_scatterpfqpd:
3751   case X86::BI__builtin_ia32_scatterpfqps:
3752     ArgNum = 3;
3753     break;
3754   case X86::BI__builtin_ia32_gatherd_pd:
3755   case X86::BI__builtin_ia32_gatherd_pd256:
3756   case X86::BI__builtin_ia32_gatherq_pd:
3757   case X86::BI__builtin_ia32_gatherq_pd256:
3758   case X86::BI__builtin_ia32_gatherd_ps:
3759   case X86::BI__builtin_ia32_gatherd_ps256:
3760   case X86::BI__builtin_ia32_gatherq_ps:
3761   case X86::BI__builtin_ia32_gatherq_ps256:
3762   case X86::BI__builtin_ia32_gatherd_q:
3763   case X86::BI__builtin_ia32_gatherd_q256:
3764   case X86::BI__builtin_ia32_gatherq_q:
3765   case X86::BI__builtin_ia32_gatherq_q256:
3766   case X86::BI__builtin_ia32_gatherd_d:
3767   case X86::BI__builtin_ia32_gatherd_d256:
3768   case X86::BI__builtin_ia32_gatherq_d:
3769   case X86::BI__builtin_ia32_gatherq_d256:
3770   case X86::BI__builtin_ia32_gather3div2df:
3771   case X86::BI__builtin_ia32_gather3div2di:
3772   case X86::BI__builtin_ia32_gather3div4df:
3773   case X86::BI__builtin_ia32_gather3div4di:
3774   case X86::BI__builtin_ia32_gather3div4sf:
3775   case X86::BI__builtin_ia32_gather3div4si:
3776   case X86::BI__builtin_ia32_gather3div8sf:
3777   case X86::BI__builtin_ia32_gather3div8si:
3778   case X86::BI__builtin_ia32_gather3siv2df:
3779   case X86::BI__builtin_ia32_gather3siv2di:
3780   case X86::BI__builtin_ia32_gather3siv4df:
3781   case X86::BI__builtin_ia32_gather3siv4di:
3782   case X86::BI__builtin_ia32_gather3siv4sf:
3783   case X86::BI__builtin_ia32_gather3siv4si:
3784   case X86::BI__builtin_ia32_gather3siv8sf:
3785   case X86::BI__builtin_ia32_gather3siv8si:
3786   case X86::BI__builtin_ia32_gathersiv8df:
3787   case X86::BI__builtin_ia32_gathersiv16sf:
3788   case X86::BI__builtin_ia32_gatherdiv8df:
3789   case X86::BI__builtin_ia32_gatherdiv16sf:
3790   case X86::BI__builtin_ia32_gathersiv8di:
3791   case X86::BI__builtin_ia32_gathersiv16si:
3792   case X86::BI__builtin_ia32_gatherdiv8di:
3793   case X86::BI__builtin_ia32_gatherdiv16si:
3794   case X86::BI__builtin_ia32_scatterdiv2df:
3795   case X86::BI__builtin_ia32_scatterdiv2di:
3796   case X86::BI__builtin_ia32_scatterdiv4df:
3797   case X86::BI__builtin_ia32_scatterdiv4di:
3798   case X86::BI__builtin_ia32_scatterdiv4sf:
3799   case X86::BI__builtin_ia32_scatterdiv4si:
3800   case X86::BI__builtin_ia32_scatterdiv8sf:
3801   case X86::BI__builtin_ia32_scatterdiv8si:
3802   case X86::BI__builtin_ia32_scattersiv2df:
3803   case X86::BI__builtin_ia32_scattersiv2di:
3804   case X86::BI__builtin_ia32_scattersiv4df:
3805   case X86::BI__builtin_ia32_scattersiv4di:
3806   case X86::BI__builtin_ia32_scattersiv4sf:
3807   case X86::BI__builtin_ia32_scattersiv4si:
3808   case X86::BI__builtin_ia32_scattersiv8sf:
3809   case X86::BI__builtin_ia32_scattersiv8si:
3810   case X86::BI__builtin_ia32_scattersiv8df:
3811   case X86::BI__builtin_ia32_scattersiv16sf:
3812   case X86::BI__builtin_ia32_scatterdiv8df:
3813   case X86::BI__builtin_ia32_scatterdiv16sf:
3814   case X86::BI__builtin_ia32_scattersiv8di:
3815   case X86::BI__builtin_ia32_scattersiv16si:
3816   case X86::BI__builtin_ia32_scatterdiv8di:
3817   case X86::BI__builtin_ia32_scatterdiv16si:
3818     ArgNum = 4;
3819     break;
3820   }
3821 
3822   llvm::APSInt Result;
3823 
3824   // We can't check the value of a dependent argument.
3825   Expr *Arg = TheCall->getArg(ArgNum);
3826   if (Arg->isTypeDependent() || Arg->isValueDependent())
3827     return false;
3828 
3829   // Check constant-ness first.
3830   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3831     return true;
3832 
3833   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
3834     return false;
3835 
3836   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
3837          << Arg->getSourceRange();
3838 }
3839 
3840 enum { TileRegLow = 0, TileRegHigh = 7 };
3841 
3842 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
3843                                              ArrayRef<int> ArgNums) {
3844   for (int ArgNum : ArgNums) {
3845     if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh))
3846       return true;
3847   }
3848   return false;
3849 }
3850 
3851 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall,
3852                                         ArrayRef<int> ArgNums) {
3853   // Because the max number of tile register is TileRegHigh + 1, so here we use
3854   // each bit to represent the usage of them in bitset.
3855   std::bitset<TileRegHigh + 1> ArgValues;
3856   for (int ArgNum : ArgNums) {
3857     Expr *Arg = TheCall->getArg(ArgNum);
3858     if (Arg->isTypeDependent() || Arg->isValueDependent())
3859       continue;
3860 
3861     llvm::APSInt Result;
3862     if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3863       return true;
3864     int ArgExtValue = Result.getExtValue();
3865     assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) &&
3866            "Incorrect tile register num.");
3867     if (ArgValues.test(ArgExtValue))
3868       return Diag(TheCall->getBeginLoc(),
3869                   diag::err_x86_builtin_tile_arg_duplicate)
3870              << TheCall->getArg(ArgNum)->getSourceRange();
3871     ArgValues.set(ArgExtValue);
3872   }
3873   return false;
3874 }
3875 
3876 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
3877                                                 ArrayRef<int> ArgNums) {
3878   return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) ||
3879          CheckX86BuiltinTileDuplicate(TheCall, ArgNums);
3880 }
3881 
3882 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) {
3883   switch (BuiltinID) {
3884   default:
3885     return false;
3886   case X86::BI__builtin_ia32_tileloadd64:
3887   case X86::BI__builtin_ia32_tileloaddt164:
3888   case X86::BI__builtin_ia32_tilestored64:
3889   case X86::BI__builtin_ia32_tilezero:
3890     return CheckX86BuiltinTileArgumentsRange(TheCall, 0);
3891   case X86::BI__builtin_ia32_tdpbssd:
3892   case X86::BI__builtin_ia32_tdpbsud:
3893   case X86::BI__builtin_ia32_tdpbusd:
3894   case X86::BI__builtin_ia32_tdpbuud:
3895   case X86::BI__builtin_ia32_tdpbf16ps:
3896     return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2});
3897   }
3898 }
3899 static bool isX86_32Builtin(unsigned BuiltinID) {
3900   // These builtins only work on x86-32 targets.
3901   switch (BuiltinID) {
3902   case X86::BI__builtin_ia32_readeflags_u32:
3903   case X86::BI__builtin_ia32_writeeflags_u32:
3904     return true;
3905   }
3906 
3907   return false;
3908 }
3909 
3910 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3911                                        CallExpr *TheCall) {
3912   if (BuiltinID == X86::BI__builtin_cpu_supports)
3913     return SemaBuiltinCpuSupports(*this, TI, TheCall);
3914 
3915   if (BuiltinID == X86::BI__builtin_cpu_is)
3916     return SemaBuiltinCpuIs(*this, TI, TheCall);
3917 
3918   // Check for 32-bit only builtins on a 64-bit target.
3919   const llvm::Triple &TT = TI.getTriple();
3920   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
3921     return Diag(TheCall->getCallee()->getBeginLoc(),
3922                 diag::err_32_bit_builtin_64_bit_tgt);
3923 
3924   // If the intrinsic has rounding or SAE make sure its valid.
3925   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
3926     return true;
3927 
3928   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
3929   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
3930     return true;
3931 
3932   // If the intrinsic has a tile arguments, make sure they are valid.
3933   if (CheckX86BuiltinTileArguments(BuiltinID, TheCall))
3934     return true;
3935 
3936   // For intrinsics which take an immediate value as part of the instruction,
3937   // range check them here.
3938   int i = 0, l = 0, u = 0;
3939   switch (BuiltinID) {
3940   default:
3941     return false;
3942   case X86::BI__builtin_ia32_vec_ext_v2si:
3943   case X86::BI__builtin_ia32_vec_ext_v2di:
3944   case X86::BI__builtin_ia32_vextractf128_pd256:
3945   case X86::BI__builtin_ia32_vextractf128_ps256:
3946   case X86::BI__builtin_ia32_vextractf128_si256:
3947   case X86::BI__builtin_ia32_extract128i256:
3948   case X86::BI__builtin_ia32_extractf64x4_mask:
3949   case X86::BI__builtin_ia32_extracti64x4_mask:
3950   case X86::BI__builtin_ia32_extractf32x8_mask:
3951   case X86::BI__builtin_ia32_extracti32x8_mask:
3952   case X86::BI__builtin_ia32_extractf64x2_256_mask:
3953   case X86::BI__builtin_ia32_extracti64x2_256_mask:
3954   case X86::BI__builtin_ia32_extractf32x4_256_mask:
3955   case X86::BI__builtin_ia32_extracti32x4_256_mask:
3956     i = 1; l = 0; u = 1;
3957     break;
3958   case X86::BI__builtin_ia32_vec_set_v2di:
3959   case X86::BI__builtin_ia32_vinsertf128_pd256:
3960   case X86::BI__builtin_ia32_vinsertf128_ps256:
3961   case X86::BI__builtin_ia32_vinsertf128_si256:
3962   case X86::BI__builtin_ia32_insert128i256:
3963   case X86::BI__builtin_ia32_insertf32x8:
3964   case X86::BI__builtin_ia32_inserti32x8:
3965   case X86::BI__builtin_ia32_insertf64x4:
3966   case X86::BI__builtin_ia32_inserti64x4:
3967   case X86::BI__builtin_ia32_insertf64x2_256:
3968   case X86::BI__builtin_ia32_inserti64x2_256:
3969   case X86::BI__builtin_ia32_insertf32x4_256:
3970   case X86::BI__builtin_ia32_inserti32x4_256:
3971     i = 2; l = 0; u = 1;
3972     break;
3973   case X86::BI__builtin_ia32_vpermilpd:
3974   case X86::BI__builtin_ia32_vec_ext_v4hi:
3975   case X86::BI__builtin_ia32_vec_ext_v4si:
3976   case X86::BI__builtin_ia32_vec_ext_v4sf:
3977   case X86::BI__builtin_ia32_vec_ext_v4di:
3978   case X86::BI__builtin_ia32_extractf32x4_mask:
3979   case X86::BI__builtin_ia32_extracti32x4_mask:
3980   case X86::BI__builtin_ia32_extractf64x2_512_mask:
3981   case X86::BI__builtin_ia32_extracti64x2_512_mask:
3982     i = 1; l = 0; u = 3;
3983     break;
3984   case X86::BI_mm_prefetch:
3985   case X86::BI__builtin_ia32_vec_ext_v8hi:
3986   case X86::BI__builtin_ia32_vec_ext_v8si:
3987     i = 1; l = 0; u = 7;
3988     break;
3989   case X86::BI__builtin_ia32_sha1rnds4:
3990   case X86::BI__builtin_ia32_blendpd:
3991   case X86::BI__builtin_ia32_shufpd:
3992   case X86::BI__builtin_ia32_vec_set_v4hi:
3993   case X86::BI__builtin_ia32_vec_set_v4si:
3994   case X86::BI__builtin_ia32_vec_set_v4di:
3995   case X86::BI__builtin_ia32_shuf_f32x4_256:
3996   case X86::BI__builtin_ia32_shuf_f64x2_256:
3997   case X86::BI__builtin_ia32_shuf_i32x4_256:
3998   case X86::BI__builtin_ia32_shuf_i64x2_256:
3999   case X86::BI__builtin_ia32_insertf64x2_512:
4000   case X86::BI__builtin_ia32_inserti64x2_512:
4001   case X86::BI__builtin_ia32_insertf32x4:
4002   case X86::BI__builtin_ia32_inserti32x4:
4003     i = 2; l = 0; u = 3;
4004     break;
4005   case X86::BI__builtin_ia32_vpermil2pd:
4006   case X86::BI__builtin_ia32_vpermil2pd256:
4007   case X86::BI__builtin_ia32_vpermil2ps:
4008   case X86::BI__builtin_ia32_vpermil2ps256:
4009     i = 3; l = 0; u = 3;
4010     break;
4011   case X86::BI__builtin_ia32_cmpb128_mask:
4012   case X86::BI__builtin_ia32_cmpw128_mask:
4013   case X86::BI__builtin_ia32_cmpd128_mask:
4014   case X86::BI__builtin_ia32_cmpq128_mask:
4015   case X86::BI__builtin_ia32_cmpb256_mask:
4016   case X86::BI__builtin_ia32_cmpw256_mask:
4017   case X86::BI__builtin_ia32_cmpd256_mask:
4018   case X86::BI__builtin_ia32_cmpq256_mask:
4019   case X86::BI__builtin_ia32_cmpb512_mask:
4020   case X86::BI__builtin_ia32_cmpw512_mask:
4021   case X86::BI__builtin_ia32_cmpd512_mask:
4022   case X86::BI__builtin_ia32_cmpq512_mask:
4023   case X86::BI__builtin_ia32_ucmpb128_mask:
4024   case X86::BI__builtin_ia32_ucmpw128_mask:
4025   case X86::BI__builtin_ia32_ucmpd128_mask:
4026   case X86::BI__builtin_ia32_ucmpq128_mask:
4027   case X86::BI__builtin_ia32_ucmpb256_mask:
4028   case X86::BI__builtin_ia32_ucmpw256_mask:
4029   case X86::BI__builtin_ia32_ucmpd256_mask:
4030   case X86::BI__builtin_ia32_ucmpq256_mask:
4031   case X86::BI__builtin_ia32_ucmpb512_mask:
4032   case X86::BI__builtin_ia32_ucmpw512_mask:
4033   case X86::BI__builtin_ia32_ucmpd512_mask:
4034   case X86::BI__builtin_ia32_ucmpq512_mask:
4035   case X86::BI__builtin_ia32_vpcomub:
4036   case X86::BI__builtin_ia32_vpcomuw:
4037   case X86::BI__builtin_ia32_vpcomud:
4038   case X86::BI__builtin_ia32_vpcomuq:
4039   case X86::BI__builtin_ia32_vpcomb:
4040   case X86::BI__builtin_ia32_vpcomw:
4041   case X86::BI__builtin_ia32_vpcomd:
4042   case X86::BI__builtin_ia32_vpcomq:
4043   case X86::BI__builtin_ia32_vec_set_v8hi:
4044   case X86::BI__builtin_ia32_vec_set_v8si:
4045     i = 2; l = 0; u = 7;
4046     break;
4047   case X86::BI__builtin_ia32_vpermilpd256:
4048   case X86::BI__builtin_ia32_roundps:
4049   case X86::BI__builtin_ia32_roundpd:
4050   case X86::BI__builtin_ia32_roundps256:
4051   case X86::BI__builtin_ia32_roundpd256:
4052   case X86::BI__builtin_ia32_getmantpd128_mask:
4053   case X86::BI__builtin_ia32_getmantpd256_mask:
4054   case X86::BI__builtin_ia32_getmantps128_mask:
4055   case X86::BI__builtin_ia32_getmantps256_mask:
4056   case X86::BI__builtin_ia32_getmantpd512_mask:
4057   case X86::BI__builtin_ia32_getmantps512_mask:
4058   case X86::BI__builtin_ia32_vec_ext_v16qi:
4059   case X86::BI__builtin_ia32_vec_ext_v16hi:
4060     i = 1; l = 0; u = 15;
4061     break;
4062   case X86::BI__builtin_ia32_pblendd128:
4063   case X86::BI__builtin_ia32_blendps:
4064   case X86::BI__builtin_ia32_blendpd256:
4065   case X86::BI__builtin_ia32_shufpd256:
4066   case X86::BI__builtin_ia32_roundss:
4067   case X86::BI__builtin_ia32_roundsd:
4068   case X86::BI__builtin_ia32_rangepd128_mask:
4069   case X86::BI__builtin_ia32_rangepd256_mask:
4070   case X86::BI__builtin_ia32_rangepd512_mask:
4071   case X86::BI__builtin_ia32_rangeps128_mask:
4072   case X86::BI__builtin_ia32_rangeps256_mask:
4073   case X86::BI__builtin_ia32_rangeps512_mask:
4074   case X86::BI__builtin_ia32_getmantsd_round_mask:
4075   case X86::BI__builtin_ia32_getmantss_round_mask:
4076   case X86::BI__builtin_ia32_vec_set_v16qi:
4077   case X86::BI__builtin_ia32_vec_set_v16hi:
4078     i = 2; l = 0; u = 15;
4079     break;
4080   case X86::BI__builtin_ia32_vec_ext_v32qi:
4081     i = 1; l = 0; u = 31;
4082     break;
4083   case X86::BI__builtin_ia32_cmpps:
4084   case X86::BI__builtin_ia32_cmpss:
4085   case X86::BI__builtin_ia32_cmppd:
4086   case X86::BI__builtin_ia32_cmpsd:
4087   case X86::BI__builtin_ia32_cmpps256:
4088   case X86::BI__builtin_ia32_cmppd256:
4089   case X86::BI__builtin_ia32_cmpps128_mask:
4090   case X86::BI__builtin_ia32_cmppd128_mask:
4091   case X86::BI__builtin_ia32_cmpps256_mask:
4092   case X86::BI__builtin_ia32_cmppd256_mask:
4093   case X86::BI__builtin_ia32_cmpps512_mask:
4094   case X86::BI__builtin_ia32_cmppd512_mask:
4095   case X86::BI__builtin_ia32_cmpsd_mask:
4096   case X86::BI__builtin_ia32_cmpss_mask:
4097   case X86::BI__builtin_ia32_vec_set_v32qi:
4098     i = 2; l = 0; u = 31;
4099     break;
4100   case X86::BI__builtin_ia32_permdf256:
4101   case X86::BI__builtin_ia32_permdi256:
4102   case X86::BI__builtin_ia32_permdf512:
4103   case X86::BI__builtin_ia32_permdi512:
4104   case X86::BI__builtin_ia32_vpermilps:
4105   case X86::BI__builtin_ia32_vpermilps256:
4106   case X86::BI__builtin_ia32_vpermilpd512:
4107   case X86::BI__builtin_ia32_vpermilps512:
4108   case X86::BI__builtin_ia32_pshufd:
4109   case X86::BI__builtin_ia32_pshufd256:
4110   case X86::BI__builtin_ia32_pshufd512:
4111   case X86::BI__builtin_ia32_pshufhw:
4112   case X86::BI__builtin_ia32_pshufhw256:
4113   case X86::BI__builtin_ia32_pshufhw512:
4114   case X86::BI__builtin_ia32_pshuflw:
4115   case X86::BI__builtin_ia32_pshuflw256:
4116   case X86::BI__builtin_ia32_pshuflw512:
4117   case X86::BI__builtin_ia32_vcvtps2ph:
4118   case X86::BI__builtin_ia32_vcvtps2ph_mask:
4119   case X86::BI__builtin_ia32_vcvtps2ph256:
4120   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
4121   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
4122   case X86::BI__builtin_ia32_rndscaleps_128_mask:
4123   case X86::BI__builtin_ia32_rndscalepd_128_mask:
4124   case X86::BI__builtin_ia32_rndscaleps_256_mask:
4125   case X86::BI__builtin_ia32_rndscalepd_256_mask:
4126   case X86::BI__builtin_ia32_rndscaleps_mask:
4127   case X86::BI__builtin_ia32_rndscalepd_mask:
4128   case X86::BI__builtin_ia32_reducepd128_mask:
4129   case X86::BI__builtin_ia32_reducepd256_mask:
4130   case X86::BI__builtin_ia32_reducepd512_mask:
4131   case X86::BI__builtin_ia32_reduceps128_mask:
4132   case X86::BI__builtin_ia32_reduceps256_mask:
4133   case X86::BI__builtin_ia32_reduceps512_mask:
4134   case X86::BI__builtin_ia32_prold512:
4135   case X86::BI__builtin_ia32_prolq512:
4136   case X86::BI__builtin_ia32_prold128:
4137   case X86::BI__builtin_ia32_prold256:
4138   case X86::BI__builtin_ia32_prolq128:
4139   case X86::BI__builtin_ia32_prolq256:
4140   case X86::BI__builtin_ia32_prord512:
4141   case X86::BI__builtin_ia32_prorq512:
4142   case X86::BI__builtin_ia32_prord128:
4143   case X86::BI__builtin_ia32_prord256:
4144   case X86::BI__builtin_ia32_prorq128:
4145   case X86::BI__builtin_ia32_prorq256:
4146   case X86::BI__builtin_ia32_fpclasspd128_mask:
4147   case X86::BI__builtin_ia32_fpclasspd256_mask:
4148   case X86::BI__builtin_ia32_fpclassps128_mask:
4149   case X86::BI__builtin_ia32_fpclassps256_mask:
4150   case X86::BI__builtin_ia32_fpclassps512_mask:
4151   case X86::BI__builtin_ia32_fpclasspd512_mask:
4152   case X86::BI__builtin_ia32_fpclasssd_mask:
4153   case X86::BI__builtin_ia32_fpclassss_mask:
4154   case X86::BI__builtin_ia32_pslldqi128_byteshift:
4155   case X86::BI__builtin_ia32_pslldqi256_byteshift:
4156   case X86::BI__builtin_ia32_pslldqi512_byteshift:
4157   case X86::BI__builtin_ia32_psrldqi128_byteshift:
4158   case X86::BI__builtin_ia32_psrldqi256_byteshift:
4159   case X86::BI__builtin_ia32_psrldqi512_byteshift:
4160   case X86::BI__builtin_ia32_kshiftliqi:
4161   case X86::BI__builtin_ia32_kshiftlihi:
4162   case X86::BI__builtin_ia32_kshiftlisi:
4163   case X86::BI__builtin_ia32_kshiftlidi:
4164   case X86::BI__builtin_ia32_kshiftriqi:
4165   case X86::BI__builtin_ia32_kshiftrihi:
4166   case X86::BI__builtin_ia32_kshiftrisi:
4167   case X86::BI__builtin_ia32_kshiftridi:
4168     i = 1; l = 0; u = 255;
4169     break;
4170   case X86::BI__builtin_ia32_vperm2f128_pd256:
4171   case X86::BI__builtin_ia32_vperm2f128_ps256:
4172   case X86::BI__builtin_ia32_vperm2f128_si256:
4173   case X86::BI__builtin_ia32_permti256:
4174   case X86::BI__builtin_ia32_pblendw128:
4175   case X86::BI__builtin_ia32_pblendw256:
4176   case X86::BI__builtin_ia32_blendps256:
4177   case X86::BI__builtin_ia32_pblendd256:
4178   case X86::BI__builtin_ia32_palignr128:
4179   case X86::BI__builtin_ia32_palignr256:
4180   case X86::BI__builtin_ia32_palignr512:
4181   case X86::BI__builtin_ia32_alignq512:
4182   case X86::BI__builtin_ia32_alignd512:
4183   case X86::BI__builtin_ia32_alignd128:
4184   case X86::BI__builtin_ia32_alignd256:
4185   case X86::BI__builtin_ia32_alignq128:
4186   case X86::BI__builtin_ia32_alignq256:
4187   case X86::BI__builtin_ia32_vcomisd:
4188   case X86::BI__builtin_ia32_vcomiss:
4189   case X86::BI__builtin_ia32_shuf_f32x4:
4190   case X86::BI__builtin_ia32_shuf_f64x2:
4191   case X86::BI__builtin_ia32_shuf_i32x4:
4192   case X86::BI__builtin_ia32_shuf_i64x2:
4193   case X86::BI__builtin_ia32_shufpd512:
4194   case X86::BI__builtin_ia32_shufps:
4195   case X86::BI__builtin_ia32_shufps256:
4196   case X86::BI__builtin_ia32_shufps512:
4197   case X86::BI__builtin_ia32_dbpsadbw128:
4198   case X86::BI__builtin_ia32_dbpsadbw256:
4199   case X86::BI__builtin_ia32_dbpsadbw512:
4200   case X86::BI__builtin_ia32_vpshldd128:
4201   case X86::BI__builtin_ia32_vpshldd256:
4202   case X86::BI__builtin_ia32_vpshldd512:
4203   case X86::BI__builtin_ia32_vpshldq128:
4204   case X86::BI__builtin_ia32_vpshldq256:
4205   case X86::BI__builtin_ia32_vpshldq512:
4206   case X86::BI__builtin_ia32_vpshldw128:
4207   case X86::BI__builtin_ia32_vpshldw256:
4208   case X86::BI__builtin_ia32_vpshldw512:
4209   case X86::BI__builtin_ia32_vpshrdd128:
4210   case X86::BI__builtin_ia32_vpshrdd256:
4211   case X86::BI__builtin_ia32_vpshrdd512:
4212   case X86::BI__builtin_ia32_vpshrdq128:
4213   case X86::BI__builtin_ia32_vpshrdq256:
4214   case X86::BI__builtin_ia32_vpshrdq512:
4215   case X86::BI__builtin_ia32_vpshrdw128:
4216   case X86::BI__builtin_ia32_vpshrdw256:
4217   case X86::BI__builtin_ia32_vpshrdw512:
4218     i = 2; l = 0; u = 255;
4219     break;
4220   case X86::BI__builtin_ia32_fixupimmpd512_mask:
4221   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
4222   case X86::BI__builtin_ia32_fixupimmps512_mask:
4223   case X86::BI__builtin_ia32_fixupimmps512_maskz:
4224   case X86::BI__builtin_ia32_fixupimmsd_mask:
4225   case X86::BI__builtin_ia32_fixupimmsd_maskz:
4226   case X86::BI__builtin_ia32_fixupimmss_mask:
4227   case X86::BI__builtin_ia32_fixupimmss_maskz:
4228   case X86::BI__builtin_ia32_fixupimmpd128_mask:
4229   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
4230   case X86::BI__builtin_ia32_fixupimmpd256_mask:
4231   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
4232   case X86::BI__builtin_ia32_fixupimmps128_mask:
4233   case X86::BI__builtin_ia32_fixupimmps128_maskz:
4234   case X86::BI__builtin_ia32_fixupimmps256_mask:
4235   case X86::BI__builtin_ia32_fixupimmps256_maskz:
4236   case X86::BI__builtin_ia32_pternlogd512_mask:
4237   case X86::BI__builtin_ia32_pternlogd512_maskz:
4238   case X86::BI__builtin_ia32_pternlogq512_mask:
4239   case X86::BI__builtin_ia32_pternlogq512_maskz:
4240   case X86::BI__builtin_ia32_pternlogd128_mask:
4241   case X86::BI__builtin_ia32_pternlogd128_maskz:
4242   case X86::BI__builtin_ia32_pternlogd256_mask:
4243   case X86::BI__builtin_ia32_pternlogd256_maskz:
4244   case X86::BI__builtin_ia32_pternlogq128_mask:
4245   case X86::BI__builtin_ia32_pternlogq128_maskz:
4246   case X86::BI__builtin_ia32_pternlogq256_mask:
4247   case X86::BI__builtin_ia32_pternlogq256_maskz:
4248     i = 3; l = 0; u = 255;
4249     break;
4250   case X86::BI__builtin_ia32_gatherpfdpd:
4251   case X86::BI__builtin_ia32_gatherpfdps:
4252   case X86::BI__builtin_ia32_gatherpfqpd:
4253   case X86::BI__builtin_ia32_gatherpfqps:
4254   case X86::BI__builtin_ia32_scatterpfdpd:
4255   case X86::BI__builtin_ia32_scatterpfdps:
4256   case X86::BI__builtin_ia32_scatterpfqpd:
4257   case X86::BI__builtin_ia32_scatterpfqps:
4258     i = 4; l = 2; u = 3;
4259     break;
4260   case X86::BI__builtin_ia32_reducesd_mask:
4261   case X86::BI__builtin_ia32_reducess_mask:
4262   case X86::BI__builtin_ia32_rndscalesd_round_mask:
4263   case X86::BI__builtin_ia32_rndscaless_round_mask:
4264     i = 4; l = 0; u = 255;
4265     break;
4266   }
4267 
4268   // Note that we don't force a hard error on the range check here, allowing
4269   // template-generated or macro-generated dead code to potentially have out-of-
4270   // range values. These need to code generate, but don't need to necessarily
4271   // make any sense. We use a warning that defaults to an error.
4272   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
4273 }
4274 
4275 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
4276 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
4277 /// Returns true when the format fits the function and the FormatStringInfo has
4278 /// been populated.
4279 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
4280                                FormatStringInfo *FSI) {
4281   FSI->HasVAListArg = Format->getFirstArg() == 0;
4282   FSI->FormatIdx = Format->getFormatIdx() - 1;
4283   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
4284 
4285   // The way the format attribute works in GCC, the implicit this argument
4286   // of member functions is counted. However, it doesn't appear in our own
4287   // lists, so decrement format_idx in that case.
4288   if (IsCXXMember) {
4289     if(FSI->FormatIdx == 0)
4290       return false;
4291     --FSI->FormatIdx;
4292     if (FSI->FirstDataArg != 0)
4293       --FSI->FirstDataArg;
4294   }
4295   return true;
4296 }
4297 
4298 /// Checks if a the given expression evaluates to null.
4299 ///
4300 /// Returns true if the value evaluates to null.
4301 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4302   // If the expression has non-null type, it doesn't evaluate to null.
4303   if (auto nullability
4304         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
4305     if (*nullability == NullabilityKind::NonNull)
4306       return false;
4307   }
4308 
4309   // As a special case, transparent unions initialized with zero are
4310   // considered null for the purposes of the nonnull attribute.
4311   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
4312     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
4313       if (const CompoundLiteralExpr *CLE =
4314           dyn_cast<CompoundLiteralExpr>(Expr))
4315         if (const InitListExpr *ILE =
4316             dyn_cast<InitListExpr>(CLE->getInitializer()))
4317           Expr = ILE->getInit(0);
4318   }
4319 
4320   bool Result;
4321   return (!Expr->isValueDependent() &&
4322           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
4323           !Result);
4324 }
4325 
4326 static void CheckNonNullArgument(Sema &S,
4327                                  const Expr *ArgExpr,
4328                                  SourceLocation CallSiteLoc) {
4329   if (CheckNonNullExpr(S, ArgExpr))
4330     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
4331                           S.PDiag(diag::warn_null_arg)
4332                               << ArgExpr->getSourceRange());
4333 }
4334 
4335 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
4336   FormatStringInfo FSI;
4337   if ((GetFormatStringType(Format) == FST_NSString) &&
4338       getFormatStringInfo(Format, false, &FSI)) {
4339     Idx = FSI.FormatIdx;
4340     return true;
4341   }
4342   return false;
4343 }
4344 
4345 /// Diagnose use of %s directive in an NSString which is being passed
4346 /// as formatting string to formatting method.
4347 static void
4348 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
4349                                         const NamedDecl *FDecl,
4350                                         Expr **Args,
4351                                         unsigned NumArgs) {
4352   unsigned Idx = 0;
4353   bool Format = false;
4354   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
4355   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
4356     Idx = 2;
4357     Format = true;
4358   }
4359   else
4360     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4361       if (S.GetFormatNSStringIdx(I, Idx)) {
4362         Format = true;
4363         break;
4364       }
4365     }
4366   if (!Format || NumArgs <= Idx)
4367     return;
4368   const Expr *FormatExpr = Args[Idx];
4369   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
4370     FormatExpr = CSCE->getSubExpr();
4371   const StringLiteral *FormatString;
4372   if (const ObjCStringLiteral *OSL =
4373       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
4374     FormatString = OSL->getString();
4375   else
4376     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
4377   if (!FormatString)
4378     return;
4379   if (S.FormatStringHasSArg(FormatString)) {
4380     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
4381       << "%s" << 1 << 1;
4382     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
4383       << FDecl->getDeclName();
4384   }
4385 }
4386 
4387 /// Determine whether the given type has a non-null nullability annotation.
4388 static bool isNonNullType(ASTContext &ctx, QualType type) {
4389   if (auto nullability = type->getNullability(ctx))
4390     return *nullability == NullabilityKind::NonNull;
4391 
4392   return false;
4393 }
4394 
4395 static void CheckNonNullArguments(Sema &S,
4396                                   const NamedDecl *FDecl,
4397                                   const FunctionProtoType *Proto,
4398                                   ArrayRef<const Expr *> Args,
4399                                   SourceLocation CallSiteLoc) {
4400   assert((FDecl || Proto) && "Need a function declaration or prototype");
4401 
4402   // Already checked by by constant evaluator.
4403   if (S.isConstantEvaluated())
4404     return;
4405   // Check the attributes attached to the method/function itself.
4406   llvm::SmallBitVector NonNullArgs;
4407   if (FDecl) {
4408     // Handle the nonnull attribute on the function/method declaration itself.
4409     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4410       if (!NonNull->args_size()) {
4411         // Easy case: all pointer arguments are nonnull.
4412         for (const auto *Arg : Args)
4413           if (S.isValidPointerAttrType(Arg->getType()))
4414             CheckNonNullArgument(S, Arg, CallSiteLoc);
4415         return;
4416       }
4417 
4418       for (const ParamIdx &Idx : NonNull->args()) {
4419         unsigned IdxAST = Idx.getASTIndex();
4420         if (IdxAST >= Args.size())
4421           continue;
4422         if (NonNullArgs.empty())
4423           NonNullArgs.resize(Args.size());
4424         NonNullArgs.set(IdxAST);
4425       }
4426     }
4427   }
4428 
4429   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4430     // Handle the nonnull attribute on the parameters of the
4431     // function/method.
4432     ArrayRef<ParmVarDecl*> parms;
4433     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4434       parms = FD->parameters();
4435     else
4436       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4437 
4438     unsigned ParamIndex = 0;
4439     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4440          I != E; ++I, ++ParamIndex) {
4441       const ParmVarDecl *PVD = *I;
4442       if (PVD->hasAttr<NonNullAttr>() ||
4443           isNonNullType(S.Context, PVD->getType())) {
4444         if (NonNullArgs.empty())
4445           NonNullArgs.resize(Args.size());
4446 
4447         NonNullArgs.set(ParamIndex);
4448       }
4449     }
4450   } else {
4451     // If we have a non-function, non-method declaration but no
4452     // function prototype, try to dig out the function prototype.
4453     if (!Proto) {
4454       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4455         QualType type = VD->getType().getNonReferenceType();
4456         if (auto pointerType = type->getAs<PointerType>())
4457           type = pointerType->getPointeeType();
4458         else if (auto blockType = type->getAs<BlockPointerType>())
4459           type = blockType->getPointeeType();
4460         // FIXME: data member pointers?
4461 
4462         // Dig out the function prototype, if there is one.
4463         Proto = type->getAs<FunctionProtoType>();
4464       }
4465     }
4466 
4467     // Fill in non-null argument information from the nullability
4468     // information on the parameter types (if we have them).
4469     if (Proto) {
4470       unsigned Index = 0;
4471       for (auto paramType : Proto->getParamTypes()) {
4472         if (isNonNullType(S.Context, paramType)) {
4473           if (NonNullArgs.empty())
4474             NonNullArgs.resize(Args.size());
4475 
4476           NonNullArgs.set(Index);
4477         }
4478 
4479         ++Index;
4480       }
4481     }
4482   }
4483 
4484   // Check for non-null arguments.
4485   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4486        ArgIndex != ArgIndexEnd; ++ArgIndex) {
4487     if (NonNullArgs[ArgIndex])
4488       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
4489   }
4490 }
4491 
4492 /// Warn if a pointer or reference argument passed to a function points to an
4493 /// object that is less aligned than the parameter. This can happen when
4494 /// creating a typedef with a lower alignment than the original type and then
4495 /// calling functions defined in terms of the original type.
4496 void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
4497                              StringRef ParamName, QualType ArgTy,
4498                              QualType ParamTy) {
4499 
4500   // If a function accepts a pointer or reference type
4501   if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
4502     return;
4503 
4504   // If the parameter is a pointer type, get the pointee type for the
4505   // argument too. If the parameter is a reference type, don't try to get
4506   // the pointee type for the argument.
4507   if (ParamTy->isPointerType())
4508     ArgTy = ArgTy->getPointeeType();
4509 
4510   // Remove reference or pointer
4511   ParamTy = ParamTy->getPointeeType();
4512 
4513   // Find expected alignment, and the actual alignment of the passed object.
4514   // getTypeAlignInChars requires complete types
4515   if (ParamTy->isIncompleteType() || ArgTy->isIncompleteType() ||
4516       ParamTy->isUndeducedType() || ArgTy->isUndeducedType())
4517     return;
4518 
4519   CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
4520   CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
4521 
4522   // If the argument is less aligned than the parameter, there is a
4523   // potential alignment issue.
4524   if (ArgAlign < ParamAlign)
4525     Diag(Loc, diag::warn_param_mismatched_alignment)
4526         << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
4527         << ParamName << FDecl;
4528 }
4529 
4530 /// Handles the checks for format strings, non-POD arguments to vararg
4531 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
4532 /// attributes.
4533 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
4534                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
4535                      bool IsMemberFunction, SourceLocation Loc,
4536                      SourceRange Range, VariadicCallType CallType) {
4537   // FIXME: We should check as much as we can in the template definition.
4538   if (CurContext->isDependentContext())
4539     return;
4540 
4541   // Printf and scanf checking.
4542   llvm::SmallBitVector CheckedVarArgs;
4543   if (FDecl) {
4544     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4545       // Only create vector if there are format attributes.
4546       CheckedVarArgs.resize(Args.size());
4547 
4548       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4549                            CheckedVarArgs);
4550     }
4551   }
4552 
4553   // Refuse POD arguments that weren't caught by the format string
4554   // checks above.
4555   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4556   if (CallType != VariadicDoesNotApply &&
4557       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4558     unsigned NumParams = Proto ? Proto->getNumParams()
4559                        : FDecl && isa<FunctionDecl>(FDecl)
4560                            ? cast<FunctionDecl>(FDecl)->getNumParams()
4561                        : FDecl && isa<ObjCMethodDecl>(FDecl)
4562                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
4563                        : 0;
4564 
4565     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4566       // Args[ArgIdx] can be null in malformed code.
4567       if (const Expr *Arg = Args[ArgIdx]) {
4568         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4569           checkVariadicArgument(Arg, CallType);
4570       }
4571     }
4572   }
4573 
4574   if (FDecl || Proto) {
4575     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4576 
4577     // Type safety checking.
4578     if (FDecl) {
4579       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4580         CheckArgumentWithTypeTag(I, Args, Loc);
4581     }
4582   }
4583 
4584   // Check that passed arguments match the alignment of original arguments.
4585   // Try to get the missing prototype from the declaration.
4586   if (!Proto && FDecl) {
4587     const auto *FT = FDecl->getFunctionType();
4588     if (isa_and_nonnull<FunctionProtoType>(FT))
4589       Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
4590   }
4591   if (Proto) {
4592     // For variadic functions, we may have more args than parameters.
4593     // For some K&R functions, we may have less args than parameters.
4594     const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
4595     for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
4596       // Args[ArgIdx] can be null in malformed code.
4597       if (const Expr *Arg = Args[ArgIdx]) {
4598         QualType ParamTy = Proto->getParamType(ArgIdx);
4599         QualType ArgTy = Arg->getType();
4600         CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
4601                           ArgTy, ParamTy);
4602       }
4603     }
4604   }
4605 
4606   if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
4607     auto *AA = FDecl->getAttr<AllocAlignAttr>();
4608     const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
4609     if (!Arg->isValueDependent()) {
4610       Expr::EvalResult Align;
4611       if (Arg->EvaluateAsInt(Align, Context)) {
4612         const llvm::APSInt &I = Align.Val.getInt();
4613         if (!I.isPowerOf2())
4614           Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
4615               << Arg->getSourceRange();
4616 
4617         if (I > Sema::MaximumAlignment)
4618           Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
4619               << Arg->getSourceRange() << Sema::MaximumAlignment;
4620       }
4621     }
4622   }
4623 
4624   if (FD)
4625     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4626 }
4627 
4628 /// CheckConstructorCall - Check a constructor call for correctness and safety
4629 /// properties not enforced by the C type system.
4630 void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
4631                                 ArrayRef<const Expr *> Args,
4632                                 const FunctionProtoType *Proto,
4633                                 SourceLocation Loc) {
4634   VariadicCallType CallType =
4635       Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4636 
4637   auto *Ctor = cast<CXXConstructorDecl>(FDecl);
4638   CheckArgAlignment(Loc, FDecl, "'this'", Context.getPointerType(ThisType),
4639                     Context.getPointerType(Ctor->getThisObjectType()));
4640 
4641   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4642             Loc, SourceRange(), CallType);
4643 }
4644 
4645 /// CheckFunctionCall - Check a direct function call for various correctness
4646 /// and safety properties not strictly enforced by the C type system.
4647 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
4648                              const FunctionProtoType *Proto) {
4649   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4650                               isa<CXXMethodDecl>(FDecl);
4651   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4652                           IsMemberOperatorCall;
4653   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4654                                                   TheCall->getCallee());
4655   Expr** Args = TheCall->getArgs();
4656   unsigned NumArgs = TheCall->getNumArgs();
4657 
4658   Expr *ImplicitThis = nullptr;
4659   if (IsMemberOperatorCall) {
4660     // If this is a call to a member operator, hide the first argument
4661     // from checkCall.
4662     // FIXME: Our choice of AST representation here is less than ideal.
4663     ImplicitThis = Args[0];
4664     ++Args;
4665     --NumArgs;
4666   } else if (IsMemberFunction)
4667     ImplicitThis =
4668         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4669 
4670   if (ImplicitThis) {
4671     // ImplicitThis may or may not be a pointer, depending on whether . or -> is
4672     // used.
4673     QualType ThisType = ImplicitThis->getType();
4674     if (!ThisType->isPointerType()) {
4675       assert(!ThisType->isReferenceType());
4676       ThisType = Context.getPointerType(ThisType);
4677     }
4678 
4679     QualType ThisTypeFromDecl =
4680         Context.getPointerType(cast<CXXMethodDecl>(FDecl)->getThisObjectType());
4681 
4682     CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
4683                       ThisTypeFromDecl);
4684   }
4685 
4686   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
4687             IsMemberFunction, TheCall->getRParenLoc(),
4688             TheCall->getCallee()->getSourceRange(), CallType);
4689 
4690   IdentifierInfo *FnInfo = FDecl->getIdentifier();
4691   // None of the checks below are needed for functions that don't have
4692   // simple names (e.g., C++ conversion functions).
4693   if (!FnInfo)
4694     return false;
4695 
4696   CheckTCBEnforcement(TheCall, FDecl);
4697 
4698   CheckAbsoluteValueFunction(TheCall, FDecl);
4699   CheckMaxUnsignedZero(TheCall, FDecl);
4700 
4701   if (getLangOpts().ObjC)
4702     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
4703 
4704   unsigned CMId = FDecl->getMemoryFunctionKind();
4705 
4706   // Handle memory setting and copying functions.
4707   switch (CMId) {
4708   case 0:
4709     return false;
4710   case Builtin::BIstrlcpy: // fallthrough
4711   case Builtin::BIstrlcat:
4712     CheckStrlcpycatArguments(TheCall, FnInfo);
4713     break;
4714   case Builtin::BIstrncat:
4715     CheckStrncatArguments(TheCall, FnInfo);
4716     break;
4717   case Builtin::BIfree:
4718     CheckFreeArguments(TheCall);
4719     break;
4720   default:
4721     CheckMemaccessArguments(TheCall, CMId, FnInfo);
4722   }
4723 
4724   return false;
4725 }
4726 
4727 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
4728                                ArrayRef<const Expr *> Args) {
4729   VariadicCallType CallType =
4730       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
4731 
4732   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
4733             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
4734             CallType);
4735 
4736   return false;
4737 }
4738 
4739 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4740                             const FunctionProtoType *Proto) {
4741   QualType Ty;
4742   if (const auto *V = dyn_cast<VarDecl>(NDecl))
4743     Ty = V->getType().getNonReferenceType();
4744   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4745     Ty = F->getType().getNonReferenceType();
4746   else
4747     return false;
4748 
4749   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4750       !Ty->isFunctionProtoType())
4751     return false;
4752 
4753   VariadicCallType CallType;
4754   if (!Proto || !Proto->isVariadic()) {
4755     CallType = VariadicDoesNotApply;
4756   } else if (Ty->isBlockPointerType()) {
4757     CallType = VariadicBlock;
4758   } else { // Ty->isFunctionPointerType()
4759     CallType = VariadicFunction;
4760   }
4761 
4762   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4763             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4764             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4765             TheCall->getCallee()->getSourceRange(), CallType);
4766 
4767   return false;
4768 }
4769 
4770 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
4771 /// such as function pointers returned from functions.
4772 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4773   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4774                                                   TheCall->getCallee());
4775   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4776             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4777             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4778             TheCall->getCallee()->getSourceRange(), CallType);
4779 
4780   return false;
4781 }
4782 
4783 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4784   if (!llvm::isValidAtomicOrderingCABI(Ordering))
4785     return false;
4786 
4787   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4788   switch (Op) {
4789   case AtomicExpr::AO__c11_atomic_init:
4790   case AtomicExpr::AO__opencl_atomic_init:
4791     llvm_unreachable("There is no ordering argument for an init");
4792 
4793   case AtomicExpr::AO__c11_atomic_load:
4794   case AtomicExpr::AO__opencl_atomic_load:
4795   case AtomicExpr::AO__atomic_load_n:
4796   case AtomicExpr::AO__atomic_load:
4797     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4798            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4799 
4800   case AtomicExpr::AO__c11_atomic_store:
4801   case AtomicExpr::AO__opencl_atomic_store:
4802   case AtomicExpr::AO__atomic_store:
4803   case AtomicExpr::AO__atomic_store_n:
4804     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4805            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4806            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4807 
4808   default:
4809     return true;
4810   }
4811 }
4812 
4813 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
4814                                          AtomicExpr::AtomicOp Op) {
4815   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4816   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4817   MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
4818   return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
4819                          DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
4820                          Op);
4821 }
4822 
4823 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
4824                                  SourceLocation RParenLoc, MultiExprArg Args,
4825                                  AtomicExpr::AtomicOp Op,
4826                                  AtomicArgumentOrder ArgOrder) {
4827   // All the non-OpenCL operations take one of the following forms.
4828   // The OpenCL operations take the __c11 forms with one extra argument for
4829   // synchronization scope.
4830   enum {
4831     // C    __c11_atomic_init(A *, C)
4832     Init,
4833 
4834     // C    __c11_atomic_load(A *, int)
4835     Load,
4836 
4837     // void __atomic_load(A *, CP, int)
4838     LoadCopy,
4839 
4840     // void __atomic_store(A *, CP, int)
4841     Copy,
4842 
4843     // C    __c11_atomic_add(A *, M, int)
4844     Arithmetic,
4845 
4846     // C    __atomic_exchange_n(A *, CP, int)
4847     Xchg,
4848 
4849     // void __atomic_exchange(A *, C *, CP, int)
4850     GNUXchg,
4851 
4852     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4853     C11CmpXchg,
4854 
4855     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4856     GNUCmpXchg
4857   } Form = Init;
4858 
4859   const unsigned NumForm = GNUCmpXchg + 1;
4860   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
4861   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
4862   // where:
4863   //   C is an appropriate type,
4864   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4865   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4866   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4867   //   the int parameters are for orderings.
4868 
4869   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4870       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4871       "need to update code for modified forms");
4872   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
4873                     AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
4874                         AtomicExpr::AO__atomic_load,
4875                 "need to update code for modified C11 atomics");
4876   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
4877                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
4878   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
4879                Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
4880                IsOpenCL;
4881   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4882              Op == AtomicExpr::AO__atomic_store_n ||
4883              Op == AtomicExpr::AO__atomic_exchange_n ||
4884              Op == AtomicExpr::AO__atomic_compare_exchange_n;
4885   bool IsAddSub = false;
4886 
4887   switch (Op) {
4888   case AtomicExpr::AO__c11_atomic_init:
4889   case AtomicExpr::AO__opencl_atomic_init:
4890     Form = Init;
4891     break;
4892 
4893   case AtomicExpr::AO__c11_atomic_load:
4894   case AtomicExpr::AO__opencl_atomic_load:
4895   case AtomicExpr::AO__atomic_load_n:
4896     Form = Load;
4897     break;
4898 
4899   case AtomicExpr::AO__atomic_load:
4900     Form = LoadCopy;
4901     break;
4902 
4903   case AtomicExpr::AO__c11_atomic_store:
4904   case AtomicExpr::AO__opencl_atomic_store:
4905   case AtomicExpr::AO__atomic_store:
4906   case AtomicExpr::AO__atomic_store_n:
4907     Form = Copy;
4908     break;
4909 
4910   case AtomicExpr::AO__c11_atomic_fetch_add:
4911   case AtomicExpr::AO__c11_atomic_fetch_sub:
4912   case AtomicExpr::AO__opencl_atomic_fetch_add:
4913   case AtomicExpr::AO__opencl_atomic_fetch_sub:
4914   case AtomicExpr::AO__atomic_fetch_add:
4915   case AtomicExpr::AO__atomic_fetch_sub:
4916   case AtomicExpr::AO__atomic_add_fetch:
4917   case AtomicExpr::AO__atomic_sub_fetch:
4918     IsAddSub = true;
4919     LLVM_FALLTHROUGH;
4920   case AtomicExpr::AO__c11_atomic_fetch_and:
4921   case AtomicExpr::AO__c11_atomic_fetch_or:
4922   case AtomicExpr::AO__c11_atomic_fetch_xor:
4923   case AtomicExpr::AO__opencl_atomic_fetch_and:
4924   case AtomicExpr::AO__opencl_atomic_fetch_or:
4925   case AtomicExpr::AO__opencl_atomic_fetch_xor:
4926   case AtomicExpr::AO__atomic_fetch_and:
4927   case AtomicExpr::AO__atomic_fetch_or:
4928   case AtomicExpr::AO__atomic_fetch_xor:
4929   case AtomicExpr::AO__atomic_fetch_nand:
4930   case AtomicExpr::AO__atomic_and_fetch:
4931   case AtomicExpr::AO__atomic_or_fetch:
4932   case AtomicExpr::AO__atomic_xor_fetch:
4933   case AtomicExpr::AO__atomic_nand_fetch:
4934   case AtomicExpr::AO__c11_atomic_fetch_min:
4935   case AtomicExpr::AO__c11_atomic_fetch_max:
4936   case AtomicExpr::AO__opencl_atomic_fetch_min:
4937   case AtomicExpr::AO__opencl_atomic_fetch_max:
4938   case AtomicExpr::AO__atomic_min_fetch:
4939   case AtomicExpr::AO__atomic_max_fetch:
4940   case AtomicExpr::AO__atomic_fetch_min:
4941   case AtomicExpr::AO__atomic_fetch_max:
4942     Form = Arithmetic;
4943     break;
4944 
4945   case AtomicExpr::AO__c11_atomic_exchange:
4946   case AtomicExpr::AO__opencl_atomic_exchange:
4947   case AtomicExpr::AO__atomic_exchange_n:
4948     Form = Xchg;
4949     break;
4950 
4951   case AtomicExpr::AO__atomic_exchange:
4952     Form = GNUXchg;
4953     break;
4954 
4955   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
4956   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
4957   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
4958   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
4959     Form = C11CmpXchg;
4960     break;
4961 
4962   case AtomicExpr::AO__atomic_compare_exchange:
4963   case AtomicExpr::AO__atomic_compare_exchange_n:
4964     Form = GNUCmpXchg;
4965     break;
4966   }
4967 
4968   unsigned AdjustedNumArgs = NumArgs[Form];
4969   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
4970     ++AdjustedNumArgs;
4971   // Check we have the right number of arguments.
4972   if (Args.size() < AdjustedNumArgs) {
4973     Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
4974         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4975         << ExprRange;
4976     return ExprError();
4977   } else if (Args.size() > AdjustedNumArgs) {
4978     Diag(Args[AdjustedNumArgs]->getBeginLoc(),
4979          diag::err_typecheck_call_too_many_args)
4980         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4981         << ExprRange;
4982     return ExprError();
4983   }
4984 
4985   // Inspect the first argument of the atomic operation.
4986   Expr *Ptr = Args[0];
4987   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
4988   if (ConvertedPtr.isInvalid())
4989     return ExprError();
4990 
4991   Ptr = ConvertedPtr.get();
4992   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
4993   if (!pointerType) {
4994     Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
4995         << Ptr->getType() << Ptr->getSourceRange();
4996     return ExprError();
4997   }
4998 
4999   // For a __c11 builtin, this should be a pointer to an _Atomic type.
5000   QualType AtomTy = pointerType->getPointeeType(); // 'A'
5001   QualType ValType = AtomTy; // 'C'
5002   if (IsC11) {
5003     if (!AtomTy->isAtomicType()) {
5004       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
5005           << Ptr->getType() << Ptr->getSourceRange();
5006       return ExprError();
5007     }
5008     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
5009         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
5010       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
5011           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
5012           << Ptr->getSourceRange();
5013       return ExprError();
5014     }
5015     ValType = AtomTy->castAs<AtomicType>()->getValueType();
5016   } else if (Form != Load && Form != LoadCopy) {
5017     if (ValType.isConstQualified()) {
5018       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
5019           << Ptr->getType() << Ptr->getSourceRange();
5020       return ExprError();
5021     }
5022   }
5023 
5024   // For an arithmetic operation, the implied arithmetic must be well-formed.
5025   if (Form == Arithmetic) {
5026     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
5027     if (IsAddSub && !ValType->isIntegerType()
5028         && !ValType->isPointerType()) {
5029       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
5030           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5031       return ExprError();
5032     }
5033     if (!IsAddSub && !ValType->isIntegerType()) {
5034       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
5035           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5036       return ExprError();
5037     }
5038     if (IsC11 && ValType->isPointerType() &&
5039         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
5040                             diag::err_incomplete_type)) {
5041       return ExprError();
5042     }
5043   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
5044     // For __atomic_*_n operations, the value type must be a scalar integral or
5045     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
5046     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
5047         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5048     return ExprError();
5049   }
5050 
5051   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
5052       !AtomTy->isScalarType()) {
5053     // For GNU atomics, require a trivially-copyable type. This is not part of
5054     // the GNU atomics specification, but we enforce it for sanity.
5055     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
5056         << Ptr->getType() << Ptr->getSourceRange();
5057     return ExprError();
5058   }
5059 
5060   switch (ValType.getObjCLifetime()) {
5061   case Qualifiers::OCL_None:
5062   case Qualifiers::OCL_ExplicitNone:
5063     // okay
5064     break;
5065 
5066   case Qualifiers::OCL_Weak:
5067   case Qualifiers::OCL_Strong:
5068   case Qualifiers::OCL_Autoreleasing:
5069     // FIXME: Can this happen? By this point, ValType should be known
5070     // to be trivially copyable.
5071     Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
5072         << ValType << Ptr->getSourceRange();
5073     return ExprError();
5074   }
5075 
5076   // All atomic operations have an overload which takes a pointer to a volatile
5077   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
5078   // into the result or the other operands. Similarly atomic_load takes a
5079   // pointer to a const 'A'.
5080   ValType.removeLocalVolatile();
5081   ValType.removeLocalConst();
5082   QualType ResultType = ValType;
5083   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
5084       Form == Init)
5085     ResultType = Context.VoidTy;
5086   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
5087     ResultType = Context.BoolTy;
5088 
5089   // The type of a parameter passed 'by value'. In the GNU atomics, such
5090   // arguments are actually passed as pointers.
5091   QualType ByValType = ValType; // 'CP'
5092   bool IsPassedByAddress = false;
5093   if (!IsC11 && !IsN) {
5094     ByValType = Ptr->getType();
5095     IsPassedByAddress = true;
5096   }
5097 
5098   SmallVector<Expr *, 5> APIOrderedArgs;
5099   if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
5100     APIOrderedArgs.push_back(Args[0]);
5101     switch (Form) {
5102     case Init:
5103     case Load:
5104       APIOrderedArgs.push_back(Args[1]); // Val1/Order
5105       break;
5106     case LoadCopy:
5107     case Copy:
5108     case Arithmetic:
5109     case Xchg:
5110       APIOrderedArgs.push_back(Args[2]); // Val1
5111       APIOrderedArgs.push_back(Args[1]); // Order
5112       break;
5113     case GNUXchg:
5114       APIOrderedArgs.push_back(Args[2]); // Val1
5115       APIOrderedArgs.push_back(Args[3]); // Val2
5116       APIOrderedArgs.push_back(Args[1]); // Order
5117       break;
5118     case C11CmpXchg:
5119       APIOrderedArgs.push_back(Args[2]); // Val1
5120       APIOrderedArgs.push_back(Args[4]); // Val2
5121       APIOrderedArgs.push_back(Args[1]); // Order
5122       APIOrderedArgs.push_back(Args[3]); // OrderFail
5123       break;
5124     case GNUCmpXchg:
5125       APIOrderedArgs.push_back(Args[2]); // Val1
5126       APIOrderedArgs.push_back(Args[4]); // Val2
5127       APIOrderedArgs.push_back(Args[5]); // Weak
5128       APIOrderedArgs.push_back(Args[1]); // Order
5129       APIOrderedArgs.push_back(Args[3]); // OrderFail
5130       break;
5131     }
5132   } else
5133     APIOrderedArgs.append(Args.begin(), Args.end());
5134 
5135   // The first argument's non-CV pointer type is used to deduce the type of
5136   // subsequent arguments, except for:
5137   //  - weak flag (always converted to bool)
5138   //  - memory order (always converted to int)
5139   //  - scope  (always converted to int)
5140   for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
5141     QualType Ty;
5142     if (i < NumVals[Form] + 1) {
5143       switch (i) {
5144       case 0:
5145         // The first argument is always a pointer. It has a fixed type.
5146         // It is always dereferenced, a nullptr is undefined.
5147         CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5148         // Nothing else to do: we already know all we want about this pointer.
5149         continue;
5150       case 1:
5151         // The second argument is the non-atomic operand. For arithmetic, this
5152         // is always passed by value, and for a compare_exchange it is always
5153         // passed by address. For the rest, GNU uses by-address and C11 uses
5154         // by-value.
5155         assert(Form != Load);
5156         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
5157           Ty = ValType;
5158         else if (Form == Copy || Form == Xchg) {
5159           if (IsPassedByAddress) {
5160             // The value pointer is always dereferenced, a nullptr is undefined.
5161             CheckNonNullArgument(*this, APIOrderedArgs[i],
5162                                  ExprRange.getBegin());
5163           }
5164           Ty = ByValType;
5165         } else if (Form == Arithmetic)
5166           Ty = Context.getPointerDiffType();
5167         else {
5168           Expr *ValArg = APIOrderedArgs[i];
5169           // The value pointer is always dereferenced, a nullptr is undefined.
5170           CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
5171           LangAS AS = LangAS::Default;
5172           // Keep address space of non-atomic pointer type.
5173           if (const PointerType *PtrTy =
5174                   ValArg->getType()->getAs<PointerType>()) {
5175             AS = PtrTy->getPointeeType().getAddressSpace();
5176           }
5177           Ty = Context.getPointerType(
5178               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
5179         }
5180         break;
5181       case 2:
5182         // The third argument to compare_exchange / GNU exchange is the desired
5183         // value, either by-value (for the C11 and *_n variant) or as a pointer.
5184         if (IsPassedByAddress)
5185           CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5186         Ty = ByValType;
5187         break;
5188       case 3:
5189         // The fourth argument to GNU compare_exchange is a 'weak' flag.
5190         Ty = Context.BoolTy;
5191         break;
5192       }
5193     } else {
5194       // The order(s) and scope are always converted to int.
5195       Ty = Context.IntTy;
5196     }
5197 
5198     InitializedEntity Entity =
5199         InitializedEntity::InitializeParameter(Context, Ty, false);
5200     ExprResult Arg = APIOrderedArgs[i];
5201     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5202     if (Arg.isInvalid())
5203       return true;
5204     APIOrderedArgs[i] = Arg.get();
5205   }
5206 
5207   // Permute the arguments into a 'consistent' order.
5208   SmallVector<Expr*, 5> SubExprs;
5209   SubExprs.push_back(Ptr);
5210   switch (Form) {
5211   case Init:
5212     // Note, AtomicExpr::getVal1() has a special case for this atomic.
5213     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5214     break;
5215   case Load:
5216     SubExprs.push_back(APIOrderedArgs[1]); // Order
5217     break;
5218   case LoadCopy:
5219   case Copy:
5220   case Arithmetic:
5221   case Xchg:
5222     SubExprs.push_back(APIOrderedArgs[2]); // Order
5223     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5224     break;
5225   case GNUXchg:
5226     // Note, AtomicExpr::getVal2() has a special case for this atomic.
5227     SubExprs.push_back(APIOrderedArgs[3]); // Order
5228     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5229     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5230     break;
5231   case C11CmpXchg:
5232     SubExprs.push_back(APIOrderedArgs[3]); // Order
5233     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5234     SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
5235     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5236     break;
5237   case GNUCmpXchg:
5238     SubExprs.push_back(APIOrderedArgs[4]); // Order
5239     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5240     SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
5241     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5242     SubExprs.push_back(APIOrderedArgs[3]); // Weak
5243     break;
5244   }
5245 
5246   if (SubExprs.size() >= 2 && Form != Init) {
5247     if (Optional<llvm::APSInt> Result =
5248             SubExprs[1]->getIntegerConstantExpr(Context))
5249       if (!isValidOrderingForOp(Result->getSExtValue(), Op))
5250         Diag(SubExprs[1]->getBeginLoc(),
5251              diag::warn_atomic_op_has_invalid_memory_order)
5252             << SubExprs[1]->getSourceRange();
5253   }
5254 
5255   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
5256     auto *Scope = Args[Args.size() - 1];
5257     if (Optional<llvm::APSInt> Result =
5258             Scope->getIntegerConstantExpr(Context)) {
5259       if (!ScopeModel->isValid(Result->getZExtValue()))
5260         Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
5261             << Scope->getSourceRange();
5262     }
5263     SubExprs.push_back(Scope);
5264   }
5265 
5266   AtomicExpr *AE = new (Context)
5267       AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
5268 
5269   if ((Op == AtomicExpr::AO__c11_atomic_load ||
5270        Op == AtomicExpr::AO__c11_atomic_store ||
5271        Op == AtomicExpr::AO__opencl_atomic_load ||
5272        Op == AtomicExpr::AO__opencl_atomic_store ) &&
5273       Context.AtomicUsesUnsupportedLibcall(AE))
5274     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
5275         << ((Op == AtomicExpr::AO__c11_atomic_load ||
5276              Op == AtomicExpr::AO__opencl_atomic_load)
5277                 ? 0
5278                 : 1);
5279 
5280   if (ValType->isExtIntType()) {
5281     Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_ext_int_prohibit);
5282     return ExprError();
5283   }
5284 
5285   return AE;
5286 }
5287 
5288 /// checkBuiltinArgument - Given a call to a builtin function, perform
5289 /// normal type-checking on the given argument, updating the call in
5290 /// place.  This is useful when a builtin function requires custom
5291 /// type-checking for some of its arguments but not necessarily all of
5292 /// them.
5293 ///
5294 /// Returns true on error.
5295 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
5296   FunctionDecl *Fn = E->getDirectCallee();
5297   assert(Fn && "builtin call without direct callee!");
5298 
5299   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
5300   InitializedEntity Entity =
5301     InitializedEntity::InitializeParameter(S.Context, Param);
5302 
5303   ExprResult Arg = E->getArg(0);
5304   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
5305   if (Arg.isInvalid())
5306     return true;
5307 
5308   E->setArg(ArgIndex, Arg.get());
5309   return false;
5310 }
5311 
5312 /// We have a call to a function like __sync_fetch_and_add, which is an
5313 /// overloaded function based on the pointer type of its first argument.
5314 /// The main BuildCallExpr routines have already promoted the types of
5315 /// arguments because all of these calls are prototyped as void(...).
5316 ///
5317 /// This function goes through and does final semantic checking for these
5318 /// builtins, as well as generating any warnings.
5319 ExprResult
5320 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
5321   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
5322   Expr *Callee = TheCall->getCallee();
5323   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
5324   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5325 
5326   // Ensure that we have at least one argument to do type inference from.
5327   if (TheCall->getNumArgs() < 1) {
5328     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5329         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
5330     return ExprError();
5331   }
5332 
5333   // Inspect the first argument of the atomic builtin.  This should always be
5334   // a pointer type, whose element is an integral scalar or pointer type.
5335   // Because it is a pointer type, we don't have to worry about any implicit
5336   // casts here.
5337   // FIXME: We don't allow floating point scalars as input.
5338   Expr *FirstArg = TheCall->getArg(0);
5339   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
5340   if (FirstArgResult.isInvalid())
5341     return ExprError();
5342   FirstArg = FirstArgResult.get();
5343   TheCall->setArg(0, FirstArg);
5344 
5345   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5346   if (!pointerType) {
5347     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
5348         << FirstArg->getType() << FirstArg->getSourceRange();
5349     return ExprError();
5350   }
5351 
5352   QualType ValType = pointerType->getPointeeType();
5353   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5354       !ValType->isBlockPointerType()) {
5355     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
5356         << FirstArg->getType() << FirstArg->getSourceRange();
5357     return ExprError();
5358   }
5359 
5360   if (ValType.isConstQualified()) {
5361     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
5362         << FirstArg->getType() << FirstArg->getSourceRange();
5363     return ExprError();
5364   }
5365 
5366   switch (ValType.getObjCLifetime()) {
5367   case Qualifiers::OCL_None:
5368   case Qualifiers::OCL_ExplicitNone:
5369     // okay
5370     break;
5371 
5372   case Qualifiers::OCL_Weak:
5373   case Qualifiers::OCL_Strong:
5374   case Qualifiers::OCL_Autoreleasing:
5375     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
5376         << ValType << FirstArg->getSourceRange();
5377     return ExprError();
5378   }
5379 
5380   // Strip any qualifiers off ValType.
5381   ValType = ValType.getUnqualifiedType();
5382 
5383   // The majority of builtins return a value, but a few have special return
5384   // types, so allow them to override appropriately below.
5385   QualType ResultType = ValType;
5386 
5387   // We need to figure out which concrete builtin this maps onto.  For example,
5388   // __sync_fetch_and_add with a 2 byte object turns into
5389   // __sync_fetch_and_add_2.
5390 #define BUILTIN_ROW(x) \
5391   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5392     Builtin::BI##x##_8, Builtin::BI##x##_16 }
5393 
5394   static const unsigned BuiltinIndices[][5] = {
5395     BUILTIN_ROW(__sync_fetch_and_add),
5396     BUILTIN_ROW(__sync_fetch_and_sub),
5397     BUILTIN_ROW(__sync_fetch_and_or),
5398     BUILTIN_ROW(__sync_fetch_and_and),
5399     BUILTIN_ROW(__sync_fetch_and_xor),
5400     BUILTIN_ROW(__sync_fetch_and_nand),
5401 
5402     BUILTIN_ROW(__sync_add_and_fetch),
5403     BUILTIN_ROW(__sync_sub_and_fetch),
5404     BUILTIN_ROW(__sync_and_and_fetch),
5405     BUILTIN_ROW(__sync_or_and_fetch),
5406     BUILTIN_ROW(__sync_xor_and_fetch),
5407     BUILTIN_ROW(__sync_nand_and_fetch),
5408 
5409     BUILTIN_ROW(__sync_val_compare_and_swap),
5410     BUILTIN_ROW(__sync_bool_compare_and_swap),
5411     BUILTIN_ROW(__sync_lock_test_and_set),
5412     BUILTIN_ROW(__sync_lock_release),
5413     BUILTIN_ROW(__sync_swap)
5414   };
5415 #undef BUILTIN_ROW
5416 
5417   // Determine the index of the size.
5418   unsigned SizeIndex;
5419   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
5420   case 1: SizeIndex = 0; break;
5421   case 2: SizeIndex = 1; break;
5422   case 4: SizeIndex = 2; break;
5423   case 8: SizeIndex = 3; break;
5424   case 16: SizeIndex = 4; break;
5425   default:
5426     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
5427         << FirstArg->getType() << FirstArg->getSourceRange();
5428     return ExprError();
5429   }
5430 
5431   // Each of these builtins has one pointer argument, followed by some number of
5432   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5433   // that we ignore.  Find out which row of BuiltinIndices to read from as well
5434   // as the number of fixed args.
5435   unsigned BuiltinID = FDecl->getBuiltinID();
5436   unsigned BuiltinIndex, NumFixed = 1;
5437   bool WarnAboutSemanticsChange = false;
5438   switch (BuiltinID) {
5439   default: llvm_unreachable("Unknown overloaded atomic builtin!");
5440   case Builtin::BI__sync_fetch_and_add:
5441   case Builtin::BI__sync_fetch_and_add_1:
5442   case Builtin::BI__sync_fetch_and_add_2:
5443   case Builtin::BI__sync_fetch_and_add_4:
5444   case Builtin::BI__sync_fetch_and_add_8:
5445   case Builtin::BI__sync_fetch_and_add_16:
5446     BuiltinIndex = 0;
5447     break;
5448 
5449   case Builtin::BI__sync_fetch_and_sub:
5450   case Builtin::BI__sync_fetch_and_sub_1:
5451   case Builtin::BI__sync_fetch_and_sub_2:
5452   case Builtin::BI__sync_fetch_and_sub_4:
5453   case Builtin::BI__sync_fetch_and_sub_8:
5454   case Builtin::BI__sync_fetch_and_sub_16:
5455     BuiltinIndex = 1;
5456     break;
5457 
5458   case Builtin::BI__sync_fetch_and_or:
5459   case Builtin::BI__sync_fetch_and_or_1:
5460   case Builtin::BI__sync_fetch_and_or_2:
5461   case Builtin::BI__sync_fetch_and_or_4:
5462   case Builtin::BI__sync_fetch_and_or_8:
5463   case Builtin::BI__sync_fetch_and_or_16:
5464     BuiltinIndex = 2;
5465     break;
5466 
5467   case Builtin::BI__sync_fetch_and_and:
5468   case Builtin::BI__sync_fetch_and_and_1:
5469   case Builtin::BI__sync_fetch_and_and_2:
5470   case Builtin::BI__sync_fetch_and_and_4:
5471   case Builtin::BI__sync_fetch_and_and_8:
5472   case Builtin::BI__sync_fetch_and_and_16:
5473     BuiltinIndex = 3;
5474     break;
5475 
5476   case Builtin::BI__sync_fetch_and_xor:
5477   case Builtin::BI__sync_fetch_and_xor_1:
5478   case Builtin::BI__sync_fetch_and_xor_2:
5479   case Builtin::BI__sync_fetch_and_xor_4:
5480   case Builtin::BI__sync_fetch_and_xor_8:
5481   case Builtin::BI__sync_fetch_and_xor_16:
5482     BuiltinIndex = 4;
5483     break;
5484 
5485   case Builtin::BI__sync_fetch_and_nand:
5486   case Builtin::BI__sync_fetch_and_nand_1:
5487   case Builtin::BI__sync_fetch_and_nand_2:
5488   case Builtin::BI__sync_fetch_and_nand_4:
5489   case Builtin::BI__sync_fetch_and_nand_8:
5490   case Builtin::BI__sync_fetch_and_nand_16:
5491     BuiltinIndex = 5;
5492     WarnAboutSemanticsChange = true;
5493     break;
5494 
5495   case Builtin::BI__sync_add_and_fetch:
5496   case Builtin::BI__sync_add_and_fetch_1:
5497   case Builtin::BI__sync_add_and_fetch_2:
5498   case Builtin::BI__sync_add_and_fetch_4:
5499   case Builtin::BI__sync_add_and_fetch_8:
5500   case Builtin::BI__sync_add_and_fetch_16:
5501     BuiltinIndex = 6;
5502     break;
5503 
5504   case Builtin::BI__sync_sub_and_fetch:
5505   case Builtin::BI__sync_sub_and_fetch_1:
5506   case Builtin::BI__sync_sub_and_fetch_2:
5507   case Builtin::BI__sync_sub_and_fetch_4:
5508   case Builtin::BI__sync_sub_and_fetch_8:
5509   case Builtin::BI__sync_sub_and_fetch_16:
5510     BuiltinIndex = 7;
5511     break;
5512 
5513   case Builtin::BI__sync_and_and_fetch:
5514   case Builtin::BI__sync_and_and_fetch_1:
5515   case Builtin::BI__sync_and_and_fetch_2:
5516   case Builtin::BI__sync_and_and_fetch_4:
5517   case Builtin::BI__sync_and_and_fetch_8:
5518   case Builtin::BI__sync_and_and_fetch_16:
5519     BuiltinIndex = 8;
5520     break;
5521 
5522   case Builtin::BI__sync_or_and_fetch:
5523   case Builtin::BI__sync_or_and_fetch_1:
5524   case Builtin::BI__sync_or_and_fetch_2:
5525   case Builtin::BI__sync_or_and_fetch_4:
5526   case Builtin::BI__sync_or_and_fetch_8:
5527   case Builtin::BI__sync_or_and_fetch_16:
5528     BuiltinIndex = 9;
5529     break;
5530 
5531   case Builtin::BI__sync_xor_and_fetch:
5532   case Builtin::BI__sync_xor_and_fetch_1:
5533   case Builtin::BI__sync_xor_and_fetch_2:
5534   case Builtin::BI__sync_xor_and_fetch_4:
5535   case Builtin::BI__sync_xor_and_fetch_8:
5536   case Builtin::BI__sync_xor_and_fetch_16:
5537     BuiltinIndex = 10;
5538     break;
5539 
5540   case Builtin::BI__sync_nand_and_fetch:
5541   case Builtin::BI__sync_nand_and_fetch_1:
5542   case Builtin::BI__sync_nand_and_fetch_2:
5543   case Builtin::BI__sync_nand_and_fetch_4:
5544   case Builtin::BI__sync_nand_and_fetch_8:
5545   case Builtin::BI__sync_nand_and_fetch_16:
5546     BuiltinIndex = 11;
5547     WarnAboutSemanticsChange = true;
5548     break;
5549 
5550   case Builtin::BI__sync_val_compare_and_swap:
5551   case Builtin::BI__sync_val_compare_and_swap_1:
5552   case Builtin::BI__sync_val_compare_and_swap_2:
5553   case Builtin::BI__sync_val_compare_and_swap_4:
5554   case Builtin::BI__sync_val_compare_and_swap_8:
5555   case Builtin::BI__sync_val_compare_and_swap_16:
5556     BuiltinIndex = 12;
5557     NumFixed = 2;
5558     break;
5559 
5560   case Builtin::BI__sync_bool_compare_and_swap:
5561   case Builtin::BI__sync_bool_compare_and_swap_1:
5562   case Builtin::BI__sync_bool_compare_and_swap_2:
5563   case Builtin::BI__sync_bool_compare_and_swap_4:
5564   case Builtin::BI__sync_bool_compare_and_swap_8:
5565   case Builtin::BI__sync_bool_compare_and_swap_16:
5566     BuiltinIndex = 13;
5567     NumFixed = 2;
5568     ResultType = Context.BoolTy;
5569     break;
5570 
5571   case Builtin::BI__sync_lock_test_and_set:
5572   case Builtin::BI__sync_lock_test_and_set_1:
5573   case Builtin::BI__sync_lock_test_and_set_2:
5574   case Builtin::BI__sync_lock_test_and_set_4:
5575   case Builtin::BI__sync_lock_test_and_set_8:
5576   case Builtin::BI__sync_lock_test_and_set_16:
5577     BuiltinIndex = 14;
5578     break;
5579 
5580   case Builtin::BI__sync_lock_release:
5581   case Builtin::BI__sync_lock_release_1:
5582   case Builtin::BI__sync_lock_release_2:
5583   case Builtin::BI__sync_lock_release_4:
5584   case Builtin::BI__sync_lock_release_8:
5585   case Builtin::BI__sync_lock_release_16:
5586     BuiltinIndex = 15;
5587     NumFixed = 0;
5588     ResultType = Context.VoidTy;
5589     break;
5590 
5591   case Builtin::BI__sync_swap:
5592   case Builtin::BI__sync_swap_1:
5593   case Builtin::BI__sync_swap_2:
5594   case Builtin::BI__sync_swap_4:
5595   case Builtin::BI__sync_swap_8:
5596   case Builtin::BI__sync_swap_16:
5597     BuiltinIndex = 16;
5598     break;
5599   }
5600 
5601   // Now that we know how many fixed arguments we expect, first check that we
5602   // have at least that many.
5603   if (TheCall->getNumArgs() < 1+NumFixed) {
5604     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5605         << 0 << 1 + NumFixed << TheCall->getNumArgs()
5606         << Callee->getSourceRange();
5607     return ExprError();
5608   }
5609 
5610   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5611       << Callee->getSourceRange();
5612 
5613   if (WarnAboutSemanticsChange) {
5614     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
5615         << Callee->getSourceRange();
5616   }
5617 
5618   // Get the decl for the concrete builtin from this, we can tell what the
5619   // concrete integer type we should convert to is.
5620   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5621   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
5622   FunctionDecl *NewBuiltinDecl;
5623   if (NewBuiltinID == BuiltinID)
5624     NewBuiltinDecl = FDecl;
5625   else {
5626     // Perform builtin lookup to avoid redeclaring it.
5627     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
5628     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5629     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5630     assert(Res.getFoundDecl());
5631     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
5632     if (!NewBuiltinDecl)
5633       return ExprError();
5634   }
5635 
5636   // The first argument --- the pointer --- has a fixed type; we
5637   // deduce the types of the rest of the arguments accordingly.  Walk
5638   // the remaining arguments, converting them to the deduced value type.
5639   for (unsigned i = 0; i != NumFixed; ++i) {
5640     ExprResult Arg = TheCall->getArg(i+1);
5641 
5642     // GCC does an implicit conversion to the pointer or integer ValType.  This
5643     // can fail in some cases (1i -> int**), check for this error case now.
5644     // Initialize the argument.
5645     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5646                                                    ValType, /*consume*/ false);
5647     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5648     if (Arg.isInvalid())
5649       return ExprError();
5650 
5651     // Okay, we have something that *can* be converted to the right type.  Check
5652     // to see if there is a potentially weird extension going on here.  This can
5653     // happen when you do an atomic operation on something like an char* and
5654     // pass in 42.  The 42 gets converted to char.  This is even more strange
5655     // for things like 45.123 -> char, etc.
5656     // FIXME: Do this check.
5657     TheCall->setArg(i+1, Arg.get());
5658   }
5659 
5660   // Create a new DeclRefExpr to refer to the new decl.
5661   DeclRefExpr *NewDRE = DeclRefExpr::Create(
5662       Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
5663       /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
5664       DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
5665 
5666   // Set the callee in the CallExpr.
5667   // FIXME: This loses syntactic information.
5668   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5669   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5670                                               CK_BuiltinFnToFnPtr);
5671   TheCall->setCallee(PromotedCall.get());
5672 
5673   // Change the result type of the call to match the original value type. This
5674   // is arbitrary, but the codegen for these builtins ins design to handle it
5675   // gracefully.
5676   TheCall->setType(ResultType);
5677 
5678   // Prohibit use of _ExtInt with atomic builtins.
5679   // The arguments would have already been converted to the first argument's
5680   // type, so only need to check the first argument.
5681   const auto *ExtIntValType = ValType->getAs<ExtIntType>();
5682   if (ExtIntValType && !llvm::isPowerOf2_64(ExtIntValType->getNumBits())) {
5683     Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
5684     return ExprError();
5685   }
5686 
5687   return TheCallResult;
5688 }
5689 
5690 /// SemaBuiltinNontemporalOverloaded - We have a call to
5691 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
5692 /// overloaded function based on the pointer type of its last argument.
5693 ///
5694 /// This function goes through and does final semantic checking for these
5695 /// builtins.
5696 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5697   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5698   DeclRefExpr *DRE =
5699       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5700   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5701   unsigned BuiltinID = FDecl->getBuiltinID();
5702   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5703           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5704          "Unexpected nontemporal load/store builtin!");
5705   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5706   unsigned numArgs = isStore ? 2 : 1;
5707 
5708   // Ensure that we have the proper number of arguments.
5709   if (checkArgCount(*this, TheCall, numArgs))
5710     return ExprError();
5711 
5712   // Inspect the last argument of the nontemporal builtin.  This should always
5713   // be a pointer type, from which we imply the type of the memory access.
5714   // Because it is a pointer type, we don't have to worry about any implicit
5715   // casts here.
5716   Expr *PointerArg = TheCall->getArg(numArgs - 1);
5717   ExprResult PointerArgResult =
5718       DefaultFunctionArrayLvalueConversion(PointerArg);
5719 
5720   if (PointerArgResult.isInvalid())
5721     return ExprError();
5722   PointerArg = PointerArgResult.get();
5723   TheCall->setArg(numArgs - 1, PointerArg);
5724 
5725   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5726   if (!pointerType) {
5727     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
5728         << PointerArg->getType() << PointerArg->getSourceRange();
5729     return ExprError();
5730   }
5731 
5732   QualType ValType = pointerType->getPointeeType();
5733 
5734   // Strip any qualifiers off ValType.
5735   ValType = ValType.getUnqualifiedType();
5736   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5737       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5738       !ValType->isVectorType()) {
5739     Diag(DRE->getBeginLoc(),
5740          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5741         << PointerArg->getType() << PointerArg->getSourceRange();
5742     return ExprError();
5743   }
5744 
5745   if (!isStore) {
5746     TheCall->setType(ValType);
5747     return TheCallResult;
5748   }
5749 
5750   ExprResult ValArg = TheCall->getArg(0);
5751   InitializedEntity Entity = InitializedEntity::InitializeParameter(
5752       Context, ValType, /*consume*/ false);
5753   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
5754   if (ValArg.isInvalid())
5755     return ExprError();
5756 
5757   TheCall->setArg(0, ValArg.get());
5758   TheCall->setType(Context.VoidTy);
5759   return TheCallResult;
5760 }
5761 
5762 /// CheckObjCString - Checks that the argument to the builtin
5763 /// CFString constructor is correct
5764 /// Note: It might also make sense to do the UTF-16 conversion here (would
5765 /// simplify the backend).
5766 bool Sema::CheckObjCString(Expr *Arg) {
5767   Arg = Arg->IgnoreParenCasts();
5768   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
5769 
5770   if (!Literal || !Literal->isAscii()) {
5771     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
5772         << Arg->getSourceRange();
5773     return true;
5774   }
5775 
5776   if (Literal->containsNonAsciiOrNull()) {
5777     StringRef String = Literal->getString();
5778     unsigned NumBytes = String.size();
5779     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
5780     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
5781     llvm::UTF16 *ToPtr = &ToBuf[0];
5782 
5783     llvm::ConversionResult Result =
5784         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
5785                                  ToPtr + NumBytes, llvm::strictConversion);
5786     // Check for conversion failure.
5787     if (Result != llvm::conversionOK)
5788       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
5789           << Arg->getSourceRange();
5790   }
5791   return false;
5792 }
5793 
5794 /// CheckObjCString - Checks that the format string argument to the os_log()
5795 /// and os_trace() functions is correct, and converts it to const char *.
5796 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5797   Arg = Arg->IgnoreParenCasts();
5798   auto *Literal = dyn_cast<StringLiteral>(Arg);
5799   if (!Literal) {
5800     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
5801       Literal = ObjcLiteral->getString();
5802     }
5803   }
5804 
5805   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
5806     return ExprError(
5807         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
5808         << Arg->getSourceRange());
5809   }
5810 
5811   ExprResult Result(Literal);
5812   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
5813   InitializedEntity Entity =
5814       InitializedEntity::InitializeParameter(Context, ResultTy, false);
5815   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
5816   return Result;
5817 }
5818 
5819 /// Check that the user is calling the appropriate va_start builtin for the
5820 /// target and calling convention.
5821 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5822   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5823   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
5824   bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
5825                     TT.getArch() == llvm::Triple::aarch64_32);
5826   bool IsWindows = TT.isOSWindows();
5827   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5828   if (IsX64 || IsAArch64) {
5829     CallingConv CC = CC_C;
5830     if (const FunctionDecl *FD = S.getCurFunctionDecl())
5831       CC = FD->getType()->castAs<FunctionType>()->getCallConv();
5832     if (IsMSVAStart) {
5833       // Don't allow this in System V ABI functions.
5834       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
5835         return S.Diag(Fn->getBeginLoc(),
5836                       diag::err_ms_va_start_used_in_sysv_function);
5837     } else {
5838       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
5839       // On x64 Windows, don't allow this in System V ABI functions.
5840       // (Yes, that means there's no corresponding way to support variadic
5841       // System V ABI functions on Windows.)
5842       if ((IsWindows && CC == CC_X86_64SysV) ||
5843           (!IsWindows && CC == CC_Win64))
5844         return S.Diag(Fn->getBeginLoc(),
5845                       diag::err_va_start_used_in_wrong_abi_function)
5846                << !IsWindows;
5847     }
5848     return false;
5849   }
5850 
5851   if (IsMSVAStart)
5852     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
5853   return false;
5854 }
5855 
5856 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
5857                                              ParmVarDecl **LastParam = nullptr) {
5858   // Determine whether the current function, block, or obj-c method is variadic
5859   // and get its parameter list.
5860   bool IsVariadic = false;
5861   ArrayRef<ParmVarDecl *> Params;
5862   DeclContext *Caller = S.CurContext;
5863   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
5864     IsVariadic = Block->isVariadic();
5865     Params = Block->parameters();
5866   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
5867     IsVariadic = FD->isVariadic();
5868     Params = FD->parameters();
5869   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
5870     IsVariadic = MD->isVariadic();
5871     // FIXME: This isn't correct for methods (results in bogus warning).
5872     Params = MD->parameters();
5873   } else if (isa<CapturedDecl>(Caller)) {
5874     // We don't support va_start in a CapturedDecl.
5875     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
5876     return true;
5877   } else {
5878     // This must be some other declcontext that parses exprs.
5879     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
5880     return true;
5881   }
5882 
5883   if (!IsVariadic) {
5884     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
5885     return true;
5886   }
5887 
5888   if (LastParam)
5889     *LastParam = Params.empty() ? nullptr : Params.back();
5890 
5891   return false;
5892 }
5893 
5894 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
5895 /// for validity.  Emit an error and return true on failure; return false
5896 /// on success.
5897 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5898   Expr *Fn = TheCall->getCallee();
5899 
5900   if (checkVAStartABI(*this, BuiltinID, Fn))
5901     return true;
5902 
5903   if (checkArgCount(*this, TheCall, 2))
5904     return true;
5905 
5906   // Type-check the first argument normally.
5907   if (checkBuiltinArgument(*this, TheCall, 0))
5908     return true;
5909 
5910   // Check that the current function is variadic, and get its last parameter.
5911   ParmVarDecl *LastParam;
5912   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
5913     return true;
5914 
5915   // Verify that the second argument to the builtin is the last argument of the
5916   // current function or method.
5917   bool SecondArgIsLastNamedArgument = false;
5918   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
5919 
5920   // These are valid if SecondArgIsLastNamedArgument is false after the next
5921   // block.
5922   QualType Type;
5923   SourceLocation ParamLoc;
5924   bool IsCRegister = false;
5925 
5926   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
5927     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
5928       SecondArgIsLastNamedArgument = PV == LastParam;
5929 
5930       Type = PV->getType();
5931       ParamLoc = PV->getLocation();
5932       IsCRegister =
5933           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
5934     }
5935   }
5936 
5937   if (!SecondArgIsLastNamedArgument)
5938     Diag(TheCall->getArg(1)->getBeginLoc(),
5939          diag::warn_second_arg_of_va_start_not_last_named_param);
5940   else if (IsCRegister || Type->isReferenceType() ||
5941            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
5942              // Promotable integers are UB, but enumerations need a bit of
5943              // extra checking to see what their promotable type actually is.
5944              if (!Type->isPromotableIntegerType())
5945                return false;
5946              if (!Type->isEnumeralType())
5947                return true;
5948              const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
5949              return !(ED &&
5950                       Context.typesAreCompatible(ED->getPromotionType(), Type));
5951            }()) {
5952     unsigned Reason = 0;
5953     if (Type->isReferenceType())  Reason = 1;
5954     else if (IsCRegister)         Reason = 2;
5955     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
5956     Diag(ParamLoc, diag::note_parameter_type) << Type;
5957   }
5958 
5959   TheCall->setType(Context.VoidTy);
5960   return false;
5961 }
5962 
5963 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
5964   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
5965   //                 const char *named_addr);
5966 
5967   Expr *Func = Call->getCallee();
5968 
5969   if (Call->getNumArgs() < 3)
5970     return Diag(Call->getEndLoc(),
5971                 diag::err_typecheck_call_too_few_args_at_least)
5972            << 0 /*function call*/ << 3 << Call->getNumArgs();
5973 
5974   // Type-check the first argument normally.
5975   if (checkBuiltinArgument(*this, Call, 0))
5976     return true;
5977 
5978   // Check that the current function is variadic.
5979   if (checkVAStartIsInVariadicFunction(*this, Func))
5980     return true;
5981 
5982   // __va_start on Windows does not validate the parameter qualifiers
5983 
5984   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
5985   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
5986 
5987   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
5988   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
5989 
5990   const QualType &ConstCharPtrTy =
5991       Context.getPointerType(Context.CharTy.withConst());
5992   if (!Arg1Ty->isPointerType() ||
5993       Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
5994     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5995         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
5996         << 0                                      /* qualifier difference */
5997         << 3                                      /* parameter mismatch */
5998         << 2 << Arg1->getType() << ConstCharPtrTy;
5999 
6000   const QualType SizeTy = Context.getSizeType();
6001   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
6002     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6003         << Arg2->getType() << SizeTy << 1 /* different class */
6004         << 0                              /* qualifier difference */
6005         << 3                              /* parameter mismatch */
6006         << 3 << Arg2->getType() << SizeTy;
6007 
6008   return false;
6009 }
6010 
6011 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
6012 /// friends.  This is declared to take (...), so we have to check everything.
6013 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
6014   if (checkArgCount(*this, TheCall, 2))
6015     return true;
6016 
6017   ExprResult OrigArg0 = TheCall->getArg(0);
6018   ExprResult OrigArg1 = TheCall->getArg(1);
6019 
6020   // Do standard promotions between the two arguments, returning their common
6021   // type.
6022   QualType Res = UsualArithmeticConversions(
6023       OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
6024   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
6025     return true;
6026 
6027   // Make sure any conversions are pushed back into the call; this is
6028   // type safe since unordered compare builtins are declared as "_Bool
6029   // foo(...)".
6030   TheCall->setArg(0, OrigArg0.get());
6031   TheCall->setArg(1, OrigArg1.get());
6032 
6033   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
6034     return false;
6035 
6036   // If the common type isn't a real floating type, then the arguments were
6037   // invalid for this operation.
6038   if (Res.isNull() || !Res->isRealFloatingType())
6039     return Diag(OrigArg0.get()->getBeginLoc(),
6040                 diag::err_typecheck_call_invalid_ordered_compare)
6041            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
6042            << SourceRange(OrigArg0.get()->getBeginLoc(),
6043                           OrigArg1.get()->getEndLoc());
6044 
6045   return false;
6046 }
6047 
6048 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
6049 /// __builtin_isnan and friends.  This is declared to take (...), so we have
6050 /// to check everything. We expect the last argument to be a floating point
6051 /// value.
6052 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
6053   if (checkArgCount(*this, TheCall, NumArgs))
6054     return true;
6055 
6056   // __builtin_fpclassify is the only case where NumArgs != 1, so we can count
6057   // on all preceding parameters just being int.  Try all of those.
6058   for (unsigned i = 0; i < NumArgs - 1; ++i) {
6059     Expr *Arg = TheCall->getArg(i);
6060 
6061     if (Arg->isTypeDependent())
6062       return false;
6063 
6064     ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);
6065 
6066     if (Res.isInvalid())
6067       return true;
6068     TheCall->setArg(i, Res.get());
6069   }
6070 
6071   Expr *OrigArg = TheCall->getArg(NumArgs-1);
6072 
6073   if (OrigArg->isTypeDependent())
6074     return false;
6075 
6076   // Usual Unary Conversions will convert half to float, which we want for
6077   // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
6078   // type how it is, but do normal L->Rvalue conversions.
6079   if (Context.getTargetInfo().useFP16ConversionIntrinsics())
6080     OrigArg = UsualUnaryConversions(OrigArg).get();
6081   else
6082     OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
6083   TheCall->setArg(NumArgs - 1, OrigArg);
6084 
6085   // This operation requires a non-_Complex floating-point number.
6086   if (!OrigArg->getType()->isRealFloatingType())
6087     return Diag(OrigArg->getBeginLoc(),
6088                 diag::err_typecheck_call_invalid_unary_fp)
6089            << OrigArg->getType() << OrigArg->getSourceRange();
6090 
6091   return false;
6092 }
6093 
6094 /// Perform semantic analysis for a call to __builtin_complex.
6095 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) {
6096   if (checkArgCount(*this, TheCall, 2))
6097     return true;
6098 
6099   bool Dependent = false;
6100   for (unsigned I = 0; I != 2; ++I) {
6101     Expr *Arg = TheCall->getArg(I);
6102     QualType T = Arg->getType();
6103     if (T->isDependentType()) {
6104       Dependent = true;
6105       continue;
6106     }
6107 
6108     // Despite supporting _Complex int, GCC requires a real floating point type
6109     // for the operands of __builtin_complex.
6110     if (!T->isRealFloatingType()) {
6111       return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
6112              << Arg->getType() << Arg->getSourceRange();
6113     }
6114 
6115     ExprResult Converted = DefaultLvalueConversion(Arg);
6116     if (Converted.isInvalid())
6117       return true;
6118     TheCall->setArg(I, Converted.get());
6119   }
6120 
6121   if (Dependent) {
6122     TheCall->setType(Context.DependentTy);
6123     return false;
6124   }
6125 
6126   Expr *Real = TheCall->getArg(0);
6127   Expr *Imag = TheCall->getArg(1);
6128   if (!Context.hasSameType(Real->getType(), Imag->getType())) {
6129     return Diag(Real->getBeginLoc(),
6130                 diag::err_typecheck_call_different_arg_types)
6131            << Real->getType() << Imag->getType()
6132            << Real->getSourceRange() << Imag->getSourceRange();
6133   }
6134 
6135   // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers;
6136   // don't allow this builtin to form those types either.
6137   // FIXME: Should we allow these types?
6138   if (Real->getType()->isFloat16Type())
6139     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6140            << "_Float16";
6141   if (Real->getType()->isHalfType())
6142     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6143            << "half";
6144 
6145   TheCall->setType(Context.getComplexType(Real->getType()));
6146   return false;
6147 }
6148 
6149 // Customized Sema Checking for VSX builtins that have the following signature:
6150 // vector [...] builtinName(vector [...], vector [...], const int);
6151 // Which takes the same type of vectors (any legal vector type) for the first
6152 // two arguments and takes compile time constant for the third argument.
6153 // Example builtins are :
6154 // vector double vec_xxpermdi(vector double, vector double, int);
6155 // vector short vec_xxsldwi(vector short, vector short, int);
6156 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
6157   unsigned ExpectedNumArgs = 3;
6158   if (checkArgCount(*this, TheCall, ExpectedNumArgs))
6159     return true;
6160 
6161   // Check the third argument is a compile time constant
6162   if (!TheCall->getArg(2)->isIntegerConstantExpr(Context))
6163     return Diag(TheCall->getBeginLoc(),
6164                 diag::err_vsx_builtin_nonconstant_argument)
6165            << 3 /* argument index */ << TheCall->getDirectCallee()
6166            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
6167                           TheCall->getArg(2)->getEndLoc());
6168 
6169   QualType Arg1Ty = TheCall->getArg(0)->getType();
6170   QualType Arg2Ty = TheCall->getArg(1)->getType();
6171 
6172   // Check the type of argument 1 and argument 2 are vectors.
6173   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
6174   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
6175       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
6176     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
6177            << TheCall->getDirectCallee()
6178            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6179                           TheCall->getArg(1)->getEndLoc());
6180   }
6181 
6182   // Check the first two arguments are the same type.
6183   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
6184     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
6185            << TheCall->getDirectCallee()
6186            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6187                           TheCall->getArg(1)->getEndLoc());
6188   }
6189 
6190   // When default clang type checking is turned off and the customized type
6191   // checking is used, the returning type of the function must be explicitly
6192   // set. Otherwise it is _Bool by default.
6193   TheCall->setType(Arg1Ty);
6194 
6195   return false;
6196 }
6197 
6198 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
6199 // This is declared to take (...), so we have to check everything.
6200 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
6201   if (TheCall->getNumArgs() < 2)
6202     return ExprError(Diag(TheCall->getEndLoc(),
6203                           diag::err_typecheck_call_too_few_args_at_least)
6204                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
6205                      << TheCall->getSourceRange());
6206 
6207   // Determine which of the following types of shufflevector we're checking:
6208   // 1) unary, vector mask: (lhs, mask)
6209   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
6210   QualType resType = TheCall->getArg(0)->getType();
6211   unsigned numElements = 0;
6212 
6213   if (!TheCall->getArg(0)->isTypeDependent() &&
6214       !TheCall->getArg(1)->isTypeDependent()) {
6215     QualType LHSType = TheCall->getArg(0)->getType();
6216     QualType RHSType = TheCall->getArg(1)->getType();
6217 
6218     if (!LHSType->isVectorType() || !RHSType->isVectorType())
6219       return ExprError(
6220           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
6221           << TheCall->getDirectCallee()
6222           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6223                          TheCall->getArg(1)->getEndLoc()));
6224 
6225     numElements = LHSType->castAs<VectorType>()->getNumElements();
6226     unsigned numResElements = TheCall->getNumArgs() - 2;
6227 
6228     // Check to see if we have a call with 2 vector arguments, the unary shuffle
6229     // with mask.  If so, verify that RHS is an integer vector type with the
6230     // same number of elts as lhs.
6231     if (TheCall->getNumArgs() == 2) {
6232       if (!RHSType->hasIntegerRepresentation() ||
6233           RHSType->castAs<VectorType>()->getNumElements() != numElements)
6234         return ExprError(Diag(TheCall->getBeginLoc(),
6235                               diag::err_vec_builtin_incompatible_vector)
6236                          << TheCall->getDirectCallee()
6237                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
6238                                         TheCall->getArg(1)->getEndLoc()));
6239     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
6240       return ExprError(Diag(TheCall->getBeginLoc(),
6241                             diag::err_vec_builtin_incompatible_vector)
6242                        << TheCall->getDirectCallee()
6243                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6244                                       TheCall->getArg(1)->getEndLoc()));
6245     } else if (numElements != numResElements) {
6246       QualType eltType = LHSType->castAs<VectorType>()->getElementType();
6247       resType = Context.getVectorType(eltType, numResElements,
6248                                       VectorType::GenericVector);
6249     }
6250   }
6251 
6252   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
6253     if (TheCall->getArg(i)->isTypeDependent() ||
6254         TheCall->getArg(i)->isValueDependent())
6255       continue;
6256 
6257     Optional<llvm::APSInt> Result;
6258     if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context)))
6259       return ExprError(Diag(TheCall->getBeginLoc(),
6260                             diag::err_shufflevector_nonconstant_argument)
6261                        << TheCall->getArg(i)->getSourceRange());
6262 
6263     // Allow -1 which will be translated to undef in the IR.
6264     if (Result->isSigned() && Result->isAllOnesValue())
6265       continue;
6266 
6267     if (Result->getActiveBits() > 64 ||
6268         Result->getZExtValue() >= numElements * 2)
6269       return ExprError(Diag(TheCall->getBeginLoc(),
6270                             diag::err_shufflevector_argument_too_large)
6271                        << TheCall->getArg(i)->getSourceRange());
6272   }
6273 
6274   SmallVector<Expr*, 32> exprs;
6275 
6276   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
6277     exprs.push_back(TheCall->getArg(i));
6278     TheCall->setArg(i, nullptr);
6279   }
6280 
6281   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
6282                                          TheCall->getCallee()->getBeginLoc(),
6283                                          TheCall->getRParenLoc());
6284 }
6285 
6286 /// SemaConvertVectorExpr - Handle __builtin_convertvector
6287 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
6288                                        SourceLocation BuiltinLoc,
6289                                        SourceLocation RParenLoc) {
6290   ExprValueKind VK = VK_RValue;
6291   ExprObjectKind OK = OK_Ordinary;
6292   QualType DstTy = TInfo->getType();
6293   QualType SrcTy = E->getType();
6294 
6295   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
6296     return ExprError(Diag(BuiltinLoc,
6297                           diag::err_convertvector_non_vector)
6298                      << E->getSourceRange());
6299   if (!DstTy->isVectorType() && !DstTy->isDependentType())
6300     return ExprError(Diag(BuiltinLoc,
6301                           diag::err_convertvector_non_vector_type));
6302 
6303   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
6304     unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
6305     unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
6306     if (SrcElts != DstElts)
6307       return ExprError(Diag(BuiltinLoc,
6308                             diag::err_convertvector_incompatible_vector)
6309                        << E->getSourceRange());
6310   }
6311 
6312   return new (Context)
6313       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
6314 }
6315 
6316 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
6317 // This is declared to take (const void*, ...) and can take two
6318 // optional constant int args.
6319 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
6320   unsigned NumArgs = TheCall->getNumArgs();
6321 
6322   if (NumArgs > 3)
6323     return Diag(TheCall->getEndLoc(),
6324                 diag::err_typecheck_call_too_many_args_at_most)
6325            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6326 
6327   // Argument 0 is checked for us and the remaining arguments must be
6328   // constant integers.
6329   for (unsigned i = 1; i != NumArgs; ++i)
6330     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
6331       return true;
6332 
6333   return false;
6334 }
6335 
6336 /// SemaBuiltinAssume - Handle __assume (MS Extension).
6337 // __assume does not evaluate its arguments, and should warn if its argument
6338 // has side effects.
6339 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
6340   Expr *Arg = TheCall->getArg(0);
6341   if (Arg->isInstantiationDependent()) return false;
6342 
6343   if (Arg->HasSideEffects(Context))
6344     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
6345         << Arg->getSourceRange()
6346         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
6347 
6348   return false;
6349 }
6350 
6351 /// Handle __builtin_alloca_with_align. This is declared
6352 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
6353 /// than 8.
6354 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
6355   // The alignment must be a constant integer.
6356   Expr *Arg = TheCall->getArg(1);
6357 
6358   // We can't check the value of a dependent argument.
6359   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6360     if (const auto *UE =
6361             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
6362       if (UE->getKind() == UETT_AlignOf ||
6363           UE->getKind() == UETT_PreferredAlignOf)
6364         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
6365             << Arg->getSourceRange();
6366 
6367     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
6368 
6369     if (!Result.isPowerOf2())
6370       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6371              << Arg->getSourceRange();
6372 
6373     if (Result < Context.getCharWidth())
6374       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
6375              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6376 
6377     if (Result > std::numeric_limits<int32_t>::max())
6378       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
6379              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6380   }
6381 
6382   return false;
6383 }
6384 
6385 /// Handle __builtin_assume_aligned. This is declared
6386 /// as (const void*, size_t, ...) and can take one optional constant int arg.
6387 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
6388   unsigned NumArgs = TheCall->getNumArgs();
6389 
6390   if (NumArgs > 3)
6391     return Diag(TheCall->getEndLoc(),
6392                 diag::err_typecheck_call_too_many_args_at_most)
6393            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6394 
6395   // The alignment must be a constant integer.
6396   Expr *Arg = TheCall->getArg(1);
6397 
6398   // We can't check the value of a dependent argument.
6399   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6400     llvm::APSInt Result;
6401     if (SemaBuiltinConstantArg(TheCall, 1, Result))
6402       return true;
6403 
6404     if (!Result.isPowerOf2())
6405       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6406              << Arg->getSourceRange();
6407 
6408     if (Result > Sema::MaximumAlignment)
6409       Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
6410           << Arg->getSourceRange() << Sema::MaximumAlignment;
6411   }
6412 
6413   if (NumArgs > 2) {
6414     ExprResult Arg(TheCall->getArg(2));
6415     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6416       Context.getSizeType(), false);
6417     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6418     if (Arg.isInvalid()) return true;
6419     TheCall->setArg(2, Arg.get());
6420   }
6421 
6422   return false;
6423 }
6424 
6425 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
6426   unsigned BuiltinID =
6427       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
6428   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6429 
6430   unsigned NumArgs = TheCall->getNumArgs();
6431   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6432   if (NumArgs < NumRequiredArgs) {
6433     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
6434            << 0 /* function call */ << NumRequiredArgs << NumArgs
6435            << TheCall->getSourceRange();
6436   }
6437   if (NumArgs >= NumRequiredArgs + 0x100) {
6438     return Diag(TheCall->getEndLoc(),
6439                 diag::err_typecheck_call_too_many_args_at_most)
6440            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6441            << TheCall->getSourceRange();
6442   }
6443   unsigned i = 0;
6444 
6445   // For formatting call, check buffer arg.
6446   if (!IsSizeCall) {
6447     ExprResult Arg(TheCall->getArg(i));
6448     InitializedEntity Entity = InitializedEntity::InitializeParameter(
6449         Context, Context.VoidPtrTy, false);
6450     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6451     if (Arg.isInvalid())
6452       return true;
6453     TheCall->setArg(i, Arg.get());
6454     i++;
6455   }
6456 
6457   // Check string literal arg.
6458   unsigned FormatIdx = i;
6459   {
6460     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
6461     if (Arg.isInvalid())
6462       return true;
6463     TheCall->setArg(i, Arg.get());
6464     i++;
6465   }
6466 
6467   // Make sure variadic args are scalar.
6468   unsigned FirstDataArg = i;
6469   while (i < NumArgs) {
6470     ExprResult Arg = DefaultVariadicArgumentPromotion(
6471         TheCall->getArg(i), VariadicFunction, nullptr);
6472     if (Arg.isInvalid())
6473       return true;
6474     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
6475     if (ArgSize.getQuantity() >= 0x100) {
6476       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
6477              << i << (int)ArgSize.getQuantity() << 0xff
6478              << TheCall->getSourceRange();
6479     }
6480     TheCall->setArg(i, Arg.get());
6481     i++;
6482   }
6483 
6484   // Check formatting specifiers. NOTE: We're only doing this for the non-size
6485   // call to avoid duplicate diagnostics.
6486   if (!IsSizeCall) {
6487     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6488     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6489     bool Success = CheckFormatArguments(
6490         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
6491         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
6492         CheckedVarArgs);
6493     if (!Success)
6494       return true;
6495   }
6496 
6497   if (IsSizeCall) {
6498     TheCall->setType(Context.getSizeType());
6499   } else {
6500     TheCall->setType(Context.VoidPtrTy);
6501   }
6502   return false;
6503 }
6504 
6505 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
6506 /// TheCall is a constant expression.
6507 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
6508                                   llvm::APSInt &Result) {
6509   Expr *Arg = TheCall->getArg(ArgNum);
6510   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6511   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6512 
6513   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
6514 
6515   Optional<llvm::APSInt> R;
6516   if (!(R = Arg->getIntegerConstantExpr(Context)))
6517     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6518            << FDecl->getDeclName() << Arg->getSourceRange();
6519   Result = *R;
6520   return false;
6521 }
6522 
6523 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
6524 /// TheCall is a constant expression in the range [Low, High].
6525 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
6526                                        int Low, int High, bool RangeIsError) {
6527   if (isConstantEvaluated())
6528     return false;
6529   llvm::APSInt Result;
6530 
6531   // We can't check the value of a dependent argument.
6532   Expr *Arg = TheCall->getArg(ArgNum);
6533   if (Arg->isTypeDependent() || Arg->isValueDependent())
6534     return false;
6535 
6536   // Check constant-ness first.
6537   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6538     return true;
6539 
6540   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6541     if (RangeIsError)
6542       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
6543              << Result.toString(10) << Low << High << Arg->getSourceRange();
6544     else
6545       // Defer the warning until we know if the code will be emitted so that
6546       // dead code can ignore this.
6547       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6548                           PDiag(diag::warn_argument_invalid_range)
6549                               << Result.toString(10) << Low << High
6550                               << Arg->getSourceRange());
6551   }
6552 
6553   return false;
6554 }
6555 
6556 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
6557 /// TheCall is a constant expression is a multiple of Num..
6558 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
6559                                           unsigned Num) {
6560   llvm::APSInt Result;
6561 
6562   // We can't check the value of a dependent argument.
6563   Expr *Arg = TheCall->getArg(ArgNum);
6564   if (Arg->isTypeDependent() || Arg->isValueDependent())
6565     return false;
6566 
6567   // Check constant-ness first.
6568   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6569     return true;
6570 
6571   if (Result.getSExtValue() % Num != 0)
6572     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6573            << Num << Arg->getSourceRange();
6574 
6575   return false;
6576 }
6577 
6578 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
6579 /// constant expression representing a power of 2.
6580 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
6581   llvm::APSInt Result;
6582 
6583   // We can't check the value of a dependent argument.
6584   Expr *Arg = TheCall->getArg(ArgNum);
6585   if (Arg->isTypeDependent() || Arg->isValueDependent())
6586     return false;
6587 
6588   // Check constant-ness first.
6589   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6590     return true;
6591 
6592   // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
6593   // and only if x is a power of 2.
6594   if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
6595     return false;
6596 
6597   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
6598          << Arg->getSourceRange();
6599 }
6600 
6601 static bool IsShiftedByte(llvm::APSInt Value) {
6602   if (Value.isNegative())
6603     return false;
6604 
6605   // Check if it's a shifted byte, by shifting it down
6606   while (true) {
6607     // If the value fits in the bottom byte, the check passes.
6608     if (Value < 0x100)
6609       return true;
6610 
6611     // Otherwise, if the value has _any_ bits in the bottom byte, the check
6612     // fails.
6613     if ((Value & 0xFF) != 0)
6614       return false;
6615 
6616     // If the bottom 8 bits are all 0, but something above that is nonzero,
6617     // then shifting the value right by 8 bits won't affect whether it's a
6618     // shifted byte or not. So do that, and go round again.
6619     Value >>= 8;
6620   }
6621 }
6622 
6623 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
6624 /// a constant expression representing an arbitrary byte value shifted left by
6625 /// a multiple of 8 bits.
6626 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
6627                                              unsigned ArgBits) {
6628   llvm::APSInt Result;
6629 
6630   // We can't check the value of a dependent argument.
6631   Expr *Arg = TheCall->getArg(ArgNum);
6632   if (Arg->isTypeDependent() || Arg->isValueDependent())
6633     return false;
6634 
6635   // Check constant-ness first.
6636   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6637     return true;
6638 
6639   // Truncate to the given size.
6640   Result = Result.getLoBits(ArgBits);
6641   Result.setIsUnsigned(true);
6642 
6643   if (IsShiftedByte(Result))
6644     return false;
6645 
6646   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
6647          << Arg->getSourceRange();
6648 }
6649 
6650 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
6651 /// TheCall is a constant expression representing either a shifted byte value,
6652 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
6653 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
6654 /// Arm MVE intrinsics.
6655 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
6656                                                    int ArgNum,
6657                                                    unsigned ArgBits) {
6658   llvm::APSInt Result;
6659 
6660   // We can't check the value of a dependent argument.
6661   Expr *Arg = TheCall->getArg(ArgNum);
6662   if (Arg->isTypeDependent() || Arg->isValueDependent())
6663     return false;
6664 
6665   // Check constant-ness first.
6666   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6667     return true;
6668 
6669   // Truncate to the given size.
6670   Result = Result.getLoBits(ArgBits);
6671   Result.setIsUnsigned(true);
6672 
6673   // Check to see if it's in either of the required forms.
6674   if (IsShiftedByte(Result) ||
6675       (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
6676     return false;
6677 
6678   return Diag(TheCall->getBeginLoc(),
6679               diag::err_argument_not_shifted_byte_or_xxff)
6680          << Arg->getSourceRange();
6681 }
6682 
6683 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
6684 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
6685   if (BuiltinID == AArch64::BI__builtin_arm_irg) {
6686     if (checkArgCount(*this, TheCall, 2))
6687       return true;
6688     Expr *Arg0 = TheCall->getArg(0);
6689     Expr *Arg1 = TheCall->getArg(1);
6690 
6691     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6692     if (FirstArg.isInvalid())
6693       return true;
6694     QualType FirstArgType = FirstArg.get()->getType();
6695     if (!FirstArgType->isAnyPointerType())
6696       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6697                << "first" << FirstArgType << Arg0->getSourceRange();
6698     TheCall->setArg(0, FirstArg.get());
6699 
6700     ExprResult SecArg = DefaultLvalueConversion(Arg1);
6701     if (SecArg.isInvalid())
6702       return true;
6703     QualType SecArgType = SecArg.get()->getType();
6704     if (!SecArgType->isIntegerType())
6705       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6706                << "second" << SecArgType << Arg1->getSourceRange();
6707 
6708     // Derive the return type from the pointer argument.
6709     TheCall->setType(FirstArgType);
6710     return false;
6711   }
6712 
6713   if (BuiltinID == AArch64::BI__builtin_arm_addg) {
6714     if (checkArgCount(*this, TheCall, 2))
6715       return true;
6716 
6717     Expr *Arg0 = TheCall->getArg(0);
6718     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6719     if (FirstArg.isInvalid())
6720       return true;
6721     QualType FirstArgType = FirstArg.get()->getType();
6722     if (!FirstArgType->isAnyPointerType())
6723       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6724                << "first" << FirstArgType << Arg0->getSourceRange();
6725     TheCall->setArg(0, FirstArg.get());
6726 
6727     // Derive the return type from the pointer argument.
6728     TheCall->setType(FirstArgType);
6729 
6730     // Second arg must be an constant in range [0,15]
6731     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6732   }
6733 
6734   if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
6735     if (checkArgCount(*this, TheCall, 2))
6736       return true;
6737     Expr *Arg0 = TheCall->getArg(0);
6738     Expr *Arg1 = TheCall->getArg(1);
6739 
6740     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6741     if (FirstArg.isInvalid())
6742       return true;
6743     QualType FirstArgType = FirstArg.get()->getType();
6744     if (!FirstArgType->isAnyPointerType())
6745       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6746                << "first" << FirstArgType << Arg0->getSourceRange();
6747 
6748     QualType SecArgType = Arg1->getType();
6749     if (!SecArgType->isIntegerType())
6750       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6751                << "second" << SecArgType << Arg1->getSourceRange();
6752     TheCall->setType(Context.IntTy);
6753     return false;
6754   }
6755 
6756   if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
6757       BuiltinID == AArch64::BI__builtin_arm_stg) {
6758     if (checkArgCount(*this, TheCall, 1))
6759       return true;
6760     Expr *Arg0 = TheCall->getArg(0);
6761     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6762     if (FirstArg.isInvalid())
6763       return true;
6764 
6765     QualType FirstArgType = FirstArg.get()->getType();
6766     if (!FirstArgType->isAnyPointerType())
6767       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6768                << "first" << FirstArgType << Arg0->getSourceRange();
6769     TheCall->setArg(0, FirstArg.get());
6770 
6771     // Derive the return type from the pointer argument.
6772     if (BuiltinID == AArch64::BI__builtin_arm_ldg)
6773       TheCall->setType(FirstArgType);
6774     return false;
6775   }
6776 
6777   if (BuiltinID == AArch64::BI__builtin_arm_subp) {
6778     Expr *ArgA = TheCall->getArg(0);
6779     Expr *ArgB = TheCall->getArg(1);
6780 
6781     ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
6782     ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
6783 
6784     if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
6785       return true;
6786 
6787     QualType ArgTypeA = ArgExprA.get()->getType();
6788     QualType ArgTypeB = ArgExprB.get()->getType();
6789 
6790     auto isNull = [&] (Expr *E) -> bool {
6791       return E->isNullPointerConstant(
6792                         Context, Expr::NPC_ValueDependentIsNotNull); };
6793 
6794     // argument should be either a pointer or null
6795     if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
6796       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6797         << "first" << ArgTypeA << ArgA->getSourceRange();
6798 
6799     if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
6800       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6801         << "second" << ArgTypeB << ArgB->getSourceRange();
6802 
6803     // Ensure Pointee types are compatible
6804     if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
6805         ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
6806       QualType pointeeA = ArgTypeA->getPointeeType();
6807       QualType pointeeB = ArgTypeB->getPointeeType();
6808       if (!Context.typesAreCompatible(
6809              Context.getCanonicalType(pointeeA).getUnqualifiedType(),
6810              Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
6811         return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
6812           << ArgTypeA <<  ArgTypeB << ArgA->getSourceRange()
6813           << ArgB->getSourceRange();
6814       }
6815     }
6816 
6817     // at least one argument should be pointer type
6818     if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
6819       return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
6820         <<  ArgTypeA << ArgTypeB << ArgA->getSourceRange();
6821 
6822     if (isNull(ArgA)) // adopt type of the other pointer
6823       ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
6824 
6825     if (isNull(ArgB))
6826       ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
6827 
6828     TheCall->setArg(0, ArgExprA.get());
6829     TheCall->setArg(1, ArgExprB.get());
6830     TheCall->setType(Context.LongLongTy);
6831     return false;
6832   }
6833   assert(false && "Unhandled ARM MTE intrinsic");
6834   return true;
6835 }
6836 
6837 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
6838 /// TheCall is an ARM/AArch64 special register string literal.
6839 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
6840                                     int ArgNum, unsigned ExpectedFieldNum,
6841                                     bool AllowName) {
6842   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
6843                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
6844                       BuiltinID == ARM::BI__builtin_arm_rsr ||
6845                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
6846                       BuiltinID == ARM::BI__builtin_arm_wsr ||
6847                       BuiltinID == ARM::BI__builtin_arm_wsrp;
6848   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
6849                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
6850                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
6851                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
6852                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
6853                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
6854   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
6855 
6856   // We can't check the value of a dependent argument.
6857   Expr *Arg = TheCall->getArg(ArgNum);
6858   if (Arg->isTypeDependent() || Arg->isValueDependent())
6859     return false;
6860 
6861   // Check if the argument is a string literal.
6862   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
6863     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
6864            << Arg->getSourceRange();
6865 
6866   // Check the type of special register given.
6867   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
6868   SmallVector<StringRef, 6> Fields;
6869   Reg.split(Fields, ":");
6870 
6871   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
6872     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6873            << Arg->getSourceRange();
6874 
6875   // If the string is the name of a register then we cannot check that it is
6876   // valid here but if the string is of one the forms described in ACLE then we
6877   // can check that the supplied fields are integers and within the valid
6878   // ranges.
6879   if (Fields.size() > 1) {
6880     bool FiveFields = Fields.size() == 5;
6881 
6882     bool ValidString = true;
6883     if (IsARMBuiltin) {
6884       ValidString &= Fields[0].startswith_lower("cp") ||
6885                      Fields[0].startswith_lower("p");
6886       if (ValidString)
6887         Fields[0] =
6888           Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
6889 
6890       ValidString &= Fields[2].startswith_lower("c");
6891       if (ValidString)
6892         Fields[2] = Fields[2].drop_front(1);
6893 
6894       if (FiveFields) {
6895         ValidString &= Fields[3].startswith_lower("c");
6896         if (ValidString)
6897           Fields[3] = Fields[3].drop_front(1);
6898       }
6899     }
6900 
6901     SmallVector<int, 5> Ranges;
6902     if (FiveFields)
6903       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
6904     else
6905       Ranges.append({15, 7, 15});
6906 
6907     for (unsigned i=0; i<Fields.size(); ++i) {
6908       int IntField;
6909       ValidString &= !Fields[i].getAsInteger(10, IntField);
6910       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
6911     }
6912 
6913     if (!ValidString)
6914       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6915              << Arg->getSourceRange();
6916   } else if (IsAArch64Builtin && Fields.size() == 1) {
6917     // If the register name is one of those that appear in the condition below
6918     // and the special register builtin being used is one of the write builtins,
6919     // then we require that the argument provided for writing to the register
6920     // is an integer constant expression. This is because it will be lowered to
6921     // an MSR (immediate) instruction, so we need to know the immediate at
6922     // compile time.
6923     if (TheCall->getNumArgs() != 2)
6924       return false;
6925 
6926     std::string RegLower = Reg.lower();
6927     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
6928         RegLower != "pan" && RegLower != "uao")
6929       return false;
6930 
6931     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6932   }
6933 
6934   return false;
6935 }
6936 
6937 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity.
6938 /// Emit an error and return true on failure; return false on success.
6939 /// TypeStr is a string containing the type descriptor of the value returned by
6940 /// the builtin and the descriptors of the expected type of the arguments.
6941 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, const char *TypeStr) {
6942 
6943   assert((TypeStr[0] != '\0') &&
6944          "Invalid types in PPC MMA builtin declaration");
6945 
6946   unsigned Mask = 0;
6947   unsigned ArgNum = 0;
6948 
6949   // The first type in TypeStr is the type of the value returned by the
6950   // builtin. So we first read that type and change the type of TheCall.
6951   QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
6952   TheCall->setType(type);
6953 
6954   while (*TypeStr != '\0') {
6955     Mask = 0;
6956     QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
6957     if (ArgNum >= TheCall->getNumArgs()) {
6958       ArgNum++;
6959       break;
6960     }
6961 
6962     Expr *Arg = TheCall->getArg(ArgNum);
6963     QualType ArgType = Arg->getType();
6964 
6965     if ((ExpectedType->isVoidPointerType() && !ArgType->isPointerType()) ||
6966         (!ExpectedType->isVoidPointerType() &&
6967            ArgType.getCanonicalType() != ExpectedType))
6968       return Diag(Arg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6969              << ArgType << ExpectedType << 1 << 0 << 0;
6970 
6971     // If the value of the Mask is not 0, we have a constraint in the size of
6972     // the integer argument so here we ensure the argument is a constant that
6973     // is in the valid range.
6974     if (Mask != 0 &&
6975         SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true))
6976       return true;
6977 
6978     ArgNum++;
6979   }
6980 
6981   // In case we exited early from the previous loop, there are other types to
6982   // read from TypeStr. So we need to read them all to ensure we have the right
6983   // number of arguments in TheCall and if it is not the case, to display a
6984   // better error message.
6985   while (*TypeStr != '\0') {
6986     (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
6987     ArgNum++;
6988   }
6989   if (checkArgCount(*this, TheCall, ArgNum))
6990     return true;
6991 
6992   return false;
6993 }
6994 
6995 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
6996 /// This checks that the target supports __builtin_longjmp and
6997 /// that val is a constant 1.
6998 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
6999   if (!Context.getTargetInfo().hasSjLjLowering())
7000     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
7001            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7002 
7003   Expr *Arg = TheCall->getArg(1);
7004   llvm::APSInt Result;
7005 
7006   // TODO: This is less than ideal. Overload this to take a value.
7007   if (SemaBuiltinConstantArg(TheCall, 1, Result))
7008     return true;
7009 
7010   if (Result != 1)
7011     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
7012            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
7013 
7014   return false;
7015 }
7016 
7017 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
7018 /// This checks that the target supports __builtin_setjmp.
7019 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
7020   if (!Context.getTargetInfo().hasSjLjLowering())
7021     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
7022            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7023   return false;
7024 }
7025 
7026 namespace {
7027 
7028 class UncoveredArgHandler {
7029   enum { Unknown = -1, AllCovered = -2 };
7030 
7031   signed FirstUncoveredArg = Unknown;
7032   SmallVector<const Expr *, 4> DiagnosticExprs;
7033 
7034 public:
7035   UncoveredArgHandler() = default;
7036 
7037   bool hasUncoveredArg() const {
7038     return (FirstUncoveredArg >= 0);
7039   }
7040 
7041   unsigned getUncoveredArg() const {
7042     assert(hasUncoveredArg() && "no uncovered argument");
7043     return FirstUncoveredArg;
7044   }
7045 
7046   void setAllCovered() {
7047     // A string has been found with all arguments covered, so clear out
7048     // the diagnostics.
7049     DiagnosticExprs.clear();
7050     FirstUncoveredArg = AllCovered;
7051   }
7052 
7053   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
7054     assert(NewFirstUncoveredArg >= 0 && "Outside range");
7055 
7056     // Don't update if a previous string covers all arguments.
7057     if (FirstUncoveredArg == AllCovered)
7058       return;
7059 
7060     // UncoveredArgHandler tracks the highest uncovered argument index
7061     // and with it all the strings that match this index.
7062     if (NewFirstUncoveredArg == FirstUncoveredArg)
7063       DiagnosticExprs.push_back(StrExpr);
7064     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
7065       DiagnosticExprs.clear();
7066       DiagnosticExprs.push_back(StrExpr);
7067       FirstUncoveredArg = NewFirstUncoveredArg;
7068     }
7069   }
7070 
7071   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
7072 };
7073 
7074 enum StringLiteralCheckType {
7075   SLCT_NotALiteral,
7076   SLCT_UncheckedLiteral,
7077   SLCT_CheckedLiteral
7078 };
7079 
7080 } // namespace
7081 
7082 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
7083                                      BinaryOperatorKind BinOpKind,
7084                                      bool AddendIsRight) {
7085   unsigned BitWidth = Offset.getBitWidth();
7086   unsigned AddendBitWidth = Addend.getBitWidth();
7087   // There might be negative interim results.
7088   if (Addend.isUnsigned()) {
7089     Addend = Addend.zext(++AddendBitWidth);
7090     Addend.setIsSigned(true);
7091   }
7092   // Adjust the bit width of the APSInts.
7093   if (AddendBitWidth > BitWidth) {
7094     Offset = Offset.sext(AddendBitWidth);
7095     BitWidth = AddendBitWidth;
7096   } else if (BitWidth > AddendBitWidth) {
7097     Addend = Addend.sext(BitWidth);
7098   }
7099 
7100   bool Ov = false;
7101   llvm::APSInt ResOffset = Offset;
7102   if (BinOpKind == BO_Add)
7103     ResOffset = Offset.sadd_ov(Addend, Ov);
7104   else {
7105     assert(AddendIsRight && BinOpKind == BO_Sub &&
7106            "operator must be add or sub with addend on the right");
7107     ResOffset = Offset.ssub_ov(Addend, Ov);
7108   }
7109 
7110   // We add an offset to a pointer here so we should support an offset as big as
7111   // possible.
7112   if (Ov) {
7113     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
7114            "index (intermediate) result too big");
7115     Offset = Offset.sext(2 * BitWidth);
7116     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
7117     return;
7118   }
7119 
7120   Offset = ResOffset;
7121 }
7122 
7123 namespace {
7124 
7125 // This is a wrapper class around StringLiteral to support offsetted string
7126 // literals as format strings. It takes the offset into account when returning
7127 // the string and its length or the source locations to display notes correctly.
7128 class FormatStringLiteral {
7129   const StringLiteral *FExpr;
7130   int64_t Offset;
7131 
7132  public:
7133   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
7134       : FExpr(fexpr), Offset(Offset) {}
7135 
7136   StringRef getString() const {
7137     return FExpr->getString().drop_front(Offset);
7138   }
7139 
7140   unsigned getByteLength() const {
7141     return FExpr->getByteLength() - getCharByteWidth() * Offset;
7142   }
7143 
7144   unsigned getLength() const { return FExpr->getLength() - Offset; }
7145   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
7146 
7147   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
7148 
7149   QualType getType() const { return FExpr->getType(); }
7150 
7151   bool isAscii() const { return FExpr->isAscii(); }
7152   bool isWide() const { return FExpr->isWide(); }
7153   bool isUTF8() const { return FExpr->isUTF8(); }
7154   bool isUTF16() const { return FExpr->isUTF16(); }
7155   bool isUTF32() const { return FExpr->isUTF32(); }
7156   bool isPascal() const { return FExpr->isPascal(); }
7157 
7158   SourceLocation getLocationOfByte(
7159       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
7160       const TargetInfo &Target, unsigned *StartToken = nullptr,
7161       unsigned *StartTokenByteOffset = nullptr) const {
7162     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
7163                                     StartToken, StartTokenByteOffset);
7164   }
7165 
7166   SourceLocation getBeginLoc() const LLVM_READONLY {
7167     return FExpr->getBeginLoc().getLocWithOffset(Offset);
7168   }
7169 
7170   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
7171 };
7172 
7173 }  // namespace
7174 
7175 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
7176                               const Expr *OrigFormatExpr,
7177                               ArrayRef<const Expr *> Args,
7178                               bool HasVAListArg, unsigned format_idx,
7179                               unsigned firstDataArg,
7180                               Sema::FormatStringType Type,
7181                               bool inFunctionCall,
7182                               Sema::VariadicCallType CallType,
7183                               llvm::SmallBitVector &CheckedVarArgs,
7184                               UncoveredArgHandler &UncoveredArg,
7185                               bool IgnoreStringsWithoutSpecifiers);
7186 
7187 // Determine if an expression is a string literal or constant string.
7188 // If this function returns false on the arguments to a function expecting a
7189 // format string, we will usually need to emit a warning.
7190 // True string literals are then checked by CheckFormatString.
7191 static StringLiteralCheckType
7192 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
7193                       bool HasVAListArg, unsigned format_idx,
7194                       unsigned firstDataArg, Sema::FormatStringType Type,
7195                       Sema::VariadicCallType CallType, bool InFunctionCall,
7196                       llvm::SmallBitVector &CheckedVarArgs,
7197                       UncoveredArgHandler &UncoveredArg,
7198                       llvm::APSInt Offset,
7199                       bool IgnoreStringsWithoutSpecifiers = false) {
7200   if (S.isConstantEvaluated())
7201     return SLCT_NotALiteral;
7202  tryAgain:
7203   assert(Offset.isSigned() && "invalid offset");
7204 
7205   if (E->isTypeDependent() || E->isValueDependent())
7206     return SLCT_NotALiteral;
7207 
7208   E = E->IgnoreParenCasts();
7209 
7210   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
7211     // Technically -Wformat-nonliteral does not warn about this case.
7212     // The behavior of printf and friends in this case is implementation
7213     // dependent.  Ideally if the format string cannot be null then
7214     // it should have a 'nonnull' attribute in the function prototype.
7215     return SLCT_UncheckedLiteral;
7216 
7217   switch (E->getStmtClass()) {
7218   case Stmt::BinaryConditionalOperatorClass:
7219   case Stmt::ConditionalOperatorClass: {
7220     // The expression is a literal if both sub-expressions were, and it was
7221     // completely checked only if both sub-expressions were checked.
7222     const AbstractConditionalOperator *C =
7223         cast<AbstractConditionalOperator>(E);
7224 
7225     // Determine whether it is necessary to check both sub-expressions, for
7226     // example, because the condition expression is a constant that can be
7227     // evaluated at compile time.
7228     bool CheckLeft = true, CheckRight = true;
7229 
7230     bool Cond;
7231     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
7232                                                  S.isConstantEvaluated())) {
7233       if (Cond)
7234         CheckRight = false;
7235       else
7236         CheckLeft = false;
7237     }
7238 
7239     // We need to maintain the offsets for the right and the left hand side
7240     // separately to check if every possible indexed expression is a valid
7241     // string literal. They might have different offsets for different string
7242     // literals in the end.
7243     StringLiteralCheckType Left;
7244     if (!CheckLeft)
7245       Left = SLCT_UncheckedLiteral;
7246     else {
7247       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
7248                                    HasVAListArg, format_idx, firstDataArg,
7249                                    Type, CallType, InFunctionCall,
7250                                    CheckedVarArgs, UncoveredArg, Offset,
7251                                    IgnoreStringsWithoutSpecifiers);
7252       if (Left == SLCT_NotALiteral || !CheckRight) {
7253         return Left;
7254       }
7255     }
7256 
7257     StringLiteralCheckType Right = checkFormatStringExpr(
7258         S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
7259         Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7260         IgnoreStringsWithoutSpecifiers);
7261 
7262     return (CheckLeft && Left < Right) ? Left : Right;
7263   }
7264 
7265   case Stmt::ImplicitCastExprClass:
7266     E = cast<ImplicitCastExpr>(E)->getSubExpr();
7267     goto tryAgain;
7268 
7269   case Stmt::OpaqueValueExprClass:
7270     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
7271       E = src;
7272       goto tryAgain;
7273     }
7274     return SLCT_NotALiteral;
7275 
7276   case Stmt::PredefinedExprClass:
7277     // While __func__, etc., are technically not string literals, they
7278     // cannot contain format specifiers and thus are not a security
7279     // liability.
7280     return SLCT_UncheckedLiteral;
7281 
7282   case Stmt::DeclRefExprClass: {
7283     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7284 
7285     // As an exception, do not flag errors for variables binding to
7286     // const string literals.
7287     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
7288       bool isConstant = false;
7289       QualType T = DR->getType();
7290 
7291       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
7292         isConstant = AT->getElementType().isConstant(S.Context);
7293       } else if (const PointerType *PT = T->getAs<PointerType>()) {
7294         isConstant = T.isConstant(S.Context) &&
7295                      PT->getPointeeType().isConstant(S.Context);
7296       } else if (T->isObjCObjectPointerType()) {
7297         // In ObjC, there is usually no "const ObjectPointer" type,
7298         // so don't check if the pointee type is constant.
7299         isConstant = T.isConstant(S.Context);
7300       }
7301 
7302       if (isConstant) {
7303         if (const Expr *Init = VD->getAnyInitializer()) {
7304           // Look through initializers like const char c[] = { "foo" }
7305           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
7306             if (InitList->isStringLiteralInit())
7307               Init = InitList->getInit(0)->IgnoreParenImpCasts();
7308           }
7309           return checkFormatStringExpr(S, Init, Args,
7310                                        HasVAListArg, format_idx,
7311                                        firstDataArg, Type, CallType,
7312                                        /*InFunctionCall*/ false, CheckedVarArgs,
7313                                        UncoveredArg, Offset);
7314         }
7315       }
7316 
7317       // For vprintf* functions (i.e., HasVAListArg==true), we add a
7318       // special check to see if the format string is a function parameter
7319       // of the function calling the printf function.  If the function
7320       // has an attribute indicating it is a printf-like function, then we
7321       // should suppress warnings concerning non-literals being used in a call
7322       // to a vprintf function.  For example:
7323       //
7324       // void
7325       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
7326       //      va_list ap;
7327       //      va_start(ap, fmt);
7328       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
7329       //      ...
7330       // }
7331       if (HasVAListArg) {
7332         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
7333           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
7334             int PVIndex = PV->getFunctionScopeIndex() + 1;
7335             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
7336               // adjust for implicit parameter
7337               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
7338                 if (MD->isInstance())
7339                   ++PVIndex;
7340               // We also check if the formats are compatible.
7341               // We can't pass a 'scanf' string to a 'printf' function.
7342               if (PVIndex == PVFormat->getFormatIdx() &&
7343                   Type == S.GetFormatStringType(PVFormat))
7344                 return SLCT_UncheckedLiteral;
7345             }
7346           }
7347         }
7348       }
7349     }
7350 
7351     return SLCT_NotALiteral;
7352   }
7353 
7354   case Stmt::CallExprClass:
7355   case Stmt::CXXMemberCallExprClass: {
7356     const CallExpr *CE = cast<CallExpr>(E);
7357     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
7358       bool IsFirst = true;
7359       StringLiteralCheckType CommonResult;
7360       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
7361         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
7362         StringLiteralCheckType Result = checkFormatStringExpr(
7363             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7364             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7365             IgnoreStringsWithoutSpecifiers);
7366         if (IsFirst) {
7367           CommonResult = Result;
7368           IsFirst = false;
7369         }
7370       }
7371       if (!IsFirst)
7372         return CommonResult;
7373 
7374       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
7375         unsigned BuiltinID = FD->getBuiltinID();
7376         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
7377             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
7378           const Expr *Arg = CE->getArg(0);
7379           return checkFormatStringExpr(S, Arg, Args,
7380                                        HasVAListArg, format_idx,
7381                                        firstDataArg, Type, CallType,
7382                                        InFunctionCall, CheckedVarArgs,
7383                                        UncoveredArg, Offset,
7384                                        IgnoreStringsWithoutSpecifiers);
7385         }
7386       }
7387     }
7388 
7389     return SLCT_NotALiteral;
7390   }
7391   case Stmt::ObjCMessageExprClass: {
7392     const auto *ME = cast<ObjCMessageExpr>(E);
7393     if (const auto *MD = ME->getMethodDecl()) {
7394       if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
7395         // As a special case heuristic, if we're using the method -[NSBundle
7396         // localizedStringForKey:value:table:], ignore any key strings that lack
7397         // format specifiers. The idea is that if the key doesn't have any
7398         // format specifiers then its probably just a key to map to the
7399         // localized strings. If it does have format specifiers though, then its
7400         // likely that the text of the key is the format string in the
7401         // programmer's language, and should be checked.
7402         const ObjCInterfaceDecl *IFace;
7403         if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
7404             IFace->getIdentifier()->isStr("NSBundle") &&
7405             MD->getSelector().isKeywordSelector(
7406                 {"localizedStringForKey", "value", "table"})) {
7407           IgnoreStringsWithoutSpecifiers = true;
7408         }
7409 
7410         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
7411         return checkFormatStringExpr(
7412             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7413             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7414             IgnoreStringsWithoutSpecifiers);
7415       }
7416     }
7417 
7418     return SLCT_NotALiteral;
7419   }
7420   case Stmt::ObjCStringLiteralClass:
7421   case Stmt::StringLiteralClass: {
7422     const StringLiteral *StrE = nullptr;
7423 
7424     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
7425       StrE = ObjCFExpr->getString();
7426     else
7427       StrE = cast<StringLiteral>(E);
7428 
7429     if (StrE) {
7430       if (Offset.isNegative() || Offset > StrE->getLength()) {
7431         // TODO: It would be better to have an explicit warning for out of
7432         // bounds literals.
7433         return SLCT_NotALiteral;
7434       }
7435       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
7436       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
7437                         firstDataArg, Type, InFunctionCall, CallType,
7438                         CheckedVarArgs, UncoveredArg,
7439                         IgnoreStringsWithoutSpecifiers);
7440       return SLCT_CheckedLiteral;
7441     }
7442 
7443     return SLCT_NotALiteral;
7444   }
7445   case Stmt::BinaryOperatorClass: {
7446     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
7447 
7448     // A string literal + an int offset is still a string literal.
7449     if (BinOp->isAdditiveOp()) {
7450       Expr::EvalResult LResult, RResult;
7451 
7452       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
7453           LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7454       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
7455           RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7456 
7457       if (LIsInt != RIsInt) {
7458         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
7459 
7460         if (LIsInt) {
7461           if (BinOpKind == BO_Add) {
7462             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
7463             E = BinOp->getRHS();
7464             goto tryAgain;
7465           }
7466         } else {
7467           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
7468           E = BinOp->getLHS();
7469           goto tryAgain;
7470         }
7471       }
7472     }
7473 
7474     return SLCT_NotALiteral;
7475   }
7476   case Stmt::UnaryOperatorClass: {
7477     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
7478     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
7479     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
7480       Expr::EvalResult IndexResult;
7481       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
7482                                        Expr::SE_NoSideEffects,
7483                                        S.isConstantEvaluated())) {
7484         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
7485                    /*RHS is int*/ true);
7486         E = ASE->getBase();
7487         goto tryAgain;
7488       }
7489     }
7490 
7491     return SLCT_NotALiteral;
7492   }
7493 
7494   default:
7495     return SLCT_NotALiteral;
7496   }
7497 }
7498 
7499 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
7500   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
7501       .Case("scanf", FST_Scanf)
7502       .Cases("printf", "printf0", FST_Printf)
7503       .Cases("NSString", "CFString", FST_NSString)
7504       .Case("strftime", FST_Strftime)
7505       .Case("strfmon", FST_Strfmon)
7506       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
7507       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
7508       .Case("os_trace", FST_OSLog)
7509       .Case("os_log", FST_OSLog)
7510       .Default(FST_Unknown);
7511 }
7512 
7513 /// CheckFormatArguments - Check calls to printf and scanf (and similar
7514 /// functions) for correct use of format strings.
7515 /// Returns true if a format string has been fully checked.
7516 bool Sema::CheckFormatArguments(const FormatAttr *Format,
7517                                 ArrayRef<const Expr *> Args,
7518                                 bool IsCXXMember,
7519                                 VariadicCallType CallType,
7520                                 SourceLocation Loc, SourceRange Range,
7521                                 llvm::SmallBitVector &CheckedVarArgs) {
7522   FormatStringInfo FSI;
7523   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
7524     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
7525                                 FSI.FirstDataArg, GetFormatStringType(Format),
7526                                 CallType, Loc, Range, CheckedVarArgs);
7527   return false;
7528 }
7529 
7530 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
7531                                 bool HasVAListArg, unsigned format_idx,
7532                                 unsigned firstDataArg, FormatStringType Type,
7533                                 VariadicCallType CallType,
7534                                 SourceLocation Loc, SourceRange Range,
7535                                 llvm::SmallBitVector &CheckedVarArgs) {
7536   // CHECK: printf/scanf-like function is called with no format string.
7537   if (format_idx >= Args.size()) {
7538     Diag(Loc, diag::warn_missing_format_string) << Range;
7539     return false;
7540   }
7541 
7542   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
7543 
7544   // CHECK: format string is not a string literal.
7545   //
7546   // Dynamically generated format strings are difficult to
7547   // automatically vet at compile time.  Requiring that format strings
7548   // are string literals: (1) permits the checking of format strings by
7549   // the compiler and thereby (2) can practically remove the source of
7550   // many format string exploits.
7551 
7552   // Format string can be either ObjC string (e.g. @"%d") or
7553   // C string (e.g. "%d")
7554   // ObjC string uses the same format specifiers as C string, so we can use
7555   // the same format string checking logic for both ObjC and C strings.
7556   UncoveredArgHandler UncoveredArg;
7557   StringLiteralCheckType CT =
7558       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
7559                             format_idx, firstDataArg, Type, CallType,
7560                             /*IsFunctionCall*/ true, CheckedVarArgs,
7561                             UncoveredArg,
7562                             /*no string offset*/ llvm::APSInt(64, false) = 0);
7563 
7564   // Generate a diagnostic where an uncovered argument is detected.
7565   if (UncoveredArg.hasUncoveredArg()) {
7566     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
7567     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
7568     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
7569   }
7570 
7571   if (CT != SLCT_NotALiteral)
7572     // Literal format string found, check done!
7573     return CT == SLCT_CheckedLiteral;
7574 
7575   // Strftime is particular as it always uses a single 'time' argument,
7576   // so it is safe to pass a non-literal string.
7577   if (Type == FST_Strftime)
7578     return false;
7579 
7580   // Do not emit diag when the string param is a macro expansion and the
7581   // format is either NSString or CFString. This is a hack to prevent
7582   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
7583   // which are usually used in place of NS and CF string literals.
7584   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
7585   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
7586     return false;
7587 
7588   // If there are no arguments specified, warn with -Wformat-security, otherwise
7589   // warn only with -Wformat-nonliteral.
7590   if (Args.size() == firstDataArg) {
7591     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
7592       << OrigFormatExpr->getSourceRange();
7593     switch (Type) {
7594     default:
7595       break;
7596     case FST_Kprintf:
7597     case FST_FreeBSDKPrintf:
7598     case FST_Printf:
7599       Diag(FormatLoc, diag::note_format_security_fixit)
7600         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
7601       break;
7602     case FST_NSString:
7603       Diag(FormatLoc, diag::note_format_security_fixit)
7604         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
7605       break;
7606     }
7607   } else {
7608     Diag(FormatLoc, diag::warn_format_nonliteral)
7609       << OrigFormatExpr->getSourceRange();
7610   }
7611   return false;
7612 }
7613 
7614 namespace {
7615 
7616 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
7617 protected:
7618   Sema &S;
7619   const FormatStringLiteral *FExpr;
7620   const Expr *OrigFormatExpr;
7621   const Sema::FormatStringType FSType;
7622   const unsigned FirstDataArg;
7623   const unsigned NumDataArgs;
7624   const char *Beg; // Start of format string.
7625   const bool HasVAListArg;
7626   ArrayRef<const Expr *> Args;
7627   unsigned FormatIdx;
7628   llvm::SmallBitVector CoveredArgs;
7629   bool usesPositionalArgs = false;
7630   bool atFirstArg = true;
7631   bool inFunctionCall;
7632   Sema::VariadicCallType CallType;
7633   llvm::SmallBitVector &CheckedVarArgs;
7634   UncoveredArgHandler &UncoveredArg;
7635 
7636 public:
7637   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
7638                      const Expr *origFormatExpr,
7639                      const Sema::FormatStringType type, unsigned firstDataArg,
7640                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
7641                      ArrayRef<const Expr *> Args, unsigned formatIdx,
7642                      bool inFunctionCall, Sema::VariadicCallType callType,
7643                      llvm::SmallBitVector &CheckedVarArgs,
7644                      UncoveredArgHandler &UncoveredArg)
7645       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
7646         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
7647         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
7648         inFunctionCall(inFunctionCall), CallType(callType),
7649         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
7650     CoveredArgs.resize(numDataArgs);
7651     CoveredArgs.reset();
7652   }
7653 
7654   void DoneProcessing();
7655 
7656   void HandleIncompleteSpecifier(const char *startSpecifier,
7657                                  unsigned specifierLen) override;
7658 
7659   void HandleInvalidLengthModifier(
7660                            const analyze_format_string::FormatSpecifier &FS,
7661                            const analyze_format_string::ConversionSpecifier &CS,
7662                            const char *startSpecifier, unsigned specifierLen,
7663                            unsigned DiagID);
7664 
7665   void HandleNonStandardLengthModifier(
7666                     const analyze_format_string::FormatSpecifier &FS,
7667                     const char *startSpecifier, unsigned specifierLen);
7668 
7669   void HandleNonStandardConversionSpecifier(
7670                     const analyze_format_string::ConversionSpecifier &CS,
7671                     const char *startSpecifier, unsigned specifierLen);
7672 
7673   void HandlePosition(const char *startPos, unsigned posLen) override;
7674 
7675   void HandleInvalidPosition(const char *startSpecifier,
7676                              unsigned specifierLen,
7677                              analyze_format_string::PositionContext p) override;
7678 
7679   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
7680 
7681   void HandleNullChar(const char *nullCharacter) override;
7682 
7683   template <typename Range>
7684   static void
7685   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
7686                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
7687                        bool IsStringLocation, Range StringRange,
7688                        ArrayRef<FixItHint> Fixit = None);
7689 
7690 protected:
7691   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
7692                                         const char *startSpec,
7693                                         unsigned specifierLen,
7694                                         const char *csStart, unsigned csLen);
7695 
7696   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
7697                                          const char *startSpec,
7698                                          unsigned specifierLen);
7699 
7700   SourceRange getFormatStringRange();
7701   CharSourceRange getSpecifierRange(const char *startSpecifier,
7702                                     unsigned specifierLen);
7703   SourceLocation getLocationOfByte(const char *x);
7704 
7705   const Expr *getDataArg(unsigned i) const;
7706 
7707   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
7708                     const analyze_format_string::ConversionSpecifier &CS,
7709                     const char *startSpecifier, unsigned specifierLen,
7710                     unsigned argIndex);
7711 
7712   template <typename Range>
7713   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
7714                             bool IsStringLocation, Range StringRange,
7715                             ArrayRef<FixItHint> Fixit = None);
7716 };
7717 
7718 } // namespace
7719 
7720 SourceRange CheckFormatHandler::getFormatStringRange() {
7721   return OrigFormatExpr->getSourceRange();
7722 }
7723 
7724 CharSourceRange CheckFormatHandler::
7725 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
7726   SourceLocation Start = getLocationOfByte(startSpecifier);
7727   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
7728 
7729   // Advance the end SourceLocation by one due to half-open ranges.
7730   End = End.getLocWithOffset(1);
7731 
7732   return CharSourceRange::getCharRange(Start, End);
7733 }
7734 
7735 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
7736   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
7737                                   S.getLangOpts(), S.Context.getTargetInfo());
7738 }
7739 
7740 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
7741                                                    unsigned specifierLen){
7742   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
7743                        getLocationOfByte(startSpecifier),
7744                        /*IsStringLocation*/true,
7745                        getSpecifierRange(startSpecifier, specifierLen));
7746 }
7747 
7748 void CheckFormatHandler::HandleInvalidLengthModifier(
7749     const analyze_format_string::FormatSpecifier &FS,
7750     const analyze_format_string::ConversionSpecifier &CS,
7751     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
7752   using namespace analyze_format_string;
7753 
7754   const LengthModifier &LM = FS.getLengthModifier();
7755   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7756 
7757   // See if we know how to fix this length modifier.
7758   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7759   if (FixedLM) {
7760     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7761                          getLocationOfByte(LM.getStart()),
7762                          /*IsStringLocation*/true,
7763                          getSpecifierRange(startSpecifier, specifierLen));
7764 
7765     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7766       << FixedLM->toString()
7767       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7768 
7769   } else {
7770     FixItHint Hint;
7771     if (DiagID == diag::warn_format_nonsensical_length)
7772       Hint = FixItHint::CreateRemoval(LMRange);
7773 
7774     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7775                          getLocationOfByte(LM.getStart()),
7776                          /*IsStringLocation*/true,
7777                          getSpecifierRange(startSpecifier, specifierLen),
7778                          Hint);
7779   }
7780 }
7781 
7782 void CheckFormatHandler::HandleNonStandardLengthModifier(
7783     const analyze_format_string::FormatSpecifier &FS,
7784     const char *startSpecifier, unsigned specifierLen) {
7785   using namespace analyze_format_string;
7786 
7787   const LengthModifier &LM = FS.getLengthModifier();
7788   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7789 
7790   // See if we know how to fix this length modifier.
7791   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7792   if (FixedLM) {
7793     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7794                            << LM.toString() << 0,
7795                          getLocationOfByte(LM.getStart()),
7796                          /*IsStringLocation*/true,
7797                          getSpecifierRange(startSpecifier, specifierLen));
7798 
7799     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7800       << FixedLM->toString()
7801       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7802 
7803   } else {
7804     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7805                            << LM.toString() << 0,
7806                          getLocationOfByte(LM.getStart()),
7807                          /*IsStringLocation*/true,
7808                          getSpecifierRange(startSpecifier, specifierLen));
7809   }
7810 }
7811 
7812 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
7813     const analyze_format_string::ConversionSpecifier &CS,
7814     const char *startSpecifier, unsigned specifierLen) {
7815   using namespace analyze_format_string;
7816 
7817   // See if we know how to fix this conversion specifier.
7818   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
7819   if (FixedCS) {
7820     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7821                           << CS.toString() << /*conversion specifier*/1,
7822                          getLocationOfByte(CS.getStart()),
7823                          /*IsStringLocation*/true,
7824                          getSpecifierRange(startSpecifier, specifierLen));
7825 
7826     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
7827     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
7828       << FixedCS->toString()
7829       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
7830   } else {
7831     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7832                           << CS.toString() << /*conversion specifier*/1,
7833                          getLocationOfByte(CS.getStart()),
7834                          /*IsStringLocation*/true,
7835                          getSpecifierRange(startSpecifier, specifierLen));
7836   }
7837 }
7838 
7839 void CheckFormatHandler::HandlePosition(const char *startPos,
7840                                         unsigned posLen) {
7841   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
7842                                getLocationOfByte(startPos),
7843                                /*IsStringLocation*/true,
7844                                getSpecifierRange(startPos, posLen));
7845 }
7846 
7847 void
7848 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
7849                                      analyze_format_string::PositionContext p) {
7850   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
7851                          << (unsigned) p,
7852                        getLocationOfByte(startPos), /*IsStringLocation*/true,
7853                        getSpecifierRange(startPos, posLen));
7854 }
7855 
7856 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
7857                                             unsigned posLen) {
7858   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
7859                                getLocationOfByte(startPos),
7860                                /*IsStringLocation*/true,
7861                                getSpecifierRange(startPos, posLen));
7862 }
7863 
7864 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
7865   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
7866     // The presence of a null character is likely an error.
7867     EmitFormatDiagnostic(
7868       S.PDiag(diag::warn_printf_format_string_contains_null_char),
7869       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
7870       getFormatStringRange());
7871   }
7872 }
7873 
7874 // Note that this may return NULL if there was an error parsing or building
7875 // one of the argument expressions.
7876 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
7877   return Args[FirstDataArg + i];
7878 }
7879 
7880 void CheckFormatHandler::DoneProcessing() {
7881   // Does the number of data arguments exceed the number of
7882   // format conversions in the format string?
7883   if (!HasVAListArg) {
7884       // Find any arguments that weren't covered.
7885     CoveredArgs.flip();
7886     signed notCoveredArg = CoveredArgs.find_first();
7887     if (notCoveredArg >= 0) {
7888       assert((unsigned)notCoveredArg < NumDataArgs);
7889       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
7890     } else {
7891       UncoveredArg.setAllCovered();
7892     }
7893   }
7894 }
7895 
7896 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
7897                                    const Expr *ArgExpr) {
7898   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
7899          "Invalid state");
7900 
7901   if (!ArgExpr)
7902     return;
7903 
7904   SourceLocation Loc = ArgExpr->getBeginLoc();
7905 
7906   if (S.getSourceManager().isInSystemMacro(Loc))
7907     return;
7908 
7909   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
7910   for (auto E : DiagnosticExprs)
7911     PDiag << E->getSourceRange();
7912 
7913   CheckFormatHandler::EmitFormatDiagnostic(
7914                                   S, IsFunctionCall, DiagnosticExprs[0],
7915                                   PDiag, Loc, /*IsStringLocation*/false,
7916                                   DiagnosticExprs[0]->getSourceRange());
7917 }
7918 
7919 bool
7920 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
7921                                                      SourceLocation Loc,
7922                                                      const char *startSpec,
7923                                                      unsigned specifierLen,
7924                                                      const char *csStart,
7925                                                      unsigned csLen) {
7926   bool keepGoing = true;
7927   if (argIndex < NumDataArgs) {
7928     // Consider the argument coverered, even though the specifier doesn't
7929     // make sense.
7930     CoveredArgs.set(argIndex);
7931   }
7932   else {
7933     // If argIndex exceeds the number of data arguments we
7934     // don't issue a warning because that is just a cascade of warnings (and
7935     // they may have intended '%%' anyway). We don't want to continue processing
7936     // the format string after this point, however, as we will like just get
7937     // gibberish when trying to match arguments.
7938     keepGoing = false;
7939   }
7940 
7941   StringRef Specifier(csStart, csLen);
7942 
7943   // If the specifier in non-printable, it could be the first byte of a UTF-8
7944   // sequence. In that case, print the UTF-8 code point. If not, print the byte
7945   // hex value.
7946   std::string CodePointStr;
7947   if (!llvm::sys::locale::isPrint(*csStart)) {
7948     llvm::UTF32 CodePoint;
7949     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
7950     const llvm::UTF8 *E =
7951         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
7952     llvm::ConversionResult Result =
7953         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
7954 
7955     if (Result != llvm::conversionOK) {
7956       unsigned char FirstChar = *csStart;
7957       CodePoint = (llvm::UTF32)FirstChar;
7958     }
7959 
7960     llvm::raw_string_ostream OS(CodePointStr);
7961     if (CodePoint < 256)
7962       OS << "\\x" << llvm::format("%02x", CodePoint);
7963     else if (CodePoint <= 0xFFFF)
7964       OS << "\\u" << llvm::format("%04x", CodePoint);
7965     else
7966       OS << "\\U" << llvm::format("%08x", CodePoint);
7967     OS.flush();
7968     Specifier = CodePointStr;
7969   }
7970 
7971   EmitFormatDiagnostic(
7972       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
7973       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
7974 
7975   return keepGoing;
7976 }
7977 
7978 void
7979 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
7980                                                       const char *startSpec,
7981                                                       unsigned specifierLen) {
7982   EmitFormatDiagnostic(
7983     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
7984     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
7985 }
7986 
7987 bool
7988 CheckFormatHandler::CheckNumArgs(
7989   const analyze_format_string::FormatSpecifier &FS,
7990   const analyze_format_string::ConversionSpecifier &CS,
7991   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
7992 
7993   if (argIndex >= NumDataArgs) {
7994     PartialDiagnostic PDiag = FS.usesPositionalArg()
7995       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
7996            << (argIndex+1) << NumDataArgs)
7997       : S.PDiag(diag::warn_printf_insufficient_data_args);
7998     EmitFormatDiagnostic(
7999       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
8000       getSpecifierRange(startSpecifier, specifierLen));
8001 
8002     // Since more arguments than conversion tokens are given, by extension
8003     // all arguments are covered, so mark this as so.
8004     UncoveredArg.setAllCovered();
8005     return false;
8006   }
8007   return true;
8008 }
8009 
8010 template<typename Range>
8011 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
8012                                               SourceLocation Loc,
8013                                               bool IsStringLocation,
8014                                               Range StringRange,
8015                                               ArrayRef<FixItHint> FixIt) {
8016   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
8017                        Loc, IsStringLocation, StringRange, FixIt);
8018 }
8019 
8020 /// If the format string is not within the function call, emit a note
8021 /// so that the function call and string are in diagnostic messages.
8022 ///
8023 /// \param InFunctionCall if true, the format string is within the function
8024 /// call and only one diagnostic message will be produced.  Otherwise, an
8025 /// extra note will be emitted pointing to location of the format string.
8026 ///
8027 /// \param ArgumentExpr the expression that is passed as the format string
8028 /// argument in the function call.  Used for getting locations when two
8029 /// diagnostics are emitted.
8030 ///
8031 /// \param PDiag the callee should already have provided any strings for the
8032 /// diagnostic message.  This function only adds locations and fixits
8033 /// to diagnostics.
8034 ///
8035 /// \param Loc primary location for diagnostic.  If two diagnostics are
8036 /// required, one will be at Loc and a new SourceLocation will be created for
8037 /// the other one.
8038 ///
8039 /// \param IsStringLocation if true, Loc points to the format string should be
8040 /// used for the note.  Otherwise, Loc points to the argument list and will
8041 /// be used with PDiag.
8042 ///
8043 /// \param StringRange some or all of the string to highlight.  This is
8044 /// templated so it can accept either a CharSourceRange or a SourceRange.
8045 ///
8046 /// \param FixIt optional fix it hint for the format string.
8047 template <typename Range>
8048 void CheckFormatHandler::EmitFormatDiagnostic(
8049     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
8050     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
8051     Range StringRange, ArrayRef<FixItHint> FixIt) {
8052   if (InFunctionCall) {
8053     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
8054     D << StringRange;
8055     D << FixIt;
8056   } else {
8057     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
8058       << ArgumentExpr->getSourceRange();
8059 
8060     const Sema::SemaDiagnosticBuilder &Note =
8061       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
8062              diag::note_format_string_defined);
8063 
8064     Note << StringRange;
8065     Note << FixIt;
8066   }
8067 }
8068 
8069 //===--- CHECK: Printf format string checking ------------------------------===//
8070 
8071 namespace {
8072 
8073 class CheckPrintfHandler : public CheckFormatHandler {
8074 public:
8075   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8076                      const Expr *origFormatExpr,
8077                      const Sema::FormatStringType type, unsigned firstDataArg,
8078                      unsigned numDataArgs, bool isObjC, const char *beg,
8079                      bool hasVAListArg, ArrayRef<const Expr *> Args,
8080                      unsigned formatIdx, bool inFunctionCall,
8081                      Sema::VariadicCallType CallType,
8082                      llvm::SmallBitVector &CheckedVarArgs,
8083                      UncoveredArgHandler &UncoveredArg)
8084       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8085                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
8086                            inFunctionCall, CallType, CheckedVarArgs,
8087                            UncoveredArg) {}
8088 
8089   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
8090 
8091   /// Returns true if '%@' specifiers are allowed in the format string.
8092   bool allowsObjCArg() const {
8093     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
8094            FSType == Sema::FST_OSTrace;
8095   }
8096 
8097   bool HandleInvalidPrintfConversionSpecifier(
8098                                       const analyze_printf::PrintfSpecifier &FS,
8099                                       const char *startSpecifier,
8100                                       unsigned specifierLen) override;
8101 
8102   void handleInvalidMaskType(StringRef MaskType) override;
8103 
8104   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8105                              const char *startSpecifier,
8106                              unsigned specifierLen) override;
8107   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8108                        const char *StartSpecifier,
8109                        unsigned SpecifierLen,
8110                        const Expr *E);
8111 
8112   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
8113                     const char *startSpecifier, unsigned specifierLen);
8114   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
8115                            const analyze_printf::OptionalAmount &Amt,
8116                            unsigned type,
8117                            const char *startSpecifier, unsigned specifierLen);
8118   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8119                   const analyze_printf::OptionalFlag &flag,
8120                   const char *startSpecifier, unsigned specifierLen);
8121   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
8122                          const analyze_printf::OptionalFlag &ignoredFlag,
8123                          const analyze_printf::OptionalFlag &flag,
8124                          const char *startSpecifier, unsigned specifierLen);
8125   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
8126                            const Expr *E);
8127 
8128   void HandleEmptyObjCModifierFlag(const char *startFlag,
8129                                    unsigned flagLen) override;
8130 
8131   void HandleInvalidObjCModifierFlag(const char *startFlag,
8132                                             unsigned flagLen) override;
8133 
8134   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
8135                                            const char *flagsEnd,
8136                                            const char *conversionPosition)
8137                                              override;
8138 };
8139 
8140 } // namespace
8141 
8142 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
8143                                       const analyze_printf::PrintfSpecifier &FS,
8144                                       const char *startSpecifier,
8145                                       unsigned specifierLen) {
8146   const analyze_printf::PrintfConversionSpecifier &CS =
8147     FS.getConversionSpecifier();
8148 
8149   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8150                                           getLocationOfByte(CS.getStart()),
8151                                           startSpecifier, specifierLen,
8152                                           CS.getStart(), CS.getLength());
8153 }
8154 
8155 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
8156   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
8157 }
8158 
8159 bool CheckPrintfHandler::HandleAmount(
8160                                const analyze_format_string::OptionalAmount &Amt,
8161                                unsigned k, const char *startSpecifier,
8162                                unsigned specifierLen) {
8163   if (Amt.hasDataArgument()) {
8164     if (!HasVAListArg) {
8165       unsigned argIndex = Amt.getArgIndex();
8166       if (argIndex >= NumDataArgs) {
8167         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
8168                                << k,
8169                              getLocationOfByte(Amt.getStart()),
8170                              /*IsStringLocation*/true,
8171                              getSpecifierRange(startSpecifier, specifierLen));
8172         // Don't do any more checking.  We will just emit
8173         // spurious errors.
8174         return false;
8175       }
8176 
8177       // Type check the data argument.  It should be an 'int'.
8178       // Although not in conformance with C99, we also allow the argument to be
8179       // an 'unsigned int' as that is a reasonably safe case.  GCC also
8180       // doesn't emit a warning for that case.
8181       CoveredArgs.set(argIndex);
8182       const Expr *Arg = getDataArg(argIndex);
8183       if (!Arg)
8184         return false;
8185 
8186       QualType T = Arg->getType();
8187 
8188       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
8189       assert(AT.isValid());
8190 
8191       if (!AT.matchesType(S.Context, T)) {
8192         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
8193                                << k << AT.getRepresentativeTypeName(S.Context)
8194                                << T << Arg->getSourceRange(),
8195                              getLocationOfByte(Amt.getStart()),
8196                              /*IsStringLocation*/true,
8197                              getSpecifierRange(startSpecifier, specifierLen));
8198         // Don't do any more checking.  We will just emit
8199         // spurious errors.
8200         return false;
8201       }
8202     }
8203   }
8204   return true;
8205 }
8206 
8207 void CheckPrintfHandler::HandleInvalidAmount(
8208                                       const analyze_printf::PrintfSpecifier &FS,
8209                                       const analyze_printf::OptionalAmount &Amt,
8210                                       unsigned type,
8211                                       const char *startSpecifier,
8212                                       unsigned specifierLen) {
8213   const analyze_printf::PrintfConversionSpecifier &CS =
8214     FS.getConversionSpecifier();
8215 
8216   FixItHint fixit =
8217     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
8218       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
8219                                  Amt.getConstantLength()))
8220       : FixItHint();
8221 
8222   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
8223                          << type << CS.toString(),
8224                        getLocationOfByte(Amt.getStart()),
8225                        /*IsStringLocation*/true,
8226                        getSpecifierRange(startSpecifier, specifierLen),
8227                        fixit);
8228 }
8229 
8230 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8231                                     const analyze_printf::OptionalFlag &flag,
8232                                     const char *startSpecifier,
8233                                     unsigned specifierLen) {
8234   // Warn about pointless flag with a fixit removal.
8235   const analyze_printf::PrintfConversionSpecifier &CS =
8236     FS.getConversionSpecifier();
8237   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
8238                          << flag.toString() << CS.toString(),
8239                        getLocationOfByte(flag.getPosition()),
8240                        /*IsStringLocation*/true,
8241                        getSpecifierRange(startSpecifier, specifierLen),
8242                        FixItHint::CreateRemoval(
8243                          getSpecifierRange(flag.getPosition(), 1)));
8244 }
8245 
8246 void CheckPrintfHandler::HandleIgnoredFlag(
8247                                 const analyze_printf::PrintfSpecifier &FS,
8248                                 const analyze_printf::OptionalFlag &ignoredFlag,
8249                                 const analyze_printf::OptionalFlag &flag,
8250                                 const char *startSpecifier,
8251                                 unsigned specifierLen) {
8252   // Warn about ignored flag with a fixit removal.
8253   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
8254                          << ignoredFlag.toString() << flag.toString(),
8255                        getLocationOfByte(ignoredFlag.getPosition()),
8256                        /*IsStringLocation*/true,
8257                        getSpecifierRange(startSpecifier, specifierLen),
8258                        FixItHint::CreateRemoval(
8259                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
8260 }
8261 
8262 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
8263                                                      unsigned flagLen) {
8264   // Warn about an empty flag.
8265   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
8266                        getLocationOfByte(startFlag),
8267                        /*IsStringLocation*/true,
8268                        getSpecifierRange(startFlag, flagLen));
8269 }
8270 
8271 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
8272                                                        unsigned flagLen) {
8273   // Warn about an invalid flag.
8274   auto Range = getSpecifierRange(startFlag, flagLen);
8275   StringRef flag(startFlag, flagLen);
8276   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
8277                       getLocationOfByte(startFlag),
8278                       /*IsStringLocation*/true,
8279                       Range, FixItHint::CreateRemoval(Range));
8280 }
8281 
8282 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
8283     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
8284     // Warn about using '[...]' without a '@' conversion.
8285     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
8286     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
8287     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
8288                          getLocationOfByte(conversionPosition),
8289                          /*IsStringLocation*/true,
8290                          Range, FixItHint::CreateRemoval(Range));
8291 }
8292 
8293 // Determines if the specified is a C++ class or struct containing
8294 // a member with the specified name and kind (e.g. a CXXMethodDecl named
8295 // "c_str()").
8296 template<typename MemberKind>
8297 static llvm::SmallPtrSet<MemberKind*, 1>
8298 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
8299   const RecordType *RT = Ty->getAs<RecordType>();
8300   llvm::SmallPtrSet<MemberKind*, 1> Results;
8301 
8302   if (!RT)
8303     return Results;
8304   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
8305   if (!RD || !RD->getDefinition())
8306     return Results;
8307 
8308   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
8309                  Sema::LookupMemberName);
8310   R.suppressDiagnostics();
8311 
8312   // We just need to include all members of the right kind turned up by the
8313   // filter, at this point.
8314   if (S.LookupQualifiedName(R, RT->getDecl()))
8315     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8316       NamedDecl *decl = (*I)->getUnderlyingDecl();
8317       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
8318         Results.insert(FK);
8319     }
8320   return Results;
8321 }
8322 
8323 /// Check if we could call '.c_str()' on an object.
8324 ///
8325 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
8326 /// allow the call, or if it would be ambiguous).
8327 bool Sema::hasCStrMethod(const Expr *E) {
8328   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8329 
8330   MethodSet Results =
8331       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
8332   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8333        MI != ME; ++MI)
8334     if ((*MI)->getMinRequiredArguments() == 0)
8335       return true;
8336   return false;
8337 }
8338 
8339 // Check if a (w)string was passed when a (w)char* was needed, and offer a
8340 // better diagnostic if so. AT is assumed to be valid.
8341 // Returns true when a c_str() conversion method is found.
8342 bool CheckPrintfHandler::checkForCStrMembers(
8343     const analyze_printf::ArgType &AT, const Expr *E) {
8344   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8345 
8346   MethodSet Results =
8347       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
8348 
8349   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8350        MI != ME; ++MI) {
8351     const CXXMethodDecl *Method = *MI;
8352     if (Method->getMinRequiredArguments() == 0 &&
8353         AT.matchesType(S.Context, Method->getReturnType())) {
8354       // FIXME: Suggest parens if the expression needs them.
8355       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
8356       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
8357           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
8358       return true;
8359     }
8360   }
8361 
8362   return false;
8363 }
8364 
8365 bool
8366 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
8367                                             &FS,
8368                                           const char *startSpecifier,
8369                                           unsigned specifierLen) {
8370   using namespace analyze_format_string;
8371   using namespace analyze_printf;
8372 
8373   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
8374 
8375   if (FS.consumesDataArgument()) {
8376     if (atFirstArg) {
8377         atFirstArg = false;
8378         usesPositionalArgs = FS.usesPositionalArg();
8379     }
8380     else if (usesPositionalArgs != FS.usesPositionalArg()) {
8381       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8382                                         startSpecifier, specifierLen);
8383       return false;
8384     }
8385   }
8386 
8387   // First check if the field width, precision, and conversion specifier
8388   // have matching data arguments.
8389   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
8390                     startSpecifier, specifierLen)) {
8391     return false;
8392   }
8393 
8394   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
8395                     startSpecifier, specifierLen)) {
8396     return false;
8397   }
8398 
8399   if (!CS.consumesDataArgument()) {
8400     // FIXME: Technically specifying a precision or field width here
8401     // makes no sense.  Worth issuing a warning at some point.
8402     return true;
8403   }
8404 
8405   // Consume the argument.
8406   unsigned argIndex = FS.getArgIndex();
8407   if (argIndex < NumDataArgs) {
8408     // The check to see if the argIndex is valid will come later.
8409     // We set the bit here because we may exit early from this
8410     // function if we encounter some other error.
8411     CoveredArgs.set(argIndex);
8412   }
8413 
8414   // FreeBSD kernel extensions.
8415   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
8416       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
8417     // We need at least two arguments.
8418     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
8419       return false;
8420 
8421     // Claim the second argument.
8422     CoveredArgs.set(argIndex + 1);
8423 
8424     // Type check the first argument (int for %b, pointer for %D)
8425     const Expr *Ex = getDataArg(argIndex);
8426     const analyze_printf::ArgType &AT =
8427       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
8428         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
8429     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
8430       EmitFormatDiagnostic(
8431           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8432               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
8433               << false << Ex->getSourceRange(),
8434           Ex->getBeginLoc(), /*IsStringLocation*/ false,
8435           getSpecifierRange(startSpecifier, specifierLen));
8436 
8437     // Type check the second argument (char * for both %b and %D)
8438     Ex = getDataArg(argIndex + 1);
8439     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
8440     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
8441       EmitFormatDiagnostic(
8442           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8443               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
8444               << false << Ex->getSourceRange(),
8445           Ex->getBeginLoc(), /*IsStringLocation*/ false,
8446           getSpecifierRange(startSpecifier, specifierLen));
8447 
8448      return true;
8449   }
8450 
8451   // Check for using an Objective-C specific conversion specifier
8452   // in a non-ObjC literal.
8453   if (!allowsObjCArg() && CS.isObjCArg()) {
8454     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8455                                                   specifierLen);
8456   }
8457 
8458   // %P can only be used with os_log.
8459   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
8460     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8461                                                   specifierLen);
8462   }
8463 
8464   // %n is not allowed with os_log.
8465   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
8466     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
8467                          getLocationOfByte(CS.getStart()),
8468                          /*IsStringLocation*/ false,
8469                          getSpecifierRange(startSpecifier, specifierLen));
8470 
8471     return true;
8472   }
8473 
8474   // Only scalars are allowed for os_trace.
8475   if (FSType == Sema::FST_OSTrace &&
8476       (CS.getKind() == ConversionSpecifier::PArg ||
8477        CS.getKind() == ConversionSpecifier::sArg ||
8478        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
8479     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8480                                                   specifierLen);
8481   }
8482 
8483   // Check for use of public/private annotation outside of os_log().
8484   if (FSType != Sema::FST_OSLog) {
8485     if (FS.isPublic().isSet()) {
8486       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8487                                << "public",
8488                            getLocationOfByte(FS.isPublic().getPosition()),
8489                            /*IsStringLocation*/ false,
8490                            getSpecifierRange(startSpecifier, specifierLen));
8491     }
8492     if (FS.isPrivate().isSet()) {
8493       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8494                                << "private",
8495                            getLocationOfByte(FS.isPrivate().getPosition()),
8496                            /*IsStringLocation*/ false,
8497                            getSpecifierRange(startSpecifier, specifierLen));
8498     }
8499   }
8500 
8501   // Check for invalid use of field width
8502   if (!FS.hasValidFieldWidth()) {
8503     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
8504         startSpecifier, specifierLen);
8505   }
8506 
8507   // Check for invalid use of precision
8508   if (!FS.hasValidPrecision()) {
8509     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
8510         startSpecifier, specifierLen);
8511   }
8512 
8513   // Precision is mandatory for %P specifier.
8514   if (CS.getKind() == ConversionSpecifier::PArg &&
8515       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
8516     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
8517                          getLocationOfByte(startSpecifier),
8518                          /*IsStringLocation*/ false,
8519                          getSpecifierRange(startSpecifier, specifierLen));
8520   }
8521 
8522   // Check each flag does not conflict with any other component.
8523   if (!FS.hasValidThousandsGroupingPrefix())
8524     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
8525   if (!FS.hasValidLeadingZeros())
8526     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
8527   if (!FS.hasValidPlusPrefix())
8528     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
8529   if (!FS.hasValidSpacePrefix())
8530     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
8531   if (!FS.hasValidAlternativeForm())
8532     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
8533   if (!FS.hasValidLeftJustified())
8534     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
8535 
8536   // Check that flags are not ignored by another flag
8537   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
8538     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
8539         startSpecifier, specifierLen);
8540   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
8541     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
8542             startSpecifier, specifierLen);
8543 
8544   // Check the length modifier is valid with the given conversion specifier.
8545   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8546                                  S.getLangOpts()))
8547     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8548                                 diag::warn_format_nonsensical_length);
8549   else if (!FS.hasStandardLengthModifier())
8550     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8551   else if (!FS.hasStandardLengthConversionCombination())
8552     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8553                                 diag::warn_format_non_standard_conversion_spec);
8554 
8555   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8556     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8557 
8558   // The remaining checks depend on the data arguments.
8559   if (HasVAListArg)
8560     return true;
8561 
8562   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8563     return false;
8564 
8565   const Expr *Arg = getDataArg(argIndex);
8566   if (!Arg)
8567     return true;
8568 
8569   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
8570 }
8571 
8572 static bool requiresParensToAddCast(const Expr *E) {
8573   // FIXME: We should have a general way to reason about operator
8574   // precedence and whether parens are actually needed here.
8575   // Take care of a few common cases where they aren't.
8576   const Expr *Inside = E->IgnoreImpCasts();
8577   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
8578     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
8579 
8580   switch (Inside->getStmtClass()) {
8581   case Stmt::ArraySubscriptExprClass:
8582   case Stmt::CallExprClass:
8583   case Stmt::CharacterLiteralClass:
8584   case Stmt::CXXBoolLiteralExprClass:
8585   case Stmt::DeclRefExprClass:
8586   case Stmt::FloatingLiteralClass:
8587   case Stmt::IntegerLiteralClass:
8588   case Stmt::MemberExprClass:
8589   case Stmt::ObjCArrayLiteralClass:
8590   case Stmt::ObjCBoolLiteralExprClass:
8591   case Stmt::ObjCBoxedExprClass:
8592   case Stmt::ObjCDictionaryLiteralClass:
8593   case Stmt::ObjCEncodeExprClass:
8594   case Stmt::ObjCIvarRefExprClass:
8595   case Stmt::ObjCMessageExprClass:
8596   case Stmt::ObjCPropertyRefExprClass:
8597   case Stmt::ObjCStringLiteralClass:
8598   case Stmt::ObjCSubscriptRefExprClass:
8599   case Stmt::ParenExprClass:
8600   case Stmt::StringLiteralClass:
8601   case Stmt::UnaryOperatorClass:
8602     return false;
8603   default:
8604     return true;
8605   }
8606 }
8607 
8608 static std::pair<QualType, StringRef>
8609 shouldNotPrintDirectly(const ASTContext &Context,
8610                        QualType IntendedTy,
8611                        const Expr *E) {
8612   // Use a 'while' to peel off layers of typedefs.
8613   QualType TyTy = IntendedTy;
8614   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
8615     StringRef Name = UserTy->getDecl()->getName();
8616     QualType CastTy = llvm::StringSwitch<QualType>(Name)
8617       .Case("CFIndex", Context.getNSIntegerType())
8618       .Case("NSInteger", Context.getNSIntegerType())
8619       .Case("NSUInteger", Context.getNSUIntegerType())
8620       .Case("SInt32", Context.IntTy)
8621       .Case("UInt32", Context.UnsignedIntTy)
8622       .Default(QualType());
8623 
8624     if (!CastTy.isNull())
8625       return std::make_pair(CastTy, Name);
8626 
8627     TyTy = UserTy->desugar();
8628   }
8629 
8630   // Strip parens if necessary.
8631   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
8632     return shouldNotPrintDirectly(Context,
8633                                   PE->getSubExpr()->getType(),
8634                                   PE->getSubExpr());
8635 
8636   // If this is a conditional expression, then its result type is constructed
8637   // via usual arithmetic conversions and thus there might be no necessary
8638   // typedef sugar there.  Recurse to operands to check for NSInteger &
8639   // Co. usage condition.
8640   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8641     QualType TrueTy, FalseTy;
8642     StringRef TrueName, FalseName;
8643 
8644     std::tie(TrueTy, TrueName) =
8645       shouldNotPrintDirectly(Context,
8646                              CO->getTrueExpr()->getType(),
8647                              CO->getTrueExpr());
8648     std::tie(FalseTy, FalseName) =
8649       shouldNotPrintDirectly(Context,
8650                              CO->getFalseExpr()->getType(),
8651                              CO->getFalseExpr());
8652 
8653     if (TrueTy == FalseTy)
8654       return std::make_pair(TrueTy, TrueName);
8655     else if (TrueTy.isNull())
8656       return std::make_pair(FalseTy, FalseName);
8657     else if (FalseTy.isNull())
8658       return std::make_pair(TrueTy, TrueName);
8659   }
8660 
8661   return std::make_pair(QualType(), StringRef());
8662 }
8663 
8664 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
8665 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
8666 /// type do not count.
8667 static bool
8668 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
8669   QualType From = ICE->getSubExpr()->getType();
8670   QualType To = ICE->getType();
8671   // It's an integer promotion if the destination type is the promoted
8672   // source type.
8673   if (ICE->getCastKind() == CK_IntegralCast &&
8674       From->isPromotableIntegerType() &&
8675       S.Context.getPromotedIntegerType(From) == To)
8676     return true;
8677   // Look through vector types, since we do default argument promotion for
8678   // those in OpenCL.
8679   if (const auto *VecTy = From->getAs<ExtVectorType>())
8680     From = VecTy->getElementType();
8681   if (const auto *VecTy = To->getAs<ExtVectorType>())
8682     To = VecTy->getElementType();
8683   // It's a floating promotion if the source type is a lower rank.
8684   return ICE->getCastKind() == CK_FloatingCast &&
8685          S.Context.getFloatingTypeOrder(From, To) < 0;
8686 }
8687 
8688 bool
8689 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8690                                     const char *StartSpecifier,
8691                                     unsigned SpecifierLen,
8692                                     const Expr *E) {
8693   using namespace analyze_format_string;
8694   using namespace analyze_printf;
8695 
8696   // Now type check the data expression that matches the
8697   // format specifier.
8698   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
8699   if (!AT.isValid())
8700     return true;
8701 
8702   QualType ExprTy = E->getType();
8703   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
8704     ExprTy = TET->getUnderlyingExpr()->getType();
8705   }
8706 
8707   // Diagnose attempts to print a boolean value as a character. Unlike other
8708   // -Wformat diagnostics, this is fine from a type perspective, but it still
8709   // doesn't make sense.
8710   if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
8711       E->isKnownToHaveBooleanValue()) {
8712     const CharSourceRange &CSR =
8713         getSpecifierRange(StartSpecifier, SpecifierLen);
8714     SmallString<4> FSString;
8715     llvm::raw_svector_ostream os(FSString);
8716     FS.toString(os);
8717     EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
8718                              << FSString,
8719                          E->getExprLoc(), false, CSR);
8720     return true;
8721   }
8722 
8723   analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
8724   if (Match == analyze_printf::ArgType::Match)
8725     return true;
8726 
8727   // Look through argument promotions for our error message's reported type.
8728   // This includes the integral and floating promotions, but excludes array
8729   // and function pointer decay (seeing that an argument intended to be a
8730   // string has type 'char [6]' is probably more confusing than 'char *') and
8731   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
8732   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8733     if (isArithmeticArgumentPromotion(S, ICE)) {
8734       E = ICE->getSubExpr();
8735       ExprTy = E->getType();
8736 
8737       // Check if we didn't match because of an implicit cast from a 'char'
8738       // or 'short' to an 'int'.  This is done because printf is a varargs
8739       // function.
8740       if (ICE->getType() == S.Context.IntTy ||
8741           ICE->getType() == S.Context.UnsignedIntTy) {
8742         // All further checking is done on the subexpression
8743         const analyze_printf::ArgType::MatchKind ImplicitMatch =
8744             AT.matchesType(S.Context, ExprTy);
8745         if (ImplicitMatch == analyze_printf::ArgType::Match)
8746           return true;
8747         if (ImplicitMatch == ArgType::NoMatchPedantic ||
8748             ImplicitMatch == ArgType::NoMatchTypeConfusion)
8749           Match = ImplicitMatch;
8750       }
8751     }
8752   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
8753     // Special case for 'a', which has type 'int' in C.
8754     // Note, however, that we do /not/ want to treat multibyte constants like
8755     // 'MooV' as characters! This form is deprecated but still exists. In
8756     // addition, don't treat expressions as of type 'char' if one byte length
8757     // modifier is provided.
8758     if (ExprTy == S.Context.IntTy &&
8759         FS.getLengthModifier().getKind() != LengthModifier::AsChar)
8760       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
8761         ExprTy = S.Context.CharTy;
8762   }
8763 
8764   // Look through enums to their underlying type.
8765   bool IsEnum = false;
8766   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
8767     ExprTy = EnumTy->getDecl()->getIntegerType();
8768     IsEnum = true;
8769   }
8770 
8771   // %C in an Objective-C context prints a unichar, not a wchar_t.
8772   // If the argument is an integer of some kind, believe the %C and suggest
8773   // a cast instead of changing the conversion specifier.
8774   QualType IntendedTy = ExprTy;
8775   if (isObjCContext() &&
8776       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
8777     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
8778         !ExprTy->isCharType()) {
8779       // 'unichar' is defined as a typedef of unsigned short, but we should
8780       // prefer using the typedef if it is visible.
8781       IntendedTy = S.Context.UnsignedShortTy;
8782 
8783       // While we are here, check if the value is an IntegerLiteral that happens
8784       // to be within the valid range.
8785       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
8786         const llvm::APInt &V = IL->getValue();
8787         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
8788           return true;
8789       }
8790 
8791       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
8792                           Sema::LookupOrdinaryName);
8793       if (S.LookupName(Result, S.getCurScope())) {
8794         NamedDecl *ND = Result.getFoundDecl();
8795         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
8796           if (TD->getUnderlyingType() == IntendedTy)
8797             IntendedTy = S.Context.getTypedefType(TD);
8798       }
8799     }
8800   }
8801 
8802   // Special-case some of Darwin's platform-independence types by suggesting
8803   // casts to primitive types that are known to be large enough.
8804   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
8805   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
8806     QualType CastTy;
8807     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
8808     if (!CastTy.isNull()) {
8809       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
8810       // (long in ASTContext). Only complain to pedants.
8811       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
8812           (AT.isSizeT() || AT.isPtrdiffT()) &&
8813           AT.matchesType(S.Context, CastTy))
8814         Match = ArgType::NoMatchPedantic;
8815       IntendedTy = CastTy;
8816       ShouldNotPrintDirectly = true;
8817     }
8818   }
8819 
8820   // We may be able to offer a FixItHint if it is a supported type.
8821   PrintfSpecifier fixedFS = FS;
8822   bool Success =
8823       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
8824 
8825   if (Success) {
8826     // Get the fix string from the fixed format specifier
8827     SmallString<16> buf;
8828     llvm::raw_svector_ostream os(buf);
8829     fixedFS.toString(os);
8830 
8831     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
8832 
8833     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
8834       unsigned Diag;
8835       switch (Match) {
8836       case ArgType::Match: llvm_unreachable("expected non-matching");
8837       case ArgType::NoMatchPedantic:
8838         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8839         break;
8840       case ArgType::NoMatchTypeConfusion:
8841         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8842         break;
8843       case ArgType::NoMatch:
8844         Diag = diag::warn_format_conversion_argument_type_mismatch;
8845         break;
8846       }
8847 
8848       // In this case, the specifier is wrong and should be changed to match
8849       // the argument.
8850       EmitFormatDiagnostic(S.PDiag(Diag)
8851                                << AT.getRepresentativeTypeName(S.Context)
8852                                << IntendedTy << IsEnum << E->getSourceRange(),
8853                            E->getBeginLoc(),
8854                            /*IsStringLocation*/ false, SpecRange,
8855                            FixItHint::CreateReplacement(SpecRange, os.str()));
8856     } else {
8857       // The canonical type for formatting this value is different from the
8858       // actual type of the expression. (This occurs, for example, with Darwin's
8859       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
8860       // should be printed as 'long' for 64-bit compatibility.)
8861       // Rather than emitting a normal format/argument mismatch, we want to
8862       // add a cast to the recommended type (and correct the format string
8863       // if necessary).
8864       SmallString<16> CastBuf;
8865       llvm::raw_svector_ostream CastFix(CastBuf);
8866       CastFix << "(";
8867       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
8868       CastFix << ")";
8869 
8870       SmallVector<FixItHint,4> Hints;
8871       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
8872         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
8873 
8874       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
8875         // If there's already a cast present, just replace it.
8876         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
8877         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
8878 
8879       } else if (!requiresParensToAddCast(E)) {
8880         // If the expression has high enough precedence,
8881         // just write the C-style cast.
8882         Hints.push_back(
8883             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8884       } else {
8885         // Otherwise, add parens around the expression as well as the cast.
8886         CastFix << "(";
8887         Hints.push_back(
8888             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8889 
8890         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
8891         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
8892       }
8893 
8894       if (ShouldNotPrintDirectly) {
8895         // The expression has a type that should not be printed directly.
8896         // We extract the name from the typedef because we don't want to show
8897         // the underlying type in the diagnostic.
8898         StringRef Name;
8899         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
8900           Name = TypedefTy->getDecl()->getName();
8901         else
8902           Name = CastTyName;
8903         unsigned Diag = Match == ArgType::NoMatchPedantic
8904                             ? diag::warn_format_argument_needs_cast_pedantic
8905                             : diag::warn_format_argument_needs_cast;
8906         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
8907                                            << E->getSourceRange(),
8908                              E->getBeginLoc(), /*IsStringLocation=*/false,
8909                              SpecRange, Hints);
8910       } else {
8911         // In this case, the expression could be printed using a different
8912         // specifier, but we've decided that the specifier is probably correct
8913         // and we should cast instead. Just use the normal warning message.
8914         EmitFormatDiagnostic(
8915             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8916                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
8917                 << E->getSourceRange(),
8918             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
8919       }
8920     }
8921   } else {
8922     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
8923                                                    SpecifierLen);
8924     // Since the warning for passing non-POD types to variadic functions
8925     // was deferred until now, we emit a warning for non-POD
8926     // arguments here.
8927     switch (S.isValidVarArgType(ExprTy)) {
8928     case Sema::VAK_Valid:
8929     case Sema::VAK_ValidInCXX11: {
8930       unsigned Diag;
8931       switch (Match) {
8932       case ArgType::Match: llvm_unreachable("expected non-matching");
8933       case ArgType::NoMatchPedantic:
8934         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8935         break;
8936       case ArgType::NoMatchTypeConfusion:
8937         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8938         break;
8939       case ArgType::NoMatch:
8940         Diag = diag::warn_format_conversion_argument_type_mismatch;
8941         break;
8942       }
8943 
8944       EmitFormatDiagnostic(
8945           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
8946                         << IsEnum << CSR << E->getSourceRange(),
8947           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8948       break;
8949     }
8950     case Sema::VAK_Undefined:
8951     case Sema::VAK_MSVCUndefined:
8952       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
8953                                << S.getLangOpts().CPlusPlus11 << ExprTy
8954                                << CallType
8955                                << AT.getRepresentativeTypeName(S.Context) << CSR
8956                                << E->getSourceRange(),
8957                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8958       checkForCStrMembers(AT, E);
8959       break;
8960 
8961     case Sema::VAK_Invalid:
8962       if (ExprTy->isObjCObjectType())
8963         EmitFormatDiagnostic(
8964             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
8965                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
8966                 << AT.getRepresentativeTypeName(S.Context) << CSR
8967                 << E->getSourceRange(),
8968             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8969       else
8970         // FIXME: If this is an initializer list, suggest removing the braces
8971         // or inserting a cast to the target type.
8972         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
8973             << isa<InitListExpr>(E) << ExprTy << CallType
8974             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
8975       break;
8976     }
8977 
8978     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
8979            "format string specifier index out of range");
8980     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
8981   }
8982 
8983   return true;
8984 }
8985 
8986 //===--- CHECK: Scanf format string checking ------------------------------===//
8987 
8988 namespace {
8989 
8990 class CheckScanfHandler : public CheckFormatHandler {
8991 public:
8992   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
8993                     const Expr *origFormatExpr, Sema::FormatStringType type,
8994                     unsigned firstDataArg, unsigned numDataArgs,
8995                     const char *beg, bool hasVAListArg,
8996                     ArrayRef<const Expr *> Args, unsigned formatIdx,
8997                     bool inFunctionCall, Sema::VariadicCallType CallType,
8998                     llvm::SmallBitVector &CheckedVarArgs,
8999                     UncoveredArgHandler &UncoveredArg)
9000       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
9001                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
9002                            inFunctionCall, CallType, CheckedVarArgs,
9003                            UncoveredArg) {}
9004 
9005   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
9006                             const char *startSpecifier,
9007                             unsigned specifierLen) override;
9008 
9009   bool HandleInvalidScanfConversionSpecifier(
9010           const analyze_scanf::ScanfSpecifier &FS,
9011           const char *startSpecifier,
9012           unsigned specifierLen) override;
9013 
9014   void HandleIncompleteScanList(const char *start, const char *end) override;
9015 };
9016 
9017 } // namespace
9018 
9019 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
9020                                                  const char *end) {
9021   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
9022                        getLocationOfByte(end), /*IsStringLocation*/true,
9023                        getSpecifierRange(start, end - start));
9024 }
9025 
9026 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
9027                                         const analyze_scanf::ScanfSpecifier &FS,
9028                                         const char *startSpecifier,
9029                                         unsigned specifierLen) {
9030   const analyze_scanf::ScanfConversionSpecifier &CS =
9031     FS.getConversionSpecifier();
9032 
9033   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
9034                                           getLocationOfByte(CS.getStart()),
9035                                           startSpecifier, specifierLen,
9036                                           CS.getStart(), CS.getLength());
9037 }
9038 
9039 bool CheckScanfHandler::HandleScanfSpecifier(
9040                                        const analyze_scanf::ScanfSpecifier &FS,
9041                                        const char *startSpecifier,
9042                                        unsigned specifierLen) {
9043   using namespace analyze_scanf;
9044   using namespace analyze_format_string;
9045 
9046   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
9047 
9048   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
9049   // be used to decide if we are using positional arguments consistently.
9050   if (FS.consumesDataArgument()) {
9051     if (atFirstArg) {
9052       atFirstArg = false;
9053       usesPositionalArgs = FS.usesPositionalArg();
9054     }
9055     else if (usesPositionalArgs != FS.usesPositionalArg()) {
9056       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9057                                         startSpecifier, specifierLen);
9058       return false;
9059     }
9060   }
9061 
9062   // Check if the field with is non-zero.
9063   const OptionalAmount &Amt = FS.getFieldWidth();
9064   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
9065     if (Amt.getConstantAmount() == 0) {
9066       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
9067                                                    Amt.getConstantLength());
9068       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
9069                            getLocationOfByte(Amt.getStart()),
9070                            /*IsStringLocation*/true, R,
9071                            FixItHint::CreateRemoval(R));
9072     }
9073   }
9074 
9075   if (!FS.consumesDataArgument()) {
9076     // FIXME: Technically specifying a precision or field width here
9077     // makes no sense.  Worth issuing a warning at some point.
9078     return true;
9079   }
9080 
9081   // Consume the argument.
9082   unsigned argIndex = FS.getArgIndex();
9083   if (argIndex < NumDataArgs) {
9084       // The check to see if the argIndex is valid will come later.
9085       // We set the bit here because we may exit early from this
9086       // function if we encounter some other error.
9087     CoveredArgs.set(argIndex);
9088   }
9089 
9090   // Check the length modifier is valid with the given conversion specifier.
9091   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
9092                                  S.getLangOpts()))
9093     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9094                                 diag::warn_format_nonsensical_length);
9095   else if (!FS.hasStandardLengthModifier())
9096     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9097   else if (!FS.hasStandardLengthConversionCombination())
9098     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9099                                 diag::warn_format_non_standard_conversion_spec);
9100 
9101   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
9102     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9103 
9104   // The remaining checks depend on the data arguments.
9105   if (HasVAListArg)
9106     return true;
9107 
9108   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9109     return false;
9110 
9111   // Check that the argument type matches the format specifier.
9112   const Expr *Ex = getDataArg(argIndex);
9113   if (!Ex)
9114     return true;
9115 
9116   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
9117 
9118   if (!AT.isValid()) {
9119     return true;
9120   }
9121 
9122   analyze_format_string::ArgType::MatchKind Match =
9123       AT.matchesType(S.Context, Ex->getType());
9124   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
9125   if (Match == analyze_format_string::ArgType::Match)
9126     return true;
9127 
9128   ScanfSpecifier fixedFS = FS;
9129   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
9130                                  S.getLangOpts(), S.Context);
9131 
9132   unsigned Diag =
9133       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9134                : diag::warn_format_conversion_argument_type_mismatch;
9135 
9136   if (Success) {
9137     // Get the fix string from the fixed format specifier.
9138     SmallString<128> buf;
9139     llvm::raw_svector_ostream os(buf);
9140     fixedFS.toString(os);
9141 
9142     EmitFormatDiagnostic(
9143         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
9144                       << Ex->getType() << false << Ex->getSourceRange(),
9145         Ex->getBeginLoc(),
9146         /*IsStringLocation*/ false,
9147         getSpecifierRange(startSpecifier, specifierLen),
9148         FixItHint::CreateReplacement(
9149             getSpecifierRange(startSpecifier, specifierLen), os.str()));
9150   } else {
9151     EmitFormatDiagnostic(S.PDiag(Diag)
9152                              << AT.getRepresentativeTypeName(S.Context)
9153                              << Ex->getType() << false << Ex->getSourceRange(),
9154                          Ex->getBeginLoc(),
9155                          /*IsStringLocation*/ false,
9156                          getSpecifierRange(startSpecifier, specifierLen));
9157   }
9158 
9159   return true;
9160 }
9161 
9162 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
9163                               const Expr *OrigFormatExpr,
9164                               ArrayRef<const Expr *> Args,
9165                               bool HasVAListArg, unsigned format_idx,
9166                               unsigned firstDataArg,
9167                               Sema::FormatStringType Type,
9168                               bool inFunctionCall,
9169                               Sema::VariadicCallType CallType,
9170                               llvm::SmallBitVector &CheckedVarArgs,
9171                               UncoveredArgHandler &UncoveredArg,
9172                               bool IgnoreStringsWithoutSpecifiers) {
9173   // CHECK: is the format string a wide literal?
9174   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
9175     CheckFormatHandler::EmitFormatDiagnostic(
9176         S, inFunctionCall, Args[format_idx],
9177         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
9178         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9179     return;
9180   }
9181 
9182   // Str - The format string.  NOTE: this is NOT null-terminated!
9183   StringRef StrRef = FExpr->getString();
9184   const char *Str = StrRef.data();
9185   // Account for cases where the string literal is truncated in a declaration.
9186   const ConstantArrayType *T =
9187     S.Context.getAsConstantArrayType(FExpr->getType());
9188   assert(T && "String literal not of constant array type!");
9189   size_t TypeSize = T->getSize().getZExtValue();
9190   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9191   const unsigned numDataArgs = Args.size() - firstDataArg;
9192 
9193   if (IgnoreStringsWithoutSpecifiers &&
9194       !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
9195           Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
9196     return;
9197 
9198   // Emit a warning if the string literal is truncated and does not contain an
9199   // embedded null character.
9200   if (TypeSize <= StrRef.size() &&
9201       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
9202     CheckFormatHandler::EmitFormatDiagnostic(
9203         S, inFunctionCall, Args[format_idx],
9204         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
9205         FExpr->getBeginLoc(),
9206         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
9207     return;
9208   }
9209 
9210   // CHECK: empty format string?
9211   if (StrLen == 0 && numDataArgs > 0) {
9212     CheckFormatHandler::EmitFormatDiagnostic(
9213         S, inFunctionCall, Args[format_idx],
9214         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
9215         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9216     return;
9217   }
9218 
9219   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
9220       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
9221       Type == Sema::FST_OSTrace) {
9222     CheckPrintfHandler H(
9223         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
9224         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
9225         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
9226         CheckedVarArgs, UncoveredArg);
9227 
9228     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
9229                                                   S.getLangOpts(),
9230                                                   S.Context.getTargetInfo(),
9231                                             Type == Sema::FST_FreeBSDKPrintf))
9232       H.DoneProcessing();
9233   } else if (Type == Sema::FST_Scanf) {
9234     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9235                         numDataArgs, Str, HasVAListArg, Args, format_idx,
9236                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
9237 
9238     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
9239                                                  S.getLangOpts(),
9240                                                  S.Context.getTargetInfo()))
9241       H.DoneProcessing();
9242   } // TODO: handle other formats
9243 }
9244 
9245 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
9246   // Str - The format string.  NOTE: this is NOT null-terminated!
9247   StringRef StrRef = FExpr->getString();
9248   const char *Str = StrRef.data();
9249   // Account for cases where the string literal is truncated in a declaration.
9250   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
9251   assert(T && "String literal not of constant array type!");
9252   size_t TypeSize = T->getSize().getZExtValue();
9253   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9254   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
9255                                                          getLangOpts(),
9256                                                          Context.getTargetInfo());
9257 }
9258 
9259 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
9260 
9261 // Returns the related absolute value function that is larger, of 0 if one
9262 // does not exist.
9263 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
9264   switch (AbsFunction) {
9265   default:
9266     return 0;
9267 
9268   case Builtin::BI__builtin_abs:
9269     return Builtin::BI__builtin_labs;
9270   case Builtin::BI__builtin_labs:
9271     return Builtin::BI__builtin_llabs;
9272   case Builtin::BI__builtin_llabs:
9273     return 0;
9274 
9275   case Builtin::BI__builtin_fabsf:
9276     return Builtin::BI__builtin_fabs;
9277   case Builtin::BI__builtin_fabs:
9278     return Builtin::BI__builtin_fabsl;
9279   case Builtin::BI__builtin_fabsl:
9280     return 0;
9281 
9282   case Builtin::BI__builtin_cabsf:
9283     return Builtin::BI__builtin_cabs;
9284   case Builtin::BI__builtin_cabs:
9285     return Builtin::BI__builtin_cabsl;
9286   case Builtin::BI__builtin_cabsl:
9287     return 0;
9288 
9289   case Builtin::BIabs:
9290     return Builtin::BIlabs;
9291   case Builtin::BIlabs:
9292     return Builtin::BIllabs;
9293   case Builtin::BIllabs:
9294     return 0;
9295 
9296   case Builtin::BIfabsf:
9297     return Builtin::BIfabs;
9298   case Builtin::BIfabs:
9299     return Builtin::BIfabsl;
9300   case Builtin::BIfabsl:
9301     return 0;
9302 
9303   case Builtin::BIcabsf:
9304    return Builtin::BIcabs;
9305   case Builtin::BIcabs:
9306     return Builtin::BIcabsl;
9307   case Builtin::BIcabsl:
9308     return 0;
9309   }
9310 }
9311 
9312 // Returns the argument type of the absolute value function.
9313 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
9314                                              unsigned AbsType) {
9315   if (AbsType == 0)
9316     return QualType();
9317 
9318   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
9319   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
9320   if (Error != ASTContext::GE_None)
9321     return QualType();
9322 
9323   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
9324   if (!FT)
9325     return QualType();
9326 
9327   if (FT->getNumParams() != 1)
9328     return QualType();
9329 
9330   return FT->getParamType(0);
9331 }
9332 
9333 // Returns the best absolute value function, or zero, based on type and
9334 // current absolute value function.
9335 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
9336                                    unsigned AbsFunctionKind) {
9337   unsigned BestKind = 0;
9338   uint64_t ArgSize = Context.getTypeSize(ArgType);
9339   for (unsigned Kind = AbsFunctionKind; Kind != 0;
9340        Kind = getLargerAbsoluteValueFunction(Kind)) {
9341     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
9342     if (Context.getTypeSize(ParamType) >= ArgSize) {
9343       if (BestKind == 0)
9344         BestKind = Kind;
9345       else if (Context.hasSameType(ParamType, ArgType)) {
9346         BestKind = Kind;
9347         break;
9348       }
9349     }
9350   }
9351   return BestKind;
9352 }
9353 
9354 enum AbsoluteValueKind {
9355   AVK_Integer,
9356   AVK_Floating,
9357   AVK_Complex
9358 };
9359 
9360 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
9361   if (T->isIntegralOrEnumerationType())
9362     return AVK_Integer;
9363   if (T->isRealFloatingType())
9364     return AVK_Floating;
9365   if (T->isAnyComplexType())
9366     return AVK_Complex;
9367 
9368   llvm_unreachable("Type not integer, floating, or complex");
9369 }
9370 
9371 // Changes the absolute value function to a different type.  Preserves whether
9372 // the function is a builtin.
9373 static unsigned changeAbsFunction(unsigned AbsKind,
9374                                   AbsoluteValueKind ValueKind) {
9375   switch (ValueKind) {
9376   case AVK_Integer:
9377     switch (AbsKind) {
9378     default:
9379       return 0;
9380     case Builtin::BI__builtin_fabsf:
9381     case Builtin::BI__builtin_fabs:
9382     case Builtin::BI__builtin_fabsl:
9383     case Builtin::BI__builtin_cabsf:
9384     case Builtin::BI__builtin_cabs:
9385     case Builtin::BI__builtin_cabsl:
9386       return Builtin::BI__builtin_abs;
9387     case Builtin::BIfabsf:
9388     case Builtin::BIfabs:
9389     case Builtin::BIfabsl:
9390     case Builtin::BIcabsf:
9391     case Builtin::BIcabs:
9392     case Builtin::BIcabsl:
9393       return Builtin::BIabs;
9394     }
9395   case AVK_Floating:
9396     switch (AbsKind) {
9397     default:
9398       return 0;
9399     case Builtin::BI__builtin_abs:
9400     case Builtin::BI__builtin_labs:
9401     case Builtin::BI__builtin_llabs:
9402     case Builtin::BI__builtin_cabsf:
9403     case Builtin::BI__builtin_cabs:
9404     case Builtin::BI__builtin_cabsl:
9405       return Builtin::BI__builtin_fabsf;
9406     case Builtin::BIabs:
9407     case Builtin::BIlabs:
9408     case Builtin::BIllabs:
9409     case Builtin::BIcabsf:
9410     case Builtin::BIcabs:
9411     case Builtin::BIcabsl:
9412       return Builtin::BIfabsf;
9413     }
9414   case AVK_Complex:
9415     switch (AbsKind) {
9416     default:
9417       return 0;
9418     case Builtin::BI__builtin_abs:
9419     case Builtin::BI__builtin_labs:
9420     case Builtin::BI__builtin_llabs:
9421     case Builtin::BI__builtin_fabsf:
9422     case Builtin::BI__builtin_fabs:
9423     case Builtin::BI__builtin_fabsl:
9424       return Builtin::BI__builtin_cabsf;
9425     case Builtin::BIabs:
9426     case Builtin::BIlabs:
9427     case Builtin::BIllabs:
9428     case Builtin::BIfabsf:
9429     case Builtin::BIfabs:
9430     case Builtin::BIfabsl:
9431       return Builtin::BIcabsf;
9432     }
9433   }
9434   llvm_unreachable("Unable to convert function");
9435 }
9436 
9437 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
9438   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
9439   if (!FnInfo)
9440     return 0;
9441 
9442   switch (FDecl->getBuiltinID()) {
9443   default:
9444     return 0;
9445   case Builtin::BI__builtin_abs:
9446   case Builtin::BI__builtin_fabs:
9447   case Builtin::BI__builtin_fabsf:
9448   case Builtin::BI__builtin_fabsl:
9449   case Builtin::BI__builtin_labs:
9450   case Builtin::BI__builtin_llabs:
9451   case Builtin::BI__builtin_cabs:
9452   case Builtin::BI__builtin_cabsf:
9453   case Builtin::BI__builtin_cabsl:
9454   case Builtin::BIabs:
9455   case Builtin::BIlabs:
9456   case Builtin::BIllabs:
9457   case Builtin::BIfabs:
9458   case Builtin::BIfabsf:
9459   case Builtin::BIfabsl:
9460   case Builtin::BIcabs:
9461   case Builtin::BIcabsf:
9462   case Builtin::BIcabsl:
9463     return FDecl->getBuiltinID();
9464   }
9465   llvm_unreachable("Unknown Builtin type");
9466 }
9467 
9468 // If the replacement is valid, emit a note with replacement function.
9469 // Additionally, suggest including the proper header if not already included.
9470 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
9471                             unsigned AbsKind, QualType ArgType) {
9472   bool EmitHeaderHint = true;
9473   const char *HeaderName = nullptr;
9474   const char *FunctionName = nullptr;
9475   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
9476     FunctionName = "std::abs";
9477     if (ArgType->isIntegralOrEnumerationType()) {
9478       HeaderName = "cstdlib";
9479     } else if (ArgType->isRealFloatingType()) {
9480       HeaderName = "cmath";
9481     } else {
9482       llvm_unreachable("Invalid Type");
9483     }
9484 
9485     // Lookup all std::abs
9486     if (NamespaceDecl *Std = S.getStdNamespace()) {
9487       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
9488       R.suppressDiagnostics();
9489       S.LookupQualifiedName(R, Std);
9490 
9491       for (const auto *I : R) {
9492         const FunctionDecl *FDecl = nullptr;
9493         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
9494           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
9495         } else {
9496           FDecl = dyn_cast<FunctionDecl>(I);
9497         }
9498         if (!FDecl)
9499           continue;
9500 
9501         // Found std::abs(), check that they are the right ones.
9502         if (FDecl->getNumParams() != 1)
9503           continue;
9504 
9505         // Check that the parameter type can handle the argument.
9506         QualType ParamType = FDecl->getParamDecl(0)->getType();
9507         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
9508             S.Context.getTypeSize(ArgType) <=
9509                 S.Context.getTypeSize(ParamType)) {
9510           // Found a function, don't need the header hint.
9511           EmitHeaderHint = false;
9512           break;
9513         }
9514       }
9515     }
9516   } else {
9517     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
9518     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
9519 
9520     if (HeaderName) {
9521       DeclarationName DN(&S.Context.Idents.get(FunctionName));
9522       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
9523       R.suppressDiagnostics();
9524       S.LookupName(R, S.getCurScope());
9525 
9526       if (R.isSingleResult()) {
9527         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
9528         if (FD && FD->getBuiltinID() == AbsKind) {
9529           EmitHeaderHint = false;
9530         } else {
9531           return;
9532         }
9533       } else if (!R.empty()) {
9534         return;
9535       }
9536     }
9537   }
9538 
9539   S.Diag(Loc, diag::note_replace_abs_function)
9540       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
9541 
9542   if (!HeaderName)
9543     return;
9544 
9545   if (!EmitHeaderHint)
9546     return;
9547 
9548   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
9549                                                     << FunctionName;
9550 }
9551 
9552 template <std::size_t StrLen>
9553 static bool IsStdFunction(const FunctionDecl *FDecl,
9554                           const char (&Str)[StrLen]) {
9555   if (!FDecl)
9556     return false;
9557   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
9558     return false;
9559   if (!FDecl->isInStdNamespace())
9560     return false;
9561 
9562   return true;
9563 }
9564 
9565 // Warn when using the wrong abs() function.
9566 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
9567                                       const FunctionDecl *FDecl) {
9568   if (Call->getNumArgs() != 1)
9569     return;
9570 
9571   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
9572   bool IsStdAbs = IsStdFunction(FDecl, "abs");
9573   if (AbsKind == 0 && !IsStdAbs)
9574     return;
9575 
9576   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9577   QualType ParamType = Call->getArg(0)->getType();
9578 
9579   // Unsigned types cannot be negative.  Suggest removing the absolute value
9580   // function call.
9581   if (ArgType->isUnsignedIntegerType()) {
9582     const char *FunctionName =
9583         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
9584     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
9585     Diag(Call->getExprLoc(), diag::note_remove_abs)
9586         << FunctionName
9587         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
9588     return;
9589   }
9590 
9591   // Taking the absolute value of a pointer is very suspicious, they probably
9592   // wanted to index into an array, dereference a pointer, call a function, etc.
9593   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
9594     unsigned DiagType = 0;
9595     if (ArgType->isFunctionType())
9596       DiagType = 1;
9597     else if (ArgType->isArrayType())
9598       DiagType = 2;
9599 
9600     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
9601     return;
9602   }
9603 
9604   // std::abs has overloads which prevent most of the absolute value problems
9605   // from occurring.
9606   if (IsStdAbs)
9607     return;
9608 
9609   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
9610   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
9611 
9612   // The argument and parameter are the same kind.  Check if they are the right
9613   // size.
9614   if (ArgValueKind == ParamValueKind) {
9615     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
9616       return;
9617 
9618     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
9619     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
9620         << FDecl << ArgType << ParamType;
9621 
9622     if (NewAbsKind == 0)
9623       return;
9624 
9625     emitReplacement(*this, Call->getExprLoc(),
9626                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9627     return;
9628   }
9629 
9630   // ArgValueKind != ParamValueKind
9631   // The wrong type of absolute value function was used.  Attempt to find the
9632   // proper one.
9633   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
9634   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
9635   if (NewAbsKind == 0)
9636     return;
9637 
9638   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
9639       << FDecl << ParamValueKind << ArgValueKind;
9640 
9641   emitReplacement(*this, Call->getExprLoc(),
9642                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9643 }
9644 
9645 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
9646 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
9647                                 const FunctionDecl *FDecl) {
9648   if (!Call || !FDecl) return;
9649 
9650   // Ignore template specializations and macros.
9651   if (inTemplateInstantiation()) return;
9652   if (Call->getExprLoc().isMacroID()) return;
9653 
9654   // Only care about the one template argument, two function parameter std::max
9655   if (Call->getNumArgs() != 2) return;
9656   if (!IsStdFunction(FDecl, "max")) return;
9657   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
9658   if (!ArgList) return;
9659   if (ArgList->size() != 1) return;
9660 
9661   // Check that template type argument is unsigned integer.
9662   const auto& TA = ArgList->get(0);
9663   if (TA.getKind() != TemplateArgument::Type) return;
9664   QualType ArgType = TA.getAsType();
9665   if (!ArgType->isUnsignedIntegerType()) return;
9666 
9667   // See if either argument is a literal zero.
9668   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
9669     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
9670     if (!MTE) return false;
9671     const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
9672     if (!Num) return false;
9673     if (Num->getValue() != 0) return false;
9674     return true;
9675   };
9676 
9677   const Expr *FirstArg = Call->getArg(0);
9678   const Expr *SecondArg = Call->getArg(1);
9679   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
9680   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
9681 
9682   // Only warn when exactly one argument is zero.
9683   if (IsFirstArgZero == IsSecondArgZero) return;
9684 
9685   SourceRange FirstRange = FirstArg->getSourceRange();
9686   SourceRange SecondRange = SecondArg->getSourceRange();
9687 
9688   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
9689 
9690   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
9691       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
9692 
9693   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
9694   SourceRange RemovalRange;
9695   if (IsFirstArgZero) {
9696     RemovalRange = SourceRange(FirstRange.getBegin(),
9697                                SecondRange.getBegin().getLocWithOffset(-1));
9698   } else {
9699     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
9700                                SecondRange.getEnd());
9701   }
9702 
9703   Diag(Call->getExprLoc(), diag::note_remove_max_call)
9704         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
9705         << FixItHint::CreateRemoval(RemovalRange);
9706 }
9707 
9708 //===--- CHECK: Standard memory functions ---------------------------------===//
9709 
9710 /// Takes the expression passed to the size_t parameter of functions
9711 /// such as memcmp, strncat, etc and warns if it's a comparison.
9712 ///
9713 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
9714 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
9715                                            IdentifierInfo *FnName,
9716                                            SourceLocation FnLoc,
9717                                            SourceLocation RParenLoc) {
9718   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
9719   if (!Size)
9720     return false;
9721 
9722   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
9723   if (!Size->isComparisonOp() && !Size->isLogicalOp())
9724     return false;
9725 
9726   SourceRange SizeRange = Size->getSourceRange();
9727   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
9728       << SizeRange << FnName;
9729   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
9730       << FnName
9731       << FixItHint::CreateInsertion(
9732              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
9733       << FixItHint::CreateRemoval(RParenLoc);
9734   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
9735       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
9736       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
9737                                     ")");
9738 
9739   return true;
9740 }
9741 
9742 /// Determine whether the given type is or contains a dynamic class type
9743 /// (e.g., whether it has a vtable).
9744 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
9745                                                      bool &IsContained) {
9746   // Look through array types while ignoring qualifiers.
9747   const Type *Ty = T->getBaseElementTypeUnsafe();
9748   IsContained = false;
9749 
9750   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
9751   RD = RD ? RD->getDefinition() : nullptr;
9752   if (!RD || RD->isInvalidDecl())
9753     return nullptr;
9754 
9755   if (RD->isDynamicClass())
9756     return RD;
9757 
9758   // Check all the fields.  If any bases were dynamic, the class is dynamic.
9759   // It's impossible for a class to transitively contain itself by value, so
9760   // infinite recursion is impossible.
9761   for (auto *FD : RD->fields()) {
9762     bool SubContained;
9763     if (const CXXRecordDecl *ContainedRD =
9764             getContainedDynamicClass(FD->getType(), SubContained)) {
9765       IsContained = true;
9766       return ContainedRD;
9767     }
9768   }
9769 
9770   return nullptr;
9771 }
9772 
9773 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
9774   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
9775     if (Unary->getKind() == UETT_SizeOf)
9776       return Unary;
9777   return nullptr;
9778 }
9779 
9780 /// If E is a sizeof expression, returns its argument expression,
9781 /// otherwise returns NULL.
9782 static const Expr *getSizeOfExprArg(const Expr *E) {
9783   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9784     if (!SizeOf->isArgumentType())
9785       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
9786   return nullptr;
9787 }
9788 
9789 /// If E is a sizeof expression, returns its argument type.
9790 static QualType getSizeOfArgType(const Expr *E) {
9791   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9792     return SizeOf->getTypeOfArgument();
9793   return QualType();
9794 }
9795 
9796 namespace {
9797 
9798 struct SearchNonTrivialToInitializeField
9799     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
9800   using Super =
9801       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
9802 
9803   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
9804 
9805   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
9806                      SourceLocation SL) {
9807     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9808       asDerived().visitArray(PDIK, AT, SL);
9809       return;
9810     }
9811 
9812     Super::visitWithKind(PDIK, FT, SL);
9813   }
9814 
9815   void visitARCStrong(QualType FT, SourceLocation SL) {
9816     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9817   }
9818   void visitARCWeak(QualType FT, SourceLocation SL) {
9819     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9820   }
9821   void visitStruct(QualType FT, SourceLocation SL) {
9822     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9823       visit(FD->getType(), FD->getLocation());
9824   }
9825   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
9826                   const ArrayType *AT, SourceLocation SL) {
9827     visit(getContext().getBaseElementType(AT), SL);
9828   }
9829   void visitTrivial(QualType FT, SourceLocation SL) {}
9830 
9831   static void diag(QualType RT, const Expr *E, Sema &S) {
9832     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
9833   }
9834 
9835   ASTContext &getContext() { return S.getASTContext(); }
9836 
9837   const Expr *E;
9838   Sema &S;
9839 };
9840 
9841 struct SearchNonTrivialToCopyField
9842     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
9843   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
9844 
9845   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
9846 
9847   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
9848                      SourceLocation SL) {
9849     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9850       asDerived().visitArray(PCK, AT, SL);
9851       return;
9852     }
9853 
9854     Super::visitWithKind(PCK, FT, SL);
9855   }
9856 
9857   void visitARCStrong(QualType FT, SourceLocation SL) {
9858     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9859   }
9860   void visitARCWeak(QualType FT, SourceLocation SL) {
9861     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9862   }
9863   void visitStruct(QualType FT, SourceLocation SL) {
9864     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9865       visit(FD->getType(), FD->getLocation());
9866   }
9867   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
9868                   SourceLocation SL) {
9869     visit(getContext().getBaseElementType(AT), SL);
9870   }
9871   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
9872                 SourceLocation SL) {}
9873   void visitTrivial(QualType FT, SourceLocation SL) {}
9874   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
9875 
9876   static void diag(QualType RT, const Expr *E, Sema &S) {
9877     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
9878   }
9879 
9880   ASTContext &getContext() { return S.getASTContext(); }
9881 
9882   const Expr *E;
9883   Sema &S;
9884 };
9885 
9886 }
9887 
9888 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
9889 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
9890   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
9891 
9892   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
9893     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
9894       return false;
9895 
9896     return doesExprLikelyComputeSize(BO->getLHS()) ||
9897            doesExprLikelyComputeSize(BO->getRHS());
9898   }
9899 
9900   return getAsSizeOfExpr(SizeofExpr) != nullptr;
9901 }
9902 
9903 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
9904 ///
9905 /// \code
9906 ///   #define MACRO 0
9907 ///   foo(MACRO);
9908 ///   foo(0);
9909 /// \endcode
9910 ///
9911 /// This should return true for the first call to foo, but not for the second
9912 /// (regardless of whether foo is a macro or function).
9913 static bool isArgumentExpandedFromMacro(SourceManager &SM,
9914                                         SourceLocation CallLoc,
9915                                         SourceLocation ArgLoc) {
9916   if (!CallLoc.isMacroID())
9917     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
9918 
9919   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
9920          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
9921 }
9922 
9923 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
9924 /// last two arguments transposed.
9925 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
9926   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
9927     return;
9928 
9929   const Expr *SizeArg =
9930     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
9931 
9932   auto isLiteralZero = [](const Expr *E) {
9933     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
9934   };
9935 
9936   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
9937   SourceLocation CallLoc = Call->getRParenLoc();
9938   SourceManager &SM = S.getSourceManager();
9939   if (isLiteralZero(SizeArg) &&
9940       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
9941 
9942     SourceLocation DiagLoc = SizeArg->getExprLoc();
9943 
9944     // Some platforms #define bzero to __builtin_memset. See if this is the
9945     // case, and if so, emit a better diagnostic.
9946     if (BId == Builtin::BIbzero ||
9947         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
9948                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
9949       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
9950       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
9951     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
9952       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
9953       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
9954     }
9955     return;
9956   }
9957 
9958   // If the second argument to a memset is a sizeof expression and the third
9959   // isn't, this is also likely an error. This should catch
9960   // 'memset(buf, sizeof(buf), 0xff)'.
9961   if (BId == Builtin::BImemset &&
9962       doesExprLikelyComputeSize(Call->getArg(1)) &&
9963       !doesExprLikelyComputeSize(Call->getArg(2))) {
9964     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
9965     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
9966     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
9967     return;
9968   }
9969 }
9970 
9971 /// Check for dangerous or invalid arguments to memset().
9972 ///
9973 /// This issues warnings on known problematic, dangerous or unspecified
9974 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
9975 /// function calls.
9976 ///
9977 /// \param Call The call expression to diagnose.
9978 void Sema::CheckMemaccessArguments(const CallExpr *Call,
9979                                    unsigned BId,
9980                                    IdentifierInfo *FnName) {
9981   assert(BId != 0);
9982 
9983   // It is possible to have a non-standard definition of memset.  Validate
9984   // we have enough arguments, and if not, abort further checking.
9985   unsigned ExpectedNumArgs =
9986       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
9987   if (Call->getNumArgs() < ExpectedNumArgs)
9988     return;
9989 
9990   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
9991                       BId == Builtin::BIstrndup ? 1 : 2);
9992   unsigned LenArg =
9993       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
9994   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
9995 
9996   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
9997                                      Call->getBeginLoc(), Call->getRParenLoc()))
9998     return;
9999 
10000   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
10001   CheckMemaccessSize(*this, BId, Call);
10002 
10003   // We have special checking when the length is a sizeof expression.
10004   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
10005   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
10006   llvm::FoldingSetNodeID SizeOfArgID;
10007 
10008   // Although widely used, 'bzero' is not a standard function. Be more strict
10009   // with the argument types before allowing diagnostics and only allow the
10010   // form bzero(ptr, sizeof(...)).
10011   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10012   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
10013     return;
10014 
10015   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
10016     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
10017     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
10018 
10019     QualType DestTy = Dest->getType();
10020     QualType PointeeTy;
10021     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
10022       PointeeTy = DestPtrTy->getPointeeType();
10023 
10024       // Never warn about void type pointers. This can be used to suppress
10025       // false positives.
10026       if (PointeeTy->isVoidType())
10027         continue;
10028 
10029       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
10030       // actually comparing the expressions for equality. Because computing the
10031       // expression IDs can be expensive, we only do this if the diagnostic is
10032       // enabled.
10033       if (SizeOfArg &&
10034           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
10035                            SizeOfArg->getExprLoc())) {
10036         // We only compute IDs for expressions if the warning is enabled, and
10037         // cache the sizeof arg's ID.
10038         if (SizeOfArgID == llvm::FoldingSetNodeID())
10039           SizeOfArg->Profile(SizeOfArgID, Context, true);
10040         llvm::FoldingSetNodeID DestID;
10041         Dest->Profile(DestID, Context, true);
10042         if (DestID == SizeOfArgID) {
10043           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
10044           //       over sizeof(src) as well.
10045           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
10046           StringRef ReadableName = FnName->getName();
10047 
10048           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
10049             if (UnaryOp->getOpcode() == UO_AddrOf)
10050               ActionIdx = 1; // If its an address-of operator, just remove it.
10051           if (!PointeeTy->isIncompleteType() &&
10052               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
10053             ActionIdx = 2; // If the pointee's size is sizeof(char),
10054                            // suggest an explicit length.
10055 
10056           // If the function is defined as a builtin macro, do not show macro
10057           // expansion.
10058           SourceLocation SL = SizeOfArg->getExprLoc();
10059           SourceRange DSR = Dest->getSourceRange();
10060           SourceRange SSR = SizeOfArg->getSourceRange();
10061           SourceManager &SM = getSourceManager();
10062 
10063           if (SM.isMacroArgExpansion(SL)) {
10064             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
10065             SL = SM.getSpellingLoc(SL);
10066             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
10067                              SM.getSpellingLoc(DSR.getEnd()));
10068             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
10069                              SM.getSpellingLoc(SSR.getEnd()));
10070           }
10071 
10072           DiagRuntimeBehavior(SL, SizeOfArg,
10073                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
10074                                 << ReadableName
10075                                 << PointeeTy
10076                                 << DestTy
10077                                 << DSR
10078                                 << SSR);
10079           DiagRuntimeBehavior(SL, SizeOfArg,
10080                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
10081                                 << ActionIdx
10082                                 << SSR);
10083 
10084           break;
10085         }
10086       }
10087 
10088       // Also check for cases where the sizeof argument is the exact same
10089       // type as the memory argument, and where it points to a user-defined
10090       // record type.
10091       if (SizeOfArgTy != QualType()) {
10092         if (PointeeTy->isRecordType() &&
10093             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
10094           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
10095                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
10096                                 << FnName << SizeOfArgTy << ArgIdx
10097                                 << PointeeTy << Dest->getSourceRange()
10098                                 << LenExpr->getSourceRange());
10099           break;
10100         }
10101       }
10102     } else if (DestTy->isArrayType()) {
10103       PointeeTy = DestTy;
10104     }
10105 
10106     if (PointeeTy == QualType())
10107       continue;
10108 
10109     // Always complain about dynamic classes.
10110     bool IsContained;
10111     if (const CXXRecordDecl *ContainedRD =
10112             getContainedDynamicClass(PointeeTy, IsContained)) {
10113 
10114       unsigned OperationType = 0;
10115       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
10116       // "overwritten" if we're warning about the destination for any call
10117       // but memcmp; otherwise a verb appropriate to the call.
10118       if (ArgIdx != 0 || IsCmp) {
10119         if (BId == Builtin::BImemcpy)
10120           OperationType = 1;
10121         else if(BId == Builtin::BImemmove)
10122           OperationType = 2;
10123         else if (IsCmp)
10124           OperationType = 3;
10125       }
10126 
10127       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10128                           PDiag(diag::warn_dyn_class_memaccess)
10129                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
10130                               << IsContained << ContainedRD << OperationType
10131                               << Call->getCallee()->getSourceRange());
10132     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
10133              BId != Builtin::BImemset)
10134       DiagRuntimeBehavior(
10135         Dest->getExprLoc(), Dest,
10136         PDiag(diag::warn_arc_object_memaccess)
10137           << ArgIdx << FnName << PointeeTy
10138           << Call->getCallee()->getSourceRange());
10139     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
10140       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10141           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
10142         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10143                             PDiag(diag::warn_cstruct_memaccess)
10144                                 << ArgIdx << FnName << PointeeTy << 0);
10145         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
10146       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10147                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
10148         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10149                             PDiag(diag::warn_cstruct_memaccess)
10150                                 << ArgIdx << FnName << PointeeTy << 1);
10151         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
10152       } else {
10153         continue;
10154       }
10155     } else
10156       continue;
10157 
10158     DiagRuntimeBehavior(
10159       Dest->getExprLoc(), Dest,
10160       PDiag(diag::note_bad_memaccess_silence)
10161         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
10162     break;
10163   }
10164 }
10165 
10166 // A little helper routine: ignore addition and subtraction of integer literals.
10167 // This intentionally does not ignore all integer constant expressions because
10168 // we don't want to remove sizeof().
10169 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
10170   Ex = Ex->IgnoreParenCasts();
10171 
10172   while (true) {
10173     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
10174     if (!BO || !BO->isAdditiveOp())
10175       break;
10176 
10177     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
10178     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
10179 
10180     if (isa<IntegerLiteral>(RHS))
10181       Ex = LHS;
10182     else if (isa<IntegerLiteral>(LHS))
10183       Ex = RHS;
10184     else
10185       break;
10186   }
10187 
10188   return Ex;
10189 }
10190 
10191 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
10192                                                       ASTContext &Context) {
10193   // Only handle constant-sized or VLAs, but not flexible members.
10194   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
10195     // Only issue the FIXIT for arrays of size > 1.
10196     if (CAT->getSize().getSExtValue() <= 1)
10197       return false;
10198   } else if (!Ty->isVariableArrayType()) {
10199     return false;
10200   }
10201   return true;
10202 }
10203 
10204 // Warn if the user has made the 'size' argument to strlcpy or strlcat
10205 // be the size of the source, instead of the destination.
10206 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
10207                                     IdentifierInfo *FnName) {
10208 
10209   // Don't crash if the user has the wrong number of arguments
10210   unsigned NumArgs = Call->getNumArgs();
10211   if ((NumArgs != 3) && (NumArgs != 4))
10212     return;
10213 
10214   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
10215   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
10216   const Expr *CompareWithSrc = nullptr;
10217 
10218   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
10219                                      Call->getBeginLoc(), Call->getRParenLoc()))
10220     return;
10221 
10222   // Look for 'strlcpy(dst, x, sizeof(x))'
10223   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
10224     CompareWithSrc = Ex;
10225   else {
10226     // Look for 'strlcpy(dst, x, strlen(x))'
10227     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
10228       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
10229           SizeCall->getNumArgs() == 1)
10230         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
10231     }
10232   }
10233 
10234   if (!CompareWithSrc)
10235     return;
10236 
10237   // Determine if the argument to sizeof/strlen is equal to the source
10238   // argument.  In principle there's all kinds of things you could do
10239   // here, for instance creating an == expression and evaluating it with
10240   // EvaluateAsBooleanCondition, but this uses a more direct technique:
10241   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
10242   if (!SrcArgDRE)
10243     return;
10244 
10245   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
10246   if (!CompareWithSrcDRE ||
10247       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
10248     return;
10249 
10250   const Expr *OriginalSizeArg = Call->getArg(2);
10251   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
10252       << OriginalSizeArg->getSourceRange() << FnName;
10253 
10254   // Output a FIXIT hint if the destination is an array (rather than a
10255   // pointer to an array).  This could be enhanced to handle some
10256   // pointers if we know the actual size, like if DstArg is 'array+2'
10257   // we could say 'sizeof(array)-2'.
10258   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
10259   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
10260     return;
10261 
10262   SmallString<128> sizeString;
10263   llvm::raw_svector_ostream OS(sizeString);
10264   OS << "sizeof(";
10265   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10266   OS << ")";
10267 
10268   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
10269       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
10270                                       OS.str());
10271 }
10272 
10273 /// Check if two expressions refer to the same declaration.
10274 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
10275   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
10276     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
10277       return D1->getDecl() == D2->getDecl();
10278   return false;
10279 }
10280 
10281 static const Expr *getStrlenExprArg(const Expr *E) {
10282   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10283     const FunctionDecl *FD = CE->getDirectCallee();
10284     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
10285       return nullptr;
10286     return CE->getArg(0)->IgnoreParenCasts();
10287   }
10288   return nullptr;
10289 }
10290 
10291 // Warn on anti-patterns as the 'size' argument to strncat.
10292 // The correct size argument should look like following:
10293 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
10294 void Sema::CheckStrncatArguments(const CallExpr *CE,
10295                                  IdentifierInfo *FnName) {
10296   // Don't crash if the user has the wrong number of arguments.
10297   if (CE->getNumArgs() < 3)
10298     return;
10299   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
10300   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
10301   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
10302 
10303   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
10304                                      CE->getRParenLoc()))
10305     return;
10306 
10307   // Identify common expressions, which are wrongly used as the size argument
10308   // to strncat and may lead to buffer overflows.
10309   unsigned PatternType = 0;
10310   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
10311     // - sizeof(dst)
10312     if (referToTheSameDecl(SizeOfArg, DstArg))
10313       PatternType = 1;
10314     // - sizeof(src)
10315     else if (referToTheSameDecl(SizeOfArg, SrcArg))
10316       PatternType = 2;
10317   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
10318     if (BE->getOpcode() == BO_Sub) {
10319       const Expr *L = BE->getLHS()->IgnoreParenCasts();
10320       const Expr *R = BE->getRHS()->IgnoreParenCasts();
10321       // - sizeof(dst) - strlen(dst)
10322       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
10323           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
10324         PatternType = 1;
10325       // - sizeof(src) - (anything)
10326       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
10327         PatternType = 2;
10328     }
10329   }
10330 
10331   if (PatternType == 0)
10332     return;
10333 
10334   // Generate the diagnostic.
10335   SourceLocation SL = LenArg->getBeginLoc();
10336   SourceRange SR = LenArg->getSourceRange();
10337   SourceManager &SM = getSourceManager();
10338 
10339   // If the function is defined as a builtin macro, do not show macro expansion.
10340   if (SM.isMacroArgExpansion(SL)) {
10341     SL = SM.getSpellingLoc(SL);
10342     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
10343                      SM.getSpellingLoc(SR.getEnd()));
10344   }
10345 
10346   // Check if the destination is an array (rather than a pointer to an array).
10347   QualType DstTy = DstArg->getType();
10348   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
10349                                                                     Context);
10350   if (!isKnownSizeArray) {
10351     if (PatternType == 1)
10352       Diag(SL, diag::warn_strncat_wrong_size) << SR;
10353     else
10354       Diag(SL, diag::warn_strncat_src_size) << SR;
10355     return;
10356   }
10357 
10358   if (PatternType == 1)
10359     Diag(SL, diag::warn_strncat_large_size) << SR;
10360   else
10361     Diag(SL, diag::warn_strncat_src_size) << SR;
10362 
10363   SmallString<128> sizeString;
10364   llvm::raw_svector_ostream OS(sizeString);
10365   OS << "sizeof(";
10366   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10367   OS << ") - ";
10368   OS << "strlen(";
10369   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10370   OS << ") - 1";
10371 
10372   Diag(SL, diag::note_strncat_wrong_size)
10373     << FixItHint::CreateReplacement(SR, OS.str());
10374 }
10375 
10376 namespace {
10377 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
10378                                 const UnaryOperator *UnaryExpr, const Decl *D) {
10379   if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) {
10380     S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
10381         << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
10382     return;
10383   }
10384 }
10385 
10386 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
10387                                  const UnaryOperator *UnaryExpr) {
10388   if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
10389     const Decl *D = Lvalue->getDecl();
10390     if (isa<VarDecl, FunctionDecl>(D))
10391       return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
10392   }
10393 
10394   if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
10395     return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
10396                                       Lvalue->getMemberDecl());
10397 }
10398 
10399 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
10400                             const UnaryOperator *UnaryExpr) {
10401   const auto *Lambda = dyn_cast<LambdaExpr>(
10402       UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens());
10403   if (!Lambda)
10404     return;
10405 
10406   S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
10407       << CalleeName << 2 /*object: lambda expression*/;
10408 }
10409 
10410 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
10411                                   const DeclRefExpr *Lvalue) {
10412   const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
10413   if (Var == nullptr)
10414     return;
10415 
10416   S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
10417       << CalleeName << 0 /*object: */ << Var;
10418 }
10419 
10420 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
10421                             const CastExpr *Cast) {
10422   SmallString<128> SizeString;
10423   llvm::raw_svector_ostream OS(SizeString);
10424 
10425   clang::CastKind Kind = Cast->getCastKind();
10426   if (Kind == clang::CK_BitCast &&
10427       !Cast->getSubExpr()->getType()->isFunctionPointerType())
10428     return;
10429   if (Kind == clang::CK_IntegralToPointer &&
10430       !isa<IntegerLiteral>(
10431           Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
10432     return;
10433 
10434   switch (Cast->getCastKind()) {
10435   case clang::CK_BitCast:
10436   case clang::CK_IntegralToPointer:
10437   case clang::CK_FunctionToPointerDecay:
10438     OS << '\'';
10439     Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
10440     OS << '\'';
10441     break;
10442   default:
10443     return;
10444   }
10445 
10446   S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
10447       << CalleeName << 0 /*object: */ << OS.str();
10448 }
10449 } // namespace
10450 
10451 /// Alerts the user that they are attempting to free a non-malloc'd object.
10452 void Sema::CheckFreeArguments(const CallExpr *E) {
10453   const std::string CalleeName =
10454       dyn_cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
10455 
10456   { // Prefer something that doesn't involve a cast to make things simpler.
10457     const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
10458     if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
10459       switch (UnaryExpr->getOpcode()) {
10460       case UnaryOperator::Opcode::UO_AddrOf:
10461         return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
10462       case UnaryOperator::Opcode::UO_Plus:
10463         return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
10464       default:
10465         break;
10466       }
10467 
10468     if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
10469       if (Lvalue->getType()->isArrayType())
10470         return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
10471 
10472     if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
10473       Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
10474           << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
10475       return;
10476     }
10477 
10478     if (isa<BlockExpr>(Arg)) {
10479       Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
10480           << CalleeName << 1 /*object: block*/;
10481       return;
10482     }
10483   }
10484   // Maybe the cast was important, check after the other cases.
10485   if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
10486     return CheckFreeArgumentsCast(*this, CalleeName, Cast);
10487 }
10488 
10489 void
10490 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
10491                          SourceLocation ReturnLoc,
10492                          bool isObjCMethod,
10493                          const AttrVec *Attrs,
10494                          const FunctionDecl *FD) {
10495   // Check if the return value is null but should not be.
10496   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
10497        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
10498       CheckNonNullExpr(*this, RetValExp))
10499     Diag(ReturnLoc, diag::warn_null_ret)
10500       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
10501 
10502   // C++11 [basic.stc.dynamic.allocation]p4:
10503   //   If an allocation function declared with a non-throwing
10504   //   exception-specification fails to allocate storage, it shall return
10505   //   a null pointer. Any other allocation function that fails to allocate
10506   //   storage shall indicate failure only by throwing an exception [...]
10507   if (FD) {
10508     OverloadedOperatorKind Op = FD->getOverloadedOperator();
10509     if (Op == OO_New || Op == OO_Array_New) {
10510       const FunctionProtoType *Proto
10511         = FD->getType()->castAs<FunctionProtoType>();
10512       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
10513           CheckNonNullExpr(*this, RetValExp))
10514         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
10515           << FD << getLangOpts().CPlusPlus11;
10516     }
10517   }
10518 
10519   // PPC MMA non-pointer types are not allowed as return type. Checking the type
10520   // here prevent the user from using a PPC MMA type as trailing return type.
10521   if (Context.getTargetInfo().getTriple().isPPC64())
10522     CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
10523 }
10524 
10525 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
10526 
10527 /// Check for comparisons of floating point operands using != and ==.
10528 /// Issue a warning if these are no self-comparisons, as they are not likely
10529 /// to do what the programmer intended.
10530 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
10531   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
10532   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
10533 
10534   // Special case: check for x == x (which is OK).
10535   // Do not emit warnings for such cases.
10536   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
10537     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
10538       if (DRL->getDecl() == DRR->getDecl())
10539         return;
10540 
10541   // Special case: check for comparisons against literals that can be exactly
10542   //  represented by APFloat.  In such cases, do not emit a warning.  This
10543   //  is a heuristic: often comparison against such literals are used to
10544   //  detect if a value in a variable has not changed.  This clearly can
10545   //  lead to false negatives.
10546   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
10547     if (FLL->isExact())
10548       return;
10549   } else
10550     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
10551       if (FLR->isExact())
10552         return;
10553 
10554   // Check for comparisons with builtin types.
10555   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
10556     if (CL->getBuiltinCallee())
10557       return;
10558 
10559   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
10560     if (CR->getBuiltinCallee())
10561       return;
10562 
10563   // Emit the diagnostic.
10564   Diag(Loc, diag::warn_floatingpoint_eq)
10565     << LHS->getSourceRange() << RHS->getSourceRange();
10566 }
10567 
10568 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
10569 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
10570 
10571 namespace {
10572 
10573 /// Structure recording the 'active' range of an integer-valued
10574 /// expression.
10575 struct IntRange {
10576   /// The number of bits active in the int. Note that this includes exactly one
10577   /// sign bit if !NonNegative.
10578   unsigned Width;
10579 
10580   /// True if the int is known not to have negative values. If so, all leading
10581   /// bits before Width are known zero, otherwise they are known to be the
10582   /// same as the MSB within Width.
10583   bool NonNegative;
10584 
10585   IntRange(unsigned Width, bool NonNegative)
10586       : Width(Width), NonNegative(NonNegative) {}
10587 
10588   /// Number of bits excluding the sign bit.
10589   unsigned valueBits() const {
10590     return NonNegative ? Width : Width - 1;
10591   }
10592 
10593   /// Returns the range of the bool type.
10594   static IntRange forBoolType() {
10595     return IntRange(1, true);
10596   }
10597 
10598   /// Returns the range of an opaque value of the given integral type.
10599   static IntRange forValueOfType(ASTContext &C, QualType T) {
10600     return forValueOfCanonicalType(C,
10601                           T->getCanonicalTypeInternal().getTypePtr());
10602   }
10603 
10604   /// Returns the range of an opaque value of a canonical integral type.
10605   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
10606     assert(T->isCanonicalUnqualified());
10607 
10608     if (const VectorType *VT = dyn_cast<VectorType>(T))
10609       T = VT->getElementType().getTypePtr();
10610     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
10611       T = CT->getElementType().getTypePtr();
10612     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
10613       T = AT->getValueType().getTypePtr();
10614 
10615     if (!C.getLangOpts().CPlusPlus) {
10616       // For enum types in C code, use the underlying datatype.
10617       if (const EnumType *ET = dyn_cast<EnumType>(T))
10618         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
10619     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
10620       // For enum types in C++, use the known bit width of the enumerators.
10621       EnumDecl *Enum = ET->getDecl();
10622       // In C++11, enums can have a fixed underlying type. Use this type to
10623       // compute the range.
10624       if (Enum->isFixed()) {
10625         return IntRange(C.getIntWidth(QualType(T, 0)),
10626                         !ET->isSignedIntegerOrEnumerationType());
10627       }
10628 
10629       unsigned NumPositive = Enum->getNumPositiveBits();
10630       unsigned NumNegative = Enum->getNumNegativeBits();
10631 
10632       if (NumNegative == 0)
10633         return IntRange(NumPositive, true/*NonNegative*/);
10634       else
10635         return IntRange(std::max(NumPositive + 1, NumNegative),
10636                         false/*NonNegative*/);
10637     }
10638 
10639     if (const auto *EIT = dyn_cast<ExtIntType>(T))
10640       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
10641 
10642     const BuiltinType *BT = cast<BuiltinType>(T);
10643     assert(BT->isInteger());
10644 
10645     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10646   }
10647 
10648   /// Returns the "target" range of a canonical integral type, i.e.
10649   /// the range of values expressible in the type.
10650   ///
10651   /// This matches forValueOfCanonicalType except that enums have the
10652   /// full range of their type, not the range of their enumerators.
10653   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
10654     assert(T->isCanonicalUnqualified());
10655 
10656     if (const VectorType *VT = dyn_cast<VectorType>(T))
10657       T = VT->getElementType().getTypePtr();
10658     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
10659       T = CT->getElementType().getTypePtr();
10660     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
10661       T = AT->getValueType().getTypePtr();
10662     if (const EnumType *ET = dyn_cast<EnumType>(T))
10663       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
10664 
10665     if (const auto *EIT = dyn_cast<ExtIntType>(T))
10666       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
10667 
10668     const BuiltinType *BT = cast<BuiltinType>(T);
10669     assert(BT->isInteger());
10670 
10671     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10672   }
10673 
10674   /// Returns the supremum of two ranges: i.e. their conservative merge.
10675   static IntRange join(IntRange L, IntRange R) {
10676     bool Unsigned = L.NonNegative && R.NonNegative;
10677     return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
10678                     L.NonNegative && R.NonNegative);
10679   }
10680 
10681   /// Return the range of a bitwise-AND of the two ranges.
10682   static IntRange bit_and(IntRange L, IntRange R) {
10683     unsigned Bits = std::max(L.Width, R.Width);
10684     bool NonNegative = false;
10685     if (L.NonNegative) {
10686       Bits = std::min(Bits, L.Width);
10687       NonNegative = true;
10688     }
10689     if (R.NonNegative) {
10690       Bits = std::min(Bits, R.Width);
10691       NonNegative = true;
10692     }
10693     return IntRange(Bits, NonNegative);
10694   }
10695 
10696   /// Return the range of a sum of the two ranges.
10697   static IntRange sum(IntRange L, IntRange R) {
10698     bool Unsigned = L.NonNegative && R.NonNegative;
10699     return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
10700                     Unsigned);
10701   }
10702 
10703   /// Return the range of a difference of the two ranges.
10704   static IntRange difference(IntRange L, IntRange R) {
10705     // We need a 1-bit-wider range if:
10706     //   1) LHS can be negative: least value can be reduced.
10707     //   2) RHS can be negative: greatest value can be increased.
10708     bool CanWiden = !L.NonNegative || !R.NonNegative;
10709     bool Unsigned = L.NonNegative && R.Width == 0;
10710     return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
10711                         !Unsigned,
10712                     Unsigned);
10713   }
10714 
10715   /// Return the range of a product of the two ranges.
10716   static IntRange product(IntRange L, IntRange R) {
10717     // If both LHS and RHS can be negative, we can form
10718     //   -2^L * -2^R = 2^(L + R)
10719     // which requires L + R + 1 value bits to represent.
10720     bool CanWiden = !L.NonNegative && !R.NonNegative;
10721     bool Unsigned = L.NonNegative && R.NonNegative;
10722     return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
10723                     Unsigned);
10724   }
10725 
10726   /// Return the range of a remainder operation between the two ranges.
10727   static IntRange rem(IntRange L, IntRange R) {
10728     // The result of a remainder can't be larger than the result of
10729     // either side. The sign of the result is the sign of the LHS.
10730     bool Unsigned = L.NonNegative;
10731     return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
10732                     Unsigned);
10733   }
10734 };
10735 
10736 } // namespace
10737 
10738 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
10739                               unsigned MaxWidth) {
10740   if (value.isSigned() && value.isNegative())
10741     return IntRange(value.getMinSignedBits(), false);
10742 
10743   if (value.getBitWidth() > MaxWidth)
10744     value = value.trunc(MaxWidth);
10745 
10746   // isNonNegative() just checks the sign bit without considering
10747   // signedness.
10748   return IntRange(value.getActiveBits(), true);
10749 }
10750 
10751 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
10752                               unsigned MaxWidth) {
10753   if (result.isInt())
10754     return GetValueRange(C, result.getInt(), MaxWidth);
10755 
10756   if (result.isVector()) {
10757     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
10758     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
10759       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
10760       R = IntRange::join(R, El);
10761     }
10762     return R;
10763   }
10764 
10765   if (result.isComplexInt()) {
10766     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
10767     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
10768     return IntRange::join(R, I);
10769   }
10770 
10771   // This can happen with lossless casts to intptr_t of "based" lvalues.
10772   // Assume it might use arbitrary bits.
10773   // FIXME: The only reason we need to pass the type in here is to get
10774   // the sign right on this one case.  It would be nice if APValue
10775   // preserved this.
10776   assert(result.isLValue() || result.isAddrLabelDiff());
10777   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
10778 }
10779 
10780 static QualType GetExprType(const Expr *E) {
10781   QualType Ty = E->getType();
10782   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
10783     Ty = AtomicRHS->getValueType();
10784   return Ty;
10785 }
10786 
10787 /// Pseudo-evaluate the given integer expression, estimating the
10788 /// range of values it might take.
10789 ///
10790 /// \param MaxWidth The width to which the value will be truncated.
10791 /// \param Approximate If \c true, return a likely range for the result: in
10792 ///        particular, assume that aritmetic on narrower types doesn't leave
10793 ///        those types. If \c false, return a range including all possible
10794 ///        result values.
10795 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
10796                              bool InConstantContext, bool Approximate) {
10797   E = E->IgnoreParens();
10798 
10799   // Try a full evaluation first.
10800   Expr::EvalResult result;
10801   if (E->EvaluateAsRValue(result, C, InConstantContext))
10802     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
10803 
10804   // I think we only want to look through implicit casts here; if the
10805   // user has an explicit widening cast, we should treat the value as
10806   // being of the new, wider type.
10807   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
10808     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
10809       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
10810                           Approximate);
10811 
10812     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
10813 
10814     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
10815                          CE->getCastKind() == CK_BooleanToSignedIntegral;
10816 
10817     // Assume that non-integer casts can span the full range of the type.
10818     if (!isIntegerCast)
10819       return OutputTypeRange;
10820 
10821     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
10822                                      std::min(MaxWidth, OutputTypeRange.Width),
10823                                      InConstantContext, Approximate);
10824 
10825     // Bail out if the subexpr's range is as wide as the cast type.
10826     if (SubRange.Width >= OutputTypeRange.Width)
10827       return OutputTypeRange;
10828 
10829     // Otherwise, we take the smaller width, and we're non-negative if
10830     // either the output type or the subexpr is.
10831     return IntRange(SubRange.Width,
10832                     SubRange.NonNegative || OutputTypeRange.NonNegative);
10833   }
10834 
10835   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
10836     // If we can fold the condition, just take that operand.
10837     bool CondResult;
10838     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
10839       return GetExprRange(C,
10840                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
10841                           MaxWidth, InConstantContext, Approximate);
10842 
10843     // Otherwise, conservatively merge.
10844     // GetExprRange requires an integer expression, but a throw expression
10845     // results in a void type.
10846     Expr *E = CO->getTrueExpr();
10847     IntRange L = E->getType()->isVoidType()
10848                      ? IntRange{0, true}
10849                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
10850     E = CO->getFalseExpr();
10851     IntRange R = E->getType()->isVoidType()
10852                      ? IntRange{0, true}
10853                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
10854     return IntRange::join(L, R);
10855   }
10856 
10857   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
10858     IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
10859 
10860     switch (BO->getOpcode()) {
10861     case BO_Cmp:
10862       llvm_unreachable("builtin <=> should have class type");
10863 
10864     // Boolean-valued operations are single-bit and positive.
10865     case BO_LAnd:
10866     case BO_LOr:
10867     case BO_LT:
10868     case BO_GT:
10869     case BO_LE:
10870     case BO_GE:
10871     case BO_EQ:
10872     case BO_NE:
10873       return IntRange::forBoolType();
10874 
10875     // The type of the assignments is the type of the LHS, so the RHS
10876     // is not necessarily the same type.
10877     case BO_MulAssign:
10878     case BO_DivAssign:
10879     case BO_RemAssign:
10880     case BO_AddAssign:
10881     case BO_SubAssign:
10882     case BO_XorAssign:
10883     case BO_OrAssign:
10884       // TODO: bitfields?
10885       return IntRange::forValueOfType(C, GetExprType(E));
10886 
10887     // Simple assignments just pass through the RHS, which will have
10888     // been coerced to the LHS type.
10889     case BO_Assign:
10890       // TODO: bitfields?
10891       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
10892                           Approximate);
10893 
10894     // Operations with opaque sources are black-listed.
10895     case BO_PtrMemD:
10896     case BO_PtrMemI:
10897       return IntRange::forValueOfType(C, GetExprType(E));
10898 
10899     // Bitwise-and uses the *infinum* of the two source ranges.
10900     case BO_And:
10901     case BO_AndAssign:
10902       Combine = IntRange::bit_and;
10903       break;
10904 
10905     // Left shift gets black-listed based on a judgement call.
10906     case BO_Shl:
10907       // ...except that we want to treat '1 << (blah)' as logically
10908       // positive.  It's an important idiom.
10909       if (IntegerLiteral *I
10910             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
10911         if (I->getValue() == 1) {
10912           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
10913           return IntRange(R.Width, /*NonNegative*/ true);
10914         }
10915       }
10916       LLVM_FALLTHROUGH;
10917 
10918     case BO_ShlAssign:
10919       return IntRange::forValueOfType(C, GetExprType(E));
10920 
10921     // Right shift by a constant can narrow its left argument.
10922     case BO_Shr:
10923     case BO_ShrAssign: {
10924       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext,
10925                                 Approximate);
10926 
10927       // If the shift amount is a positive constant, drop the width by
10928       // that much.
10929       if (Optional<llvm::APSInt> shift =
10930               BO->getRHS()->getIntegerConstantExpr(C)) {
10931         if (shift->isNonNegative()) {
10932           unsigned zext = shift->getZExtValue();
10933           if (zext >= L.Width)
10934             L.Width = (L.NonNegative ? 0 : 1);
10935           else
10936             L.Width -= zext;
10937         }
10938       }
10939 
10940       return L;
10941     }
10942 
10943     // Comma acts as its right operand.
10944     case BO_Comma:
10945       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
10946                           Approximate);
10947 
10948     case BO_Add:
10949       if (!Approximate)
10950         Combine = IntRange::sum;
10951       break;
10952 
10953     case BO_Sub:
10954       if (BO->getLHS()->getType()->isPointerType())
10955         return IntRange::forValueOfType(C, GetExprType(E));
10956       if (!Approximate)
10957         Combine = IntRange::difference;
10958       break;
10959 
10960     case BO_Mul:
10961       if (!Approximate)
10962         Combine = IntRange::product;
10963       break;
10964 
10965     // The width of a division result is mostly determined by the size
10966     // of the LHS.
10967     case BO_Div: {
10968       // Don't 'pre-truncate' the operands.
10969       unsigned opWidth = C.getIntWidth(GetExprType(E));
10970       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext,
10971                                 Approximate);
10972 
10973       // If the divisor is constant, use that.
10974       if (Optional<llvm::APSInt> divisor =
10975               BO->getRHS()->getIntegerConstantExpr(C)) {
10976         unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
10977         if (log2 >= L.Width)
10978           L.Width = (L.NonNegative ? 0 : 1);
10979         else
10980           L.Width = std::min(L.Width - log2, MaxWidth);
10981         return L;
10982       }
10983 
10984       // Otherwise, just use the LHS's width.
10985       // FIXME: This is wrong if the LHS could be its minimal value and the RHS
10986       // could be -1.
10987       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext,
10988                                 Approximate);
10989       return IntRange(L.Width, L.NonNegative && R.NonNegative);
10990     }
10991 
10992     case BO_Rem:
10993       Combine = IntRange::rem;
10994       break;
10995 
10996     // The default behavior is okay for these.
10997     case BO_Xor:
10998     case BO_Or:
10999       break;
11000     }
11001 
11002     // Combine the two ranges, but limit the result to the type in which we
11003     // performed the computation.
11004     QualType T = GetExprType(E);
11005     unsigned opWidth = C.getIntWidth(T);
11006     IntRange L =
11007         GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate);
11008     IntRange R =
11009         GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate);
11010     IntRange C = Combine(L, R);
11011     C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
11012     C.Width = std::min(C.Width, MaxWidth);
11013     return C;
11014   }
11015 
11016   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
11017     switch (UO->getOpcode()) {
11018     // Boolean-valued operations are white-listed.
11019     case UO_LNot:
11020       return IntRange::forBoolType();
11021 
11022     // Operations with opaque sources are black-listed.
11023     case UO_Deref:
11024     case UO_AddrOf: // should be impossible
11025       return IntRange::forValueOfType(C, GetExprType(E));
11026 
11027     default:
11028       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11029                           Approximate);
11030     }
11031   }
11032 
11033   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
11034     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
11035                         Approximate);
11036 
11037   if (const auto *BitField = E->getSourceBitField())
11038     return IntRange(BitField->getBitWidthValue(C),
11039                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
11040 
11041   return IntRange::forValueOfType(C, GetExprType(E));
11042 }
11043 
11044 static IntRange GetExprRange(ASTContext &C, const Expr *E,
11045                              bool InConstantContext, bool Approximate) {
11046   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
11047                       Approximate);
11048 }
11049 
11050 /// Checks whether the given value, which currently has the given
11051 /// source semantics, has the same value when coerced through the
11052 /// target semantics.
11053 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
11054                                  const llvm::fltSemantics &Src,
11055                                  const llvm::fltSemantics &Tgt) {
11056   llvm::APFloat truncated = value;
11057 
11058   bool ignored;
11059   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
11060   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
11061 
11062   return truncated.bitwiseIsEqual(value);
11063 }
11064 
11065 /// Checks whether the given value, which currently has the given
11066 /// source semantics, has the same value when coerced through the
11067 /// target semantics.
11068 ///
11069 /// The value might be a vector of floats (or a complex number).
11070 static bool IsSameFloatAfterCast(const APValue &value,
11071                                  const llvm::fltSemantics &Src,
11072                                  const llvm::fltSemantics &Tgt) {
11073   if (value.isFloat())
11074     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
11075 
11076   if (value.isVector()) {
11077     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
11078       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
11079         return false;
11080     return true;
11081   }
11082 
11083   assert(value.isComplexFloat());
11084   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
11085           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
11086 }
11087 
11088 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
11089                                        bool IsListInit = false);
11090 
11091 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
11092   // Suppress cases where we are comparing against an enum constant.
11093   if (const DeclRefExpr *DR =
11094       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
11095     if (isa<EnumConstantDecl>(DR->getDecl()))
11096       return true;
11097 
11098   // Suppress cases where the value is expanded from a macro, unless that macro
11099   // is how a language represents a boolean literal. This is the case in both C
11100   // and Objective-C.
11101   SourceLocation BeginLoc = E->getBeginLoc();
11102   if (BeginLoc.isMacroID()) {
11103     StringRef MacroName = Lexer::getImmediateMacroName(
11104         BeginLoc, S.getSourceManager(), S.getLangOpts());
11105     return MacroName != "YES" && MacroName != "NO" &&
11106            MacroName != "true" && MacroName != "false";
11107   }
11108 
11109   return false;
11110 }
11111 
11112 static bool isKnownToHaveUnsignedValue(Expr *E) {
11113   return E->getType()->isIntegerType() &&
11114          (!E->getType()->isSignedIntegerType() ||
11115           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
11116 }
11117 
11118 namespace {
11119 /// The promoted range of values of a type. In general this has the
11120 /// following structure:
11121 ///
11122 ///     |-----------| . . . |-----------|
11123 ///     ^           ^       ^           ^
11124 ///    Min       HoleMin  HoleMax      Max
11125 ///
11126 /// ... where there is only a hole if a signed type is promoted to unsigned
11127 /// (in which case Min and Max are the smallest and largest representable
11128 /// values).
11129 struct PromotedRange {
11130   // Min, or HoleMax if there is a hole.
11131   llvm::APSInt PromotedMin;
11132   // Max, or HoleMin if there is a hole.
11133   llvm::APSInt PromotedMax;
11134 
11135   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
11136     if (R.Width == 0)
11137       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
11138     else if (R.Width >= BitWidth && !Unsigned) {
11139       // Promotion made the type *narrower*. This happens when promoting
11140       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
11141       // Treat all values of 'signed int' as being in range for now.
11142       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
11143       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
11144     } else {
11145       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
11146                         .extOrTrunc(BitWidth);
11147       PromotedMin.setIsUnsigned(Unsigned);
11148 
11149       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
11150                         .extOrTrunc(BitWidth);
11151       PromotedMax.setIsUnsigned(Unsigned);
11152     }
11153   }
11154 
11155   // Determine whether this range is contiguous (has no hole).
11156   bool isContiguous() const { return PromotedMin <= PromotedMax; }
11157 
11158   // Where a constant value is within the range.
11159   enum ComparisonResult {
11160     LT = 0x1,
11161     LE = 0x2,
11162     GT = 0x4,
11163     GE = 0x8,
11164     EQ = 0x10,
11165     NE = 0x20,
11166     InRangeFlag = 0x40,
11167 
11168     Less = LE | LT | NE,
11169     Min = LE | InRangeFlag,
11170     InRange = InRangeFlag,
11171     Max = GE | InRangeFlag,
11172     Greater = GE | GT | NE,
11173 
11174     OnlyValue = LE | GE | EQ | InRangeFlag,
11175     InHole = NE
11176   };
11177 
11178   ComparisonResult compare(const llvm::APSInt &Value) const {
11179     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
11180            Value.isUnsigned() == PromotedMin.isUnsigned());
11181     if (!isContiguous()) {
11182       assert(Value.isUnsigned() && "discontiguous range for signed compare");
11183       if (Value.isMinValue()) return Min;
11184       if (Value.isMaxValue()) return Max;
11185       if (Value >= PromotedMin) return InRange;
11186       if (Value <= PromotedMax) return InRange;
11187       return InHole;
11188     }
11189 
11190     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
11191     case -1: return Less;
11192     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
11193     case 1:
11194       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
11195       case -1: return InRange;
11196       case 0: return Max;
11197       case 1: return Greater;
11198       }
11199     }
11200 
11201     llvm_unreachable("impossible compare result");
11202   }
11203 
11204   static llvm::Optional<StringRef>
11205   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
11206     if (Op == BO_Cmp) {
11207       ComparisonResult LTFlag = LT, GTFlag = GT;
11208       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
11209 
11210       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
11211       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
11212       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
11213       return llvm::None;
11214     }
11215 
11216     ComparisonResult TrueFlag, FalseFlag;
11217     if (Op == BO_EQ) {
11218       TrueFlag = EQ;
11219       FalseFlag = NE;
11220     } else if (Op == BO_NE) {
11221       TrueFlag = NE;
11222       FalseFlag = EQ;
11223     } else {
11224       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
11225         TrueFlag = LT;
11226         FalseFlag = GE;
11227       } else {
11228         TrueFlag = GT;
11229         FalseFlag = LE;
11230       }
11231       if (Op == BO_GE || Op == BO_LE)
11232         std::swap(TrueFlag, FalseFlag);
11233     }
11234     if (R & TrueFlag)
11235       return StringRef("true");
11236     if (R & FalseFlag)
11237       return StringRef("false");
11238     return llvm::None;
11239   }
11240 };
11241 }
11242 
11243 static bool HasEnumType(Expr *E) {
11244   // Strip off implicit integral promotions.
11245   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
11246     if (ICE->getCastKind() != CK_IntegralCast &&
11247         ICE->getCastKind() != CK_NoOp)
11248       break;
11249     E = ICE->getSubExpr();
11250   }
11251 
11252   return E->getType()->isEnumeralType();
11253 }
11254 
11255 static int classifyConstantValue(Expr *Constant) {
11256   // The values of this enumeration are used in the diagnostics
11257   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
11258   enum ConstantValueKind {
11259     Miscellaneous = 0,
11260     LiteralTrue,
11261     LiteralFalse
11262   };
11263   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
11264     return BL->getValue() ? ConstantValueKind::LiteralTrue
11265                           : ConstantValueKind::LiteralFalse;
11266   return ConstantValueKind::Miscellaneous;
11267 }
11268 
11269 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
11270                                         Expr *Constant, Expr *Other,
11271                                         const llvm::APSInt &Value,
11272                                         bool RhsConstant) {
11273   if (S.inTemplateInstantiation())
11274     return false;
11275 
11276   Expr *OriginalOther = Other;
11277 
11278   Constant = Constant->IgnoreParenImpCasts();
11279   Other = Other->IgnoreParenImpCasts();
11280 
11281   // Suppress warnings on tautological comparisons between values of the same
11282   // enumeration type. There are only two ways we could warn on this:
11283   //  - If the constant is outside the range of representable values of
11284   //    the enumeration. In such a case, we should warn about the cast
11285   //    to enumeration type, not about the comparison.
11286   //  - If the constant is the maximum / minimum in-range value. For an
11287   //    enumeratin type, such comparisons can be meaningful and useful.
11288   if (Constant->getType()->isEnumeralType() &&
11289       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
11290     return false;
11291 
11292   IntRange OtherValueRange = GetExprRange(
11293       S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false);
11294 
11295   QualType OtherT = Other->getType();
11296   if (const auto *AT = OtherT->getAs<AtomicType>())
11297     OtherT = AT->getValueType();
11298   IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
11299 
11300   // Special case for ObjC BOOL on targets where its a typedef for a signed char
11301   // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
11302   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
11303                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
11304                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
11305 
11306   // Whether we're treating Other as being a bool because of the form of
11307   // expression despite it having another type (typically 'int' in C).
11308   bool OtherIsBooleanDespiteType =
11309       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
11310   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
11311     OtherTypeRange = OtherValueRange = IntRange::forBoolType();
11312 
11313   // Check if all values in the range of possible values of this expression
11314   // lead to the same comparison outcome.
11315   PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(),
11316                                         Value.isUnsigned());
11317   auto Cmp = OtherPromotedValueRange.compare(Value);
11318   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
11319   if (!Result)
11320     return false;
11321 
11322   // Also consider the range determined by the type alone. This allows us to
11323   // classify the warning under the proper diagnostic group.
11324   bool TautologicalTypeCompare = false;
11325   {
11326     PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
11327                                          Value.isUnsigned());
11328     auto TypeCmp = OtherPromotedTypeRange.compare(Value);
11329     if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
11330                                                        RhsConstant)) {
11331       TautologicalTypeCompare = true;
11332       Cmp = TypeCmp;
11333       Result = TypeResult;
11334     }
11335   }
11336 
11337   // Don't warn if the non-constant operand actually always evaluates to the
11338   // same value.
11339   if (!TautologicalTypeCompare && OtherValueRange.Width == 0)
11340     return false;
11341 
11342   // Suppress the diagnostic for an in-range comparison if the constant comes
11343   // from a macro or enumerator. We don't want to diagnose
11344   //
11345   //   some_long_value <= INT_MAX
11346   //
11347   // when sizeof(int) == sizeof(long).
11348   bool InRange = Cmp & PromotedRange::InRangeFlag;
11349   if (InRange && IsEnumConstOrFromMacro(S, Constant))
11350     return false;
11351 
11352   // A comparison of an unsigned bit-field against 0 is really a type problem,
11353   // even though at the type level the bit-field might promote to 'signed int'.
11354   if (Other->refersToBitField() && InRange && Value == 0 &&
11355       Other->getType()->isUnsignedIntegerOrEnumerationType())
11356     TautologicalTypeCompare = true;
11357 
11358   // If this is a comparison to an enum constant, include that
11359   // constant in the diagnostic.
11360   const EnumConstantDecl *ED = nullptr;
11361   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
11362     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
11363 
11364   // Should be enough for uint128 (39 decimal digits)
11365   SmallString<64> PrettySourceValue;
11366   llvm::raw_svector_ostream OS(PrettySourceValue);
11367   if (ED) {
11368     OS << '\'' << *ED << "' (" << Value << ")";
11369   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
11370                Constant->IgnoreParenImpCasts())) {
11371     OS << (BL->getValue() ? "YES" : "NO");
11372   } else {
11373     OS << Value;
11374   }
11375 
11376   if (!TautologicalTypeCompare) {
11377     S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
11378         << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative
11379         << E->getOpcodeStr() << OS.str() << *Result
11380         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11381     return true;
11382   }
11383 
11384   if (IsObjCSignedCharBool) {
11385     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
11386                           S.PDiag(diag::warn_tautological_compare_objc_bool)
11387                               << OS.str() << *Result);
11388     return true;
11389   }
11390 
11391   // FIXME: We use a somewhat different formatting for the in-range cases and
11392   // cases involving boolean values for historical reasons. We should pick a
11393   // consistent way of presenting these diagnostics.
11394   if (!InRange || Other->isKnownToHaveBooleanValue()) {
11395 
11396     S.DiagRuntimeBehavior(
11397         E->getOperatorLoc(), E,
11398         S.PDiag(!InRange ? diag::warn_out_of_range_compare
11399                          : diag::warn_tautological_bool_compare)
11400             << OS.str() << classifyConstantValue(Constant) << OtherT
11401             << OtherIsBooleanDespiteType << *Result
11402             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
11403   } else {
11404     unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
11405                         ? (HasEnumType(OriginalOther)
11406                                ? diag::warn_unsigned_enum_always_true_comparison
11407                                : diag::warn_unsigned_always_true_comparison)
11408                         : diag::warn_tautological_constant_compare;
11409 
11410     S.Diag(E->getOperatorLoc(), Diag)
11411         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
11412         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11413   }
11414 
11415   return true;
11416 }
11417 
11418 /// Analyze the operands of the given comparison.  Implements the
11419 /// fallback case from AnalyzeComparison.
11420 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
11421   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11422   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11423 }
11424 
11425 /// Implements -Wsign-compare.
11426 ///
11427 /// \param E the binary operator to check for warnings
11428 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
11429   // The type the comparison is being performed in.
11430   QualType T = E->getLHS()->getType();
11431 
11432   // Only analyze comparison operators where both sides have been converted to
11433   // the same type.
11434   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
11435     return AnalyzeImpConvsInComparison(S, E);
11436 
11437   // Don't analyze value-dependent comparisons directly.
11438   if (E->isValueDependent())
11439     return AnalyzeImpConvsInComparison(S, E);
11440 
11441   Expr *LHS = E->getLHS();
11442   Expr *RHS = E->getRHS();
11443 
11444   if (T->isIntegralType(S.Context)) {
11445     Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context);
11446     Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context);
11447 
11448     // We don't care about expressions whose result is a constant.
11449     if (RHSValue && LHSValue)
11450       return AnalyzeImpConvsInComparison(S, E);
11451 
11452     // We only care about expressions where just one side is literal
11453     if ((bool)RHSValue ^ (bool)LHSValue) {
11454       // Is the constant on the RHS or LHS?
11455       const bool RhsConstant = (bool)RHSValue;
11456       Expr *Const = RhsConstant ? RHS : LHS;
11457       Expr *Other = RhsConstant ? LHS : RHS;
11458       const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
11459 
11460       // Check whether an integer constant comparison results in a value
11461       // of 'true' or 'false'.
11462       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
11463         return AnalyzeImpConvsInComparison(S, E);
11464     }
11465   }
11466 
11467   if (!T->hasUnsignedIntegerRepresentation()) {
11468     // We don't do anything special if this isn't an unsigned integral
11469     // comparison:  we're only interested in integral comparisons, and
11470     // signed comparisons only happen in cases we don't care to warn about.
11471     return AnalyzeImpConvsInComparison(S, E);
11472   }
11473 
11474   LHS = LHS->IgnoreParenImpCasts();
11475   RHS = RHS->IgnoreParenImpCasts();
11476 
11477   if (!S.getLangOpts().CPlusPlus) {
11478     // Avoid warning about comparison of integers with different signs when
11479     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
11480     // the type of `E`.
11481     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
11482       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11483     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
11484       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11485   }
11486 
11487   // Check to see if one of the (unmodified) operands is of different
11488   // signedness.
11489   Expr *signedOperand, *unsignedOperand;
11490   if (LHS->getType()->hasSignedIntegerRepresentation()) {
11491     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
11492            "unsigned comparison between two signed integer expressions?");
11493     signedOperand = LHS;
11494     unsignedOperand = RHS;
11495   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
11496     signedOperand = RHS;
11497     unsignedOperand = LHS;
11498   } else {
11499     return AnalyzeImpConvsInComparison(S, E);
11500   }
11501 
11502   // Otherwise, calculate the effective range of the signed operand.
11503   IntRange signedRange = GetExprRange(
11504       S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true);
11505 
11506   // Go ahead and analyze implicit conversions in the operands.  Note
11507   // that we skip the implicit conversions on both sides.
11508   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
11509   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
11510 
11511   // If the signed range is non-negative, -Wsign-compare won't fire.
11512   if (signedRange.NonNegative)
11513     return;
11514 
11515   // For (in)equality comparisons, if the unsigned operand is a
11516   // constant which cannot collide with a overflowed signed operand,
11517   // then reinterpreting the signed operand as unsigned will not
11518   // change the result of the comparison.
11519   if (E->isEqualityOp()) {
11520     unsigned comparisonWidth = S.Context.getIntWidth(T);
11521     IntRange unsignedRange =
11522         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(),
11523                      /*Approximate*/ true);
11524 
11525     // We should never be unable to prove that the unsigned operand is
11526     // non-negative.
11527     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
11528 
11529     if (unsignedRange.Width < comparisonWidth)
11530       return;
11531   }
11532 
11533   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
11534                         S.PDiag(diag::warn_mixed_sign_comparison)
11535                             << LHS->getType() << RHS->getType()
11536                             << LHS->getSourceRange() << RHS->getSourceRange());
11537 }
11538 
11539 /// Analyzes an attempt to assign the given value to a bitfield.
11540 ///
11541 /// Returns true if there was something fishy about the attempt.
11542 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
11543                                       SourceLocation InitLoc) {
11544   assert(Bitfield->isBitField());
11545   if (Bitfield->isInvalidDecl())
11546     return false;
11547 
11548   // White-list bool bitfields.
11549   QualType BitfieldType = Bitfield->getType();
11550   if (BitfieldType->isBooleanType())
11551      return false;
11552 
11553   if (BitfieldType->isEnumeralType()) {
11554     EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
11555     // If the underlying enum type was not explicitly specified as an unsigned
11556     // type and the enum contain only positive values, MSVC++ will cause an
11557     // inconsistency by storing this as a signed type.
11558     if (S.getLangOpts().CPlusPlus11 &&
11559         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
11560         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
11561         BitfieldEnumDecl->getNumNegativeBits() == 0) {
11562       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
11563           << BitfieldEnumDecl;
11564     }
11565   }
11566 
11567   if (Bitfield->getType()->isBooleanType())
11568     return false;
11569 
11570   // Ignore value- or type-dependent expressions.
11571   if (Bitfield->getBitWidth()->isValueDependent() ||
11572       Bitfield->getBitWidth()->isTypeDependent() ||
11573       Init->isValueDependent() ||
11574       Init->isTypeDependent())
11575     return false;
11576 
11577   Expr *OriginalInit = Init->IgnoreParenImpCasts();
11578   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
11579 
11580   Expr::EvalResult Result;
11581   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
11582                                    Expr::SE_AllowSideEffects)) {
11583     // The RHS is not constant.  If the RHS has an enum type, make sure the
11584     // bitfield is wide enough to hold all the values of the enum without
11585     // truncation.
11586     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
11587       EnumDecl *ED = EnumTy->getDecl();
11588       bool SignedBitfield = BitfieldType->isSignedIntegerType();
11589 
11590       // Enum types are implicitly signed on Windows, so check if there are any
11591       // negative enumerators to see if the enum was intended to be signed or
11592       // not.
11593       bool SignedEnum = ED->getNumNegativeBits() > 0;
11594 
11595       // Check for surprising sign changes when assigning enum values to a
11596       // bitfield of different signedness.  If the bitfield is signed and we
11597       // have exactly the right number of bits to store this unsigned enum,
11598       // suggest changing the enum to an unsigned type. This typically happens
11599       // on Windows where unfixed enums always use an underlying type of 'int'.
11600       unsigned DiagID = 0;
11601       if (SignedEnum && !SignedBitfield) {
11602         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
11603       } else if (SignedBitfield && !SignedEnum &&
11604                  ED->getNumPositiveBits() == FieldWidth) {
11605         DiagID = diag::warn_signed_bitfield_enum_conversion;
11606       }
11607 
11608       if (DiagID) {
11609         S.Diag(InitLoc, DiagID) << Bitfield << ED;
11610         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
11611         SourceRange TypeRange =
11612             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
11613         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
11614             << SignedEnum << TypeRange;
11615       }
11616 
11617       // Compute the required bitwidth. If the enum has negative values, we need
11618       // one more bit than the normal number of positive bits to represent the
11619       // sign bit.
11620       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
11621                                                   ED->getNumNegativeBits())
11622                                        : ED->getNumPositiveBits();
11623 
11624       // Check the bitwidth.
11625       if (BitsNeeded > FieldWidth) {
11626         Expr *WidthExpr = Bitfield->getBitWidth();
11627         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
11628             << Bitfield << ED;
11629         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
11630             << BitsNeeded << ED << WidthExpr->getSourceRange();
11631       }
11632     }
11633 
11634     return false;
11635   }
11636 
11637   llvm::APSInt Value = Result.Val.getInt();
11638 
11639   unsigned OriginalWidth = Value.getBitWidth();
11640 
11641   if (!Value.isSigned() || Value.isNegative())
11642     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
11643       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
11644         OriginalWidth = Value.getMinSignedBits();
11645 
11646   if (OriginalWidth <= FieldWidth)
11647     return false;
11648 
11649   // Compute the value which the bitfield will contain.
11650   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
11651   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
11652 
11653   // Check whether the stored value is equal to the original value.
11654   TruncatedValue = TruncatedValue.extend(OriginalWidth);
11655   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
11656     return false;
11657 
11658   // Special-case bitfields of width 1: booleans are naturally 0/1, and
11659   // therefore don't strictly fit into a signed bitfield of width 1.
11660   if (FieldWidth == 1 && Value == 1)
11661     return false;
11662 
11663   std::string PrettyValue = Value.toString(10);
11664   std::string PrettyTrunc = TruncatedValue.toString(10);
11665 
11666   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
11667     << PrettyValue << PrettyTrunc << OriginalInit->getType()
11668     << Init->getSourceRange();
11669 
11670   return true;
11671 }
11672 
11673 /// Analyze the given simple or compound assignment for warning-worthy
11674 /// operations.
11675 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
11676   // Just recurse on the LHS.
11677   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11678 
11679   // We want to recurse on the RHS as normal unless we're assigning to
11680   // a bitfield.
11681   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
11682     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
11683                                   E->getOperatorLoc())) {
11684       // Recurse, ignoring any implicit conversions on the RHS.
11685       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
11686                                         E->getOperatorLoc());
11687     }
11688   }
11689 
11690   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11691 
11692   // Diagnose implicitly sequentially-consistent atomic assignment.
11693   if (E->getLHS()->getType()->isAtomicType())
11694     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
11695 }
11696 
11697 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
11698 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
11699                             SourceLocation CContext, unsigned diag,
11700                             bool pruneControlFlow = false) {
11701   if (pruneControlFlow) {
11702     S.DiagRuntimeBehavior(E->getExprLoc(), E,
11703                           S.PDiag(diag)
11704                               << SourceType << T << E->getSourceRange()
11705                               << SourceRange(CContext));
11706     return;
11707   }
11708   S.Diag(E->getExprLoc(), diag)
11709     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
11710 }
11711 
11712 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
11713 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
11714                             SourceLocation CContext,
11715                             unsigned diag, bool pruneControlFlow = false) {
11716   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
11717 }
11718 
11719 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
11720   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
11721       S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
11722 }
11723 
11724 static void adornObjCBoolConversionDiagWithTernaryFixit(
11725     Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
11726   Expr *Ignored = SourceExpr->IgnoreImplicit();
11727   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
11728     Ignored = OVE->getSourceExpr();
11729   bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
11730                      isa<BinaryOperator>(Ignored) ||
11731                      isa<CXXOperatorCallExpr>(Ignored);
11732   SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
11733   if (NeedsParens)
11734     Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
11735             << FixItHint::CreateInsertion(EndLoc, ")");
11736   Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
11737 }
11738 
11739 /// Diagnose an implicit cast from a floating point value to an integer value.
11740 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
11741                                     SourceLocation CContext) {
11742   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
11743   const bool PruneWarnings = S.inTemplateInstantiation();
11744 
11745   Expr *InnerE = E->IgnoreParenImpCasts();
11746   // We also want to warn on, e.g., "int i = -1.234"
11747   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
11748     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
11749       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
11750 
11751   const bool IsLiteral =
11752       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
11753 
11754   llvm::APFloat Value(0.0);
11755   bool IsConstant =
11756     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
11757   if (!IsConstant) {
11758     if (isObjCSignedCharBool(S, T)) {
11759       return adornObjCBoolConversionDiagWithTernaryFixit(
11760           S, E,
11761           S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
11762               << E->getType());
11763     }
11764 
11765     return DiagnoseImpCast(S, E, T, CContext,
11766                            diag::warn_impcast_float_integer, PruneWarnings);
11767   }
11768 
11769   bool isExact = false;
11770 
11771   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
11772                             T->hasUnsignedIntegerRepresentation());
11773   llvm::APFloat::opStatus Result = Value.convertToInteger(
11774       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
11775 
11776   // FIXME: Force the precision of the source value down so we don't print
11777   // digits which are usually useless (we don't really care here if we
11778   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
11779   // would automatically print the shortest representation, but it's a bit
11780   // tricky to implement.
11781   SmallString<16> PrettySourceValue;
11782   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
11783   precision = (precision * 59 + 195) / 196;
11784   Value.toString(PrettySourceValue, precision);
11785 
11786   if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
11787     return adornObjCBoolConversionDiagWithTernaryFixit(
11788         S, E,
11789         S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
11790             << PrettySourceValue);
11791   }
11792 
11793   if (Result == llvm::APFloat::opOK && isExact) {
11794     if (IsLiteral) return;
11795     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
11796                            PruneWarnings);
11797   }
11798 
11799   // Conversion of a floating-point value to a non-bool integer where the
11800   // integral part cannot be represented by the integer type is undefined.
11801   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
11802     return DiagnoseImpCast(
11803         S, E, T, CContext,
11804         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
11805                   : diag::warn_impcast_float_to_integer_out_of_range,
11806         PruneWarnings);
11807 
11808   unsigned DiagID = 0;
11809   if (IsLiteral) {
11810     // Warn on floating point literal to integer.
11811     DiagID = diag::warn_impcast_literal_float_to_integer;
11812   } else if (IntegerValue == 0) {
11813     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
11814       return DiagnoseImpCast(S, E, T, CContext,
11815                              diag::warn_impcast_float_integer, PruneWarnings);
11816     }
11817     // Warn on non-zero to zero conversion.
11818     DiagID = diag::warn_impcast_float_to_integer_zero;
11819   } else {
11820     if (IntegerValue.isUnsigned()) {
11821       if (!IntegerValue.isMaxValue()) {
11822         return DiagnoseImpCast(S, E, T, CContext,
11823                                diag::warn_impcast_float_integer, PruneWarnings);
11824       }
11825     } else {  // IntegerValue.isSigned()
11826       if (!IntegerValue.isMaxSignedValue() &&
11827           !IntegerValue.isMinSignedValue()) {
11828         return DiagnoseImpCast(S, E, T, CContext,
11829                                diag::warn_impcast_float_integer, PruneWarnings);
11830       }
11831     }
11832     // Warn on evaluatable floating point expression to integer conversion.
11833     DiagID = diag::warn_impcast_float_to_integer;
11834   }
11835 
11836   SmallString<16> PrettyTargetValue;
11837   if (IsBool)
11838     PrettyTargetValue = Value.isZero() ? "false" : "true";
11839   else
11840     IntegerValue.toString(PrettyTargetValue);
11841 
11842   if (PruneWarnings) {
11843     S.DiagRuntimeBehavior(E->getExprLoc(), E,
11844                           S.PDiag(DiagID)
11845                               << E->getType() << T.getUnqualifiedType()
11846                               << PrettySourceValue << PrettyTargetValue
11847                               << E->getSourceRange() << SourceRange(CContext));
11848   } else {
11849     S.Diag(E->getExprLoc(), DiagID)
11850         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
11851         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
11852   }
11853 }
11854 
11855 /// Analyze the given compound assignment for the possible losing of
11856 /// floating-point precision.
11857 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
11858   assert(isa<CompoundAssignOperator>(E) &&
11859          "Must be compound assignment operation");
11860   // Recurse on the LHS and RHS in here
11861   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11862   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11863 
11864   if (E->getLHS()->getType()->isAtomicType())
11865     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
11866 
11867   // Now check the outermost expression
11868   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
11869   const auto *RBT = cast<CompoundAssignOperator>(E)
11870                         ->getComputationResultType()
11871                         ->getAs<BuiltinType>();
11872 
11873   // The below checks assume source is floating point.
11874   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
11875 
11876   // If source is floating point but target is an integer.
11877   if (ResultBT->isInteger())
11878     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
11879                            E->getExprLoc(), diag::warn_impcast_float_integer);
11880 
11881   if (!ResultBT->isFloatingPoint())
11882     return;
11883 
11884   // If both source and target are floating points, warn about losing precision.
11885   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
11886       QualType(ResultBT, 0), QualType(RBT, 0));
11887   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
11888     // warn about dropping FP rank.
11889     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
11890                     diag::warn_impcast_float_result_precision);
11891 }
11892 
11893 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
11894                                       IntRange Range) {
11895   if (!Range.Width) return "0";
11896 
11897   llvm::APSInt ValueInRange = Value;
11898   ValueInRange.setIsSigned(!Range.NonNegative);
11899   ValueInRange = ValueInRange.trunc(Range.Width);
11900   return ValueInRange.toString(10);
11901 }
11902 
11903 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
11904   if (!isa<ImplicitCastExpr>(Ex))
11905     return false;
11906 
11907   Expr *InnerE = Ex->IgnoreParenImpCasts();
11908   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
11909   const Type *Source =
11910     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
11911   if (Target->isDependentType())
11912     return false;
11913 
11914   const BuiltinType *FloatCandidateBT =
11915     dyn_cast<BuiltinType>(ToBool ? Source : Target);
11916   const Type *BoolCandidateType = ToBool ? Target : Source;
11917 
11918   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
11919           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
11920 }
11921 
11922 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
11923                                              SourceLocation CC) {
11924   unsigned NumArgs = TheCall->getNumArgs();
11925   for (unsigned i = 0; i < NumArgs; ++i) {
11926     Expr *CurrA = TheCall->getArg(i);
11927     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
11928       continue;
11929 
11930     bool IsSwapped = ((i > 0) &&
11931         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
11932     IsSwapped |= ((i < (NumArgs - 1)) &&
11933         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
11934     if (IsSwapped) {
11935       // Warn on this floating-point to bool conversion.
11936       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
11937                       CurrA->getType(), CC,
11938                       diag::warn_impcast_floating_point_to_bool);
11939     }
11940   }
11941 }
11942 
11943 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
11944                                    SourceLocation CC) {
11945   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
11946                         E->getExprLoc()))
11947     return;
11948 
11949   // Don't warn on functions which have return type nullptr_t.
11950   if (isa<CallExpr>(E))
11951     return;
11952 
11953   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
11954   const Expr::NullPointerConstantKind NullKind =
11955       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
11956   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
11957     return;
11958 
11959   // Return if target type is a safe conversion.
11960   if (T->isAnyPointerType() || T->isBlockPointerType() ||
11961       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
11962     return;
11963 
11964   SourceLocation Loc = E->getSourceRange().getBegin();
11965 
11966   // Venture through the macro stacks to get to the source of macro arguments.
11967   // The new location is a better location than the complete location that was
11968   // passed in.
11969   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
11970   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
11971 
11972   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
11973   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
11974     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
11975         Loc, S.SourceMgr, S.getLangOpts());
11976     if (MacroName == "NULL")
11977       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
11978   }
11979 
11980   // Only warn if the null and context location are in the same macro expansion.
11981   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
11982     return;
11983 
11984   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
11985       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
11986       << FixItHint::CreateReplacement(Loc,
11987                                       S.getFixItZeroLiteralForType(T, Loc));
11988 }
11989 
11990 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
11991                                   ObjCArrayLiteral *ArrayLiteral);
11992 
11993 static void
11994 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
11995                            ObjCDictionaryLiteral *DictionaryLiteral);
11996 
11997 /// Check a single element within a collection literal against the
11998 /// target element type.
11999 static void checkObjCCollectionLiteralElement(Sema &S,
12000                                               QualType TargetElementType,
12001                                               Expr *Element,
12002                                               unsigned ElementKind) {
12003   // Skip a bitcast to 'id' or qualified 'id'.
12004   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
12005     if (ICE->getCastKind() == CK_BitCast &&
12006         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
12007       Element = ICE->getSubExpr();
12008   }
12009 
12010   QualType ElementType = Element->getType();
12011   ExprResult ElementResult(Element);
12012   if (ElementType->getAs<ObjCObjectPointerType>() &&
12013       S.CheckSingleAssignmentConstraints(TargetElementType,
12014                                          ElementResult,
12015                                          false, false)
12016         != Sema::Compatible) {
12017     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
12018         << ElementType << ElementKind << TargetElementType
12019         << Element->getSourceRange();
12020   }
12021 
12022   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
12023     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
12024   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
12025     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
12026 }
12027 
12028 /// Check an Objective-C array literal being converted to the given
12029 /// target type.
12030 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12031                                   ObjCArrayLiteral *ArrayLiteral) {
12032   if (!S.NSArrayDecl)
12033     return;
12034 
12035   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12036   if (!TargetObjCPtr)
12037     return;
12038 
12039   if (TargetObjCPtr->isUnspecialized() ||
12040       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12041         != S.NSArrayDecl->getCanonicalDecl())
12042     return;
12043 
12044   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12045   if (TypeArgs.size() != 1)
12046     return;
12047 
12048   QualType TargetElementType = TypeArgs[0];
12049   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
12050     checkObjCCollectionLiteralElement(S, TargetElementType,
12051                                       ArrayLiteral->getElement(I),
12052                                       0);
12053   }
12054 }
12055 
12056 /// Check an Objective-C dictionary literal being converted to the given
12057 /// target type.
12058 static void
12059 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12060                            ObjCDictionaryLiteral *DictionaryLiteral) {
12061   if (!S.NSDictionaryDecl)
12062     return;
12063 
12064   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12065   if (!TargetObjCPtr)
12066     return;
12067 
12068   if (TargetObjCPtr->isUnspecialized() ||
12069       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12070         != S.NSDictionaryDecl->getCanonicalDecl())
12071     return;
12072 
12073   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12074   if (TypeArgs.size() != 2)
12075     return;
12076 
12077   QualType TargetKeyType = TypeArgs[0];
12078   QualType TargetObjectType = TypeArgs[1];
12079   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
12080     auto Element = DictionaryLiteral->getKeyValueElement(I);
12081     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
12082     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
12083   }
12084 }
12085 
12086 // Helper function to filter out cases for constant width constant conversion.
12087 // Don't warn on char array initialization or for non-decimal values.
12088 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
12089                                           SourceLocation CC) {
12090   // If initializing from a constant, and the constant starts with '0',
12091   // then it is a binary, octal, or hexadecimal.  Allow these constants
12092   // to fill all the bits, even if there is a sign change.
12093   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
12094     const char FirstLiteralCharacter =
12095         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
12096     if (FirstLiteralCharacter == '0')
12097       return false;
12098   }
12099 
12100   // If the CC location points to a '{', and the type is char, then assume
12101   // assume it is an array initialization.
12102   if (CC.isValid() && T->isCharType()) {
12103     const char FirstContextCharacter =
12104         S.getSourceManager().getCharacterData(CC)[0];
12105     if (FirstContextCharacter == '{')
12106       return false;
12107   }
12108 
12109   return true;
12110 }
12111 
12112 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
12113   const auto *IL = dyn_cast<IntegerLiteral>(E);
12114   if (!IL) {
12115     if (auto *UO = dyn_cast<UnaryOperator>(E)) {
12116       if (UO->getOpcode() == UO_Minus)
12117         return dyn_cast<IntegerLiteral>(UO->getSubExpr());
12118     }
12119   }
12120 
12121   return IL;
12122 }
12123 
12124 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
12125   E = E->IgnoreParenImpCasts();
12126   SourceLocation ExprLoc = E->getExprLoc();
12127 
12128   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
12129     BinaryOperator::Opcode Opc = BO->getOpcode();
12130     Expr::EvalResult Result;
12131     // Do not diagnose unsigned shifts.
12132     if (Opc == BO_Shl) {
12133       const auto *LHS = getIntegerLiteral(BO->getLHS());
12134       const auto *RHS = getIntegerLiteral(BO->getRHS());
12135       if (LHS && LHS->getValue() == 0)
12136         S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
12137       else if (!E->isValueDependent() && LHS && RHS &&
12138                RHS->getValue().isNonNegative() &&
12139                E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
12140         S.Diag(ExprLoc, diag::warn_left_shift_always)
12141             << (Result.Val.getInt() != 0);
12142       else if (E->getType()->isSignedIntegerType())
12143         S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
12144     }
12145   }
12146 
12147   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
12148     const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
12149     const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
12150     if (!LHS || !RHS)
12151       return;
12152     if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
12153         (RHS->getValue() == 0 || RHS->getValue() == 1))
12154       // Do not diagnose common idioms.
12155       return;
12156     if (LHS->getValue() != 0 && RHS->getValue() != 0)
12157       S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
12158   }
12159 }
12160 
12161 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
12162                                     SourceLocation CC,
12163                                     bool *ICContext = nullptr,
12164                                     bool IsListInit = false) {
12165   if (E->isTypeDependent() || E->isValueDependent()) return;
12166 
12167   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
12168   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
12169   if (Source == Target) return;
12170   if (Target->isDependentType()) return;
12171 
12172   // If the conversion context location is invalid don't complain. We also
12173   // don't want to emit a warning if the issue occurs from the expansion of
12174   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
12175   // delay this check as long as possible. Once we detect we are in that
12176   // scenario, we just return.
12177   if (CC.isInvalid())
12178     return;
12179 
12180   if (Source->isAtomicType())
12181     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
12182 
12183   // Diagnose implicit casts to bool.
12184   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
12185     if (isa<StringLiteral>(E))
12186       // Warn on string literal to bool.  Checks for string literals in logical
12187       // and expressions, for instance, assert(0 && "error here"), are
12188       // prevented by a check in AnalyzeImplicitConversions().
12189       return DiagnoseImpCast(S, E, T, CC,
12190                              diag::warn_impcast_string_literal_to_bool);
12191     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
12192         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
12193       // This covers the literal expressions that evaluate to Objective-C
12194       // objects.
12195       return DiagnoseImpCast(S, E, T, CC,
12196                              diag::warn_impcast_objective_c_literal_to_bool);
12197     }
12198     if (Source->isPointerType() || Source->canDecayToPointerType()) {
12199       // Warn on pointer to bool conversion that is always true.
12200       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
12201                                      SourceRange(CC));
12202     }
12203   }
12204 
12205   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
12206   // is a typedef for signed char (macOS), then that constant value has to be 1
12207   // or 0.
12208   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
12209     Expr::EvalResult Result;
12210     if (E->EvaluateAsInt(Result, S.getASTContext(),
12211                          Expr::SE_AllowSideEffects)) {
12212       if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
12213         adornObjCBoolConversionDiagWithTernaryFixit(
12214             S, E,
12215             S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
12216                 << Result.Val.getInt().toString(10));
12217       }
12218       return;
12219     }
12220   }
12221 
12222   // Check implicit casts from Objective-C collection literals to specialized
12223   // collection types, e.g., NSArray<NSString *> *.
12224   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
12225     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
12226   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
12227     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
12228 
12229   // Strip vector types.
12230   if (const auto *SourceVT = dyn_cast<VectorType>(Source)) {
12231     if (Target->isVLSTBuiltinType()) {
12232       auto SourceVectorKind = SourceVT->getVectorKind();
12233       if (SourceVectorKind == VectorType::SveFixedLengthDataVector ||
12234           SourceVectorKind == VectorType::SveFixedLengthPredicateVector ||
12235           (SourceVectorKind == VectorType::GenericVector &&
12236            S.Context.getTypeSize(Source) == S.getLangOpts().ArmSveVectorBits))
12237         return;
12238     }
12239 
12240     if (!isa<VectorType>(Target)) {
12241       if (S.SourceMgr.isInSystemMacro(CC))
12242         return;
12243       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
12244     }
12245 
12246     // If the vector cast is cast between two vectors of the same size, it is
12247     // a bitcast, not a conversion.
12248     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
12249       return;
12250 
12251     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
12252     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
12253   }
12254   if (auto VecTy = dyn_cast<VectorType>(Target))
12255     Target = VecTy->getElementType().getTypePtr();
12256 
12257   // Strip complex types.
12258   if (isa<ComplexType>(Source)) {
12259     if (!isa<ComplexType>(Target)) {
12260       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
12261         return;
12262 
12263       return DiagnoseImpCast(S, E, T, CC,
12264                              S.getLangOpts().CPlusPlus
12265                                  ? diag::err_impcast_complex_scalar
12266                                  : diag::warn_impcast_complex_scalar);
12267     }
12268 
12269     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
12270     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
12271   }
12272 
12273   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
12274   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
12275 
12276   // If the source is floating point...
12277   if (SourceBT && SourceBT->isFloatingPoint()) {
12278     // ...and the target is floating point...
12279     if (TargetBT && TargetBT->isFloatingPoint()) {
12280       // ...then warn if we're dropping FP rank.
12281 
12282       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12283           QualType(SourceBT, 0), QualType(TargetBT, 0));
12284       if (Order > 0) {
12285         // Don't warn about float constants that are precisely
12286         // representable in the target type.
12287         Expr::EvalResult result;
12288         if (E->EvaluateAsRValue(result, S.Context)) {
12289           // Value might be a float, a float vector, or a float complex.
12290           if (IsSameFloatAfterCast(result.Val,
12291                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
12292                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
12293             return;
12294         }
12295 
12296         if (S.SourceMgr.isInSystemMacro(CC))
12297           return;
12298 
12299         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
12300       }
12301       // ... or possibly if we're increasing rank, too
12302       else if (Order < 0) {
12303         if (S.SourceMgr.isInSystemMacro(CC))
12304           return;
12305 
12306         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
12307       }
12308       return;
12309     }
12310 
12311     // If the target is integral, always warn.
12312     if (TargetBT && TargetBT->isInteger()) {
12313       if (S.SourceMgr.isInSystemMacro(CC))
12314         return;
12315 
12316       DiagnoseFloatingImpCast(S, E, T, CC);
12317     }
12318 
12319     // Detect the case where a call result is converted from floating-point to
12320     // to bool, and the final argument to the call is converted from bool, to
12321     // discover this typo:
12322     //
12323     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
12324     //
12325     // FIXME: This is an incredibly special case; is there some more general
12326     // way to detect this class of misplaced-parentheses bug?
12327     if (Target->isBooleanType() && isa<CallExpr>(E)) {
12328       // Check last argument of function call to see if it is an
12329       // implicit cast from a type matching the type the result
12330       // is being cast to.
12331       CallExpr *CEx = cast<CallExpr>(E);
12332       if (unsigned NumArgs = CEx->getNumArgs()) {
12333         Expr *LastA = CEx->getArg(NumArgs - 1);
12334         Expr *InnerE = LastA->IgnoreParenImpCasts();
12335         if (isa<ImplicitCastExpr>(LastA) &&
12336             InnerE->getType()->isBooleanType()) {
12337           // Warn on this floating-point to bool conversion
12338           DiagnoseImpCast(S, E, T, CC,
12339                           diag::warn_impcast_floating_point_to_bool);
12340         }
12341       }
12342     }
12343     return;
12344   }
12345 
12346   // Valid casts involving fixed point types should be accounted for here.
12347   if (Source->isFixedPointType()) {
12348     if (Target->isUnsaturatedFixedPointType()) {
12349       Expr::EvalResult Result;
12350       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
12351                                   S.isConstantEvaluated())) {
12352         llvm::APFixedPoint Value = Result.Val.getFixedPoint();
12353         llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
12354         llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T);
12355         if (Value > MaxVal || Value < MinVal) {
12356           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12357                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12358                                     << Value.toString() << T
12359                                     << E->getSourceRange()
12360                                     << clang::SourceRange(CC));
12361           return;
12362         }
12363       }
12364     } else if (Target->isIntegerType()) {
12365       Expr::EvalResult Result;
12366       if (!S.isConstantEvaluated() &&
12367           E->EvaluateAsFixedPoint(Result, S.Context,
12368                                   Expr::SE_AllowSideEffects)) {
12369         llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
12370 
12371         bool Overflowed;
12372         llvm::APSInt IntResult = FXResult.convertToInt(
12373             S.Context.getIntWidth(T),
12374             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
12375 
12376         if (Overflowed) {
12377           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12378                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12379                                     << FXResult.toString() << T
12380                                     << E->getSourceRange()
12381                                     << clang::SourceRange(CC));
12382           return;
12383         }
12384       }
12385     }
12386   } else if (Target->isUnsaturatedFixedPointType()) {
12387     if (Source->isIntegerType()) {
12388       Expr::EvalResult Result;
12389       if (!S.isConstantEvaluated() &&
12390           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
12391         llvm::APSInt Value = Result.Val.getInt();
12392 
12393         bool Overflowed;
12394         llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
12395             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
12396 
12397         if (Overflowed) {
12398           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12399                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12400                                     << Value.toString(/*Radix=*/10) << T
12401                                     << E->getSourceRange()
12402                                     << clang::SourceRange(CC));
12403           return;
12404         }
12405       }
12406     }
12407   }
12408 
12409   // If we are casting an integer type to a floating point type without
12410   // initialization-list syntax, we might lose accuracy if the floating
12411   // point type has a narrower significand than the integer type.
12412   if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
12413       TargetBT->isFloatingType() && !IsListInit) {
12414     // Determine the number of precision bits in the source integer type.
12415     IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(),
12416                                         /*Approximate*/ true);
12417     unsigned int SourcePrecision = SourceRange.Width;
12418 
12419     // Determine the number of precision bits in the
12420     // target floating point type.
12421     unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
12422         S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12423 
12424     if (SourcePrecision > 0 && TargetPrecision > 0 &&
12425         SourcePrecision > TargetPrecision) {
12426 
12427       if (Optional<llvm::APSInt> SourceInt =
12428               E->getIntegerConstantExpr(S.Context)) {
12429         // If the source integer is a constant, convert it to the target
12430         // floating point type. Issue a warning if the value changes
12431         // during the whole conversion.
12432         llvm::APFloat TargetFloatValue(
12433             S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12434         llvm::APFloat::opStatus ConversionStatus =
12435             TargetFloatValue.convertFromAPInt(
12436                 *SourceInt, SourceBT->isSignedInteger(),
12437                 llvm::APFloat::rmNearestTiesToEven);
12438 
12439         if (ConversionStatus != llvm::APFloat::opOK) {
12440           std::string PrettySourceValue = SourceInt->toString(10);
12441           SmallString<32> PrettyTargetValue;
12442           TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
12443 
12444           S.DiagRuntimeBehavior(
12445               E->getExprLoc(), E,
12446               S.PDiag(diag::warn_impcast_integer_float_precision_constant)
12447                   << PrettySourceValue << PrettyTargetValue << E->getType() << T
12448                   << E->getSourceRange() << clang::SourceRange(CC));
12449         }
12450       } else {
12451         // Otherwise, the implicit conversion may lose precision.
12452         DiagnoseImpCast(S, E, T, CC,
12453                         diag::warn_impcast_integer_float_precision);
12454       }
12455     }
12456   }
12457 
12458   DiagnoseNullConversion(S, E, T, CC);
12459 
12460   S.DiscardMisalignedMemberAddress(Target, E);
12461 
12462   if (Target->isBooleanType())
12463     DiagnoseIntInBoolContext(S, E);
12464 
12465   if (!Source->isIntegerType() || !Target->isIntegerType())
12466     return;
12467 
12468   // TODO: remove this early return once the false positives for constant->bool
12469   // in templates, macros, etc, are reduced or removed.
12470   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
12471     return;
12472 
12473   if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
12474       !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
12475     return adornObjCBoolConversionDiagWithTernaryFixit(
12476         S, E,
12477         S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
12478             << E->getType());
12479   }
12480 
12481   IntRange SourceTypeRange =
12482       IntRange::forTargetOfCanonicalType(S.Context, Source);
12483   IntRange LikelySourceRange =
12484       GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true);
12485   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
12486 
12487   if (LikelySourceRange.Width > TargetRange.Width) {
12488     // If the source is a constant, use a default-on diagnostic.
12489     // TODO: this should happen for bitfield stores, too.
12490     Expr::EvalResult Result;
12491     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
12492                          S.isConstantEvaluated())) {
12493       llvm::APSInt Value(32);
12494       Value = Result.Val.getInt();
12495 
12496       if (S.SourceMgr.isInSystemMacro(CC))
12497         return;
12498 
12499       std::string PrettySourceValue = Value.toString(10);
12500       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
12501 
12502       S.DiagRuntimeBehavior(
12503           E->getExprLoc(), E,
12504           S.PDiag(diag::warn_impcast_integer_precision_constant)
12505               << PrettySourceValue << PrettyTargetValue << E->getType() << T
12506               << E->getSourceRange() << SourceRange(CC));
12507       return;
12508     }
12509 
12510     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
12511     if (S.SourceMgr.isInSystemMacro(CC))
12512       return;
12513 
12514     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
12515       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
12516                              /* pruneControlFlow */ true);
12517     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
12518   }
12519 
12520   if (TargetRange.Width > SourceTypeRange.Width) {
12521     if (auto *UO = dyn_cast<UnaryOperator>(E))
12522       if (UO->getOpcode() == UO_Minus)
12523         if (Source->isUnsignedIntegerType()) {
12524           if (Target->isUnsignedIntegerType())
12525             return DiagnoseImpCast(S, E, T, CC,
12526                                    diag::warn_impcast_high_order_zero_bits);
12527           if (Target->isSignedIntegerType())
12528             return DiagnoseImpCast(S, E, T, CC,
12529                                    diag::warn_impcast_nonnegative_result);
12530         }
12531   }
12532 
12533   if (TargetRange.Width == LikelySourceRange.Width &&
12534       !TargetRange.NonNegative && LikelySourceRange.NonNegative &&
12535       Source->isSignedIntegerType()) {
12536     // Warn when doing a signed to signed conversion, warn if the positive
12537     // source value is exactly the width of the target type, which will
12538     // cause a negative value to be stored.
12539 
12540     Expr::EvalResult Result;
12541     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
12542         !S.SourceMgr.isInSystemMacro(CC)) {
12543       llvm::APSInt Value = Result.Val.getInt();
12544       if (isSameWidthConstantConversion(S, E, T, CC)) {
12545         std::string PrettySourceValue = Value.toString(10);
12546         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
12547 
12548         S.DiagRuntimeBehavior(
12549             E->getExprLoc(), E,
12550             S.PDiag(diag::warn_impcast_integer_precision_constant)
12551                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
12552                 << E->getSourceRange() << SourceRange(CC));
12553         return;
12554       }
12555     }
12556 
12557     // Fall through for non-constants to give a sign conversion warning.
12558   }
12559 
12560   if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) ||
12561       (!TargetRange.NonNegative && LikelySourceRange.NonNegative &&
12562        LikelySourceRange.Width == TargetRange.Width)) {
12563     if (S.SourceMgr.isInSystemMacro(CC))
12564       return;
12565 
12566     unsigned DiagID = diag::warn_impcast_integer_sign;
12567 
12568     // Traditionally, gcc has warned about this under -Wsign-compare.
12569     // We also want to warn about it in -Wconversion.
12570     // So if -Wconversion is off, use a completely identical diagnostic
12571     // in the sign-compare group.
12572     // The conditional-checking code will
12573     if (ICContext) {
12574       DiagID = diag::warn_impcast_integer_sign_conditional;
12575       *ICContext = true;
12576     }
12577 
12578     return DiagnoseImpCast(S, E, T, CC, DiagID);
12579   }
12580 
12581   // Diagnose conversions between different enumeration types.
12582   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
12583   // type, to give us better diagnostics.
12584   QualType SourceType = E->getType();
12585   if (!S.getLangOpts().CPlusPlus) {
12586     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12587       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
12588         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
12589         SourceType = S.Context.getTypeDeclType(Enum);
12590         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
12591       }
12592   }
12593 
12594   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
12595     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
12596       if (SourceEnum->getDecl()->hasNameForLinkage() &&
12597           TargetEnum->getDecl()->hasNameForLinkage() &&
12598           SourceEnum != TargetEnum) {
12599         if (S.SourceMgr.isInSystemMacro(CC))
12600           return;
12601 
12602         return DiagnoseImpCast(S, E, SourceType, T, CC,
12603                                diag::warn_impcast_different_enum_types);
12604       }
12605 }
12606 
12607 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
12608                                      SourceLocation CC, QualType T);
12609 
12610 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
12611                                     SourceLocation CC, bool &ICContext) {
12612   E = E->IgnoreParenImpCasts();
12613 
12614   if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
12615     return CheckConditionalOperator(S, CO, CC, T);
12616 
12617   AnalyzeImplicitConversions(S, E, CC);
12618   if (E->getType() != T)
12619     return CheckImplicitConversion(S, E, T, CC, &ICContext);
12620 }
12621 
12622 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
12623                                      SourceLocation CC, QualType T) {
12624   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
12625 
12626   Expr *TrueExpr = E->getTrueExpr();
12627   if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
12628     TrueExpr = BCO->getCommon();
12629 
12630   bool Suspicious = false;
12631   CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
12632   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
12633 
12634   if (T->isBooleanType())
12635     DiagnoseIntInBoolContext(S, E);
12636 
12637   // If -Wconversion would have warned about either of the candidates
12638   // for a signedness conversion to the context type...
12639   if (!Suspicious) return;
12640 
12641   // ...but it's currently ignored...
12642   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
12643     return;
12644 
12645   // ...then check whether it would have warned about either of the
12646   // candidates for a signedness conversion to the condition type.
12647   if (E->getType() == T) return;
12648 
12649   Suspicious = false;
12650   CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(),
12651                           E->getType(), CC, &Suspicious);
12652   if (!Suspicious)
12653     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
12654                             E->getType(), CC, &Suspicious);
12655 }
12656 
12657 /// Check conversion of given expression to boolean.
12658 /// Input argument E is a logical expression.
12659 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
12660   if (S.getLangOpts().Bool)
12661     return;
12662   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
12663     return;
12664   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
12665 }
12666 
12667 namespace {
12668 struct AnalyzeImplicitConversionsWorkItem {
12669   Expr *E;
12670   SourceLocation CC;
12671   bool IsListInit;
12672 };
12673 }
12674 
12675 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
12676 /// that should be visited are added to WorkList.
12677 static void AnalyzeImplicitConversions(
12678     Sema &S, AnalyzeImplicitConversionsWorkItem Item,
12679     llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
12680   Expr *OrigE = Item.E;
12681   SourceLocation CC = Item.CC;
12682 
12683   QualType T = OrigE->getType();
12684   Expr *E = OrigE->IgnoreParenImpCasts();
12685 
12686   // Propagate whether we are in a C++ list initialization expression.
12687   // If so, we do not issue warnings for implicit int-float conversion
12688   // precision loss, because C++11 narrowing already handles it.
12689   bool IsListInit = Item.IsListInit ||
12690                     (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
12691 
12692   if (E->isTypeDependent() || E->isValueDependent())
12693     return;
12694 
12695   Expr *SourceExpr = E;
12696   // Examine, but don't traverse into the source expression of an
12697   // OpaqueValueExpr, since it may have multiple parents and we don't want to
12698   // emit duplicate diagnostics. Its fine to examine the form or attempt to
12699   // evaluate it in the context of checking the specific conversion to T though.
12700   if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
12701     if (auto *Src = OVE->getSourceExpr())
12702       SourceExpr = Src;
12703 
12704   if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
12705     if (UO->getOpcode() == UO_Not &&
12706         UO->getSubExpr()->isKnownToHaveBooleanValue())
12707       S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
12708           << OrigE->getSourceRange() << T->isBooleanType()
12709           << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
12710 
12711   // For conditional operators, we analyze the arguments as if they
12712   // were being fed directly into the output.
12713   if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
12714     CheckConditionalOperator(S, CO, CC, T);
12715     return;
12716   }
12717 
12718   // Check implicit argument conversions for function calls.
12719   if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
12720     CheckImplicitArgumentConversions(S, Call, CC);
12721 
12722   // Go ahead and check any implicit conversions we might have skipped.
12723   // The non-canonical typecheck is just an optimization;
12724   // CheckImplicitConversion will filter out dead implicit conversions.
12725   if (SourceExpr->getType() != T)
12726     CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit);
12727 
12728   // Now continue drilling into this expression.
12729 
12730   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
12731     // The bound subexpressions in a PseudoObjectExpr are not reachable
12732     // as transitive children.
12733     // FIXME: Use a more uniform representation for this.
12734     for (auto *SE : POE->semantics())
12735       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
12736         WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
12737   }
12738 
12739   // Skip past explicit casts.
12740   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
12741     E = CE->getSubExpr()->IgnoreParenImpCasts();
12742     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
12743       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12744     WorkList.push_back({E, CC, IsListInit});
12745     return;
12746   }
12747 
12748   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12749     // Do a somewhat different check with comparison operators.
12750     if (BO->isComparisonOp())
12751       return AnalyzeComparison(S, BO);
12752 
12753     // And with simple assignments.
12754     if (BO->getOpcode() == BO_Assign)
12755       return AnalyzeAssignment(S, BO);
12756     // And with compound assignments.
12757     if (BO->isAssignmentOp())
12758       return AnalyzeCompoundAssignment(S, BO);
12759   }
12760 
12761   // These break the otherwise-useful invariant below.  Fortunately,
12762   // we don't really need to recurse into them, because any internal
12763   // expressions should have been analyzed already when they were
12764   // built into statements.
12765   if (isa<StmtExpr>(E)) return;
12766 
12767   // Don't descend into unevaluated contexts.
12768   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
12769 
12770   // Now just recurse over the expression's children.
12771   CC = E->getExprLoc();
12772   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
12773   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
12774   for (Stmt *SubStmt : E->children()) {
12775     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
12776     if (!ChildExpr)
12777       continue;
12778 
12779     if (IsLogicalAndOperator &&
12780         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
12781       // Ignore checking string literals that are in logical and operators.
12782       // This is a common pattern for asserts.
12783       continue;
12784     WorkList.push_back({ChildExpr, CC, IsListInit});
12785   }
12786 
12787   if (BO && BO->isLogicalOp()) {
12788     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
12789     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
12790       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
12791 
12792     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
12793     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
12794       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
12795   }
12796 
12797   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
12798     if (U->getOpcode() == UO_LNot) {
12799       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
12800     } else if (U->getOpcode() != UO_AddrOf) {
12801       if (U->getSubExpr()->getType()->isAtomicType())
12802         S.Diag(U->getSubExpr()->getBeginLoc(),
12803                diag::warn_atomic_implicit_seq_cst);
12804     }
12805   }
12806 }
12807 
12808 /// AnalyzeImplicitConversions - Find and report any interesting
12809 /// implicit conversions in the given expression.  There are a couple
12810 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
12811 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
12812                                        bool IsListInit/*= false*/) {
12813   llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
12814   WorkList.push_back({OrigE, CC, IsListInit});
12815   while (!WorkList.empty())
12816     AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
12817 }
12818 
12819 /// Diagnose integer type and any valid implicit conversion to it.
12820 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
12821   // Taking into account implicit conversions,
12822   // allow any integer.
12823   if (!E->getType()->isIntegerType()) {
12824     S.Diag(E->getBeginLoc(),
12825            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
12826     return true;
12827   }
12828   // Potentially emit standard warnings for implicit conversions if enabled
12829   // using -Wconversion.
12830   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
12831   return false;
12832 }
12833 
12834 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
12835 // Returns true when emitting a warning about taking the address of a reference.
12836 static bool CheckForReference(Sema &SemaRef, const Expr *E,
12837                               const PartialDiagnostic &PD) {
12838   E = E->IgnoreParenImpCasts();
12839 
12840   const FunctionDecl *FD = nullptr;
12841 
12842   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12843     if (!DRE->getDecl()->getType()->isReferenceType())
12844       return false;
12845   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
12846     if (!M->getMemberDecl()->getType()->isReferenceType())
12847       return false;
12848   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
12849     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
12850       return false;
12851     FD = Call->getDirectCallee();
12852   } else {
12853     return false;
12854   }
12855 
12856   SemaRef.Diag(E->getExprLoc(), PD);
12857 
12858   // If possible, point to location of function.
12859   if (FD) {
12860     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
12861   }
12862 
12863   return true;
12864 }
12865 
12866 // Returns true if the SourceLocation is expanded from any macro body.
12867 // Returns false if the SourceLocation is invalid, is from not in a macro
12868 // expansion, or is from expanded from a top-level macro argument.
12869 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
12870   if (Loc.isInvalid())
12871     return false;
12872 
12873   while (Loc.isMacroID()) {
12874     if (SM.isMacroBodyExpansion(Loc))
12875       return true;
12876     Loc = SM.getImmediateMacroCallerLoc(Loc);
12877   }
12878 
12879   return false;
12880 }
12881 
12882 /// Diagnose pointers that are always non-null.
12883 /// \param E the expression containing the pointer
12884 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
12885 /// compared to a null pointer
12886 /// \param IsEqual True when the comparison is equal to a null pointer
12887 /// \param Range Extra SourceRange to highlight in the diagnostic
12888 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
12889                                         Expr::NullPointerConstantKind NullKind,
12890                                         bool IsEqual, SourceRange Range) {
12891   if (!E)
12892     return;
12893 
12894   // Don't warn inside macros.
12895   if (E->getExprLoc().isMacroID()) {
12896     const SourceManager &SM = getSourceManager();
12897     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
12898         IsInAnyMacroBody(SM, Range.getBegin()))
12899       return;
12900   }
12901   E = E->IgnoreImpCasts();
12902 
12903   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
12904 
12905   if (isa<CXXThisExpr>(E)) {
12906     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
12907                                 : diag::warn_this_bool_conversion;
12908     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
12909     return;
12910   }
12911 
12912   bool IsAddressOf = false;
12913 
12914   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
12915     if (UO->getOpcode() != UO_AddrOf)
12916       return;
12917     IsAddressOf = true;
12918     E = UO->getSubExpr();
12919   }
12920 
12921   if (IsAddressOf) {
12922     unsigned DiagID = IsCompare
12923                           ? diag::warn_address_of_reference_null_compare
12924                           : diag::warn_address_of_reference_bool_conversion;
12925     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
12926                                          << IsEqual;
12927     if (CheckForReference(*this, E, PD)) {
12928       return;
12929     }
12930   }
12931 
12932   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
12933     bool IsParam = isa<NonNullAttr>(NonnullAttr);
12934     std::string Str;
12935     llvm::raw_string_ostream S(Str);
12936     E->printPretty(S, nullptr, getPrintingPolicy());
12937     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
12938                                 : diag::warn_cast_nonnull_to_bool;
12939     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
12940       << E->getSourceRange() << Range << IsEqual;
12941     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
12942   };
12943 
12944   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
12945   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
12946     if (auto *Callee = Call->getDirectCallee()) {
12947       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
12948         ComplainAboutNonnullParamOrCall(A);
12949         return;
12950       }
12951     }
12952   }
12953 
12954   // Expect to find a single Decl.  Skip anything more complicated.
12955   ValueDecl *D = nullptr;
12956   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
12957     D = R->getDecl();
12958   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
12959     D = M->getMemberDecl();
12960   }
12961 
12962   // Weak Decls can be null.
12963   if (!D || D->isWeak())
12964     return;
12965 
12966   // Check for parameter decl with nonnull attribute
12967   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
12968     if (getCurFunction() &&
12969         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
12970       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
12971         ComplainAboutNonnullParamOrCall(A);
12972         return;
12973       }
12974 
12975       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
12976         // Skip function template not specialized yet.
12977         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
12978           return;
12979         auto ParamIter = llvm::find(FD->parameters(), PV);
12980         assert(ParamIter != FD->param_end());
12981         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
12982 
12983         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
12984           if (!NonNull->args_size()) {
12985               ComplainAboutNonnullParamOrCall(NonNull);
12986               return;
12987           }
12988 
12989           for (const ParamIdx &ArgNo : NonNull->args()) {
12990             if (ArgNo.getASTIndex() == ParamNo) {
12991               ComplainAboutNonnullParamOrCall(NonNull);
12992               return;
12993             }
12994           }
12995         }
12996       }
12997     }
12998   }
12999 
13000   QualType T = D->getType();
13001   const bool IsArray = T->isArrayType();
13002   const bool IsFunction = T->isFunctionType();
13003 
13004   // Address of function is used to silence the function warning.
13005   if (IsAddressOf && IsFunction) {
13006     return;
13007   }
13008 
13009   // Found nothing.
13010   if (!IsAddressOf && !IsFunction && !IsArray)
13011     return;
13012 
13013   // Pretty print the expression for the diagnostic.
13014   std::string Str;
13015   llvm::raw_string_ostream S(Str);
13016   E->printPretty(S, nullptr, getPrintingPolicy());
13017 
13018   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
13019                               : diag::warn_impcast_pointer_to_bool;
13020   enum {
13021     AddressOf,
13022     FunctionPointer,
13023     ArrayPointer
13024   } DiagType;
13025   if (IsAddressOf)
13026     DiagType = AddressOf;
13027   else if (IsFunction)
13028     DiagType = FunctionPointer;
13029   else if (IsArray)
13030     DiagType = ArrayPointer;
13031   else
13032     llvm_unreachable("Could not determine diagnostic.");
13033   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
13034                                 << Range << IsEqual;
13035 
13036   if (!IsFunction)
13037     return;
13038 
13039   // Suggest '&' to silence the function warning.
13040   Diag(E->getExprLoc(), diag::note_function_warning_silence)
13041       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
13042 
13043   // Check to see if '()' fixit should be emitted.
13044   QualType ReturnType;
13045   UnresolvedSet<4> NonTemplateOverloads;
13046   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
13047   if (ReturnType.isNull())
13048     return;
13049 
13050   if (IsCompare) {
13051     // There are two cases here.  If there is null constant, the only suggest
13052     // for a pointer return type.  If the null is 0, then suggest if the return
13053     // type is a pointer or an integer type.
13054     if (!ReturnType->isPointerType()) {
13055       if (NullKind == Expr::NPCK_ZeroExpression ||
13056           NullKind == Expr::NPCK_ZeroLiteral) {
13057         if (!ReturnType->isIntegerType())
13058           return;
13059       } else {
13060         return;
13061       }
13062     }
13063   } else { // !IsCompare
13064     // For function to bool, only suggest if the function pointer has bool
13065     // return type.
13066     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
13067       return;
13068   }
13069   Diag(E->getExprLoc(), diag::note_function_to_function_call)
13070       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
13071 }
13072 
13073 /// Diagnoses "dangerous" implicit conversions within the given
13074 /// expression (which is a full expression).  Implements -Wconversion
13075 /// and -Wsign-compare.
13076 ///
13077 /// \param CC the "context" location of the implicit conversion, i.e.
13078 ///   the most location of the syntactic entity requiring the implicit
13079 ///   conversion
13080 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
13081   // Don't diagnose in unevaluated contexts.
13082   if (isUnevaluatedContext())
13083     return;
13084 
13085   // Don't diagnose for value- or type-dependent expressions.
13086   if (E->isTypeDependent() || E->isValueDependent())
13087     return;
13088 
13089   // Check for array bounds violations in cases where the check isn't triggered
13090   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
13091   // ArraySubscriptExpr is on the RHS of a variable initialization.
13092   CheckArrayAccess(E);
13093 
13094   // This is not the right CC for (e.g.) a variable initialization.
13095   AnalyzeImplicitConversions(*this, E, CC);
13096 }
13097 
13098 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
13099 /// Input argument E is a logical expression.
13100 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
13101   ::CheckBoolLikeConversion(*this, E, CC);
13102 }
13103 
13104 /// Diagnose when expression is an integer constant expression and its evaluation
13105 /// results in integer overflow
13106 void Sema::CheckForIntOverflow (Expr *E) {
13107   // Use a work list to deal with nested struct initializers.
13108   SmallVector<Expr *, 2> Exprs(1, E);
13109 
13110   do {
13111     Expr *OriginalE = Exprs.pop_back_val();
13112     Expr *E = OriginalE->IgnoreParenCasts();
13113 
13114     if (isa<BinaryOperator>(E)) {
13115       E->EvaluateForOverflow(Context);
13116       continue;
13117     }
13118 
13119     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
13120       Exprs.append(InitList->inits().begin(), InitList->inits().end());
13121     else if (isa<ObjCBoxedExpr>(OriginalE))
13122       E->EvaluateForOverflow(Context);
13123     else if (auto Call = dyn_cast<CallExpr>(E))
13124       Exprs.append(Call->arg_begin(), Call->arg_end());
13125     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
13126       Exprs.append(Message->arg_begin(), Message->arg_end());
13127   } while (!Exprs.empty());
13128 }
13129 
13130 namespace {
13131 
13132 /// Visitor for expressions which looks for unsequenced operations on the
13133 /// same object.
13134 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
13135   using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
13136 
13137   /// A tree of sequenced regions within an expression. Two regions are
13138   /// unsequenced if one is an ancestor or a descendent of the other. When we
13139   /// finish processing an expression with sequencing, such as a comma
13140   /// expression, we fold its tree nodes into its parent, since they are
13141   /// unsequenced with respect to nodes we will visit later.
13142   class SequenceTree {
13143     struct Value {
13144       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
13145       unsigned Parent : 31;
13146       unsigned Merged : 1;
13147     };
13148     SmallVector<Value, 8> Values;
13149 
13150   public:
13151     /// A region within an expression which may be sequenced with respect
13152     /// to some other region.
13153     class Seq {
13154       friend class SequenceTree;
13155 
13156       unsigned Index;
13157 
13158       explicit Seq(unsigned N) : Index(N) {}
13159 
13160     public:
13161       Seq() : Index(0) {}
13162     };
13163 
13164     SequenceTree() { Values.push_back(Value(0)); }
13165     Seq root() const { return Seq(0); }
13166 
13167     /// Create a new sequence of operations, which is an unsequenced
13168     /// subset of \p Parent. This sequence of operations is sequenced with
13169     /// respect to other children of \p Parent.
13170     Seq allocate(Seq Parent) {
13171       Values.push_back(Value(Parent.Index));
13172       return Seq(Values.size() - 1);
13173     }
13174 
13175     /// Merge a sequence of operations into its parent.
13176     void merge(Seq S) {
13177       Values[S.Index].Merged = true;
13178     }
13179 
13180     /// Determine whether two operations are unsequenced. This operation
13181     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
13182     /// should have been merged into its parent as appropriate.
13183     bool isUnsequenced(Seq Cur, Seq Old) {
13184       unsigned C = representative(Cur.Index);
13185       unsigned Target = representative(Old.Index);
13186       while (C >= Target) {
13187         if (C == Target)
13188           return true;
13189         C = Values[C].Parent;
13190       }
13191       return false;
13192     }
13193 
13194   private:
13195     /// Pick a representative for a sequence.
13196     unsigned representative(unsigned K) {
13197       if (Values[K].Merged)
13198         // Perform path compression as we go.
13199         return Values[K].Parent = representative(Values[K].Parent);
13200       return K;
13201     }
13202   };
13203 
13204   /// An object for which we can track unsequenced uses.
13205   using Object = const NamedDecl *;
13206 
13207   /// Different flavors of object usage which we track. We only track the
13208   /// least-sequenced usage of each kind.
13209   enum UsageKind {
13210     /// A read of an object. Multiple unsequenced reads are OK.
13211     UK_Use,
13212 
13213     /// A modification of an object which is sequenced before the value
13214     /// computation of the expression, such as ++n in C++.
13215     UK_ModAsValue,
13216 
13217     /// A modification of an object which is not sequenced before the value
13218     /// computation of the expression, such as n++.
13219     UK_ModAsSideEffect,
13220 
13221     UK_Count = UK_ModAsSideEffect + 1
13222   };
13223 
13224   /// Bundle together a sequencing region and the expression corresponding
13225   /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
13226   struct Usage {
13227     const Expr *UsageExpr;
13228     SequenceTree::Seq Seq;
13229 
13230     Usage() : UsageExpr(nullptr), Seq() {}
13231   };
13232 
13233   struct UsageInfo {
13234     Usage Uses[UK_Count];
13235 
13236     /// Have we issued a diagnostic for this object already?
13237     bool Diagnosed;
13238 
13239     UsageInfo() : Uses(), Diagnosed(false) {}
13240   };
13241   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
13242 
13243   Sema &SemaRef;
13244 
13245   /// Sequenced regions within the expression.
13246   SequenceTree Tree;
13247 
13248   /// Declaration modifications and references which we have seen.
13249   UsageInfoMap UsageMap;
13250 
13251   /// The region we are currently within.
13252   SequenceTree::Seq Region;
13253 
13254   /// Filled in with declarations which were modified as a side-effect
13255   /// (that is, post-increment operations).
13256   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
13257 
13258   /// Expressions to check later. We defer checking these to reduce
13259   /// stack usage.
13260   SmallVectorImpl<const Expr *> &WorkList;
13261 
13262   /// RAII object wrapping the visitation of a sequenced subexpression of an
13263   /// expression. At the end of this process, the side-effects of the evaluation
13264   /// become sequenced with respect to the value computation of the result, so
13265   /// we downgrade any UK_ModAsSideEffect within the evaluation to
13266   /// UK_ModAsValue.
13267   struct SequencedSubexpression {
13268     SequencedSubexpression(SequenceChecker &Self)
13269       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
13270       Self.ModAsSideEffect = &ModAsSideEffect;
13271     }
13272 
13273     ~SequencedSubexpression() {
13274       for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
13275         // Add a new usage with usage kind UK_ModAsValue, and then restore
13276         // the previous usage with UK_ModAsSideEffect (thus clearing it if
13277         // the previous one was empty).
13278         UsageInfo &UI = Self.UsageMap[M.first];
13279         auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
13280         Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
13281         SideEffectUsage = M.second;
13282       }
13283       Self.ModAsSideEffect = OldModAsSideEffect;
13284     }
13285 
13286     SequenceChecker &Self;
13287     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
13288     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
13289   };
13290 
13291   /// RAII object wrapping the visitation of a subexpression which we might
13292   /// choose to evaluate as a constant. If any subexpression is evaluated and
13293   /// found to be non-constant, this allows us to suppress the evaluation of
13294   /// the outer expression.
13295   class EvaluationTracker {
13296   public:
13297     EvaluationTracker(SequenceChecker &Self)
13298         : Self(Self), Prev(Self.EvalTracker) {
13299       Self.EvalTracker = this;
13300     }
13301 
13302     ~EvaluationTracker() {
13303       Self.EvalTracker = Prev;
13304       if (Prev)
13305         Prev->EvalOK &= EvalOK;
13306     }
13307 
13308     bool evaluate(const Expr *E, bool &Result) {
13309       if (!EvalOK || E->isValueDependent())
13310         return false;
13311       EvalOK = E->EvaluateAsBooleanCondition(
13312           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
13313       return EvalOK;
13314     }
13315 
13316   private:
13317     SequenceChecker &Self;
13318     EvaluationTracker *Prev;
13319     bool EvalOK = true;
13320   } *EvalTracker = nullptr;
13321 
13322   /// Find the object which is produced by the specified expression,
13323   /// if any.
13324   Object getObject(const Expr *E, bool Mod) const {
13325     E = E->IgnoreParenCasts();
13326     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13327       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
13328         return getObject(UO->getSubExpr(), Mod);
13329     } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13330       if (BO->getOpcode() == BO_Comma)
13331         return getObject(BO->getRHS(), Mod);
13332       if (Mod && BO->isAssignmentOp())
13333         return getObject(BO->getLHS(), Mod);
13334     } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13335       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
13336       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
13337         return ME->getMemberDecl();
13338     } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13339       // FIXME: If this is a reference, map through to its value.
13340       return DRE->getDecl();
13341     return nullptr;
13342   }
13343 
13344   /// Note that an object \p O was modified or used by an expression
13345   /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
13346   /// the object \p O as obtained via the \p UsageMap.
13347   void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
13348     // Get the old usage for the given object and usage kind.
13349     Usage &U = UI.Uses[UK];
13350     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
13351       // If we have a modification as side effect and are in a sequenced
13352       // subexpression, save the old Usage so that we can restore it later
13353       // in SequencedSubexpression::~SequencedSubexpression.
13354       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
13355         ModAsSideEffect->push_back(std::make_pair(O, U));
13356       // Then record the new usage with the current sequencing region.
13357       U.UsageExpr = UsageExpr;
13358       U.Seq = Region;
13359     }
13360   }
13361 
13362   /// Check whether a modification or use of an object \p O in an expression
13363   /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
13364   /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
13365   /// \p IsModMod is true when we are checking for a mod-mod unsequenced
13366   /// usage and false we are checking for a mod-use unsequenced usage.
13367   void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
13368                   UsageKind OtherKind, bool IsModMod) {
13369     if (UI.Diagnosed)
13370       return;
13371 
13372     const Usage &U = UI.Uses[OtherKind];
13373     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
13374       return;
13375 
13376     const Expr *Mod = U.UsageExpr;
13377     const Expr *ModOrUse = UsageExpr;
13378     if (OtherKind == UK_Use)
13379       std::swap(Mod, ModOrUse);
13380 
13381     SemaRef.DiagRuntimeBehavior(
13382         Mod->getExprLoc(), {Mod, ModOrUse},
13383         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
13384                                : diag::warn_unsequenced_mod_use)
13385             << O << SourceRange(ModOrUse->getExprLoc()));
13386     UI.Diagnosed = true;
13387   }
13388 
13389   // A note on note{Pre, Post}{Use, Mod}:
13390   //
13391   // (It helps to follow the algorithm with an expression such as
13392   //  "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
13393   //  operations before C++17 and both are well-defined in C++17).
13394   //
13395   // When visiting a node which uses/modify an object we first call notePreUse
13396   // or notePreMod before visiting its sub-expression(s). At this point the
13397   // children of the current node have not yet been visited and so the eventual
13398   // uses/modifications resulting from the children of the current node have not
13399   // been recorded yet.
13400   //
13401   // We then visit the children of the current node. After that notePostUse or
13402   // notePostMod is called. These will 1) detect an unsequenced modification
13403   // as side effect (as in "k++ + k") and 2) add a new usage with the
13404   // appropriate usage kind.
13405   //
13406   // We also have to be careful that some operation sequences modification as
13407   // side effect as well (for example: || or ,). To account for this we wrap
13408   // the visitation of such a sub-expression (for example: the LHS of || or ,)
13409   // with SequencedSubexpression. SequencedSubexpression is an RAII object
13410   // which record usages which are modifications as side effect, and then
13411   // downgrade them (or more accurately restore the previous usage which was a
13412   // modification as side effect) when exiting the scope of the sequenced
13413   // subexpression.
13414 
13415   void notePreUse(Object O, const Expr *UseExpr) {
13416     UsageInfo &UI = UsageMap[O];
13417     // Uses conflict with other modifications.
13418     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
13419   }
13420 
13421   void notePostUse(Object O, const Expr *UseExpr) {
13422     UsageInfo &UI = UsageMap[O];
13423     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
13424                /*IsModMod=*/false);
13425     addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
13426   }
13427 
13428   void notePreMod(Object O, const Expr *ModExpr) {
13429     UsageInfo &UI = UsageMap[O];
13430     // Modifications conflict with other modifications and with uses.
13431     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
13432     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
13433   }
13434 
13435   void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
13436     UsageInfo &UI = UsageMap[O];
13437     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
13438                /*IsModMod=*/true);
13439     addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
13440   }
13441 
13442 public:
13443   SequenceChecker(Sema &S, const Expr *E,
13444                   SmallVectorImpl<const Expr *> &WorkList)
13445       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
13446     Visit(E);
13447     // Silence a -Wunused-private-field since WorkList is now unused.
13448     // TODO: Evaluate if it can be used, and if not remove it.
13449     (void)this->WorkList;
13450   }
13451 
13452   void VisitStmt(const Stmt *S) {
13453     // Skip all statements which aren't expressions for now.
13454   }
13455 
13456   void VisitExpr(const Expr *E) {
13457     // By default, just recurse to evaluated subexpressions.
13458     Base::VisitStmt(E);
13459   }
13460 
13461   void VisitCastExpr(const CastExpr *E) {
13462     Object O = Object();
13463     if (E->getCastKind() == CK_LValueToRValue)
13464       O = getObject(E->getSubExpr(), false);
13465 
13466     if (O)
13467       notePreUse(O, E);
13468     VisitExpr(E);
13469     if (O)
13470       notePostUse(O, E);
13471   }
13472 
13473   void VisitSequencedExpressions(const Expr *SequencedBefore,
13474                                  const Expr *SequencedAfter) {
13475     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
13476     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
13477     SequenceTree::Seq OldRegion = Region;
13478 
13479     {
13480       SequencedSubexpression SeqBefore(*this);
13481       Region = BeforeRegion;
13482       Visit(SequencedBefore);
13483     }
13484 
13485     Region = AfterRegion;
13486     Visit(SequencedAfter);
13487 
13488     Region = OldRegion;
13489 
13490     Tree.merge(BeforeRegion);
13491     Tree.merge(AfterRegion);
13492   }
13493 
13494   void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
13495     // C++17 [expr.sub]p1:
13496     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
13497     //   expression E1 is sequenced before the expression E2.
13498     if (SemaRef.getLangOpts().CPlusPlus17)
13499       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
13500     else {
13501       Visit(ASE->getLHS());
13502       Visit(ASE->getRHS());
13503     }
13504   }
13505 
13506   void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
13507   void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
13508   void VisitBinPtrMem(const BinaryOperator *BO) {
13509     // C++17 [expr.mptr.oper]p4:
13510     //  Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
13511     //  the expression E1 is sequenced before the expression E2.
13512     if (SemaRef.getLangOpts().CPlusPlus17)
13513       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13514     else {
13515       Visit(BO->getLHS());
13516       Visit(BO->getRHS());
13517     }
13518   }
13519 
13520   void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
13521   void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
13522   void VisitBinShlShr(const BinaryOperator *BO) {
13523     // C++17 [expr.shift]p4:
13524     //  The expression E1 is sequenced before the expression E2.
13525     if (SemaRef.getLangOpts().CPlusPlus17)
13526       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13527     else {
13528       Visit(BO->getLHS());
13529       Visit(BO->getRHS());
13530     }
13531   }
13532 
13533   void VisitBinComma(const BinaryOperator *BO) {
13534     // C++11 [expr.comma]p1:
13535     //   Every value computation and side effect associated with the left
13536     //   expression is sequenced before every value computation and side
13537     //   effect associated with the right expression.
13538     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13539   }
13540 
13541   void VisitBinAssign(const BinaryOperator *BO) {
13542     SequenceTree::Seq RHSRegion;
13543     SequenceTree::Seq LHSRegion;
13544     if (SemaRef.getLangOpts().CPlusPlus17) {
13545       RHSRegion = Tree.allocate(Region);
13546       LHSRegion = Tree.allocate(Region);
13547     } else {
13548       RHSRegion = Region;
13549       LHSRegion = Region;
13550     }
13551     SequenceTree::Seq OldRegion = Region;
13552 
13553     // C++11 [expr.ass]p1:
13554     //  [...] the assignment is sequenced after the value computation
13555     //  of the right and left operands, [...]
13556     //
13557     // so check it before inspecting the operands and update the
13558     // map afterwards.
13559     Object O = getObject(BO->getLHS(), /*Mod=*/true);
13560     if (O)
13561       notePreMod(O, BO);
13562 
13563     if (SemaRef.getLangOpts().CPlusPlus17) {
13564       // C++17 [expr.ass]p1:
13565       //  [...] The right operand is sequenced before the left operand. [...]
13566       {
13567         SequencedSubexpression SeqBefore(*this);
13568         Region = RHSRegion;
13569         Visit(BO->getRHS());
13570       }
13571 
13572       Region = LHSRegion;
13573       Visit(BO->getLHS());
13574 
13575       if (O && isa<CompoundAssignOperator>(BO))
13576         notePostUse(O, BO);
13577 
13578     } else {
13579       // C++11 does not specify any sequencing between the LHS and RHS.
13580       Region = LHSRegion;
13581       Visit(BO->getLHS());
13582 
13583       if (O && isa<CompoundAssignOperator>(BO))
13584         notePostUse(O, BO);
13585 
13586       Region = RHSRegion;
13587       Visit(BO->getRHS());
13588     }
13589 
13590     // C++11 [expr.ass]p1:
13591     //  the assignment is sequenced [...] before the value computation of the
13592     //  assignment expression.
13593     // C11 6.5.16/3 has no such rule.
13594     Region = OldRegion;
13595     if (O)
13596       notePostMod(O, BO,
13597                   SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
13598                                                   : UK_ModAsSideEffect);
13599     if (SemaRef.getLangOpts().CPlusPlus17) {
13600       Tree.merge(RHSRegion);
13601       Tree.merge(LHSRegion);
13602     }
13603   }
13604 
13605   void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
13606     VisitBinAssign(CAO);
13607   }
13608 
13609   void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
13610   void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
13611   void VisitUnaryPreIncDec(const UnaryOperator *UO) {
13612     Object O = getObject(UO->getSubExpr(), true);
13613     if (!O)
13614       return VisitExpr(UO);
13615 
13616     notePreMod(O, UO);
13617     Visit(UO->getSubExpr());
13618     // C++11 [expr.pre.incr]p1:
13619     //   the expression ++x is equivalent to x+=1
13620     notePostMod(O, UO,
13621                 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
13622                                                 : UK_ModAsSideEffect);
13623   }
13624 
13625   void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
13626   void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
13627   void VisitUnaryPostIncDec(const UnaryOperator *UO) {
13628     Object O = getObject(UO->getSubExpr(), true);
13629     if (!O)
13630       return VisitExpr(UO);
13631 
13632     notePreMod(O, UO);
13633     Visit(UO->getSubExpr());
13634     notePostMod(O, UO, UK_ModAsSideEffect);
13635   }
13636 
13637   void VisitBinLOr(const BinaryOperator *BO) {
13638     // C++11 [expr.log.or]p2:
13639     //  If the second expression is evaluated, every value computation and
13640     //  side effect associated with the first expression is sequenced before
13641     //  every value computation and side effect associated with the
13642     //  second expression.
13643     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
13644     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
13645     SequenceTree::Seq OldRegion = Region;
13646 
13647     EvaluationTracker Eval(*this);
13648     {
13649       SequencedSubexpression Sequenced(*this);
13650       Region = LHSRegion;
13651       Visit(BO->getLHS());
13652     }
13653 
13654     // C++11 [expr.log.or]p1:
13655     //  [...] the second operand is not evaluated if the first operand
13656     //  evaluates to true.
13657     bool EvalResult = false;
13658     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
13659     bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
13660     if (ShouldVisitRHS) {
13661       Region = RHSRegion;
13662       Visit(BO->getRHS());
13663     }
13664 
13665     Region = OldRegion;
13666     Tree.merge(LHSRegion);
13667     Tree.merge(RHSRegion);
13668   }
13669 
13670   void VisitBinLAnd(const BinaryOperator *BO) {
13671     // C++11 [expr.log.and]p2:
13672     //  If the second expression is evaluated, every value computation and
13673     //  side effect associated with the first expression is sequenced before
13674     //  every value computation and side effect associated with the
13675     //  second expression.
13676     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
13677     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
13678     SequenceTree::Seq OldRegion = Region;
13679 
13680     EvaluationTracker Eval(*this);
13681     {
13682       SequencedSubexpression Sequenced(*this);
13683       Region = LHSRegion;
13684       Visit(BO->getLHS());
13685     }
13686 
13687     // C++11 [expr.log.and]p1:
13688     //  [...] the second operand is not evaluated if the first operand is false.
13689     bool EvalResult = false;
13690     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
13691     bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
13692     if (ShouldVisitRHS) {
13693       Region = RHSRegion;
13694       Visit(BO->getRHS());
13695     }
13696 
13697     Region = OldRegion;
13698     Tree.merge(LHSRegion);
13699     Tree.merge(RHSRegion);
13700   }
13701 
13702   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
13703     // C++11 [expr.cond]p1:
13704     //  [...] Every value computation and side effect associated with the first
13705     //  expression is sequenced before every value computation and side effect
13706     //  associated with the second or third expression.
13707     SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
13708 
13709     // No sequencing is specified between the true and false expression.
13710     // However since exactly one of both is going to be evaluated we can
13711     // consider them to be sequenced. This is needed to avoid warning on
13712     // something like "x ? y+= 1 : y += 2;" in the case where we will visit
13713     // both the true and false expressions because we can't evaluate x.
13714     // This will still allow us to detect an expression like (pre C++17)
13715     // "(x ? y += 1 : y += 2) = y".
13716     //
13717     // We don't wrap the visitation of the true and false expression with
13718     // SequencedSubexpression because we don't want to downgrade modifications
13719     // as side effect in the true and false expressions after the visition
13720     // is done. (for example in the expression "(x ? y++ : y++) + y" we should
13721     // not warn between the two "y++", but we should warn between the "y++"
13722     // and the "y".
13723     SequenceTree::Seq TrueRegion = Tree.allocate(Region);
13724     SequenceTree::Seq FalseRegion = Tree.allocate(Region);
13725     SequenceTree::Seq OldRegion = Region;
13726 
13727     EvaluationTracker Eval(*this);
13728     {
13729       SequencedSubexpression Sequenced(*this);
13730       Region = ConditionRegion;
13731       Visit(CO->getCond());
13732     }
13733 
13734     // C++11 [expr.cond]p1:
13735     // [...] The first expression is contextually converted to bool (Clause 4).
13736     // It is evaluated and if it is true, the result of the conditional
13737     // expression is the value of the second expression, otherwise that of the
13738     // third expression. Only one of the second and third expressions is
13739     // evaluated. [...]
13740     bool EvalResult = false;
13741     bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
13742     bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
13743     bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
13744     if (ShouldVisitTrueExpr) {
13745       Region = TrueRegion;
13746       Visit(CO->getTrueExpr());
13747     }
13748     if (ShouldVisitFalseExpr) {
13749       Region = FalseRegion;
13750       Visit(CO->getFalseExpr());
13751     }
13752 
13753     Region = OldRegion;
13754     Tree.merge(ConditionRegion);
13755     Tree.merge(TrueRegion);
13756     Tree.merge(FalseRegion);
13757   }
13758 
13759   void VisitCallExpr(const CallExpr *CE) {
13760     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
13761 
13762     if (CE->isUnevaluatedBuiltinCall(Context))
13763       return;
13764 
13765     // C++11 [intro.execution]p15:
13766     //   When calling a function [...], every value computation and side effect
13767     //   associated with any argument expression, or with the postfix expression
13768     //   designating the called function, is sequenced before execution of every
13769     //   expression or statement in the body of the function [and thus before
13770     //   the value computation of its result].
13771     SequencedSubexpression Sequenced(*this);
13772     SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
13773       // C++17 [expr.call]p5
13774       //   The postfix-expression is sequenced before each expression in the
13775       //   expression-list and any default argument. [...]
13776       SequenceTree::Seq CalleeRegion;
13777       SequenceTree::Seq OtherRegion;
13778       if (SemaRef.getLangOpts().CPlusPlus17) {
13779         CalleeRegion = Tree.allocate(Region);
13780         OtherRegion = Tree.allocate(Region);
13781       } else {
13782         CalleeRegion = Region;
13783         OtherRegion = Region;
13784       }
13785       SequenceTree::Seq OldRegion = Region;
13786 
13787       // Visit the callee expression first.
13788       Region = CalleeRegion;
13789       if (SemaRef.getLangOpts().CPlusPlus17) {
13790         SequencedSubexpression Sequenced(*this);
13791         Visit(CE->getCallee());
13792       } else {
13793         Visit(CE->getCallee());
13794       }
13795 
13796       // Then visit the argument expressions.
13797       Region = OtherRegion;
13798       for (const Expr *Argument : CE->arguments())
13799         Visit(Argument);
13800 
13801       Region = OldRegion;
13802       if (SemaRef.getLangOpts().CPlusPlus17) {
13803         Tree.merge(CalleeRegion);
13804         Tree.merge(OtherRegion);
13805       }
13806     });
13807   }
13808 
13809   void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
13810     // C++17 [over.match.oper]p2:
13811     //   [...] the operator notation is first transformed to the equivalent
13812     //   function-call notation as summarized in Table 12 (where @ denotes one
13813     //   of the operators covered in the specified subclause). However, the
13814     //   operands are sequenced in the order prescribed for the built-in
13815     //   operator (Clause 8).
13816     //
13817     // From the above only overloaded binary operators and overloaded call
13818     // operators have sequencing rules in C++17 that we need to handle
13819     // separately.
13820     if (!SemaRef.getLangOpts().CPlusPlus17 ||
13821         (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
13822       return VisitCallExpr(CXXOCE);
13823 
13824     enum {
13825       NoSequencing,
13826       LHSBeforeRHS,
13827       RHSBeforeLHS,
13828       LHSBeforeRest
13829     } SequencingKind;
13830     switch (CXXOCE->getOperator()) {
13831     case OO_Equal:
13832     case OO_PlusEqual:
13833     case OO_MinusEqual:
13834     case OO_StarEqual:
13835     case OO_SlashEqual:
13836     case OO_PercentEqual:
13837     case OO_CaretEqual:
13838     case OO_AmpEqual:
13839     case OO_PipeEqual:
13840     case OO_LessLessEqual:
13841     case OO_GreaterGreaterEqual:
13842       SequencingKind = RHSBeforeLHS;
13843       break;
13844 
13845     case OO_LessLess:
13846     case OO_GreaterGreater:
13847     case OO_AmpAmp:
13848     case OO_PipePipe:
13849     case OO_Comma:
13850     case OO_ArrowStar:
13851     case OO_Subscript:
13852       SequencingKind = LHSBeforeRHS;
13853       break;
13854 
13855     case OO_Call:
13856       SequencingKind = LHSBeforeRest;
13857       break;
13858 
13859     default:
13860       SequencingKind = NoSequencing;
13861       break;
13862     }
13863 
13864     if (SequencingKind == NoSequencing)
13865       return VisitCallExpr(CXXOCE);
13866 
13867     // This is a call, so all subexpressions are sequenced before the result.
13868     SequencedSubexpression Sequenced(*this);
13869 
13870     SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
13871       assert(SemaRef.getLangOpts().CPlusPlus17 &&
13872              "Should only get there with C++17 and above!");
13873       assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
13874              "Should only get there with an overloaded binary operator"
13875              " or an overloaded call operator!");
13876 
13877       if (SequencingKind == LHSBeforeRest) {
13878         assert(CXXOCE->getOperator() == OO_Call &&
13879                "We should only have an overloaded call operator here!");
13880 
13881         // This is very similar to VisitCallExpr, except that we only have the
13882         // C++17 case. The postfix-expression is the first argument of the
13883         // CXXOperatorCallExpr. The expressions in the expression-list, if any,
13884         // are in the following arguments.
13885         //
13886         // Note that we intentionally do not visit the callee expression since
13887         // it is just a decayed reference to a function.
13888         SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
13889         SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
13890         SequenceTree::Seq OldRegion = Region;
13891 
13892         assert(CXXOCE->getNumArgs() >= 1 &&
13893                "An overloaded call operator must have at least one argument"
13894                " for the postfix-expression!");
13895         const Expr *PostfixExpr = CXXOCE->getArgs()[0];
13896         llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
13897                                           CXXOCE->getNumArgs() - 1);
13898 
13899         // Visit the postfix-expression first.
13900         {
13901           Region = PostfixExprRegion;
13902           SequencedSubexpression Sequenced(*this);
13903           Visit(PostfixExpr);
13904         }
13905 
13906         // Then visit the argument expressions.
13907         Region = ArgsRegion;
13908         for (const Expr *Arg : Args)
13909           Visit(Arg);
13910 
13911         Region = OldRegion;
13912         Tree.merge(PostfixExprRegion);
13913         Tree.merge(ArgsRegion);
13914       } else {
13915         assert(CXXOCE->getNumArgs() == 2 &&
13916                "Should only have two arguments here!");
13917         assert((SequencingKind == LHSBeforeRHS ||
13918                 SequencingKind == RHSBeforeLHS) &&
13919                "Unexpected sequencing kind!");
13920 
13921         // We do not visit the callee expression since it is just a decayed
13922         // reference to a function.
13923         const Expr *E1 = CXXOCE->getArg(0);
13924         const Expr *E2 = CXXOCE->getArg(1);
13925         if (SequencingKind == RHSBeforeLHS)
13926           std::swap(E1, E2);
13927 
13928         return VisitSequencedExpressions(E1, E2);
13929       }
13930     });
13931   }
13932 
13933   void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
13934     // This is a call, so all subexpressions are sequenced before the result.
13935     SequencedSubexpression Sequenced(*this);
13936 
13937     if (!CCE->isListInitialization())
13938       return VisitExpr(CCE);
13939 
13940     // In C++11, list initializations are sequenced.
13941     SmallVector<SequenceTree::Seq, 32> Elts;
13942     SequenceTree::Seq Parent = Region;
13943     for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
13944                                               E = CCE->arg_end();
13945          I != E; ++I) {
13946       Region = Tree.allocate(Parent);
13947       Elts.push_back(Region);
13948       Visit(*I);
13949     }
13950 
13951     // Forget that the initializers are sequenced.
13952     Region = Parent;
13953     for (unsigned I = 0; I < Elts.size(); ++I)
13954       Tree.merge(Elts[I]);
13955   }
13956 
13957   void VisitInitListExpr(const InitListExpr *ILE) {
13958     if (!SemaRef.getLangOpts().CPlusPlus11)
13959       return VisitExpr(ILE);
13960 
13961     // In C++11, list initializations are sequenced.
13962     SmallVector<SequenceTree::Seq, 32> Elts;
13963     SequenceTree::Seq Parent = Region;
13964     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
13965       const Expr *E = ILE->getInit(I);
13966       if (!E)
13967         continue;
13968       Region = Tree.allocate(Parent);
13969       Elts.push_back(Region);
13970       Visit(E);
13971     }
13972 
13973     // Forget that the initializers are sequenced.
13974     Region = Parent;
13975     for (unsigned I = 0; I < Elts.size(); ++I)
13976       Tree.merge(Elts[I]);
13977   }
13978 };
13979 
13980 } // namespace
13981 
13982 void Sema::CheckUnsequencedOperations(const Expr *E) {
13983   SmallVector<const Expr *, 8> WorkList;
13984   WorkList.push_back(E);
13985   while (!WorkList.empty()) {
13986     const Expr *Item = WorkList.pop_back_val();
13987     SequenceChecker(*this, Item, WorkList);
13988   }
13989 }
13990 
13991 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
13992                               bool IsConstexpr) {
13993   llvm::SaveAndRestore<bool> ConstantContext(
13994       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
13995   CheckImplicitConversions(E, CheckLoc);
13996   if (!E->isInstantiationDependent())
13997     CheckUnsequencedOperations(E);
13998   if (!IsConstexpr && !E->isValueDependent())
13999     CheckForIntOverflow(E);
14000   DiagnoseMisalignedMembers();
14001 }
14002 
14003 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
14004                                        FieldDecl *BitField,
14005                                        Expr *Init) {
14006   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
14007 }
14008 
14009 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
14010                                          SourceLocation Loc) {
14011   if (!PType->isVariablyModifiedType())
14012     return;
14013   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
14014     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
14015     return;
14016   }
14017   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
14018     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
14019     return;
14020   }
14021   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
14022     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
14023     return;
14024   }
14025 
14026   const ArrayType *AT = S.Context.getAsArrayType(PType);
14027   if (!AT)
14028     return;
14029 
14030   if (AT->getSizeModifier() != ArrayType::Star) {
14031     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
14032     return;
14033   }
14034 
14035   S.Diag(Loc, diag::err_array_star_in_function_definition);
14036 }
14037 
14038 /// CheckParmsForFunctionDef - Check that the parameters of the given
14039 /// function are appropriate for the definition of a function. This
14040 /// takes care of any checks that cannot be performed on the
14041 /// declaration itself, e.g., that the types of each of the function
14042 /// parameters are complete.
14043 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
14044                                     bool CheckParameterNames) {
14045   bool HasInvalidParm = false;
14046   for (ParmVarDecl *Param : Parameters) {
14047     // C99 6.7.5.3p4: the parameters in a parameter type list in a
14048     // function declarator that is part of a function definition of
14049     // that function shall not have incomplete type.
14050     //
14051     // This is also C++ [dcl.fct]p6.
14052     if (!Param->isInvalidDecl() &&
14053         RequireCompleteType(Param->getLocation(), Param->getType(),
14054                             diag::err_typecheck_decl_incomplete_type)) {
14055       Param->setInvalidDecl();
14056       HasInvalidParm = true;
14057     }
14058 
14059     // C99 6.9.1p5: If the declarator includes a parameter type list, the
14060     // declaration of each parameter shall include an identifier.
14061     if (CheckParameterNames && Param->getIdentifier() == nullptr &&
14062         !Param->isImplicit() && !getLangOpts().CPlusPlus) {
14063       // Diagnose this as an extension in C17 and earlier.
14064       if (!getLangOpts().C2x)
14065         Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
14066     }
14067 
14068     // C99 6.7.5.3p12:
14069     //   If the function declarator is not part of a definition of that
14070     //   function, parameters may have incomplete type and may use the [*]
14071     //   notation in their sequences of declarator specifiers to specify
14072     //   variable length array types.
14073     QualType PType = Param->getOriginalType();
14074     // FIXME: This diagnostic should point the '[*]' if source-location
14075     // information is added for it.
14076     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
14077 
14078     // If the parameter is a c++ class type and it has to be destructed in the
14079     // callee function, declare the destructor so that it can be called by the
14080     // callee function. Do not perform any direct access check on the dtor here.
14081     if (!Param->isInvalidDecl()) {
14082       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
14083         if (!ClassDecl->isInvalidDecl() &&
14084             !ClassDecl->hasIrrelevantDestructor() &&
14085             !ClassDecl->isDependentContext() &&
14086             ClassDecl->isParamDestroyedInCallee()) {
14087           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
14088           MarkFunctionReferenced(Param->getLocation(), Destructor);
14089           DiagnoseUseOfDecl(Destructor, Param->getLocation());
14090         }
14091       }
14092     }
14093 
14094     // Parameters with the pass_object_size attribute only need to be marked
14095     // constant at function definitions. Because we lack information about
14096     // whether we're on a declaration or definition when we're instantiating the
14097     // attribute, we need to check for constness here.
14098     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
14099       if (!Param->getType().isConstQualified())
14100         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
14101             << Attr->getSpelling() << 1;
14102 
14103     // Check for parameter names shadowing fields from the class.
14104     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
14105       // The owning context for the parameter should be the function, but we
14106       // want to see if this function's declaration context is a record.
14107       DeclContext *DC = Param->getDeclContext();
14108       if (DC && DC->isFunctionOrMethod()) {
14109         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
14110           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
14111                                      RD, /*DeclIsField*/ false);
14112       }
14113     }
14114   }
14115 
14116   return HasInvalidParm;
14117 }
14118 
14119 Optional<std::pair<CharUnits, CharUnits>>
14120 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx);
14121 
14122 /// Compute the alignment and offset of the base class object given the
14123 /// derived-to-base cast expression and the alignment and offset of the derived
14124 /// class object.
14125 static std::pair<CharUnits, CharUnits>
14126 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
14127                                    CharUnits BaseAlignment, CharUnits Offset,
14128                                    ASTContext &Ctx) {
14129   for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
14130        ++PathI) {
14131     const CXXBaseSpecifier *Base = *PathI;
14132     const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
14133     if (Base->isVirtual()) {
14134       // The complete object may have a lower alignment than the non-virtual
14135       // alignment of the base, in which case the base may be misaligned. Choose
14136       // the smaller of the non-virtual alignment and BaseAlignment, which is a
14137       // conservative lower bound of the complete object alignment.
14138       CharUnits NonVirtualAlignment =
14139           Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment();
14140       BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
14141       Offset = CharUnits::Zero();
14142     } else {
14143       const ASTRecordLayout &RL =
14144           Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
14145       Offset += RL.getBaseClassOffset(BaseDecl);
14146     }
14147     DerivedType = Base->getType();
14148   }
14149 
14150   return std::make_pair(BaseAlignment, Offset);
14151 }
14152 
14153 /// Compute the alignment and offset of a binary additive operator.
14154 static Optional<std::pair<CharUnits, CharUnits>>
14155 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
14156                                      bool IsSub, ASTContext &Ctx) {
14157   QualType PointeeType = PtrE->getType()->getPointeeType();
14158 
14159   if (!PointeeType->isConstantSizeType())
14160     return llvm::None;
14161 
14162   auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
14163 
14164   if (!P)
14165     return llvm::None;
14166 
14167   CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
14168   if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
14169     CharUnits Offset = EltSize * IdxRes->getExtValue();
14170     if (IsSub)
14171       Offset = -Offset;
14172     return std::make_pair(P->first, P->second + Offset);
14173   }
14174 
14175   // If the integer expression isn't a constant expression, compute the lower
14176   // bound of the alignment using the alignment and offset of the pointer
14177   // expression and the element size.
14178   return std::make_pair(
14179       P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
14180       CharUnits::Zero());
14181 }
14182 
14183 /// This helper function takes an lvalue expression and returns the alignment of
14184 /// a VarDecl and a constant offset from the VarDecl.
14185 Optional<std::pair<CharUnits, CharUnits>>
14186 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) {
14187   E = E->IgnoreParens();
14188   switch (E->getStmtClass()) {
14189   default:
14190     break;
14191   case Stmt::CStyleCastExprClass:
14192   case Stmt::CXXStaticCastExprClass:
14193   case Stmt::ImplicitCastExprClass: {
14194     auto *CE = cast<CastExpr>(E);
14195     const Expr *From = CE->getSubExpr();
14196     switch (CE->getCastKind()) {
14197     default:
14198       break;
14199     case CK_NoOp:
14200       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14201     case CK_UncheckedDerivedToBase:
14202     case CK_DerivedToBase: {
14203       auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14204       if (!P)
14205         break;
14206       return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
14207                                                 P->second, Ctx);
14208     }
14209     }
14210     break;
14211   }
14212   case Stmt::ArraySubscriptExprClass: {
14213     auto *ASE = cast<ArraySubscriptExpr>(E);
14214     return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(),
14215                                                 false, Ctx);
14216   }
14217   case Stmt::DeclRefExprClass: {
14218     if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
14219       // FIXME: If VD is captured by copy or is an escaping __block variable,
14220       // use the alignment of VD's type.
14221       if (!VD->getType()->isReferenceType())
14222         return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
14223       if (VD->hasInit())
14224         return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
14225     }
14226     break;
14227   }
14228   case Stmt::MemberExprClass: {
14229     auto *ME = cast<MemberExpr>(E);
14230     auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
14231     if (!FD || FD->getType()->isReferenceType())
14232       break;
14233     Optional<std::pair<CharUnits, CharUnits>> P;
14234     if (ME->isArrow())
14235       P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
14236     else
14237       P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
14238     if (!P)
14239       break;
14240     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
14241     uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
14242     return std::make_pair(P->first,
14243                           P->second + CharUnits::fromQuantity(Offset));
14244   }
14245   case Stmt::UnaryOperatorClass: {
14246     auto *UO = cast<UnaryOperator>(E);
14247     switch (UO->getOpcode()) {
14248     default:
14249       break;
14250     case UO_Deref:
14251       return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx);
14252     }
14253     break;
14254   }
14255   case Stmt::BinaryOperatorClass: {
14256     auto *BO = cast<BinaryOperator>(E);
14257     auto Opcode = BO->getOpcode();
14258     switch (Opcode) {
14259     default:
14260       break;
14261     case BO_Comma:
14262       return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx);
14263     }
14264     break;
14265   }
14266   }
14267   return llvm::None;
14268 }
14269 
14270 /// This helper function takes a pointer expression and returns the alignment of
14271 /// a VarDecl and a constant offset from the VarDecl.
14272 Optional<std::pair<CharUnits, CharUnits>>
14273 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) {
14274   E = E->IgnoreParens();
14275   switch (E->getStmtClass()) {
14276   default:
14277     break;
14278   case Stmt::CStyleCastExprClass:
14279   case Stmt::CXXStaticCastExprClass:
14280   case Stmt::ImplicitCastExprClass: {
14281     auto *CE = cast<CastExpr>(E);
14282     const Expr *From = CE->getSubExpr();
14283     switch (CE->getCastKind()) {
14284     default:
14285       break;
14286     case CK_NoOp:
14287       return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14288     case CK_ArrayToPointerDecay:
14289       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14290     case CK_UncheckedDerivedToBase:
14291     case CK_DerivedToBase: {
14292       auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14293       if (!P)
14294         break;
14295       return getDerivedToBaseAlignmentAndOffset(
14296           CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
14297     }
14298     }
14299     break;
14300   }
14301   case Stmt::CXXThisExprClass: {
14302     auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
14303     CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment();
14304     return std::make_pair(Alignment, CharUnits::Zero());
14305   }
14306   case Stmt::UnaryOperatorClass: {
14307     auto *UO = cast<UnaryOperator>(E);
14308     if (UO->getOpcode() == UO_AddrOf)
14309       return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx);
14310     break;
14311   }
14312   case Stmt::BinaryOperatorClass: {
14313     auto *BO = cast<BinaryOperator>(E);
14314     auto Opcode = BO->getOpcode();
14315     switch (Opcode) {
14316     default:
14317       break;
14318     case BO_Add:
14319     case BO_Sub: {
14320       const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
14321       if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
14322         std::swap(LHS, RHS);
14323       return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
14324                                                   Ctx);
14325     }
14326     case BO_Comma:
14327       return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
14328     }
14329     break;
14330   }
14331   }
14332   return llvm::None;
14333 }
14334 
14335 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
14336   // See if we can compute the alignment of a VarDecl and an offset from it.
14337   Optional<std::pair<CharUnits, CharUnits>> P =
14338       getBaseAlignmentAndOffsetFromPtr(E, S.Context);
14339 
14340   if (P)
14341     return P->first.alignmentAtOffset(P->second);
14342 
14343   // If that failed, return the type's alignment.
14344   return S.Context.getTypeAlignInChars(E->getType()->getPointeeType());
14345 }
14346 
14347 /// CheckCastAlign - Implements -Wcast-align, which warns when a
14348 /// pointer cast increases the alignment requirements.
14349 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
14350   // This is actually a lot of work to potentially be doing on every
14351   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
14352   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
14353     return;
14354 
14355   // Ignore dependent types.
14356   if (T->isDependentType() || Op->getType()->isDependentType())
14357     return;
14358 
14359   // Require that the destination be a pointer type.
14360   const PointerType *DestPtr = T->getAs<PointerType>();
14361   if (!DestPtr) return;
14362 
14363   // If the destination has alignment 1, we're done.
14364   QualType DestPointee = DestPtr->getPointeeType();
14365   if (DestPointee->isIncompleteType()) return;
14366   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
14367   if (DestAlign.isOne()) return;
14368 
14369   // Require that the source be a pointer type.
14370   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
14371   if (!SrcPtr) return;
14372   QualType SrcPointee = SrcPtr->getPointeeType();
14373 
14374   // Explicitly allow casts from cv void*.  We already implicitly
14375   // allowed casts to cv void*, since they have alignment 1.
14376   // Also allow casts involving incomplete types, which implicitly
14377   // includes 'void'.
14378   if (SrcPointee->isIncompleteType()) return;
14379 
14380   CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
14381 
14382   if (SrcAlign >= DestAlign) return;
14383 
14384   Diag(TRange.getBegin(), diag::warn_cast_align)
14385     << Op->getType() << T
14386     << static_cast<unsigned>(SrcAlign.getQuantity())
14387     << static_cast<unsigned>(DestAlign.getQuantity())
14388     << TRange << Op->getSourceRange();
14389 }
14390 
14391 /// Check whether this array fits the idiom of a size-one tail padded
14392 /// array member of a struct.
14393 ///
14394 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
14395 /// commonly used to emulate flexible arrays in C89 code.
14396 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
14397                                     const NamedDecl *ND) {
14398   if (Size != 1 || !ND) return false;
14399 
14400   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
14401   if (!FD) return false;
14402 
14403   // Don't consider sizes resulting from macro expansions or template argument
14404   // substitution to form C89 tail-padded arrays.
14405 
14406   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
14407   while (TInfo) {
14408     TypeLoc TL = TInfo->getTypeLoc();
14409     // Look through typedefs.
14410     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
14411       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
14412       TInfo = TDL->getTypeSourceInfo();
14413       continue;
14414     }
14415     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
14416       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
14417       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
14418         return false;
14419     }
14420     break;
14421   }
14422 
14423   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
14424   if (!RD) return false;
14425   if (RD->isUnion()) return false;
14426   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
14427     if (!CRD->isStandardLayout()) return false;
14428   }
14429 
14430   // See if this is the last field decl in the record.
14431   const Decl *D = FD;
14432   while ((D = D->getNextDeclInContext()))
14433     if (isa<FieldDecl>(D))
14434       return false;
14435   return true;
14436 }
14437 
14438 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
14439                             const ArraySubscriptExpr *ASE,
14440                             bool AllowOnePastEnd, bool IndexNegated) {
14441   // Already diagnosed by the constant evaluator.
14442   if (isConstantEvaluated())
14443     return;
14444 
14445   IndexExpr = IndexExpr->IgnoreParenImpCasts();
14446   if (IndexExpr->isValueDependent())
14447     return;
14448 
14449   const Type *EffectiveType =
14450       BaseExpr->getType()->getPointeeOrArrayElementType();
14451   BaseExpr = BaseExpr->IgnoreParenCasts();
14452   const ConstantArrayType *ArrayTy =
14453       Context.getAsConstantArrayType(BaseExpr->getType());
14454 
14455   if (!ArrayTy)
14456     return;
14457 
14458   const Type *BaseType = ArrayTy->getElementType().getTypePtr();
14459   if (EffectiveType->isDependentType() || BaseType->isDependentType())
14460     return;
14461 
14462   Expr::EvalResult Result;
14463   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
14464     return;
14465 
14466   llvm::APSInt index = Result.Val.getInt();
14467   if (IndexNegated)
14468     index = -index;
14469 
14470   const NamedDecl *ND = nullptr;
14471   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14472     ND = DRE->getDecl();
14473   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
14474     ND = ME->getMemberDecl();
14475 
14476   if (index.isUnsigned() || !index.isNegative()) {
14477     // It is possible that the type of the base expression after
14478     // IgnoreParenCasts is incomplete, even though the type of the base
14479     // expression before IgnoreParenCasts is complete (see PR39746 for an
14480     // example). In this case we have no information about whether the array
14481     // access exceeds the array bounds. However we can still diagnose an array
14482     // access which precedes the array bounds.
14483     if (BaseType->isIncompleteType())
14484       return;
14485 
14486     llvm::APInt size = ArrayTy->getSize();
14487     if (!size.isStrictlyPositive())
14488       return;
14489 
14490     if (BaseType != EffectiveType) {
14491       // Make sure we're comparing apples to apples when comparing index to size
14492       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
14493       uint64_t array_typesize = Context.getTypeSize(BaseType);
14494       // Handle ptrarith_typesize being zero, such as when casting to void*
14495       if (!ptrarith_typesize) ptrarith_typesize = 1;
14496       if (ptrarith_typesize != array_typesize) {
14497         // There's a cast to a different size type involved
14498         uint64_t ratio = array_typesize / ptrarith_typesize;
14499         // TODO: Be smarter about handling cases where array_typesize is not a
14500         // multiple of ptrarith_typesize
14501         if (ptrarith_typesize * ratio == array_typesize)
14502           size *= llvm::APInt(size.getBitWidth(), ratio);
14503       }
14504     }
14505 
14506     if (size.getBitWidth() > index.getBitWidth())
14507       index = index.zext(size.getBitWidth());
14508     else if (size.getBitWidth() < index.getBitWidth())
14509       size = size.zext(index.getBitWidth());
14510 
14511     // For array subscripting the index must be less than size, but for pointer
14512     // arithmetic also allow the index (offset) to be equal to size since
14513     // computing the next address after the end of the array is legal and
14514     // commonly done e.g. in C++ iterators and range-based for loops.
14515     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
14516       return;
14517 
14518     // Also don't warn for arrays of size 1 which are members of some
14519     // structure. These are often used to approximate flexible arrays in C89
14520     // code.
14521     if (IsTailPaddedMemberArray(*this, size, ND))
14522       return;
14523 
14524     // Suppress the warning if the subscript expression (as identified by the
14525     // ']' location) and the index expression are both from macro expansions
14526     // within a system header.
14527     if (ASE) {
14528       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
14529           ASE->getRBracketLoc());
14530       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
14531         SourceLocation IndexLoc =
14532             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
14533         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
14534           return;
14535       }
14536     }
14537 
14538     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
14539     if (ASE)
14540       DiagID = diag::warn_array_index_exceeds_bounds;
14541 
14542     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
14543                         PDiag(DiagID) << index.toString(10, true)
14544                                       << size.toString(10, true)
14545                                       << (unsigned)size.getLimitedValue(~0U)
14546                                       << IndexExpr->getSourceRange());
14547   } else {
14548     unsigned DiagID = diag::warn_array_index_precedes_bounds;
14549     if (!ASE) {
14550       DiagID = diag::warn_ptr_arith_precedes_bounds;
14551       if (index.isNegative()) index = -index;
14552     }
14553 
14554     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
14555                         PDiag(DiagID) << index.toString(10, true)
14556                                       << IndexExpr->getSourceRange());
14557   }
14558 
14559   if (!ND) {
14560     // Try harder to find a NamedDecl to point at in the note.
14561     while (const ArraySubscriptExpr *ASE =
14562            dyn_cast<ArraySubscriptExpr>(BaseExpr))
14563       BaseExpr = ASE->getBase()->IgnoreParenCasts();
14564     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14565       ND = DRE->getDecl();
14566     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
14567       ND = ME->getMemberDecl();
14568   }
14569 
14570   if (ND)
14571     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
14572                         PDiag(diag::note_array_declared_here) << ND);
14573 }
14574 
14575 void Sema::CheckArrayAccess(const Expr *expr) {
14576   int AllowOnePastEnd = 0;
14577   while (expr) {
14578     expr = expr->IgnoreParenImpCasts();
14579     switch (expr->getStmtClass()) {
14580       case Stmt::ArraySubscriptExprClass: {
14581         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
14582         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
14583                          AllowOnePastEnd > 0);
14584         expr = ASE->getBase();
14585         break;
14586       }
14587       case Stmt::MemberExprClass: {
14588         expr = cast<MemberExpr>(expr)->getBase();
14589         break;
14590       }
14591       case Stmt::OMPArraySectionExprClass: {
14592         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
14593         if (ASE->getLowerBound())
14594           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
14595                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
14596         return;
14597       }
14598       case Stmt::UnaryOperatorClass: {
14599         // Only unwrap the * and & unary operators
14600         const UnaryOperator *UO = cast<UnaryOperator>(expr);
14601         expr = UO->getSubExpr();
14602         switch (UO->getOpcode()) {
14603           case UO_AddrOf:
14604             AllowOnePastEnd++;
14605             break;
14606           case UO_Deref:
14607             AllowOnePastEnd--;
14608             break;
14609           default:
14610             return;
14611         }
14612         break;
14613       }
14614       case Stmt::ConditionalOperatorClass: {
14615         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
14616         if (const Expr *lhs = cond->getLHS())
14617           CheckArrayAccess(lhs);
14618         if (const Expr *rhs = cond->getRHS())
14619           CheckArrayAccess(rhs);
14620         return;
14621       }
14622       case Stmt::CXXOperatorCallExprClass: {
14623         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
14624         for (const auto *Arg : OCE->arguments())
14625           CheckArrayAccess(Arg);
14626         return;
14627       }
14628       default:
14629         return;
14630     }
14631   }
14632 }
14633 
14634 //===--- CHECK: Objective-C retain cycles ----------------------------------//
14635 
14636 namespace {
14637 
14638 struct RetainCycleOwner {
14639   VarDecl *Variable = nullptr;
14640   SourceRange Range;
14641   SourceLocation Loc;
14642   bool Indirect = false;
14643 
14644   RetainCycleOwner() = default;
14645 
14646   void setLocsFrom(Expr *e) {
14647     Loc = e->getExprLoc();
14648     Range = e->getSourceRange();
14649   }
14650 };
14651 
14652 } // namespace
14653 
14654 /// Consider whether capturing the given variable can possibly lead to
14655 /// a retain cycle.
14656 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
14657   // In ARC, it's captured strongly iff the variable has __strong
14658   // lifetime.  In MRR, it's captured strongly if the variable is
14659   // __block and has an appropriate type.
14660   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
14661     return false;
14662 
14663   owner.Variable = var;
14664   if (ref)
14665     owner.setLocsFrom(ref);
14666   return true;
14667 }
14668 
14669 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
14670   while (true) {
14671     e = e->IgnoreParens();
14672     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
14673       switch (cast->getCastKind()) {
14674       case CK_BitCast:
14675       case CK_LValueBitCast:
14676       case CK_LValueToRValue:
14677       case CK_ARCReclaimReturnedObject:
14678         e = cast->getSubExpr();
14679         continue;
14680 
14681       default:
14682         return false;
14683       }
14684     }
14685 
14686     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
14687       ObjCIvarDecl *ivar = ref->getDecl();
14688       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
14689         return false;
14690 
14691       // Try to find a retain cycle in the base.
14692       if (!findRetainCycleOwner(S, ref->getBase(), owner))
14693         return false;
14694 
14695       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
14696       owner.Indirect = true;
14697       return true;
14698     }
14699 
14700     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
14701       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
14702       if (!var) return false;
14703       return considerVariable(var, ref, owner);
14704     }
14705 
14706     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
14707       if (member->isArrow()) return false;
14708 
14709       // Don't count this as an indirect ownership.
14710       e = member->getBase();
14711       continue;
14712     }
14713 
14714     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
14715       // Only pay attention to pseudo-objects on property references.
14716       ObjCPropertyRefExpr *pre
14717         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
14718                                               ->IgnoreParens());
14719       if (!pre) return false;
14720       if (pre->isImplicitProperty()) return false;
14721       ObjCPropertyDecl *property = pre->getExplicitProperty();
14722       if (!property->isRetaining() &&
14723           !(property->getPropertyIvarDecl() &&
14724             property->getPropertyIvarDecl()->getType()
14725               .getObjCLifetime() == Qualifiers::OCL_Strong))
14726           return false;
14727 
14728       owner.Indirect = true;
14729       if (pre->isSuperReceiver()) {
14730         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
14731         if (!owner.Variable)
14732           return false;
14733         owner.Loc = pre->getLocation();
14734         owner.Range = pre->getSourceRange();
14735         return true;
14736       }
14737       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
14738                               ->getSourceExpr());
14739       continue;
14740     }
14741 
14742     // Array ivars?
14743 
14744     return false;
14745   }
14746 }
14747 
14748 namespace {
14749 
14750   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
14751     ASTContext &Context;
14752     VarDecl *Variable;
14753     Expr *Capturer = nullptr;
14754     bool VarWillBeReased = false;
14755 
14756     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
14757         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
14758           Context(Context), Variable(variable) {}
14759 
14760     void VisitDeclRefExpr(DeclRefExpr *ref) {
14761       if (ref->getDecl() == Variable && !Capturer)
14762         Capturer = ref;
14763     }
14764 
14765     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
14766       if (Capturer) return;
14767       Visit(ref->getBase());
14768       if (Capturer && ref->isFreeIvar())
14769         Capturer = ref;
14770     }
14771 
14772     void VisitBlockExpr(BlockExpr *block) {
14773       // Look inside nested blocks
14774       if (block->getBlockDecl()->capturesVariable(Variable))
14775         Visit(block->getBlockDecl()->getBody());
14776     }
14777 
14778     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
14779       if (Capturer) return;
14780       if (OVE->getSourceExpr())
14781         Visit(OVE->getSourceExpr());
14782     }
14783 
14784     void VisitBinaryOperator(BinaryOperator *BinOp) {
14785       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
14786         return;
14787       Expr *LHS = BinOp->getLHS();
14788       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
14789         if (DRE->getDecl() != Variable)
14790           return;
14791         if (Expr *RHS = BinOp->getRHS()) {
14792           RHS = RHS->IgnoreParenCasts();
14793           Optional<llvm::APSInt> Value;
14794           VarWillBeReased =
14795               (RHS && (Value = RHS->getIntegerConstantExpr(Context)) &&
14796                *Value == 0);
14797         }
14798       }
14799     }
14800   };
14801 
14802 } // namespace
14803 
14804 /// Check whether the given argument is a block which captures a
14805 /// variable.
14806 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
14807   assert(owner.Variable && owner.Loc.isValid());
14808 
14809   e = e->IgnoreParenCasts();
14810 
14811   // Look through [^{...} copy] and Block_copy(^{...}).
14812   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
14813     Selector Cmd = ME->getSelector();
14814     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
14815       e = ME->getInstanceReceiver();
14816       if (!e)
14817         return nullptr;
14818       e = e->IgnoreParenCasts();
14819     }
14820   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
14821     if (CE->getNumArgs() == 1) {
14822       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
14823       if (Fn) {
14824         const IdentifierInfo *FnI = Fn->getIdentifier();
14825         if (FnI && FnI->isStr("_Block_copy")) {
14826           e = CE->getArg(0)->IgnoreParenCasts();
14827         }
14828       }
14829     }
14830   }
14831 
14832   BlockExpr *block = dyn_cast<BlockExpr>(e);
14833   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
14834     return nullptr;
14835 
14836   FindCaptureVisitor visitor(S.Context, owner.Variable);
14837   visitor.Visit(block->getBlockDecl()->getBody());
14838   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
14839 }
14840 
14841 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
14842                                 RetainCycleOwner &owner) {
14843   assert(capturer);
14844   assert(owner.Variable && owner.Loc.isValid());
14845 
14846   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
14847     << owner.Variable << capturer->getSourceRange();
14848   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
14849     << owner.Indirect << owner.Range;
14850 }
14851 
14852 /// Check for a keyword selector that starts with the word 'add' or
14853 /// 'set'.
14854 static bool isSetterLikeSelector(Selector sel) {
14855   if (sel.isUnarySelector()) return false;
14856 
14857   StringRef str = sel.getNameForSlot(0);
14858   while (!str.empty() && str.front() == '_') str = str.substr(1);
14859   if (str.startswith("set"))
14860     str = str.substr(3);
14861   else if (str.startswith("add")) {
14862     // Specially allow 'addOperationWithBlock:'.
14863     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
14864       return false;
14865     str = str.substr(3);
14866   }
14867   else
14868     return false;
14869 
14870   if (str.empty()) return true;
14871   return !isLowercase(str.front());
14872 }
14873 
14874 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
14875                                                     ObjCMessageExpr *Message) {
14876   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
14877                                                 Message->getReceiverInterface(),
14878                                                 NSAPI::ClassId_NSMutableArray);
14879   if (!IsMutableArray) {
14880     return None;
14881   }
14882 
14883   Selector Sel = Message->getSelector();
14884 
14885   Optional<NSAPI::NSArrayMethodKind> MKOpt =
14886     S.NSAPIObj->getNSArrayMethodKind(Sel);
14887   if (!MKOpt) {
14888     return None;
14889   }
14890 
14891   NSAPI::NSArrayMethodKind MK = *MKOpt;
14892 
14893   switch (MK) {
14894     case NSAPI::NSMutableArr_addObject:
14895     case NSAPI::NSMutableArr_insertObjectAtIndex:
14896     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
14897       return 0;
14898     case NSAPI::NSMutableArr_replaceObjectAtIndex:
14899       return 1;
14900 
14901     default:
14902       return None;
14903   }
14904 
14905   return None;
14906 }
14907 
14908 static
14909 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
14910                                                   ObjCMessageExpr *Message) {
14911   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
14912                                             Message->getReceiverInterface(),
14913                                             NSAPI::ClassId_NSMutableDictionary);
14914   if (!IsMutableDictionary) {
14915     return None;
14916   }
14917 
14918   Selector Sel = Message->getSelector();
14919 
14920   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
14921     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
14922   if (!MKOpt) {
14923     return None;
14924   }
14925 
14926   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
14927 
14928   switch (MK) {
14929     case NSAPI::NSMutableDict_setObjectForKey:
14930     case NSAPI::NSMutableDict_setValueForKey:
14931     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
14932       return 0;
14933 
14934     default:
14935       return None;
14936   }
14937 
14938   return None;
14939 }
14940 
14941 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
14942   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
14943                                                 Message->getReceiverInterface(),
14944                                                 NSAPI::ClassId_NSMutableSet);
14945 
14946   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
14947                                             Message->getReceiverInterface(),
14948                                             NSAPI::ClassId_NSMutableOrderedSet);
14949   if (!IsMutableSet && !IsMutableOrderedSet) {
14950     return None;
14951   }
14952 
14953   Selector Sel = Message->getSelector();
14954 
14955   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
14956   if (!MKOpt) {
14957     return None;
14958   }
14959 
14960   NSAPI::NSSetMethodKind MK = *MKOpt;
14961 
14962   switch (MK) {
14963     case NSAPI::NSMutableSet_addObject:
14964     case NSAPI::NSOrderedSet_setObjectAtIndex:
14965     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
14966     case NSAPI::NSOrderedSet_insertObjectAtIndex:
14967       return 0;
14968     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
14969       return 1;
14970   }
14971 
14972   return None;
14973 }
14974 
14975 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
14976   if (!Message->isInstanceMessage()) {
14977     return;
14978   }
14979 
14980   Optional<int> ArgOpt;
14981 
14982   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
14983       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
14984       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
14985     return;
14986   }
14987 
14988   int ArgIndex = *ArgOpt;
14989 
14990   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
14991   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
14992     Arg = OE->getSourceExpr()->IgnoreImpCasts();
14993   }
14994 
14995   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
14996     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
14997       if (ArgRE->isObjCSelfExpr()) {
14998         Diag(Message->getSourceRange().getBegin(),
14999              diag::warn_objc_circular_container)
15000           << ArgRE->getDecl() << StringRef("'super'");
15001       }
15002     }
15003   } else {
15004     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
15005 
15006     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
15007       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
15008     }
15009 
15010     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
15011       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
15012         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
15013           ValueDecl *Decl = ReceiverRE->getDecl();
15014           Diag(Message->getSourceRange().getBegin(),
15015                diag::warn_objc_circular_container)
15016             << Decl << Decl;
15017           if (!ArgRE->isObjCSelfExpr()) {
15018             Diag(Decl->getLocation(),
15019                  diag::note_objc_circular_container_declared_here)
15020               << Decl;
15021           }
15022         }
15023       }
15024     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
15025       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
15026         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
15027           ObjCIvarDecl *Decl = IvarRE->getDecl();
15028           Diag(Message->getSourceRange().getBegin(),
15029                diag::warn_objc_circular_container)
15030             << Decl << Decl;
15031           Diag(Decl->getLocation(),
15032                diag::note_objc_circular_container_declared_here)
15033             << Decl;
15034         }
15035       }
15036     }
15037   }
15038 }
15039 
15040 /// Check a message send to see if it's likely to cause a retain cycle.
15041 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
15042   // Only check instance methods whose selector looks like a setter.
15043   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
15044     return;
15045 
15046   // Try to find a variable that the receiver is strongly owned by.
15047   RetainCycleOwner owner;
15048   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
15049     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
15050       return;
15051   } else {
15052     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
15053     owner.Variable = getCurMethodDecl()->getSelfDecl();
15054     owner.Loc = msg->getSuperLoc();
15055     owner.Range = msg->getSuperLoc();
15056   }
15057 
15058   // Check whether the receiver is captured by any of the arguments.
15059   const ObjCMethodDecl *MD = msg->getMethodDecl();
15060   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
15061     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
15062       // noescape blocks should not be retained by the method.
15063       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
15064         continue;
15065       return diagnoseRetainCycle(*this, capturer, owner);
15066     }
15067   }
15068 }
15069 
15070 /// Check a property assign to see if it's likely to cause a retain cycle.
15071 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
15072   RetainCycleOwner owner;
15073   if (!findRetainCycleOwner(*this, receiver, owner))
15074     return;
15075 
15076   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
15077     diagnoseRetainCycle(*this, capturer, owner);
15078 }
15079 
15080 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
15081   RetainCycleOwner Owner;
15082   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
15083     return;
15084 
15085   // Because we don't have an expression for the variable, we have to set the
15086   // location explicitly here.
15087   Owner.Loc = Var->getLocation();
15088   Owner.Range = Var->getSourceRange();
15089 
15090   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
15091     diagnoseRetainCycle(*this, Capturer, Owner);
15092 }
15093 
15094 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
15095                                      Expr *RHS, bool isProperty) {
15096   // Check if RHS is an Objective-C object literal, which also can get
15097   // immediately zapped in a weak reference.  Note that we explicitly
15098   // allow ObjCStringLiterals, since those are designed to never really die.
15099   RHS = RHS->IgnoreParenImpCasts();
15100 
15101   // This enum needs to match with the 'select' in
15102   // warn_objc_arc_literal_assign (off-by-1).
15103   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
15104   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
15105     return false;
15106 
15107   S.Diag(Loc, diag::warn_arc_literal_assign)
15108     << (unsigned) Kind
15109     << (isProperty ? 0 : 1)
15110     << RHS->getSourceRange();
15111 
15112   return true;
15113 }
15114 
15115 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
15116                                     Qualifiers::ObjCLifetime LT,
15117                                     Expr *RHS, bool isProperty) {
15118   // Strip off any implicit cast added to get to the one ARC-specific.
15119   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15120     if (cast->getCastKind() == CK_ARCConsumeObject) {
15121       S.Diag(Loc, diag::warn_arc_retained_assign)
15122         << (LT == Qualifiers::OCL_ExplicitNone)
15123         << (isProperty ? 0 : 1)
15124         << RHS->getSourceRange();
15125       return true;
15126     }
15127     RHS = cast->getSubExpr();
15128   }
15129 
15130   if (LT == Qualifiers::OCL_Weak &&
15131       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
15132     return true;
15133 
15134   return false;
15135 }
15136 
15137 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
15138                               QualType LHS, Expr *RHS) {
15139   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
15140 
15141   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
15142     return false;
15143 
15144   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
15145     return true;
15146 
15147   return false;
15148 }
15149 
15150 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
15151                               Expr *LHS, Expr *RHS) {
15152   QualType LHSType;
15153   // PropertyRef on LHS type need be directly obtained from
15154   // its declaration as it has a PseudoType.
15155   ObjCPropertyRefExpr *PRE
15156     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
15157   if (PRE && !PRE->isImplicitProperty()) {
15158     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15159     if (PD)
15160       LHSType = PD->getType();
15161   }
15162 
15163   if (LHSType.isNull())
15164     LHSType = LHS->getType();
15165 
15166   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
15167 
15168   if (LT == Qualifiers::OCL_Weak) {
15169     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
15170       getCurFunction()->markSafeWeakUse(LHS);
15171   }
15172 
15173   if (checkUnsafeAssigns(Loc, LHSType, RHS))
15174     return;
15175 
15176   // FIXME. Check for other life times.
15177   if (LT != Qualifiers::OCL_None)
15178     return;
15179 
15180   if (PRE) {
15181     if (PRE->isImplicitProperty())
15182       return;
15183     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15184     if (!PD)
15185       return;
15186 
15187     unsigned Attributes = PD->getPropertyAttributes();
15188     if (Attributes & ObjCPropertyAttribute::kind_assign) {
15189       // when 'assign' attribute was not explicitly specified
15190       // by user, ignore it and rely on property type itself
15191       // for lifetime info.
15192       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
15193       if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
15194           LHSType->isObjCRetainableType())
15195         return;
15196 
15197       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15198         if (cast->getCastKind() == CK_ARCConsumeObject) {
15199           Diag(Loc, diag::warn_arc_retained_property_assign)
15200           << RHS->getSourceRange();
15201           return;
15202         }
15203         RHS = cast->getSubExpr();
15204       }
15205     } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
15206       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
15207         return;
15208     }
15209   }
15210 }
15211 
15212 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
15213 
15214 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
15215                                         SourceLocation StmtLoc,
15216                                         const NullStmt *Body) {
15217   // Do not warn if the body is a macro that expands to nothing, e.g:
15218   //
15219   // #define CALL(x)
15220   // if (condition)
15221   //   CALL(0);
15222   if (Body->hasLeadingEmptyMacro())
15223     return false;
15224 
15225   // Get line numbers of statement and body.
15226   bool StmtLineInvalid;
15227   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
15228                                                       &StmtLineInvalid);
15229   if (StmtLineInvalid)
15230     return false;
15231 
15232   bool BodyLineInvalid;
15233   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
15234                                                       &BodyLineInvalid);
15235   if (BodyLineInvalid)
15236     return false;
15237 
15238   // Warn if null statement and body are on the same line.
15239   if (StmtLine != BodyLine)
15240     return false;
15241 
15242   return true;
15243 }
15244 
15245 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
15246                                  const Stmt *Body,
15247                                  unsigned DiagID) {
15248   // Since this is a syntactic check, don't emit diagnostic for template
15249   // instantiations, this just adds noise.
15250   if (CurrentInstantiationScope)
15251     return;
15252 
15253   // The body should be a null statement.
15254   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15255   if (!NBody)
15256     return;
15257 
15258   // Do the usual checks.
15259   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15260     return;
15261 
15262   Diag(NBody->getSemiLoc(), DiagID);
15263   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15264 }
15265 
15266 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
15267                                  const Stmt *PossibleBody) {
15268   assert(!CurrentInstantiationScope); // Ensured by caller
15269 
15270   SourceLocation StmtLoc;
15271   const Stmt *Body;
15272   unsigned DiagID;
15273   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
15274     StmtLoc = FS->getRParenLoc();
15275     Body = FS->getBody();
15276     DiagID = diag::warn_empty_for_body;
15277   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
15278     StmtLoc = WS->getCond()->getSourceRange().getEnd();
15279     Body = WS->getBody();
15280     DiagID = diag::warn_empty_while_body;
15281   } else
15282     return; // Neither `for' nor `while'.
15283 
15284   // The body should be a null statement.
15285   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15286   if (!NBody)
15287     return;
15288 
15289   // Skip expensive checks if diagnostic is disabled.
15290   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
15291     return;
15292 
15293   // Do the usual checks.
15294   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15295     return;
15296 
15297   // `for(...);' and `while(...);' are popular idioms, so in order to keep
15298   // noise level low, emit diagnostics only if for/while is followed by a
15299   // CompoundStmt, e.g.:
15300   //    for (int i = 0; i < n; i++);
15301   //    {
15302   //      a(i);
15303   //    }
15304   // or if for/while is followed by a statement with more indentation
15305   // than for/while itself:
15306   //    for (int i = 0; i < n; i++);
15307   //      a(i);
15308   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
15309   if (!ProbableTypo) {
15310     bool BodyColInvalid;
15311     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
15312         PossibleBody->getBeginLoc(), &BodyColInvalid);
15313     if (BodyColInvalid)
15314       return;
15315 
15316     bool StmtColInvalid;
15317     unsigned StmtCol =
15318         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
15319     if (StmtColInvalid)
15320       return;
15321 
15322     if (BodyCol > StmtCol)
15323       ProbableTypo = true;
15324   }
15325 
15326   if (ProbableTypo) {
15327     Diag(NBody->getSemiLoc(), DiagID);
15328     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15329   }
15330 }
15331 
15332 //===--- CHECK: Warn on self move with std::move. -------------------------===//
15333 
15334 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
15335 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
15336                              SourceLocation OpLoc) {
15337   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
15338     return;
15339 
15340   if (inTemplateInstantiation())
15341     return;
15342 
15343   // Strip parens and casts away.
15344   LHSExpr = LHSExpr->IgnoreParenImpCasts();
15345   RHSExpr = RHSExpr->IgnoreParenImpCasts();
15346 
15347   // Check for a call expression
15348   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
15349   if (!CE || CE->getNumArgs() != 1)
15350     return;
15351 
15352   // Check for a call to std::move
15353   if (!CE->isCallToStdMove())
15354     return;
15355 
15356   // Get argument from std::move
15357   RHSExpr = CE->getArg(0);
15358 
15359   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
15360   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
15361 
15362   // Two DeclRefExpr's, check that the decls are the same.
15363   if (LHSDeclRef && RHSDeclRef) {
15364     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15365       return;
15366     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15367         RHSDeclRef->getDecl()->getCanonicalDecl())
15368       return;
15369 
15370     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15371                                         << LHSExpr->getSourceRange()
15372                                         << RHSExpr->getSourceRange();
15373     return;
15374   }
15375 
15376   // Member variables require a different approach to check for self moves.
15377   // MemberExpr's are the same if every nested MemberExpr refers to the same
15378   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
15379   // the base Expr's are CXXThisExpr's.
15380   const Expr *LHSBase = LHSExpr;
15381   const Expr *RHSBase = RHSExpr;
15382   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
15383   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
15384   if (!LHSME || !RHSME)
15385     return;
15386 
15387   while (LHSME && RHSME) {
15388     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
15389         RHSME->getMemberDecl()->getCanonicalDecl())
15390       return;
15391 
15392     LHSBase = LHSME->getBase();
15393     RHSBase = RHSME->getBase();
15394     LHSME = dyn_cast<MemberExpr>(LHSBase);
15395     RHSME = dyn_cast<MemberExpr>(RHSBase);
15396   }
15397 
15398   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
15399   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
15400   if (LHSDeclRef && RHSDeclRef) {
15401     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15402       return;
15403     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15404         RHSDeclRef->getDecl()->getCanonicalDecl())
15405       return;
15406 
15407     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15408                                         << LHSExpr->getSourceRange()
15409                                         << RHSExpr->getSourceRange();
15410     return;
15411   }
15412 
15413   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
15414     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15415                                         << LHSExpr->getSourceRange()
15416                                         << RHSExpr->getSourceRange();
15417 }
15418 
15419 //===--- Layout compatibility ----------------------------------------------//
15420 
15421 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
15422 
15423 /// Check if two enumeration types are layout-compatible.
15424 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
15425   // C++11 [dcl.enum] p8:
15426   // Two enumeration types are layout-compatible if they have the same
15427   // underlying type.
15428   return ED1->isComplete() && ED2->isComplete() &&
15429          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
15430 }
15431 
15432 /// Check if two fields are layout-compatible.
15433 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
15434                                FieldDecl *Field2) {
15435   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
15436     return false;
15437 
15438   if (Field1->isBitField() != Field2->isBitField())
15439     return false;
15440 
15441   if (Field1->isBitField()) {
15442     // Make sure that the bit-fields are the same length.
15443     unsigned Bits1 = Field1->getBitWidthValue(C);
15444     unsigned Bits2 = Field2->getBitWidthValue(C);
15445 
15446     if (Bits1 != Bits2)
15447       return false;
15448   }
15449 
15450   return true;
15451 }
15452 
15453 /// Check if two standard-layout structs are layout-compatible.
15454 /// (C++11 [class.mem] p17)
15455 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
15456                                      RecordDecl *RD2) {
15457   // If both records are C++ classes, check that base classes match.
15458   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
15459     // If one of records is a CXXRecordDecl we are in C++ mode,
15460     // thus the other one is a CXXRecordDecl, too.
15461     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
15462     // Check number of base classes.
15463     if (D1CXX->getNumBases() != D2CXX->getNumBases())
15464       return false;
15465 
15466     // Check the base classes.
15467     for (CXXRecordDecl::base_class_const_iterator
15468                Base1 = D1CXX->bases_begin(),
15469            BaseEnd1 = D1CXX->bases_end(),
15470               Base2 = D2CXX->bases_begin();
15471          Base1 != BaseEnd1;
15472          ++Base1, ++Base2) {
15473       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
15474         return false;
15475     }
15476   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
15477     // If only RD2 is a C++ class, it should have zero base classes.
15478     if (D2CXX->getNumBases() > 0)
15479       return false;
15480   }
15481 
15482   // Check the fields.
15483   RecordDecl::field_iterator Field2 = RD2->field_begin(),
15484                              Field2End = RD2->field_end(),
15485                              Field1 = RD1->field_begin(),
15486                              Field1End = RD1->field_end();
15487   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
15488     if (!isLayoutCompatible(C, *Field1, *Field2))
15489       return false;
15490   }
15491   if (Field1 != Field1End || Field2 != Field2End)
15492     return false;
15493 
15494   return true;
15495 }
15496 
15497 /// Check if two standard-layout unions are layout-compatible.
15498 /// (C++11 [class.mem] p18)
15499 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
15500                                     RecordDecl *RD2) {
15501   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
15502   for (auto *Field2 : RD2->fields())
15503     UnmatchedFields.insert(Field2);
15504 
15505   for (auto *Field1 : RD1->fields()) {
15506     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
15507         I = UnmatchedFields.begin(),
15508         E = UnmatchedFields.end();
15509 
15510     for ( ; I != E; ++I) {
15511       if (isLayoutCompatible(C, Field1, *I)) {
15512         bool Result = UnmatchedFields.erase(*I);
15513         (void) Result;
15514         assert(Result);
15515         break;
15516       }
15517     }
15518     if (I == E)
15519       return false;
15520   }
15521 
15522   return UnmatchedFields.empty();
15523 }
15524 
15525 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
15526                                RecordDecl *RD2) {
15527   if (RD1->isUnion() != RD2->isUnion())
15528     return false;
15529 
15530   if (RD1->isUnion())
15531     return isLayoutCompatibleUnion(C, RD1, RD2);
15532   else
15533     return isLayoutCompatibleStruct(C, RD1, RD2);
15534 }
15535 
15536 /// Check if two types are layout-compatible in C++11 sense.
15537 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
15538   if (T1.isNull() || T2.isNull())
15539     return false;
15540 
15541   // C++11 [basic.types] p11:
15542   // If two types T1 and T2 are the same type, then T1 and T2 are
15543   // layout-compatible types.
15544   if (C.hasSameType(T1, T2))
15545     return true;
15546 
15547   T1 = T1.getCanonicalType().getUnqualifiedType();
15548   T2 = T2.getCanonicalType().getUnqualifiedType();
15549 
15550   const Type::TypeClass TC1 = T1->getTypeClass();
15551   const Type::TypeClass TC2 = T2->getTypeClass();
15552 
15553   if (TC1 != TC2)
15554     return false;
15555 
15556   if (TC1 == Type::Enum) {
15557     return isLayoutCompatible(C,
15558                               cast<EnumType>(T1)->getDecl(),
15559                               cast<EnumType>(T2)->getDecl());
15560   } else if (TC1 == Type::Record) {
15561     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
15562       return false;
15563 
15564     return isLayoutCompatible(C,
15565                               cast<RecordType>(T1)->getDecl(),
15566                               cast<RecordType>(T2)->getDecl());
15567   }
15568 
15569   return false;
15570 }
15571 
15572 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
15573 
15574 /// Given a type tag expression find the type tag itself.
15575 ///
15576 /// \param TypeExpr Type tag expression, as it appears in user's code.
15577 ///
15578 /// \param VD Declaration of an identifier that appears in a type tag.
15579 ///
15580 /// \param MagicValue Type tag magic value.
15581 ///
15582 /// \param isConstantEvaluated wether the evalaution should be performed in
15583 
15584 /// constant context.
15585 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
15586                             const ValueDecl **VD, uint64_t *MagicValue,
15587                             bool isConstantEvaluated) {
15588   while(true) {
15589     if (!TypeExpr)
15590       return false;
15591 
15592     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
15593 
15594     switch (TypeExpr->getStmtClass()) {
15595     case Stmt::UnaryOperatorClass: {
15596       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
15597       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
15598         TypeExpr = UO->getSubExpr();
15599         continue;
15600       }
15601       return false;
15602     }
15603 
15604     case Stmt::DeclRefExprClass: {
15605       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
15606       *VD = DRE->getDecl();
15607       return true;
15608     }
15609 
15610     case Stmt::IntegerLiteralClass: {
15611       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
15612       llvm::APInt MagicValueAPInt = IL->getValue();
15613       if (MagicValueAPInt.getActiveBits() <= 64) {
15614         *MagicValue = MagicValueAPInt.getZExtValue();
15615         return true;
15616       } else
15617         return false;
15618     }
15619 
15620     case Stmt::BinaryConditionalOperatorClass:
15621     case Stmt::ConditionalOperatorClass: {
15622       const AbstractConditionalOperator *ACO =
15623           cast<AbstractConditionalOperator>(TypeExpr);
15624       bool Result;
15625       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
15626                                                      isConstantEvaluated)) {
15627         if (Result)
15628           TypeExpr = ACO->getTrueExpr();
15629         else
15630           TypeExpr = ACO->getFalseExpr();
15631         continue;
15632       }
15633       return false;
15634     }
15635 
15636     case Stmt::BinaryOperatorClass: {
15637       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
15638       if (BO->getOpcode() == BO_Comma) {
15639         TypeExpr = BO->getRHS();
15640         continue;
15641       }
15642       return false;
15643     }
15644 
15645     default:
15646       return false;
15647     }
15648   }
15649 }
15650 
15651 /// Retrieve the C type corresponding to type tag TypeExpr.
15652 ///
15653 /// \param TypeExpr Expression that specifies a type tag.
15654 ///
15655 /// \param MagicValues Registered magic values.
15656 ///
15657 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
15658 ///        kind.
15659 ///
15660 /// \param TypeInfo Information about the corresponding C type.
15661 ///
15662 /// \param isConstantEvaluated wether the evalaution should be performed in
15663 /// constant context.
15664 ///
15665 /// \returns true if the corresponding C type was found.
15666 static bool GetMatchingCType(
15667     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
15668     const ASTContext &Ctx,
15669     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
15670         *MagicValues,
15671     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
15672     bool isConstantEvaluated) {
15673   FoundWrongKind = false;
15674 
15675   // Variable declaration that has type_tag_for_datatype attribute.
15676   const ValueDecl *VD = nullptr;
15677 
15678   uint64_t MagicValue;
15679 
15680   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
15681     return false;
15682 
15683   if (VD) {
15684     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
15685       if (I->getArgumentKind() != ArgumentKind) {
15686         FoundWrongKind = true;
15687         return false;
15688       }
15689       TypeInfo.Type = I->getMatchingCType();
15690       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
15691       TypeInfo.MustBeNull = I->getMustBeNull();
15692       return true;
15693     }
15694     return false;
15695   }
15696 
15697   if (!MagicValues)
15698     return false;
15699 
15700   llvm::DenseMap<Sema::TypeTagMagicValue,
15701                  Sema::TypeTagData>::const_iterator I =
15702       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
15703   if (I == MagicValues->end())
15704     return false;
15705 
15706   TypeInfo = I->second;
15707   return true;
15708 }
15709 
15710 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
15711                                       uint64_t MagicValue, QualType Type,
15712                                       bool LayoutCompatible,
15713                                       bool MustBeNull) {
15714   if (!TypeTagForDatatypeMagicValues)
15715     TypeTagForDatatypeMagicValues.reset(
15716         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
15717 
15718   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
15719   (*TypeTagForDatatypeMagicValues)[Magic] =
15720       TypeTagData(Type, LayoutCompatible, MustBeNull);
15721 }
15722 
15723 static bool IsSameCharType(QualType T1, QualType T2) {
15724   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
15725   if (!BT1)
15726     return false;
15727 
15728   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
15729   if (!BT2)
15730     return false;
15731 
15732   BuiltinType::Kind T1Kind = BT1->getKind();
15733   BuiltinType::Kind T2Kind = BT2->getKind();
15734 
15735   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
15736          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
15737          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
15738          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
15739 }
15740 
15741 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
15742                                     const ArrayRef<const Expr *> ExprArgs,
15743                                     SourceLocation CallSiteLoc) {
15744   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
15745   bool IsPointerAttr = Attr->getIsPointer();
15746 
15747   // Retrieve the argument representing the 'type_tag'.
15748   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
15749   if (TypeTagIdxAST >= ExprArgs.size()) {
15750     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
15751         << 0 << Attr->getTypeTagIdx().getSourceIndex();
15752     return;
15753   }
15754   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
15755   bool FoundWrongKind;
15756   TypeTagData TypeInfo;
15757   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
15758                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
15759                         TypeInfo, isConstantEvaluated())) {
15760     if (FoundWrongKind)
15761       Diag(TypeTagExpr->getExprLoc(),
15762            diag::warn_type_tag_for_datatype_wrong_kind)
15763         << TypeTagExpr->getSourceRange();
15764     return;
15765   }
15766 
15767   // Retrieve the argument representing the 'arg_idx'.
15768   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
15769   if (ArgumentIdxAST >= ExprArgs.size()) {
15770     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
15771         << 1 << Attr->getArgumentIdx().getSourceIndex();
15772     return;
15773   }
15774   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
15775   if (IsPointerAttr) {
15776     // Skip implicit cast of pointer to `void *' (as a function argument).
15777     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
15778       if (ICE->getType()->isVoidPointerType() &&
15779           ICE->getCastKind() == CK_BitCast)
15780         ArgumentExpr = ICE->getSubExpr();
15781   }
15782   QualType ArgumentType = ArgumentExpr->getType();
15783 
15784   // Passing a `void*' pointer shouldn't trigger a warning.
15785   if (IsPointerAttr && ArgumentType->isVoidPointerType())
15786     return;
15787 
15788   if (TypeInfo.MustBeNull) {
15789     // Type tag with matching void type requires a null pointer.
15790     if (!ArgumentExpr->isNullPointerConstant(Context,
15791                                              Expr::NPC_ValueDependentIsNotNull)) {
15792       Diag(ArgumentExpr->getExprLoc(),
15793            diag::warn_type_safety_null_pointer_required)
15794           << ArgumentKind->getName()
15795           << ArgumentExpr->getSourceRange()
15796           << TypeTagExpr->getSourceRange();
15797     }
15798     return;
15799   }
15800 
15801   QualType RequiredType = TypeInfo.Type;
15802   if (IsPointerAttr)
15803     RequiredType = Context.getPointerType(RequiredType);
15804 
15805   bool mismatch = false;
15806   if (!TypeInfo.LayoutCompatible) {
15807     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
15808 
15809     // C++11 [basic.fundamental] p1:
15810     // Plain char, signed char, and unsigned char are three distinct types.
15811     //
15812     // But we treat plain `char' as equivalent to `signed char' or `unsigned
15813     // char' depending on the current char signedness mode.
15814     if (mismatch)
15815       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
15816                                            RequiredType->getPointeeType())) ||
15817           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
15818         mismatch = false;
15819   } else
15820     if (IsPointerAttr)
15821       mismatch = !isLayoutCompatible(Context,
15822                                      ArgumentType->getPointeeType(),
15823                                      RequiredType->getPointeeType());
15824     else
15825       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
15826 
15827   if (mismatch)
15828     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
15829         << ArgumentType << ArgumentKind
15830         << TypeInfo.LayoutCompatible << RequiredType
15831         << ArgumentExpr->getSourceRange()
15832         << TypeTagExpr->getSourceRange();
15833 }
15834 
15835 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
15836                                          CharUnits Alignment) {
15837   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
15838 }
15839 
15840 void Sema::DiagnoseMisalignedMembers() {
15841   for (MisalignedMember &m : MisalignedMembers) {
15842     const NamedDecl *ND = m.RD;
15843     if (ND->getName().empty()) {
15844       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
15845         ND = TD;
15846     }
15847     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
15848         << m.MD << ND << m.E->getSourceRange();
15849   }
15850   MisalignedMembers.clear();
15851 }
15852 
15853 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
15854   E = E->IgnoreParens();
15855   if (!T->isPointerType() && !T->isIntegerType())
15856     return;
15857   if (isa<UnaryOperator>(E) &&
15858       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
15859     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
15860     if (isa<MemberExpr>(Op)) {
15861       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
15862       if (MA != MisalignedMembers.end() &&
15863           (T->isIntegerType() ||
15864            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
15865                                    Context.getTypeAlignInChars(
15866                                        T->getPointeeType()) <= MA->Alignment))))
15867         MisalignedMembers.erase(MA);
15868     }
15869   }
15870 }
15871 
15872 void Sema::RefersToMemberWithReducedAlignment(
15873     Expr *E,
15874     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
15875         Action) {
15876   const auto *ME = dyn_cast<MemberExpr>(E);
15877   if (!ME)
15878     return;
15879 
15880   // No need to check expressions with an __unaligned-qualified type.
15881   if (E->getType().getQualifiers().hasUnaligned())
15882     return;
15883 
15884   // For a chain of MemberExpr like "a.b.c.d" this list
15885   // will keep FieldDecl's like [d, c, b].
15886   SmallVector<FieldDecl *, 4> ReverseMemberChain;
15887   const MemberExpr *TopME = nullptr;
15888   bool AnyIsPacked = false;
15889   do {
15890     QualType BaseType = ME->getBase()->getType();
15891     if (BaseType->isDependentType())
15892       return;
15893     if (ME->isArrow())
15894       BaseType = BaseType->getPointeeType();
15895     RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
15896     if (RD->isInvalidDecl())
15897       return;
15898 
15899     ValueDecl *MD = ME->getMemberDecl();
15900     auto *FD = dyn_cast<FieldDecl>(MD);
15901     // We do not care about non-data members.
15902     if (!FD || FD->isInvalidDecl())
15903       return;
15904 
15905     AnyIsPacked =
15906         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
15907     ReverseMemberChain.push_back(FD);
15908 
15909     TopME = ME;
15910     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
15911   } while (ME);
15912   assert(TopME && "We did not compute a topmost MemberExpr!");
15913 
15914   // Not the scope of this diagnostic.
15915   if (!AnyIsPacked)
15916     return;
15917 
15918   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
15919   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
15920   // TODO: The innermost base of the member expression may be too complicated.
15921   // For now, just disregard these cases. This is left for future
15922   // improvement.
15923   if (!DRE && !isa<CXXThisExpr>(TopBase))
15924       return;
15925 
15926   // Alignment expected by the whole expression.
15927   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
15928 
15929   // No need to do anything else with this case.
15930   if (ExpectedAlignment.isOne())
15931     return;
15932 
15933   // Synthesize offset of the whole access.
15934   CharUnits Offset;
15935   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
15936        I++) {
15937     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
15938   }
15939 
15940   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
15941   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
15942       ReverseMemberChain.back()->getParent()->getTypeForDecl());
15943 
15944   // The base expression of the innermost MemberExpr may give
15945   // stronger guarantees than the class containing the member.
15946   if (DRE && !TopME->isArrow()) {
15947     const ValueDecl *VD = DRE->getDecl();
15948     if (!VD->getType()->isReferenceType())
15949       CompleteObjectAlignment =
15950           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
15951   }
15952 
15953   // Check if the synthesized offset fulfills the alignment.
15954   if (Offset % ExpectedAlignment != 0 ||
15955       // It may fulfill the offset it but the effective alignment may still be
15956       // lower than the expected expression alignment.
15957       CompleteObjectAlignment < ExpectedAlignment) {
15958     // If this happens, we want to determine a sensible culprit of this.
15959     // Intuitively, watching the chain of member expressions from right to
15960     // left, we start with the required alignment (as required by the field
15961     // type) but some packed attribute in that chain has reduced the alignment.
15962     // It may happen that another packed structure increases it again. But if
15963     // we are here such increase has not been enough. So pointing the first
15964     // FieldDecl that either is packed or else its RecordDecl is,
15965     // seems reasonable.
15966     FieldDecl *FD = nullptr;
15967     CharUnits Alignment;
15968     for (FieldDecl *FDI : ReverseMemberChain) {
15969       if (FDI->hasAttr<PackedAttr>() ||
15970           FDI->getParent()->hasAttr<PackedAttr>()) {
15971         FD = FDI;
15972         Alignment = std::min(
15973             Context.getTypeAlignInChars(FD->getType()),
15974             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
15975         break;
15976       }
15977     }
15978     assert(FD && "We did not find a packed FieldDecl!");
15979     Action(E, FD->getParent(), FD, Alignment);
15980   }
15981 }
15982 
15983 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
15984   using namespace std::placeholders;
15985 
15986   RefersToMemberWithReducedAlignment(
15987       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
15988                      _2, _3, _4));
15989 }
15990 
15991 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall,
15992                                             ExprResult CallResult) {
15993   if (checkArgCount(*this, TheCall, 1))
15994     return ExprError();
15995 
15996   ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
15997   if (MatrixArg.isInvalid())
15998     return MatrixArg;
15999   Expr *Matrix = MatrixArg.get();
16000 
16001   auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
16002   if (!MType) {
16003     Diag(Matrix->getBeginLoc(), diag::err_builtin_matrix_arg);
16004     return ExprError();
16005   }
16006 
16007   // Create returned matrix type by swapping rows and columns of the argument
16008   // matrix type.
16009   QualType ResultType = Context.getConstantMatrixType(
16010       MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
16011 
16012   // Change the return type to the type of the returned matrix.
16013   TheCall->setType(ResultType);
16014 
16015   // Update call argument to use the possibly converted matrix argument.
16016   TheCall->setArg(0, Matrix);
16017   return CallResult;
16018 }
16019 
16020 // Get and verify the matrix dimensions.
16021 static llvm::Optional<unsigned>
16022 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {
16023   SourceLocation ErrorPos;
16024   Optional<llvm::APSInt> Value =
16025       Expr->getIntegerConstantExpr(S.Context, &ErrorPos);
16026   if (!Value) {
16027     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
16028         << Name;
16029     return {};
16030   }
16031   uint64_t Dim = Value->getZExtValue();
16032   if (!ConstantMatrixType::isDimensionValid(Dim)) {
16033     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
16034         << Name << ConstantMatrixType::getMaxElementsPerDimension();
16035     return {};
16036   }
16037   return Dim;
16038 }
16039 
16040 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
16041                                                   ExprResult CallResult) {
16042   if (!getLangOpts().MatrixTypes) {
16043     Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
16044     return ExprError();
16045   }
16046 
16047   if (checkArgCount(*this, TheCall, 4))
16048     return ExprError();
16049 
16050   unsigned PtrArgIdx = 0;
16051   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16052   Expr *RowsExpr = TheCall->getArg(1);
16053   Expr *ColumnsExpr = TheCall->getArg(2);
16054   Expr *StrideExpr = TheCall->getArg(3);
16055 
16056   bool ArgError = false;
16057 
16058   // Check pointer argument.
16059   {
16060     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
16061     if (PtrConv.isInvalid())
16062       return PtrConv;
16063     PtrExpr = PtrConv.get();
16064     TheCall->setArg(0, PtrExpr);
16065     if (PtrExpr->isTypeDependent()) {
16066       TheCall->setType(Context.DependentTy);
16067       return TheCall;
16068     }
16069   }
16070 
16071   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16072   QualType ElementTy;
16073   if (!PtrTy) {
16074     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
16075         << PtrArgIdx + 1;
16076     ArgError = true;
16077   } else {
16078     ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
16079 
16080     if (!ConstantMatrixType::isValidElementType(ElementTy)) {
16081       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
16082           << PtrArgIdx + 1;
16083       ArgError = true;
16084     }
16085   }
16086 
16087   // Apply default Lvalue conversions and convert the expression to size_t.
16088   auto ApplyArgumentConversions = [this](Expr *E) {
16089     ExprResult Conv = DefaultLvalueConversion(E);
16090     if (Conv.isInvalid())
16091       return Conv;
16092 
16093     return tryConvertExprToType(Conv.get(), Context.getSizeType());
16094   };
16095 
16096   // Apply conversion to row and column expressions.
16097   ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
16098   if (!RowsConv.isInvalid()) {
16099     RowsExpr = RowsConv.get();
16100     TheCall->setArg(1, RowsExpr);
16101   } else
16102     RowsExpr = nullptr;
16103 
16104   ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
16105   if (!ColumnsConv.isInvalid()) {
16106     ColumnsExpr = ColumnsConv.get();
16107     TheCall->setArg(2, ColumnsExpr);
16108   } else
16109     ColumnsExpr = nullptr;
16110 
16111   // If any any part of the result matrix type is still pending, just use
16112   // Context.DependentTy, until all parts are resolved.
16113   if ((RowsExpr && RowsExpr->isTypeDependent()) ||
16114       (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
16115     TheCall->setType(Context.DependentTy);
16116     return CallResult;
16117   }
16118 
16119   // Check row and column dimenions.
16120   llvm::Optional<unsigned> MaybeRows;
16121   if (RowsExpr)
16122     MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
16123 
16124   llvm::Optional<unsigned> MaybeColumns;
16125   if (ColumnsExpr)
16126     MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
16127 
16128   // Check stride argument.
16129   ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
16130   if (StrideConv.isInvalid())
16131     return ExprError();
16132   StrideExpr = StrideConv.get();
16133   TheCall->setArg(3, StrideExpr);
16134 
16135   if (MaybeRows) {
16136     if (Optional<llvm::APSInt> Value =
16137             StrideExpr->getIntegerConstantExpr(Context)) {
16138       uint64_t Stride = Value->getZExtValue();
16139       if (Stride < *MaybeRows) {
16140         Diag(StrideExpr->getBeginLoc(),
16141              diag::err_builtin_matrix_stride_too_small);
16142         ArgError = true;
16143       }
16144     }
16145   }
16146 
16147   if (ArgError || !MaybeRows || !MaybeColumns)
16148     return ExprError();
16149 
16150   TheCall->setType(
16151       Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
16152   return CallResult;
16153 }
16154 
16155 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
16156                                                    ExprResult CallResult) {
16157   if (checkArgCount(*this, TheCall, 3))
16158     return ExprError();
16159 
16160   unsigned PtrArgIdx = 1;
16161   Expr *MatrixExpr = TheCall->getArg(0);
16162   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16163   Expr *StrideExpr = TheCall->getArg(2);
16164 
16165   bool ArgError = false;
16166 
16167   {
16168     ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
16169     if (MatrixConv.isInvalid())
16170       return MatrixConv;
16171     MatrixExpr = MatrixConv.get();
16172     TheCall->setArg(0, MatrixExpr);
16173   }
16174   if (MatrixExpr->isTypeDependent()) {
16175     TheCall->setType(Context.DependentTy);
16176     return TheCall;
16177   }
16178 
16179   auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
16180   if (!MatrixTy) {
16181     Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_matrix_arg) << 0;
16182     ArgError = true;
16183   }
16184 
16185   {
16186     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
16187     if (PtrConv.isInvalid())
16188       return PtrConv;
16189     PtrExpr = PtrConv.get();
16190     TheCall->setArg(1, PtrExpr);
16191     if (PtrExpr->isTypeDependent()) {
16192       TheCall->setType(Context.DependentTy);
16193       return TheCall;
16194     }
16195   }
16196 
16197   // Check pointer argument.
16198   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16199   if (!PtrTy) {
16200     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
16201         << PtrArgIdx + 1;
16202     ArgError = true;
16203   } else {
16204     QualType ElementTy = PtrTy->getPointeeType();
16205     if (ElementTy.isConstQualified()) {
16206       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
16207       ArgError = true;
16208     }
16209     ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
16210     if (MatrixTy &&
16211         !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
16212       Diag(PtrExpr->getBeginLoc(),
16213            diag::err_builtin_matrix_pointer_arg_mismatch)
16214           << ElementTy << MatrixTy->getElementType();
16215       ArgError = true;
16216     }
16217   }
16218 
16219   // Apply default Lvalue conversions and convert the stride expression to
16220   // size_t.
16221   {
16222     ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
16223     if (StrideConv.isInvalid())
16224       return StrideConv;
16225 
16226     StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
16227     if (StrideConv.isInvalid())
16228       return StrideConv;
16229     StrideExpr = StrideConv.get();
16230     TheCall->setArg(2, StrideExpr);
16231   }
16232 
16233   // Check stride argument.
16234   if (MatrixTy) {
16235     if (Optional<llvm::APSInt> Value =
16236             StrideExpr->getIntegerConstantExpr(Context)) {
16237       uint64_t Stride = Value->getZExtValue();
16238       if (Stride < MatrixTy->getNumRows()) {
16239         Diag(StrideExpr->getBeginLoc(),
16240              diag::err_builtin_matrix_stride_too_small);
16241         ArgError = true;
16242       }
16243     }
16244   }
16245 
16246   if (ArgError)
16247     return ExprError();
16248 
16249   return CallResult;
16250 }
16251 
16252 /// \brief Enforce the bounds of a TCB
16253 /// CheckTCBEnforcement - Enforces that every function in a named TCB only
16254 /// directly calls other functions in the same TCB as marked by the enforce_tcb
16255 /// and enforce_tcb_leaf attributes.
16256 void Sema::CheckTCBEnforcement(const CallExpr *TheCall,
16257                                const FunctionDecl *Callee) {
16258   const FunctionDecl *Caller = getCurFunctionDecl();
16259 
16260   // Calls to builtins are not enforced.
16261   if (!Caller || !Caller->hasAttr<EnforceTCBAttr>() ||
16262       Callee->getBuiltinID() != 0)
16263     return;
16264 
16265   // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
16266   // all TCBs the callee is a part of.
16267   llvm::StringSet<> CalleeTCBs;
16268   for_each(Callee->specific_attrs<EnforceTCBAttr>(),
16269            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
16270   for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(),
16271            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
16272 
16273   // Go through the TCBs the caller is a part of and emit warnings if Caller
16274   // is in a TCB that the Callee is not.
16275   for_each(
16276       Caller->specific_attrs<EnforceTCBAttr>(),
16277       [&](const auto *A) {
16278         StringRef CallerTCB = A->getTCBName();
16279         if (CalleeTCBs.count(CallerTCB) == 0) {
16280           this->Diag(TheCall->getExprLoc(),
16281                      diag::warn_tcb_enforcement_violation) << Callee
16282                                                            << CallerTCB;
16283         }
16284       });
16285 }
16286