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/Stmt.h"
34 #include "clang/AST/TemplateBase.h"
35 #include "clang/AST/Type.h"
36 #include "clang/AST/TypeLoc.h"
37 #include "clang/AST/UnresolvedSet.h"
38 #include "clang/Basic/AddressSpaces.h"
39 #include "clang/Basic/CharInfo.h"
40 #include "clang/Basic/Diagnostic.h"
41 #include "clang/Basic/IdentifierTable.h"
42 #include "clang/Basic/LLVM.h"
43 #include "clang/Basic/LangOptions.h"
44 #include "clang/Basic/OpenCLOptions.h"
45 #include "clang/Basic/OperatorKinds.h"
46 #include "clang/Basic/PartialDiagnostic.h"
47 #include "clang/Basic/SourceLocation.h"
48 #include "clang/Basic/SourceManager.h"
49 #include "clang/Basic/Specifiers.h"
50 #include "clang/Basic/SyncScope.h"
51 #include "clang/Basic/TargetBuiltins.h"
52 #include "clang/Basic/TargetCXXABI.h"
53 #include "clang/Basic/TargetInfo.h"
54 #include "clang/Basic/TypeTraits.h"
55 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
56 #include "clang/Sema/Initialization.h"
57 #include "clang/Sema/Lookup.h"
58 #include "clang/Sema/Ownership.h"
59 #include "clang/Sema/Scope.h"
60 #include "clang/Sema/ScopeInfo.h"
61 #include "clang/Sema/Sema.h"
62 #include "clang/Sema/SemaInternal.h"
63 #include "llvm/ADT/APFloat.h"
64 #include "llvm/ADT/APInt.h"
65 #include "llvm/ADT/APSInt.h"
66 #include "llvm/ADT/ArrayRef.h"
67 #include "llvm/ADT/DenseMap.h"
68 #include "llvm/ADT/FoldingSet.h"
69 #include "llvm/ADT/None.h"
70 #include "llvm/ADT/Optional.h"
71 #include "llvm/ADT/STLExtras.h"
72 #include "llvm/ADT/SmallBitVector.h"
73 #include "llvm/ADT/SmallPtrSet.h"
74 #include "llvm/ADT/SmallString.h"
75 #include "llvm/ADT/SmallVector.h"
76 #include "llvm/ADT/StringRef.h"
77 #include "llvm/ADT/StringSwitch.h"
78 #include "llvm/ADT/Triple.h"
79 #include "llvm/Support/AtomicOrdering.h"
80 #include "llvm/Support/Casting.h"
81 #include "llvm/Support/Compiler.h"
82 #include "llvm/Support/ConvertUTF.h"
83 #include "llvm/Support/ErrorHandling.h"
84 #include "llvm/Support/Format.h"
85 #include "llvm/Support/Locale.h"
86 #include "llvm/Support/MathExtras.h"
87 #include "llvm/Support/SaveAndRestore.h"
88 #include "llvm/Support/raw_ostream.h"
89 #include <algorithm>
90 #include <cassert>
91 #include <cstddef>
92 #include <cstdint>
93 #include <functional>
94 #include <limits>
95 #include <string>
96 #include <tuple>
97 #include <utility>
98 
99 using namespace clang;
100 using namespace sema;
101 
102 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
103                                                     unsigned ByteNo) const {
104   return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
105                                Context.getTargetInfo());
106 }
107 
108 /// Checks that a call expression's argument count is the desired number.
109 /// This is useful when doing custom type-checking.  Returns true on error.
110 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
111   unsigned argCount = call->getNumArgs();
112   if (argCount == desiredArgCount) return false;
113 
114   if (argCount < desiredArgCount)
115     return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args)
116            << 0 /*function call*/ << desiredArgCount << argCount
117            << call->getSourceRange();
118 
119   // Highlight all the excess arguments.
120   SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(),
121                     call->getArg(argCount - 1)->getEndLoc());
122 
123   return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
124     << 0 /*function call*/ << desiredArgCount << argCount
125     << call->getArg(1)->getSourceRange();
126 }
127 
128 /// Check that the first argument to __builtin_annotation is an integer
129 /// and the second argument is a non-wide string literal.
130 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
131   if (checkArgCount(S, TheCall, 2))
132     return true;
133 
134   // First argument should be an integer.
135   Expr *ValArg = TheCall->getArg(0);
136   QualType Ty = ValArg->getType();
137   if (!Ty->isIntegerType()) {
138     S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
139         << ValArg->getSourceRange();
140     return true;
141   }
142 
143   // Second argument should be a constant string.
144   Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
145   StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
146   if (!Literal || !Literal->isAscii()) {
147     S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
148         << StrArg->getSourceRange();
149     return true;
150   }
151 
152   TheCall->setType(Ty);
153   return false;
154 }
155 
156 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
157   // We need at least one argument.
158   if (TheCall->getNumArgs() < 1) {
159     S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
160         << 0 << 1 << TheCall->getNumArgs()
161         << TheCall->getCallee()->getSourceRange();
162     return true;
163   }
164 
165   // All arguments should be wide string literals.
166   for (Expr *Arg : TheCall->arguments()) {
167     auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
168     if (!Literal || !Literal->isWide()) {
169       S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
170           << Arg->getSourceRange();
171       return true;
172     }
173   }
174 
175   return false;
176 }
177 
178 /// Check that the argument to __builtin_addressof is a glvalue, and set the
179 /// result type to the corresponding pointer type.
180 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
181   if (checkArgCount(S, TheCall, 1))
182     return true;
183 
184   ExprResult Arg(TheCall->getArg(0));
185   QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
186   if (ResultType.isNull())
187     return true;
188 
189   TheCall->setArg(0, Arg.get());
190   TheCall->setType(ResultType);
191   return false;
192 }
193 
194 /// Check the number of arguments and set the result type to
195 /// the argument type.
196 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
197   if (checkArgCount(S, TheCall, 1))
198     return true;
199 
200   TheCall->setType(TheCall->getArg(0)->getType());
201   return false;
202 }
203 
204 /// Check that the value argument for __builtin_is_aligned(value, alignment) and
205 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
206 /// type (but not a function pointer) and that the alignment is a power-of-two.
207 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
208   if (checkArgCount(S, TheCall, 2))
209     return true;
210 
211   clang::Expr *Source = TheCall->getArg(0);
212   bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
213 
214   auto IsValidIntegerType = [](QualType Ty) {
215     return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
216   };
217   QualType SrcTy = Source->getType();
218   // We should also be able to use it with arrays (but not functions!).
219   if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
220     SrcTy = S.Context.getDecayedType(SrcTy);
221   }
222   if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
223       SrcTy->isFunctionPointerType()) {
224     // FIXME: this is not quite the right error message since we don't allow
225     // floating point types, or member pointers.
226     S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand)
227         << SrcTy;
228     return true;
229   }
230 
231   clang::Expr *AlignOp = TheCall->getArg(1);
232   if (!IsValidIntegerType(AlignOp->getType())) {
233     S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int)
234         << AlignOp->getType();
235     return true;
236   }
237   Expr::EvalResult AlignResult;
238   unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1;
239   // We can't check validity of alignment if it is type dependent.
240   if (!AlignOp->isInstantiationDependent() &&
241       AlignOp->EvaluateAsInt(AlignResult, S.Context,
242                              Expr::SE_AllowSideEffects)) {
243     llvm::APSInt AlignValue = AlignResult.Val.getInt();
244     llvm::APSInt MaxValue(
245         llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits));
246     if (AlignValue < 1) {
247       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1;
248       return true;
249     }
250     if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) {
251       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big)
252           << MaxValue.toString(10);
253       return true;
254     }
255     if (!AlignValue.isPowerOf2()) {
256       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two);
257       return true;
258     }
259     if (AlignValue == 1) {
260       S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless)
261           << IsBooleanAlignBuiltin;
262     }
263   }
264 
265   ExprResult SrcArg = S.PerformCopyInitialization(
266       InitializedEntity::InitializeParameter(S.Context, SrcTy, false),
267       SourceLocation(), Source);
268   if (SrcArg.isInvalid())
269     return true;
270   TheCall->setArg(0, SrcArg.get());
271   ExprResult AlignArg =
272       S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
273                                       S.Context, AlignOp->getType(), false),
274                                   SourceLocation(), AlignOp);
275   if (AlignArg.isInvalid())
276     return true;
277   TheCall->setArg(1, AlignArg.get());
278   // For align_up/align_down, the return type is the same as the (potentially
279   // decayed) argument type including qualifiers. For is_aligned(), the result
280   // is always bool.
281   TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
282   return false;
283 }
284 
285 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
286   if (checkArgCount(S, TheCall, 3))
287     return true;
288 
289   // First two arguments should be integers.
290   for (unsigned I = 0; I < 2; ++I) {
291     ExprResult Arg = TheCall->getArg(I);
292     QualType Ty = Arg.get()->getType();
293     if (!Ty->isIntegerType()) {
294       S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
295           << Ty << Arg.get()->getSourceRange();
296       return true;
297     }
298     InitializedEntity Entity = InitializedEntity::InitializeParameter(
299         S.getASTContext(), Ty, /*consume*/ false);
300     Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
301     if (Arg.isInvalid())
302       return true;
303     TheCall->setArg(I, Arg.get());
304   }
305 
306   // Third argument should be a pointer to a non-const integer.
307   // IRGen correctly handles volatile, restrict, and address spaces, and
308   // the other qualifiers aren't possible.
309   {
310     ExprResult Arg = TheCall->getArg(2);
311     QualType Ty = Arg.get()->getType();
312     const auto *PtrTy = Ty->getAs<PointerType>();
313     if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
314           !PtrTy->getPointeeType().isConstQualified())) {
315       S.Diag(Arg.get()->getBeginLoc(),
316              diag::err_overflow_builtin_must_be_ptr_int)
317           << Ty << Arg.get()->getSourceRange();
318       return true;
319     }
320     InitializedEntity Entity = InitializedEntity::InitializeParameter(
321         S.getASTContext(), Ty, /*consume*/ false);
322     Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
323     if (Arg.isInvalid())
324       return true;
325     TheCall->setArg(2, Arg.get());
326   }
327   return false;
328 }
329 
330 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
331   if (checkArgCount(S, BuiltinCall, 2))
332     return true;
333 
334   SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
335   Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
336   Expr *Call = BuiltinCall->getArg(0);
337   Expr *Chain = BuiltinCall->getArg(1);
338 
339   if (Call->getStmtClass() != Stmt::CallExprClass) {
340     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
341         << Call->getSourceRange();
342     return true;
343   }
344 
345   auto CE = cast<CallExpr>(Call);
346   if (CE->getCallee()->getType()->isBlockPointerType()) {
347     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
348         << Call->getSourceRange();
349     return true;
350   }
351 
352   const Decl *TargetDecl = CE->getCalleeDecl();
353   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
354     if (FD->getBuiltinID()) {
355       S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
356           << Call->getSourceRange();
357       return true;
358     }
359 
360   if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
361     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
362         << Call->getSourceRange();
363     return true;
364   }
365 
366   ExprResult ChainResult = S.UsualUnaryConversions(Chain);
367   if (ChainResult.isInvalid())
368     return true;
369   if (!ChainResult.get()->getType()->isPointerType()) {
370     S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
371         << Chain->getSourceRange();
372     return true;
373   }
374 
375   QualType ReturnTy = CE->getCallReturnType(S.Context);
376   QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
377   QualType BuiltinTy = S.Context.getFunctionType(
378       ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
379   QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
380 
381   Builtin =
382       S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
383 
384   BuiltinCall->setType(CE->getType());
385   BuiltinCall->setValueKind(CE->getValueKind());
386   BuiltinCall->setObjectKind(CE->getObjectKind());
387   BuiltinCall->setCallee(Builtin);
388   BuiltinCall->setArg(1, ChainResult.get());
389 
390   return false;
391 }
392 
393 /// Check a call to BuiltinID for buffer overflows. If BuiltinID is a
394 /// __builtin_*_chk function, then use the object size argument specified in the
395 /// source. Otherwise, infer the object size using __builtin_object_size.
396 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
397                                                CallExpr *TheCall) {
398   // FIXME: There are some more useful checks we could be doing here:
399   //  - Analyze the format string of sprintf to see how much of buffer is used.
400   //  - Evaluate strlen of strcpy arguments, use as object size.
401 
402   if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
403       isConstantEvaluated())
404     return;
405 
406   unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true);
407   if (!BuiltinID)
408     return;
409 
410   unsigned DiagID = 0;
411   bool IsChkVariant = false;
412   unsigned SizeIndex, ObjectIndex;
413   switch (BuiltinID) {
414   default:
415     return;
416   case Builtin::BI__builtin___memcpy_chk:
417   case Builtin::BI__builtin___memmove_chk:
418   case Builtin::BI__builtin___memset_chk:
419   case Builtin::BI__builtin___strlcat_chk:
420   case Builtin::BI__builtin___strlcpy_chk:
421   case Builtin::BI__builtin___strncat_chk:
422   case Builtin::BI__builtin___strncpy_chk:
423   case Builtin::BI__builtin___stpncpy_chk:
424   case Builtin::BI__builtin___memccpy_chk:
425   case Builtin::BI__builtin___mempcpy_chk: {
426     DiagID = diag::warn_builtin_chk_overflow;
427     IsChkVariant = true;
428     SizeIndex = TheCall->getNumArgs() - 2;
429     ObjectIndex = TheCall->getNumArgs() - 1;
430     break;
431   }
432 
433   case Builtin::BI__builtin___snprintf_chk:
434   case Builtin::BI__builtin___vsnprintf_chk: {
435     DiagID = diag::warn_builtin_chk_overflow;
436     IsChkVariant = true;
437     SizeIndex = 1;
438     ObjectIndex = 3;
439     break;
440   }
441 
442   case Builtin::BIstrncat:
443   case Builtin::BI__builtin_strncat:
444   case Builtin::BIstrncpy:
445   case Builtin::BI__builtin_strncpy:
446   case Builtin::BIstpncpy:
447   case Builtin::BI__builtin_stpncpy: {
448     // Whether these functions overflow depends on the runtime strlen of the
449     // string, not just the buffer size, so emitting the "always overflow"
450     // diagnostic isn't quite right. We should still diagnose passing a buffer
451     // size larger than the destination buffer though; this is a runtime abort
452     // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
453     DiagID = diag::warn_fortify_source_size_mismatch;
454     SizeIndex = TheCall->getNumArgs() - 1;
455     ObjectIndex = 0;
456     break;
457   }
458 
459   case Builtin::BImemcpy:
460   case Builtin::BI__builtin_memcpy:
461   case Builtin::BImemmove:
462   case Builtin::BI__builtin_memmove:
463   case Builtin::BImemset:
464   case Builtin::BI__builtin_memset:
465   case Builtin::BImempcpy:
466   case Builtin::BI__builtin_mempcpy: {
467     DiagID = diag::warn_fortify_source_overflow;
468     SizeIndex = TheCall->getNumArgs() - 1;
469     ObjectIndex = 0;
470     break;
471   }
472   case Builtin::BIsnprintf:
473   case Builtin::BI__builtin_snprintf:
474   case Builtin::BIvsnprintf:
475   case Builtin::BI__builtin_vsnprintf: {
476     DiagID = diag::warn_fortify_source_size_mismatch;
477     SizeIndex = 1;
478     ObjectIndex = 0;
479     break;
480   }
481   }
482 
483   llvm::APSInt ObjectSize;
484   // For __builtin___*_chk, the object size is explicitly provided by the caller
485   // (usually using __builtin_object_size). Use that value to check this call.
486   if (IsChkVariant) {
487     Expr::EvalResult Result;
488     Expr *SizeArg = TheCall->getArg(ObjectIndex);
489     if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
490       return;
491     ObjectSize = Result.Val.getInt();
492 
493   // Otherwise, try to evaluate an imaginary call to __builtin_object_size.
494   } else {
495     // If the parameter has a pass_object_size attribute, then we should use its
496     // (potentially) more strict checking mode. Otherwise, conservatively assume
497     // type 0.
498     int BOSType = 0;
499     if (const auto *POS =
500             FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>())
501       BOSType = POS->getType();
502 
503     Expr *ObjArg = TheCall->getArg(ObjectIndex);
504     uint64_t Result;
505     if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
506       return;
507     // Get the object size in the target's size_t width.
508     const TargetInfo &TI = getASTContext().getTargetInfo();
509     unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
510     ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
511   }
512 
513   // Evaluate the number of bytes of the object that this call will use.
514   Expr::EvalResult Result;
515   Expr *UsedSizeArg = TheCall->getArg(SizeIndex);
516   if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext()))
517     return;
518   llvm::APSInt UsedSize = Result.Val.getInt();
519 
520   if (UsedSize.ule(ObjectSize))
521     return;
522 
523   StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
524   // Skim off the details of whichever builtin was called to produce a better
525   // diagnostic, as it's unlikley that the user wrote the __builtin explicitly.
526   if (IsChkVariant) {
527     FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
528     FunctionName = FunctionName.drop_back(std::strlen("_chk"));
529   } else if (FunctionName.startswith("__builtin_")) {
530     FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
531   }
532 
533   DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
534                       PDiag(DiagID)
535                           << FunctionName << ObjectSize.toString(/*Radix=*/10)
536                           << UsedSize.toString(/*Radix=*/10));
537 }
538 
539 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
540                                      Scope::ScopeFlags NeededScopeFlags,
541                                      unsigned DiagID) {
542   // Scopes aren't available during instantiation. Fortunately, builtin
543   // functions cannot be template args so they cannot be formed through template
544   // instantiation. Therefore checking once during the parse is sufficient.
545   if (SemaRef.inTemplateInstantiation())
546     return false;
547 
548   Scope *S = SemaRef.getCurScope();
549   while (S && !S->isSEHExceptScope())
550     S = S->getParent();
551   if (!S || !(S->getFlags() & NeededScopeFlags)) {
552     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
553     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
554         << DRE->getDecl()->getIdentifier();
555     return true;
556   }
557 
558   return false;
559 }
560 
561 static inline bool isBlockPointer(Expr *Arg) {
562   return Arg->getType()->isBlockPointerType();
563 }
564 
565 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
566 /// void*, which is a requirement of device side enqueue.
567 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
568   const BlockPointerType *BPT =
569       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
570   ArrayRef<QualType> Params =
571       BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes();
572   unsigned ArgCounter = 0;
573   bool IllegalParams = false;
574   // Iterate through the block parameters until either one is found that is not
575   // a local void*, or the block is valid.
576   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
577        I != E; ++I, ++ArgCounter) {
578     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
579         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
580             LangAS::opencl_local) {
581       // Get the location of the error. If a block literal has been passed
582       // (BlockExpr) then we can point straight to the offending argument,
583       // else we just point to the variable reference.
584       SourceLocation ErrorLoc;
585       if (isa<BlockExpr>(BlockArg)) {
586         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
587         ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
588       } else if (isa<DeclRefExpr>(BlockArg)) {
589         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
590       }
591       S.Diag(ErrorLoc,
592              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
593       IllegalParams = true;
594     }
595   }
596 
597   return IllegalParams;
598 }
599 
600 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
601   if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
602     S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
603         << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
604     return true;
605   }
606   return false;
607 }
608 
609 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
610   if (checkArgCount(S, TheCall, 2))
611     return true;
612 
613   if (checkOpenCLSubgroupExt(S, TheCall))
614     return true;
615 
616   // First argument is an ndrange_t type.
617   Expr *NDRangeArg = TheCall->getArg(0);
618   if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
619     S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
620         << TheCall->getDirectCallee() << "'ndrange_t'";
621     return true;
622   }
623 
624   Expr *BlockArg = TheCall->getArg(1);
625   if (!isBlockPointer(BlockArg)) {
626     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
627         << TheCall->getDirectCallee() << "block";
628     return true;
629   }
630   return checkOpenCLBlockArgs(S, BlockArg);
631 }
632 
633 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
634 /// get_kernel_work_group_size
635 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
636 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
637   if (checkArgCount(S, TheCall, 1))
638     return true;
639 
640   Expr *BlockArg = TheCall->getArg(0);
641   if (!isBlockPointer(BlockArg)) {
642     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
643         << TheCall->getDirectCallee() << "block";
644     return true;
645   }
646   return checkOpenCLBlockArgs(S, BlockArg);
647 }
648 
649 /// Diagnose integer type and any valid implicit conversion to it.
650 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
651                                       const QualType &IntType);
652 
653 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
654                                             unsigned Start, unsigned End) {
655   bool IllegalParams = false;
656   for (unsigned I = Start; I <= End; ++I)
657     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
658                                               S.Context.getSizeType());
659   return IllegalParams;
660 }
661 
662 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
663 /// 'local void*' parameter of passed block.
664 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
665                                            Expr *BlockArg,
666                                            unsigned NumNonVarArgs) {
667   const BlockPointerType *BPT =
668       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
669   unsigned NumBlockParams =
670       BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams();
671   unsigned TotalNumArgs = TheCall->getNumArgs();
672 
673   // For each argument passed to the block, a corresponding uint needs to
674   // be passed to describe the size of the local memory.
675   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
676     S.Diag(TheCall->getBeginLoc(),
677            diag::err_opencl_enqueue_kernel_local_size_args);
678     return true;
679   }
680 
681   // Check that the sizes of the local memory are specified by integers.
682   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
683                                          TotalNumArgs - 1);
684 }
685 
686 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
687 /// overload formats specified in Table 6.13.17.1.
688 /// int enqueue_kernel(queue_t queue,
689 ///                    kernel_enqueue_flags_t flags,
690 ///                    const ndrange_t ndrange,
691 ///                    void (^block)(void))
692 /// int enqueue_kernel(queue_t queue,
693 ///                    kernel_enqueue_flags_t flags,
694 ///                    const ndrange_t ndrange,
695 ///                    uint num_events_in_wait_list,
696 ///                    clk_event_t *event_wait_list,
697 ///                    clk_event_t *event_ret,
698 ///                    void (^block)(void))
699 /// int enqueue_kernel(queue_t queue,
700 ///                    kernel_enqueue_flags_t flags,
701 ///                    const ndrange_t ndrange,
702 ///                    void (^block)(local void*, ...),
703 ///                    uint size0, ...)
704 /// int enqueue_kernel(queue_t queue,
705 ///                    kernel_enqueue_flags_t flags,
706 ///                    const ndrange_t ndrange,
707 ///                    uint num_events_in_wait_list,
708 ///                    clk_event_t *event_wait_list,
709 ///                    clk_event_t *event_ret,
710 ///                    void (^block)(local void*, ...),
711 ///                    uint size0, ...)
712 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
713   unsigned NumArgs = TheCall->getNumArgs();
714 
715   if (NumArgs < 4) {
716     S.Diag(TheCall->getBeginLoc(),
717            diag::err_typecheck_call_too_few_args_at_least)
718         << 0 << 4 << NumArgs;
719     return true;
720   }
721 
722   Expr *Arg0 = TheCall->getArg(0);
723   Expr *Arg1 = TheCall->getArg(1);
724   Expr *Arg2 = TheCall->getArg(2);
725   Expr *Arg3 = TheCall->getArg(3);
726 
727   // First argument always needs to be a queue_t type.
728   if (!Arg0->getType()->isQueueT()) {
729     S.Diag(TheCall->getArg(0)->getBeginLoc(),
730            diag::err_opencl_builtin_expected_type)
731         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
732     return true;
733   }
734 
735   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
736   if (!Arg1->getType()->isIntegerType()) {
737     S.Diag(TheCall->getArg(1)->getBeginLoc(),
738            diag::err_opencl_builtin_expected_type)
739         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
740     return true;
741   }
742 
743   // Third argument is always an ndrange_t type.
744   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
745     S.Diag(TheCall->getArg(2)->getBeginLoc(),
746            diag::err_opencl_builtin_expected_type)
747         << TheCall->getDirectCallee() << "'ndrange_t'";
748     return true;
749   }
750 
751   // With four arguments, there is only one form that the function could be
752   // called in: no events and no variable arguments.
753   if (NumArgs == 4) {
754     // check that the last argument is the right block type.
755     if (!isBlockPointer(Arg3)) {
756       S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
757           << TheCall->getDirectCallee() << "block";
758       return true;
759     }
760     // we have a block type, check the prototype
761     const BlockPointerType *BPT =
762         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
763     if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) {
764       S.Diag(Arg3->getBeginLoc(),
765              diag::err_opencl_enqueue_kernel_blocks_no_args);
766       return true;
767     }
768     return false;
769   }
770   // we can have block + varargs.
771   if (isBlockPointer(Arg3))
772     return (checkOpenCLBlockArgs(S, Arg3) ||
773             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
774   // last two cases with either exactly 7 args or 7 args and varargs.
775   if (NumArgs >= 7) {
776     // check common block argument.
777     Expr *Arg6 = TheCall->getArg(6);
778     if (!isBlockPointer(Arg6)) {
779       S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
780           << TheCall->getDirectCallee() << "block";
781       return true;
782     }
783     if (checkOpenCLBlockArgs(S, Arg6))
784       return true;
785 
786     // Forth argument has to be any integer type.
787     if (!Arg3->getType()->isIntegerType()) {
788       S.Diag(TheCall->getArg(3)->getBeginLoc(),
789              diag::err_opencl_builtin_expected_type)
790           << TheCall->getDirectCallee() << "integer";
791       return true;
792     }
793     // check remaining common arguments.
794     Expr *Arg4 = TheCall->getArg(4);
795     Expr *Arg5 = TheCall->getArg(5);
796 
797     // Fifth argument is always passed as a pointer to clk_event_t.
798     if (!Arg4->isNullPointerConstant(S.Context,
799                                      Expr::NPC_ValueDependentIsNotNull) &&
800         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
801       S.Diag(TheCall->getArg(4)->getBeginLoc(),
802              diag::err_opencl_builtin_expected_type)
803           << TheCall->getDirectCallee()
804           << S.Context.getPointerType(S.Context.OCLClkEventTy);
805       return true;
806     }
807 
808     // Sixth argument is always passed as a pointer to clk_event_t.
809     if (!Arg5->isNullPointerConstant(S.Context,
810                                      Expr::NPC_ValueDependentIsNotNull) &&
811         !(Arg5->getType()->isPointerType() &&
812           Arg5->getType()->getPointeeType()->isClkEventT())) {
813       S.Diag(TheCall->getArg(5)->getBeginLoc(),
814              diag::err_opencl_builtin_expected_type)
815           << TheCall->getDirectCallee()
816           << S.Context.getPointerType(S.Context.OCLClkEventTy);
817       return true;
818     }
819 
820     if (NumArgs == 7)
821       return false;
822 
823     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
824   }
825 
826   // None of the specific case has been detected, give generic error
827   S.Diag(TheCall->getBeginLoc(),
828          diag::err_opencl_enqueue_kernel_incorrect_args);
829   return true;
830 }
831 
832 /// Returns OpenCL access qual.
833 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
834     return D->getAttr<OpenCLAccessAttr>();
835 }
836 
837 /// Returns true if pipe element type is different from the pointer.
838 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
839   const Expr *Arg0 = Call->getArg(0);
840   // First argument type should always be pipe.
841   if (!Arg0->getType()->isPipeType()) {
842     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
843         << Call->getDirectCallee() << Arg0->getSourceRange();
844     return true;
845   }
846   OpenCLAccessAttr *AccessQual =
847       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
848   // Validates the access qualifier is compatible with the call.
849   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
850   // read_only and write_only, and assumed to be read_only if no qualifier is
851   // specified.
852   switch (Call->getDirectCallee()->getBuiltinID()) {
853   case Builtin::BIread_pipe:
854   case Builtin::BIreserve_read_pipe:
855   case Builtin::BIcommit_read_pipe:
856   case Builtin::BIwork_group_reserve_read_pipe:
857   case Builtin::BIsub_group_reserve_read_pipe:
858   case Builtin::BIwork_group_commit_read_pipe:
859   case Builtin::BIsub_group_commit_read_pipe:
860     if (!(!AccessQual || AccessQual->isReadOnly())) {
861       S.Diag(Arg0->getBeginLoc(),
862              diag::err_opencl_builtin_pipe_invalid_access_modifier)
863           << "read_only" << Arg0->getSourceRange();
864       return true;
865     }
866     break;
867   case Builtin::BIwrite_pipe:
868   case Builtin::BIreserve_write_pipe:
869   case Builtin::BIcommit_write_pipe:
870   case Builtin::BIwork_group_reserve_write_pipe:
871   case Builtin::BIsub_group_reserve_write_pipe:
872   case Builtin::BIwork_group_commit_write_pipe:
873   case Builtin::BIsub_group_commit_write_pipe:
874     if (!(AccessQual && AccessQual->isWriteOnly())) {
875       S.Diag(Arg0->getBeginLoc(),
876              diag::err_opencl_builtin_pipe_invalid_access_modifier)
877           << "write_only" << Arg0->getSourceRange();
878       return true;
879     }
880     break;
881   default:
882     break;
883   }
884   return false;
885 }
886 
887 /// Returns true if pipe element type is different from the pointer.
888 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
889   const Expr *Arg0 = Call->getArg(0);
890   const Expr *ArgIdx = Call->getArg(Idx);
891   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
892   const QualType EltTy = PipeTy->getElementType();
893   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
894   // The Idx argument should be a pointer and the type of the pointer and
895   // the type of pipe element should also be the same.
896   if (!ArgTy ||
897       !S.Context.hasSameType(
898           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
899     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
900         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
901         << ArgIdx->getType() << ArgIdx->getSourceRange();
902     return true;
903   }
904   return false;
905 }
906 
907 // Performs semantic analysis for the read/write_pipe call.
908 // \param S Reference to the semantic analyzer.
909 // \param Call A pointer to the builtin call.
910 // \return True if a semantic error has been found, false otherwise.
911 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
912   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
913   // functions have two forms.
914   switch (Call->getNumArgs()) {
915   case 2:
916     if (checkOpenCLPipeArg(S, Call))
917       return true;
918     // The call with 2 arguments should be
919     // read/write_pipe(pipe T, T*).
920     // Check packet type T.
921     if (checkOpenCLPipePacketType(S, Call, 1))
922       return true;
923     break;
924 
925   case 4: {
926     if (checkOpenCLPipeArg(S, Call))
927       return true;
928     // The call with 4 arguments should be
929     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
930     // Check reserve_id_t.
931     if (!Call->getArg(1)->getType()->isReserveIDT()) {
932       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
933           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
934           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
935       return true;
936     }
937 
938     // Check the index.
939     const Expr *Arg2 = Call->getArg(2);
940     if (!Arg2->getType()->isIntegerType() &&
941         !Arg2->getType()->isUnsignedIntegerType()) {
942       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
943           << Call->getDirectCallee() << S.Context.UnsignedIntTy
944           << Arg2->getType() << Arg2->getSourceRange();
945       return true;
946     }
947 
948     // Check packet type T.
949     if (checkOpenCLPipePacketType(S, Call, 3))
950       return true;
951   } break;
952   default:
953     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
954         << Call->getDirectCallee() << Call->getSourceRange();
955     return true;
956   }
957 
958   return false;
959 }
960 
961 // Performs a semantic analysis on the {work_group_/sub_group_
962 //        /_}reserve_{read/write}_pipe
963 // \param S Reference to the semantic analyzer.
964 // \param Call The call to the builtin function to be analyzed.
965 // \return True if a semantic error was found, false otherwise.
966 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
967   if (checkArgCount(S, Call, 2))
968     return true;
969 
970   if (checkOpenCLPipeArg(S, Call))
971     return true;
972 
973   // Check the reserve size.
974   if (!Call->getArg(1)->getType()->isIntegerType() &&
975       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
976     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
977         << Call->getDirectCallee() << S.Context.UnsignedIntTy
978         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
979     return true;
980   }
981 
982   // Since return type of reserve_read/write_pipe built-in function is
983   // reserve_id_t, which is not defined in the builtin def file , we used int
984   // as return type and need to override the return type of these functions.
985   Call->setType(S.Context.OCLReserveIDTy);
986 
987   return false;
988 }
989 
990 // Performs a semantic analysis on {work_group_/sub_group_
991 //        /_}commit_{read/write}_pipe
992 // \param S Reference to the semantic analyzer.
993 // \param Call The call to the builtin function to be analyzed.
994 // \return True if a semantic error was found, false otherwise.
995 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
996   if (checkArgCount(S, Call, 2))
997     return true;
998 
999   if (checkOpenCLPipeArg(S, Call))
1000     return true;
1001 
1002   // Check reserve_id_t.
1003   if (!Call->getArg(1)->getType()->isReserveIDT()) {
1004     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1005         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1006         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1007     return true;
1008   }
1009 
1010   return false;
1011 }
1012 
1013 // Performs a semantic analysis on the call to built-in Pipe
1014 //        Query Functions.
1015 // \param S Reference to the semantic analyzer.
1016 // \param Call The call to the builtin function to be analyzed.
1017 // \return True if a semantic error was found, false otherwise.
1018 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
1019   if (checkArgCount(S, Call, 1))
1020     return true;
1021 
1022   if (!Call->getArg(0)->getType()->isPipeType()) {
1023     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1024         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
1025     return true;
1026   }
1027 
1028   return false;
1029 }
1030 
1031 // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
1032 // Performs semantic analysis for the to_global/local/private call.
1033 // \param S Reference to the semantic analyzer.
1034 // \param BuiltinID ID of the builtin function.
1035 // \param Call A pointer to the builtin call.
1036 // \return True if a semantic error has been found, false otherwise.
1037 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
1038                                     CallExpr *Call) {
1039   if (Call->getNumArgs() != 1) {
1040     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_arg_num)
1041         << Call->getDirectCallee() << Call->getSourceRange();
1042     return true;
1043   }
1044 
1045   auto RT = Call->getArg(0)->getType();
1046   if (!RT->isPointerType() || RT->getPointeeType()
1047       .getAddressSpace() == LangAS::opencl_constant) {
1048     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
1049         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
1050     return true;
1051   }
1052 
1053   if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
1054     S.Diag(Call->getArg(0)->getBeginLoc(),
1055            diag::warn_opencl_generic_address_space_arg)
1056         << Call->getDirectCallee()->getNameInfo().getAsString()
1057         << Call->getArg(0)->getSourceRange();
1058   }
1059 
1060   RT = RT->getPointeeType();
1061   auto Qual = RT.getQualifiers();
1062   switch (BuiltinID) {
1063   case Builtin::BIto_global:
1064     Qual.setAddressSpace(LangAS::opencl_global);
1065     break;
1066   case Builtin::BIto_local:
1067     Qual.setAddressSpace(LangAS::opencl_local);
1068     break;
1069   case Builtin::BIto_private:
1070     Qual.setAddressSpace(LangAS::opencl_private);
1071     break;
1072   default:
1073     llvm_unreachable("Invalid builtin function");
1074   }
1075   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
1076       RT.getUnqualifiedType(), Qual)));
1077 
1078   return false;
1079 }
1080 
1081 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
1082   if (checkArgCount(S, TheCall, 1))
1083     return ExprError();
1084 
1085   // Compute __builtin_launder's parameter type from the argument.
1086   // The parameter type is:
1087   //  * The type of the argument if it's not an array or function type,
1088   //  Otherwise,
1089   //  * The decayed argument type.
1090   QualType ParamTy = [&]() {
1091     QualType ArgTy = TheCall->getArg(0)->getType();
1092     if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1093       return S.Context.getPointerType(Ty->getElementType());
1094     if (ArgTy->isFunctionType()) {
1095       return S.Context.getPointerType(ArgTy);
1096     }
1097     return ArgTy;
1098   }();
1099 
1100   TheCall->setType(ParamTy);
1101 
1102   auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
1103     if (!ParamTy->isPointerType())
1104       return 0;
1105     if (ParamTy->isFunctionPointerType())
1106       return 1;
1107     if (ParamTy->isVoidPointerType())
1108       return 2;
1109     return llvm::Optional<unsigned>{};
1110   }();
1111   if (DiagSelect.hasValue()) {
1112     S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1113         << DiagSelect.getValue() << TheCall->getSourceRange();
1114     return ExprError();
1115   }
1116 
1117   // We either have an incomplete class type, or we have a class template
1118   // whose instantiation has not been forced. Example:
1119   //
1120   //   template <class T> struct Foo { T value; };
1121   //   Foo<int> *p = nullptr;
1122   //   auto *d = __builtin_launder(p);
1123   if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1124                             diag::err_incomplete_type))
1125     return ExprError();
1126 
1127   assert(ParamTy->getPointeeType()->isObjectType() &&
1128          "Unhandled non-object pointer case");
1129 
1130   InitializedEntity Entity =
1131       InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
1132   ExprResult Arg =
1133       S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1134   if (Arg.isInvalid())
1135     return ExprError();
1136   TheCall->setArg(0, Arg.get());
1137 
1138   return TheCall;
1139 }
1140 
1141 // Emit an error and return true if the current architecture is not in the list
1142 // of supported architectures.
1143 static bool
1144 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1145                           ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
1146   llvm::Triple::ArchType CurArch =
1147       S.getASTContext().getTargetInfo().getTriple().getArch();
1148   if (llvm::is_contained(SupportedArchs, CurArch))
1149     return false;
1150   S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1151       << TheCall->getSourceRange();
1152   return true;
1153 }
1154 
1155 ExprResult
1156 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
1157                                CallExpr *TheCall) {
1158   ExprResult TheCallResult(TheCall);
1159 
1160   // Find out if any arguments are required to be integer constant expressions.
1161   unsigned ICEArguments = 0;
1162   ASTContext::GetBuiltinTypeError Error;
1163   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
1164   if (Error != ASTContext::GE_None)
1165     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
1166 
1167   // If any arguments are required to be ICE's, check and diagnose.
1168   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
1169     // Skip arguments not required to be ICE's.
1170     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
1171 
1172     llvm::APSInt Result;
1173     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
1174       return true;
1175     ICEArguments &= ~(1 << ArgNo);
1176   }
1177 
1178   switch (BuiltinID) {
1179   case Builtin::BI__builtin___CFStringMakeConstantString:
1180     assert(TheCall->getNumArgs() == 1 &&
1181            "Wrong # arguments to builtin CFStringMakeConstantString");
1182     if (CheckObjCString(TheCall->getArg(0)))
1183       return ExprError();
1184     break;
1185   case Builtin::BI__builtin_ms_va_start:
1186   case Builtin::BI__builtin_stdarg_start:
1187   case Builtin::BI__builtin_va_start:
1188     if (SemaBuiltinVAStart(BuiltinID, TheCall))
1189       return ExprError();
1190     break;
1191   case Builtin::BI__va_start: {
1192     switch (Context.getTargetInfo().getTriple().getArch()) {
1193     case llvm::Triple::aarch64:
1194     case llvm::Triple::arm:
1195     case llvm::Triple::thumb:
1196       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
1197         return ExprError();
1198       break;
1199     default:
1200       if (SemaBuiltinVAStart(BuiltinID, TheCall))
1201         return ExprError();
1202       break;
1203     }
1204     break;
1205   }
1206 
1207   // The acquire, release, and no fence variants are ARM and AArch64 only.
1208   case Builtin::BI_interlockedbittestandset_acq:
1209   case Builtin::BI_interlockedbittestandset_rel:
1210   case Builtin::BI_interlockedbittestandset_nf:
1211   case Builtin::BI_interlockedbittestandreset_acq:
1212   case Builtin::BI_interlockedbittestandreset_rel:
1213   case Builtin::BI_interlockedbittestandreset_nf:
1214     if (CheckBuiltinTargetSupport(
1215             *this, BuiltinID, TheCall,
1216             {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
1217       return ExprError();
1218     break;
1219 
1220   // The 64-bit bittest variants are x64, ARM, and AArch64 only.
1221   case Builtin::BI_bittest64:
1222   case Builtin::BI_bittestandcomplement64:
1223   case Builtin::BI_bittestandreset64:
1224   case Builtin::BI_bittestandset64:
1225   case Builtin::BI_interlockedbittestandreset64:
1226   case Builtin::BI_interlockedbittestandset64:
1227     if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
1228                                   {llvm::Triple::x86_64, llvm::Triple::arm,
1229                                    llvm::Triple::thumb, llvm::Triple::aarch64}))
1230       return ExprError();
1231     break;
1232 
1233   case Builtin::BI__builtin_isgreater:
1234   case Builtin::BI__builtin_isgreaterequal:
1235   case Builtin::BI__builtin_isless:
1236   case Builtin::BI__builtin_islessequal:
1237   case Builtin::BI__builtin_islessgreater:
1238   case Builtin::BI__builtin_isunordered:
1239     if (SemaBuiltinUnorderedCompare(TheCall))
1240       return ExprError();
1241     break;
1242   case Builtin::BI__builtin_fpclassify:
1243     if (SemaBuiltinFPClassification(TheCall, 6))
1244       return ExprError();
1245     break;
1246   case Builtin::BI__builtin_isfinite:
1247   case Builtin::BI__builtin_isinf:
1248   case Builtin::BI__builtin_isinf_sign:
1249   case Builtin::BI__builtin_isnan:
1250   case Builtin::BI__builtin_isnormal:
1251   case Builtin::BI__builtin_signbit:
1252   case Builtin::BI__builtin_signbitf:
1253   case Builtin::BI__builtin_signbitl:
1254     if (SemaBuiltinFPClassification(TheCall, 1))
1255       return ExprError();
1256     break;
1257   case Builtin::BI__builtin_shufflevector:
1258     return SemaBuiltinShuffleVector(TheCall);
1259     // TheCall will be freed by the smart pointer here, but that's fine, since
1260     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1261   case Builtin::BI__builtin_prefetch:
1262     if (SemaBuiltinPrefetch(TheCall))
1263       return ExprError();
1264     break;
1265   case Builtin::BI__builtin_alloca_with_align:
1266     if (SemaBuiltinAllocaWithAlign(TheCall))
1267       return ExprError();
1268     LLVM_FALLTHROUGH;
1269   case Builtin::BI__builtin_alloca:
1270     Diag(TheCall->getBeginLoc(), diag::warn_alloca)
1271         << TheCall->getDirectCallee();
1272     break;
1273   case Builtin::BI__assume:
1274   case Builtin::BI__builtin_assume:
1275     if (SemaBuiltinAssume(TheCall))
1276       return ExprError();
1277     break;
1278   case Builtin::BI__builtin_assume_aligned:
1279     if (SemaBuiltinAssumeAligned(TheCall))
1280       return ExprError();
1281     break;
1282   case Builtin::BI__builtin_dynamic_object_size:
1283   case Builtin::BI__builtin_object_size:
1284     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1285       return ExprError();
1286     break;
1287   case Builtin::BI__builtin_longjmp:
1288     if (SemaBuiltinLongjmp(TheCall))
1289       return ExprError();
1290     break;
1291   case Builtin::BI__builtin_setjmp:
1292     if (SemaBuiltinSetjmp(TheCall))
1293       return ExprError();
1294     break;
1295   case Builtin::BI_setjmp:
1296   case Builtin::BI_setjmpex:
1297     if (checkArgCount(*this, TheCall, 1))
1298       return true;
1299     break;
1300   case Builtin::BI__builtin_classify_type:
1301     if (checkArgCount(*this, TheCall, 1)) return true;
1302     TheCall->setType(Context.IntTy);
1303     break;
1304   case Builtin::BI__builtin_constant_p: {
1305     if (checkArgCount(*this, TheCall, 1)) return true;
1306     ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
1307     if (Arg.isInvalid()) return true;
1308     TheCall->setArg(0, Arg.get());
1309     TheCall->setType(Context.IntTy);
1310     break;
1311   }
1312   case Builtin::BI__builtin_launder:
1313     return SemaBuiltinLaunder(*this, TheCall);
1314   case Builtin::BI__sync_fetch_and_add:
1315   case Builtin::BI__sync_fetch_and_add_1:
1316   case Builtin::BI__sync_fetch_and_add_2:
1317   case Builtin::BI__sync_fetch_and_add_4:
1318   case Builtin::BI__sync_fetch_and_add_8:
1319   case Builtin::BI__sync_fetch_and_add_16:
1320   case Builtin::BI__sync_fetch_and_sub:
1321   case Builtin::BI__sync_fetch_and_sub_1:
1322   case Builtin::BI__sync_fetch_and_sub_2:
1323   case Builtin::BI__sync_fetch_and_sub_4:
1324   case Builtin::BI__sync_fetch_and_sub_8:
1325   case Builtin::BI__sync_fetch_and_sub_16:
1326   case Builtin::BI__sync_fetch_and_or:
1327   case Builtin::BI__sync_fetch_and_or_1:
1328   case Builtin::BI__sync_fetch_and_or_2:
1329   case Builtin::BI__sync_fetch_and_or_4:
1330   case Builtin::BI__sync_fetch_and_or_8:
1331   case Builtin::BI__sync_fetch_and_or_16:
1332   case Builtin::BI__sync_fetch_and_and:
1333   case Builtin::BI__sync_fetch_and_and_1:
1334   case Builtin::BI__sync_fetch_and_and_2:
1335   case Builtin::BI__sync_fetch_and_and_4:
1336   case Builtin::BI__sync_fetch_and_and_8:
1337   case Builtin::BI__sync_fetch_and_and_16:
1338   case Builtin::BI__sync_fetch_and_xor:
1339   case Builtin::BI__sync_fetch_and_xor_1:
1340   case Builtin::BI__sync_fetch_and_xor_2:
1341   case Builtin::BI__sync_fetch_and_xor_4:
1342   case Builtin::BI__sync_fetch_and_xor_8:
1343   case Builtin::BI__sync_fetch_and_xor_16:
1344   case Builtin::BI__sync_fetch_and_nand:
1345   case Builtin::BI__sync_fetch_and_nand_1:
1346   case Builtin::BI__sync_fetch_and_nand_2:
1347   case Builtin::BI__sync_fetch_and_nand_4:
1348   case Builtin::BI__sync_fetch_and_nand_8:
1349   case Builtin::BI__sync_fetch_and_nand_16:
1350   case Builtin::BI__sync_add_and_fetch:
1351   case Builtin::BI__sync_add_and_fetch_1:
1352   case Builtin::BI__sync_add_and_fetch_2:
1353   case Builtin::BI__sync_add_and_fetch_4:
1354   case Builtin::BI__sync_add_and_fetch_8:
1355   case Builtin::BI__sync_add_and_fetch_16:
1356   case Builtin::BI__sync_sub_and_fetch:
1357   case Builtin::BI__sync_sub_and_fetch_1:
1358   case Builtin::BI__sync_sub_and_fetch_2:
1359   case Builtin::BI__sync_sub_and_fetch_4:
1360   case Builtin::BI__sync_sub_and_fetch_8:
1361   case Builtin::BI__sync_sub_and_fetch_16:
1362   case Builtin::BI__sync_and_and_fetch:
1363   case Builtin::BI__sync_and_and_fetch_1:
1364   case Builtin::BI__sync_and_and_fetch_2:
1365   case Builtin::BI__sync_and_and_fetch_4:
1366   case Builtin::BI__sync_and_and_fetch_8:
1367   case Builtin::BI__sync_and_and_fetch_16:
1368   case Builtin::BI__sync_or_and_fetch:
1369   case Builtin::BI__sync_or_and_fetch_1:
1370   case Builtin::BI__sync_or_and_fetch_2:
1371   case Builtin::BI__sync_or_and_fetch_4:
1372   case Builtin::BI__sync_or_and_fetch_8:
1373   case Builtin::BI__sync_or_and_fetch_16:
1374   case Builtin::BI__sync_xor_and_fetch:
1375   case Builtin::BI__sync_xor_and_fetch_1:
1376   case Builtin::BI__sync_xor_and_fetch_2:
1377   case Builtin::BI__sync_xor_and_fetch_4:
1378   case Builtin::BI__sync_xor_and_fetch_8:
1379   case Builtin::BI__sync_xor_and_fetch_16:
1380   case Builtin::BI__sync_nand_and_fetch:
1381   case Builtin::BI__sync_nand_and_fetch_1:
1382   case Builtin::BI__sync_nand_and_fetch_2:
1383   case Builtin::BI__sync_nand_and_fetch_4:
1384   case Builtin::BI__sync_nand_and_fetch_8:
1385   case Builtin::BI__sync_nand_and_fetch_16:
1386   case Builtin::BI__sync_val_compare_and_swap:
1387   case Builtin::BI__sync_val_compare_and_swap_1:
1388   case Builtin::BI__sync_val_compare_and_swap_2:
1389   case Builtin::BI__sync_val_compare_and_swap_4:
1390   case Builtin::BI__sync_val_compare_and_swap_8:
1391   case Builtin::BI__sync_val_compare_and_swap_16:
1392   case Builtin::BI__sync_bool_compare_and_swap:
1393   case Builtin::BI__sync_bool_compare_and_swap_1:
1394   case Builtin::BI__sync_bool_compare_and_swap_2:
1395   case Builtin::BI__sync_bool_compare_and_swap_4:
1396   case Builtin::BI__sync_bool_compare_and_swap_8:
1397   case Builtin::BI__sync_bool_compare_and_swap_16:
1398   case Builtin::BI__sync_lock_test_and_set:
1399   case Builtin::BI__sync_lock_test_and_set_1:
1400   case Builtin::BI__sync_lock_test_and_set_2:
1401   case Builtin::BI__sync_lock_test_and_set_4:
1402   case Builtin::BI__sync_lock_test_and_set_8:
1403   case Builtin::BI__sync_lock_test_and_set_16:
1404   case Builtin::BI__sync_lock_release:
1405   case Builtin::BI__sync_lock_release_1:
1406   case Builtin::BI__sync_lock_release_2:
1407   case Builtin::BI__sync_lock_release_4:
1408   case Builtin::BI__sync_lock_release_8:
1409   case Builtin::BI__sync_lock_release_16:
1410   case Builtin::BI__sync_swap:
1411   case Builtin::BI__sync_swap_1:
1412   case Builtin::BI__sync_swap_2:
1413   case Builtin::BI__sync_swap_4:
1414   case Builtin::BI__sync_swap_8:
1415   case Builtin::BI__sync_swap_16:
1416     return SemaBuiltinAtomicOverloaded(TheCallResult);
1417   case Builtin::BI__sync_synchronize:
1418     Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1419         << TheCall->getCallee()->getSourceRange();
1420     break;
1421   case Builtin::BI__builtin_nontemporal_load:
1422   case Builtin::BI__builtin_nontemporal_store:
1423     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1424 #define BUILTIN(ID, TYPE, ATTRS)
1425 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1426   case Builtin::BI##ID: \
1427     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1428 #include "clang/Basic/Builtins.def"
1429   case Builtin::BI__annotation:
1430     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1431       return ExprError();
1432     break;
1433   case Builtin::BI__builtin_annotation:
1434     if (SemaBuiltinAnnotation(*this, TheCall))
1435       return ExprError();
1436     break;
1437   case Builtin::BI__builtin_addressof:
1438     if (SemaBuiltinAddressof(*this, TheCall))
1439       return ExprError();
1440     break;
1441   case Builtin::BI__builtin_is_aligned:
1442   case Builtin::BI__builtin_align_up:
1443   case Builtin::BI__builtin_align_down:
1444     if (SemaBuiltinAlignment(*this, TheCall, BuiltinID))
1445       return ExprError();
1446     break;
1447   case Builtin::BI__builtin_add_overflow:
1448   case Builtin::BI__builtin_sub_overflow:
1449   case Builtin::BI__builtin_mul_overflow:
1450     if (SemaBuiltinOverflow(*this, TheCall))
1451       return ExprError();
1452     break;
1453   case Builtin::BI__builtin_operator_new:
1454   case Builtin::BI__builtin_operator_delete: {
1455     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1456     ExprResult Res =
1457         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1458     if (Res.isInvalid())
1459       CorrectDelayedTyposInExpr(TheCallResult.get());
1460     return Res;
1461   }
1462   case Builtin::BI__builtin_dump_struct: {
1463     // We first want to ensure we are called with 2 arguments
1464     if (checkArgCount(*this, TheCall, 2))
1465       return ExprError();
1466     // Ensure that the first argument is of type 'struct XX *'
1467     const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1468     const QualType PtrArgType = PtrArg->getType();
1469     if (!PtrArgType->isPointerType() ||
1470         !PtrArgType->getPointeeType()->isRecordType()) {
1471       Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1472           << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1473           << "structure pointer";
1474       return ExprError();
1475     }
1476 
1477     // Ensure that the second argument is of type 'FunctionType'
1478     const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1479     const QualType FnPtrArgType = FnPtrArg->getType();
1480     if (!FnPtrArgType->isPointerType()) {
1481       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1482           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1483           << FnPtrArgType << "'int (*)(const char *, ...)'";
1484       return ExprError();
1485     }
1486 
1487     const auto *FuncType =
1488         FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1489 
1490     if (!FuncType) {
1491       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1492           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1493           << FnPtrArgType << "'int (*)(const char *, ...)'";
1494       return ExprError();
1495     }
1496 
1497     if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1498       if (!FT->getNumParams()) {
1499         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1500             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1501             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1502         return ExprError();
1503       }
1504       QualType PT = FT->getParamType(0);
1505       if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1506           !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1507           !PT->getPointeeType().isConstQualified()) {
1508         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1509             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1510             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1511         return ExprError();
1512       }
1513     }
1514 
1515     TheCall->setType(Context.IntTy);
1516     break;
1517   }
1518   case Builtin::BI__builtin_preserve_access_index:
1519     if (SemaBuiltinPreserveAI(*this, TheCall))
1520       return ExprError();
1521     break;
1522   case Builtin::BI__builtin_call_with_static_chain:
1523     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1524       return ExprError();
1525     break;
1526   case Builtin::BI__exception_code:
1527   case Builtin::BI_exception_code:
1528     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1529                                  diag::err_seh___except_block))
1530       return ExprError();
1531     break;
1532   case Builtin::BI__exception_info:
1533   case Builtin::BI_exception_info:
1534     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1535                                  diag::err_seh___except_filter))
1536       return ExprError();
1537     break;
1538   case Builtin::BI__GetExceptionInfo:
1539     if (checkArgCount(*this, TheCall, 1))
1540       return ExprError();
1541 
1542     if (CheckCXXThrowOperand(
1543             TheCall->getBeginLoc(),
1544             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1545             TheCall))
1546       return ExprError();
1547 
1548     TheCall->setType(Context.VoidPtrTy);
1549     break;
1550   // OpenCL v2.0, s6.13.16 - Pipe functions
1551   case Builtin::BIread_pipe:
1552   case Builtin::BIwrite_pipe:
1553     // Since those two functions are declared with var args, we need a semantic
1554     // check for the argument.
1555     if (SemaBuiltinRWPipe(*this, TheCall))
1556       return ExprError();
1557     break;
1558   case Builtin::BIreserve_read_pipe:
1559   case Builtin::BIreserve_write_pipe:
1560   case Builtin::BIwork_group_reserve_read_pipe:
1561   case Builtin::BIwork_group_reserve_write_pipe:
1562     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1563       return ExprError();
1564     break;
1565   case Builtin::BIsub_group_reserve_read_pipe:
1566   case Builtin::BIsub_group_reserve_write_pipe:
1567     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1568         SemaBuiltinReserveRWPipe(*this, TheCall))
1569       return ExprError();
1570     break;
1571   case Builtin::BIcommit_read_pipe:
1572   case Builtin::BIcommit_write_pipe:
1573   case Builtin::BIwork_group_commit_read_pipe:
1574   case Builtin::BIwork_group_commit_write_pipe:
1575     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1576       return ExprError();
1577     break;
1578   case Builtin::BIsub_group_commit_read_pipe:
1579   case Builtin::BIsub_group_commit_write_pipe:
1580     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1581         SemaBuiltinCommitRWPipe(*this, TheCall))
1582       return ExprError();
1583     break;
1584   case Builtin::BIget_pipe_num_packets:
1585   case Builtin::BIget_pipe_max_packets:
1586     if (SemaBuiltinPipePackets(*this, TheCall))
1587       return ExprError();
1588     break;
1589   case Builtin::BIto_global:
1590   case Builtin::BIto_local:
1591   case Builtin::BIto_private:
1592     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1593       return ExprError();
1594     break;
1595   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1596   case Builtin::BIenqueue_kernel:
1597     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1598       return ExprError();
1599     break;
1600   case Builtin::BIget_kernel_work_group_size:
1601   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1602     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1603       return ExprError();
1604     break;
1605   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1606   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1607     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1608       return ExprError();
1609     break;
1610   case Builtin::BI__builtin_os_log_format:
1611   case Builtin::BI__builtin_os_log_format_buffer_size:
1612     if (SemaBuiltinOSLogFormat(TheCall))
1613       return ExprError();
1614     break;
1615   }
1616 
1617   // Since the target specific builtins for each arch overlap, only check those
1618   // of the arch we are compiling for.
1619   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1620     switch (Context.getTargetInfo().getTriple().getArch()) {
1621       case llvm::Triple::arm:
1622       case llvm::Triple::armeb:
1623       case llvm::Triple::thumb:
1624       case llvm::Triple::thumbeb:
1625         if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1626           return ExprError();
1627         break;
1628       case llvm::Triple::aarch64:
1629       case llvm::Triple::aarch64_32:
1630       case llvm::Triple::aarch64_be:
1631         if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
1632           return ExprError();
1633         break;
1634       case llvm::Triple::bpfeb:
1635       case llvm::Triple::bpfel:
1636         if (CheckBPFBuiltinFunctionCall(BuiltinID, TheCall))
1637           return ExprError();
1638         break;
1639       case llvm::Triple::hexagon:
1640         if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall))
1641           return ExprError();
1642         break;
1643       case llvm::Triple::mips:
1644       case llvm::Triple::mipsel:
1645       case llvm::Triple::mips64:
1646       case llvm::Triple::mips64el:
1647         if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1648           return ExprError();
1649         break;
1650       case llvm::Triple::systemz:
1651         if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1652           return ExprError();
1653         break;
1654       case llvm::Triple::x86:
1655       case llvm::Triple::x86_64:
1656         if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1657           return ExprError();
1658         break;
1659       case llvm::Triple::ppc:
1660       case llvm::Triple::ppc64:
1661       case llvm::Triple::ppc64le:
1662         if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1663           return ExprError();
1664         break;
1665       default:
1666         break;
1667     }
1668   }
1669 
1670   return TheCallResult;
1671 }
1672 
1673 // Get the valid immediate range for the specified NEON type code.
1674 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1675   NeonTypeFlags Type(t);
1676   int IsQuad = ForceQuad ? true : Type.isQuad();
1677   switch (Type.getEltType()) {
1678   case NeonTypeFlags::Int8:
1679   case NeonTypeFlags::Poly8:
1680     return shift ? 7 : (8 << IsQuad) - 1;
1681   case NeonTypeFlags::Int16:
1682   case NeonTypeFlags::Poly16:
1683     return shift ? 15 : (4 << IsQuad) - 1;
1684   case NeonTypeFlags::Int32:
1685     return shift ? 31 : (2 << IsQuad) - 1;
1686   case NeonTypeFlags::Int64:
1687   case NeonTypeFlags::Poly64:
1688     return shift ? 63 : (1 << IsQuad) - 1;
1689   case NeonTypeFlags::Poly128:
1690     return shift ? 127 : (1 << IsQuad) - 1;
1691   case NeonTypeFlags::Float16:
1692     assert(!shift && "cannot shift float types!");
1693     return (4 << IsQuad) - 1;
1694   case NeonTypeFlags::Float32:
1695     assert(!shift && "cannot shift float types!");
1696     return (2 << IsQuad) - 1;
1697   case NeonTypeFlags::Float64:
1698     assert(!shift && "cannot shift float types!");
1699     return (1 << IsQuad) - 1;
1700   }
1701   llvm_unreachable("Invalid NeonTypeFlag!");
1702 }
1703 
1704 /// getNeonEltType - Return the QualType corresponding to the elements of
1705 /// the vector type specified by the NeonTypeFlags.  This is used to check
1706 /// the pointer arguments for Neon load/store intrinsics.
1707 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
1708                                bool IsPolyUnsigned, bool IsInt64Long) {
1709   switch (Flags.getEltType()) {
1710   case NeonTypeFlags::Int8:
1711     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1712   case NeonTypeFlags::Int16:
1713     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1714   case NeonTypeFlags::Int32:
1715     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1716   case NeonTypeFlags::Int64:
1717     if (IsInt64Long)
1718       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1719     else
1720       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1721                                 : Context.LongLongTy;
1722   case NeonTypeFlags::Poly8:
1723     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
1724   case NeonTypeFlags::Poly16:
1725     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
1726   case NeonTypeFlags::Poly64:
1727     if (IsInt64Long)
1728       return Context.UnsignedLongTy;
1729     else
1730       return Context.UnsignedLongLongTy;
1731   case NeonTypeFlags::Poly128:
1732     break;
1733   case NeonTypeFlags::Float16:
1734     return Context.HalfTy;
1735   case NeonTypeFlags::Float32:
1736     return Context.FloatTy;
1737   case NeonTypeFlags::Float64:
1738     return Context.DoubleTy;
1739   }
1740   llvm_unreachable("Invalid NeonTypeFlag!");
1741 }
1742 
1743 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1744   llvm::APSInt Result;
1745   uint64_t mask = 0;
1746   unsigned TV = 0;
1747   int PtrArgNum = -1;
1748   bool HasConstPtr = false;
1749   switch (BuiltinID) {
1750 #define GET_NEON_OVERLOAD_CHECK
1751 #include "clang/Basic/arm_neon.inc"
1752 #include "clang/Basic/arm_fp16.inc"
1753 #undef GET_NEON_OVERLOAD_CHECK
1754   }
1755 
1756   // For NEON intrinsics which are overloaded on vector element type, validate
1757   // the immediate which specifies which variant to emit.
1758   unsigned ImmArg = TheCall->getNumArgs()-1;
1759   if (mask) {
1760     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1761       return true;
1762 
1763     TV = Result.getLimitedValue(64);
1764     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1765       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
1766              << TheCall->getArg(ImmArg)->getSourceRange();
1767   }
1768 
1769   if (PtrArgNum >= 0) {
1770     // Check that pointer arguments have the specified type.
1771     Expr *Arg = TheCall->getArg(PtrArgNum);
1772     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1773       Arg = ICE->getSubExpr();
1774     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1775     QualType RHSTy = RHS.get()->getType();
1776 
1777     llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
1778     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
1779                           Arch == llvm::Triple::aarch64_32 ||
1780                           Arch == llvm::Triple::aarch64_be;
1781     bool IsInt64Long =
1782         Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1783     QualType EltTy =
1784         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
1785     if (HasConstPtr)
1786       EltTy = EltTy.withConst();
1787     QualType LHSTy = Context.getPointerType(EltTy);
1788     AssignConvertType ConvTy;
1789     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1790     if (RHS.isInvalid())
1791       return true;
1792     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
1793                                  RHS.get(), AA_Assigning))
1794       return true;
1795   }
1796 
1797   // For NEON intrinsics which take an immediate value as part of the
1798   // instruction, range check them here.
1799   unsigned i = 0, l = 0, u = 0;
1800   switch (BuiltinID) {
1801   default:
1802     return false;
1803   #define GET_NEON_IMMEDIATE_CHECK
1804   #include "clang/Basic/arm_neon.inc"
1805   #include "clang/Basic/arm_fp16.inc"
1806   #undef GET_NEON_IMMEDIATE_CHECK
1807   }
1808 
1809   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1810 }
1811 
1812 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1813   switch (BuiltinID) {
1814   default:
1815     return false;
1816   #include "clang/Basic/arm_mve_builtin_sema.inc"
1817   }
1818 }
1819 
1820 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1821                                         unsigned MaxWidth) {
1822   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
1823           BuiltinID == ARM::BI__builtin_arm_ldaex ||
1824           BuiltinID == ARM::BI__builtin_arm_strex ||
1825           BuiltinID == ARM::BI__builtin_arm_stlex ||
1826           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1827           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1828           BuiltinID == AArch64::BI__builtin_arm_strex ||
1829           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
1830          "unexpected ARM builtin");
1831   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
1832                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
1833                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1834                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
1835 
1836   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1837 
1838   // Ensure that we have the proper number of arguments.
1839   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1840     return true;
1841 
1842   // Inspect the pointer argument of the atomic builtin.  This should always be
1843   // a pointer type, whose element is an integral scalar or pointer type.
1844   // Because it is a pointer type, we don't have to worry about any implicit
1845   // casts here.
1846   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1847   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1848   if (PointerArgRes.isInvalid())
1849     return true;
1850   PointerArg = PointerArgRes.get();
1851 
1852   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1853   if (!pointerType) {
1854     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
1855         << PointerArg->getType() << PointerArg->getSourceRange();
1856     return true;
1857   }
1858 
1859   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1860   // task is to insert the appropriate casts into the AST. First work out just
1861   // what the appropriate type is.
1862   QualType ValType = pointerType->getPointeeType();
1863   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1864   if (IsLdrex)
1865     AddrType.addConst();
1866 
1867   // Issue a warning if the cast is dodgy.
1868   CastKind CastNeeded = CK_NoOp;
1869   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1870     CastNeeded = CK_BitCast;
1871     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
1872         << PointerArg->getType() << Context.getPointerType(AddrType)
1873         << AA_Passing << PointerArg->getSourceRange();
1874   }
1875 
1876   // Finally, do the cast and replace the argument with the corrected version.
1877   AddrType = Context.getPointerType(AddrType);
1878   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1879   if (PointerArgRes.isInvalid())
1880     return true;
1881   PointerArg = PointerArgRes.get();
1882 
1883   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1884 
1885   // In general, we allow ints, floats and pointers to be loaded and stored.
1886   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1887       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1888     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1889         << PointerArg->getType() << PointerArg->getSourceRange();
1890     return true;
1891   }
1892 
1893   // But ARM doesn't have instructions to deal with 128-bit versions.
1894   if (Context.getTypeSize(ValType) > MaxWidth) {
1895     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
1896     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
1897         << PointerArg->getType() << PointerArg->getSourceRange();
1898     return true;
1899   }
1900 
1901   switch (ValType.getObjCLifetime()) {
1902   case Qualifiers::OCL_None:
1903   case Qualifiers::OCL_ExplicitNone:
1904     // okay
1905     break;
1906 
1907   case Qualifiers::OCL_Weak:
1908   case Qualifiers::OCL_Strong:
1909   case Qualifiers::OCL_Autoreleasing:
1910     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
1911         << ValType << PointerArg->getSourceRange();
1912     return true;
1913   }
1914 
1915   if (IsLdrex) {
1916     TheCall->setType(ValType);
1917     return false;
1918   }
1919 
1920   // Initialize the argument to be stored.
1921   ExprResult ValArg = TheCall->getArg(0);
1922   InitializedEntity Entity = InitializedEntity::InitializeParameter(
1923       Context, ValType, /*consume*/ false);
1924   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1925   if (ValArg.isInvalid())
1926     return true;
1927   TheCall->setArg(0, ValArg.get());
1928 
1929   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1930   // but the custom checker bypasses all default analysis.
1931   TheCall->setType(Context.IntTy);
1932   return false;
1933 }
1934 
1935 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1936   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
1937       BuiltinID == ARM::BI__builtin_arm_ldaex ||
1938       BuiltinID == ARM::BI__builtin_arm_strex ||
1939       BuiltinID == ARM::BI__builtin_arm_stlex) {
1940     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
1941   }
1942 
1943   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1944     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1945       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1946   }
1947 
1948   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1949       BuiltinID == ARM::BI__builtin_arm_wsr64)
1950     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1951 
1952   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1953       BuiltinID == ARM::BI__builtin_arm_rsrp ||
1954       BuiltinID == ARM::BI__builtin_arm_wsr ||
1955       BuiltinID == ARM::BI__builtin_arm_wsrp)
1956     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1957 
1958   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1959     return true;
1960   if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
1961     return true;
1962 
1963   // For intrinsics which take an immediate value as part of the instruction,
1964   // range check them here.
1965   // FIXME: VFP Intrinsics should error if VFP not present.
1966   switch (BuiltinID) {
1967   default: return false;
1968   case ARM::BI__builtin_arm_ssat:
1969     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
1970   case ARM::BI__builtin_arm_usat:
1971     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
1972   case ARM::BI__builtin_arm_ssat16:
1973     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
1974   case ARM::BI__builtin_arm_usat16:
1975     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
1976   case ARM::BI__builtin_arm_vcvtr_f:
1977   case ARM::BI__builtin_arm_vcvtr_d:
1978     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
1979   case ARM::BI__builtin_arm_dmb:
1980   case ARM::BI__builtin_arm_dsb:
1981   case ARM::BI__builtin_arm_isb:
1982   case ARM::BI__builtin_arm_dbg:
1983     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
1984   }
1985 }
1986 
1987 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
1988                                          CallExpr *TheCall) {
1989   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1990       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1991       BuiltinID == AArch64::BI__builtin_arm_strex ||
1992       BuiltinID == AArch64::BI__builtin_arm_stlex) {
1993     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1994   }
1995 
1996   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1997     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1998       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1999       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
2000       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
2001   }
2002 
2003   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2004       BuiltinID == AArch64::BI__builtin_arm_wsr64)
2005     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2006 
2007   // Memory Tagging Extensions (MTE) Intrinsics
2008   if (BuiltinID == AArch64::BI__builtin_arm_irg ||
2009       BuiltinID == AArch64::BI__builtin_arm_addg ||
2010       BuiltinID == AArch64::BI__builtin_arm_gmi ||
2011       BuiltinID == AArch64::BI__builtin_arm_ldg ||
2012       BuiltinID == AArch64::BI__builtin_arm_stg ||
2013       BuiltinID == AArch64::BI__builtin_arm_subp) {
2014     return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
2015   }
2016 
2017   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
2018       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2019       BuiltinID == AArch64::BI__builtin_arm_wsr ||
2020       BuiltinID == AArch64::BI__builtin_arm_wsrp)
2021     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2022 
2023   // Only check the valid encoding range. Any constant in this range would be
2024   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
2025   // an exception for incorrect registers. This matches MSVC behavior.
2026   if (BuiltinID == AArch64::BI_ReadStatusReg ||
2027       BuiltinID == AArch64::BI_WriteStatusReg)
2028     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
2029 
2030   if (BuiltinID == AArch64::BI__getReg)
2031     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
2032 
2033   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
2034     return true;
2035 
2036   // For intrinsics which take an immediate value as part of the instruction,
2037   // range check them here.
2038   unsigned i = 0, l = 0, u = 0;
2039   switch (BuiltinID) {
2040   default: return false;
2041   case AArch64::BI__builtin_arm_dmb:
2042   case AArch64::BI__builtin_arm_dsb:
2043   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
2044   case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
2045   }
2046 
2047   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2048 }
2049 
2050 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
2051                                        CallExpr *TheCall) {
2052   assert(BuiltinID == BPF::BI__builtin_preserve_field_info &&
2053          "unexpected ARM builtin");
2054 
2055   if (checkArgCount(*this, TheCall, 2))
2056     return true;
2057 
2058   // The first argument needs to be a record field access.
2059   // If it is an array element access, we delay decision
2060   // to BPF backend to check whether the access is a
2061   // field access or not.
2062   Expr *Arg = TheCall->getArg(0);
2063   if (Arg->getType()->getAsPlaceholderType() ||
2064       (Arg->IgnoreParens()->getObjectKind() != OK_BitField &&
2065        !dyn_cast<MemberExpr>(Arg->IgnoreParens()) &&
2066        !dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens()))) {
2067     Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_field)
2068         << 1 << Arg->getSourceRange();
2069     return true;
2070   }
2071 
2072   // The second argument needs to be a constant int
2073   llvm::APSInt Value;
2074   if (!TheCall->getArg(1)->isIntegerConstantExpr(Value, Context)) {
2075     Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_const)
2076         << 2 << Arg->getSourceRange();
2077     return true;
2078   }
2079 
2080   TheCall->setType(Context.UnsignedIntTy);
2081   return false;
2082 }
2083 
2084 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2085   struct ArgInfo {
2086     uint8_t OpNum;
2087     bool IsSigned;
2088     uint8_t BitWidth;
2089     uint8_t Align;
2090   };
2091   struct BuiltinInfo {
2092     unsigned BuiltinID;
2093     ArgInfo Infos[2];
2094   };
2095 
2096   static BuiltinInfo Infos[] = {
2097     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
2098     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
2099     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
2100     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  1 }} },
2101     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
2102     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
2103     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
2104     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
2105     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
2106     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
2107     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
2108 
2109     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
2110     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
2111     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
2112     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
2113     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
2114     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
2115     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
2116     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
2117     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
2118     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
2119     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
2120 
2121     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
2122     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
2123     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
2124     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
2125     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
2126     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
2127     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
2128     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
2129     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
2130     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
2131     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
2132     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
2133     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
2134     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
2135     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
2136     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
2137     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
2138     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
2139     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
2140     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
2141     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
2142     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
2143     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
2144     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
2145     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
2146     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
2147     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
2148     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
2149     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
2150     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
2151     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
2152     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
2153     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
2154     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
2155     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
2156     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
2157     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
2158     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
2159     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
2160     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
2161     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
2162     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
2163     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
2164     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
2165     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
2166     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
2167     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
2168     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
2169     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
2170     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
2171     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
2172     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
2173                                                       {{ 1, false, 6,  0 }} },
2174     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
2175     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
2176     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
2177     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
2178     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
2179     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
2180     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
2181                                                       {{ 1, false, 5,  0 }} },
2182     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
2183     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
2184     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
2185     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
2186     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
2187     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
2188                                                        { 2, false, 5,  0 }} },
2189     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
2190                                                        { 2, false, 6,  0 }} },
2191     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
2192                                                        { 3, false, 5,  0 }} },
2193     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
2194                                                        { 3, false, 6,  0 }} },
2195     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
2196     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
2197     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
2198     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
2199     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
2200     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
2201     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
2202     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
2203     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
2204     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
2205     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
2206     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
2207     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
2208     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
2209     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
2210     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
2211                                                       {{ 2, false, 4,  0 },
2212                                                        { 3, false, 5,  0 }} },
2213     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
2214                                                       {{ 2, false, 4,  0 },
2215                                                        { 3, false, 5,  0 }} },
2216     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
2217                                                       {{ 2, false, 4,  0 },
2218                                                        { 3, false, 5,  0 }} },
2219     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
2220                                                       {{ 2, false, 4,  0 },
2221                                                        { 3, false, 5,  0 }} },
2222     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
2223     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
2224     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
2225     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
2226     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
2227     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
2228     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
2229     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
2230     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
2231     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
2232     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
2233                                                        { 2, false, 5,  0 }} },
2234     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
2235                                                        { 2, false, 6,  0 }} },
2236     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
2237     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
2238     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
2239     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
2240     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
2241     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
2242     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
2243     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
2244     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
2245                                                       {{ 1, false, 4,  0 }} },
2246     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
2247     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
2248                                                       {{ 1, false, 4,  0 }} },
2249     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
2250     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
2251     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
2252     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
2253     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
2254     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
2255     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
2256     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
2257     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
2258     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
2259     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
2260     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
2261     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
2262     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
2263     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
2264     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
2265     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
2266     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
2267     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
2268     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
2269                                                       {{ 3, false, 1,  0 }} },
2270     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
2271     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
2272     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
2273     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
2274                                                       {{ 3, false, 1,  0 }} },
2275     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
2276     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
2277     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
2278     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
2279                                                       {{ 3, false, 1,  0 }} },
2280   };
2281 
2282   // Use a dynamically initialized static to sort the table exactly once on
2283   // first run.
2284   static const bool SortOnce =
2285       (llvm::sort(Infos,
2286                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
2287                    return LHS.BuiltinID < RHS.BuiltinID;
2288                  }),
2289        true);
2290   (void)SortOnce;
2291 
2292   const BuiltinInfo *F = llvm::partition_point(
2293       Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
2294   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
2295     return false;
2296 
2297   bool Error = false;
2298 
2299   for (const ArgInfo &A : F->Infos) {
2300     // Ignore empty ArgInfo elements.
2301     if (A.BitWidth == 0)
2302       continue;
2303 
2304     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
2305     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
2306     if (!A.Align) {
2307       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
2308     } else {
2309       unsigned M = 1 << A.Align;
2310       Min *= M;
2311       Max *= M;
2312       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
2313                SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
2314     }
2315   }
2316   return Error;
2317 }
2318 
2319 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
2320                                            CallExpr *TheCall) {
2321   return CheckHexagonBuiltinArgument(BuiltinID, TheCall);
2322 }
2323 
2324 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2325   return CheckMipsBuiltinCpu(BuiltinID, TheCall) ||
2326          CheckMipsBuiltinArgument(BuiltinID, TheCall);
2327 }
2328 
2329 bool Sema::CheckMipsBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) {
2330   const TargetInfo &TI = Context.getTargetInfo();
2331 
2332   if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
2333       BuiltinID <= Mips::BI__builtin_mips_lwx) {
2334     if (!TI.hasFeature("dsp"))
2335       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
2336   }
2337 
2338   if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
2339       BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
2340     if (!TI.hasFeature("dspr2"))
2341       return Diag(TheCall->getBeginLoc(),
2342                   diag::err_mips_builtin_requires_dspr2);
2343   }
2344 
2345   if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
2346       BuiltinID <= Mips::BI__builtin_msa_xori_b) {
2347     if (!TI.hasFeature("msa"))
2348       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
2349   }
2350 
2351   return false;
2352 }
2353 
2354 // CheckMipsBuiltinArgument - Checks the constant value passed to the
2355 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
2356 // ordering for DSP is unspecified. MSA is ordered by the data format used
2357 // by the underlying instruction i.e., df/m, df/n and then by size.
2358 //
2359 // FIXME: The size tests here should instead be tablegen'd along with the
2360 //        definitions from include/clang/Basic/BuiltinsMips.def.
2361 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
2362 //        be too.
2363 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2364   unsigned i = 0, l = 0, u = 0, m = 0;
2365   switch (BuiltinID) {
2366   default: return false;
2367   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
2368   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
2369   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
2370   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
2371   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
2372   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
2373   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
2374   // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
2375   // df/m field.
2376   // These intrinsics take an unsigned 3 bit immediate.
2377   case Mips::BI__builtin_msa_bclri_b:
2378   case Mips::BI__builtin_msa_bnegi_b:
2379   case Mips::BI__builtin_msa_bseti_b:
2380   case Mips::BI__builtin_msa_sat_s_b:
2381   case Mips::BI__builtin_msa_sat_u_b:
2382   case Mips::BI__builtin_msa_slli_b:
2383   case Mips::BI__builtin_msa_srai_b:
2384   case Mips::BI__builtin_msa_srari_b:
2385   case Mips::BI__builtin_msa_srli_b:
2386   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
2387   case Mips::BI__builtin_msa_binsli_b:
2388   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
2389   // These intrinsics take an unsigned 4 bit immediate.
2390   case Mips::BI__builtin_msa_bclri_h:
2391   case Mips::BI__builtin_msa_bnegi_h:
2392   case Mips::BI__builtin_msa_bseti_h:
2393   case Mips::BI__builtin_msa_sat_s_h:
2394   case Mips::BI__builtin_msa_sat_u_h:
2395   case Mips::BI__builtin_msa_slli_h:
2396   case Mips::BI__builtin_msa_srai_h:
2397   case Mips::BI__builtin_msa_srari_h:
2398   case Mips::BI__builtin_msa_srli_h:
2399   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
2400   case Mips::BI__builtin_msa_binsli_h:
2401   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
2402   // These intrinsics take an unsigned 5 bit immediate.
2403   // The first block of intrinsics actually have an unsigned 5 bit field,
2404   // not a df/n field.
2405   case Mips::BI__builtin_msa_cfcmsa:
2406   case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
2407   case Mips::BI__builtin_msa_clei_u_b:
2408   case Mips::BI__builtin_msa_clei_u_h:
2409   case Mips::BI__builtin_msa_clei_u_w:
2410   case Mips::BI__builtin_msa_clei_u_d:
2411   case Mips::BI__builtin_msa_clti_u_b:
2412   case Mips::BI__builtin_msa_clti_u_h:
2413   case Mips::BI__builtin_msa_clti_u_w:
2414   case Mips::BI__builtin_msa_clti_u_d:
2415   case Mips::BI__builtin_msa_maxi_u_b:
2416   case Mips::BI__builtin_msa_maxi_u_h:
2417   case Mips::BI__builtin_msa_maxi_u_w:
2418   case Mips::BI__builtin_msa_maxi_u_d:
2419   case Mips::BI__builtin_msa_mini_u_b:
2420   case Mips::BI__builtin_msa_mini_u_h:
2421   case Mips::BI__builtin_msa_mini_u_w:
2422   case Mips::BI__builtin_msa_mini_u_d:
2423   case Mips::BI__builtin_msa_addvi_b:
2424   case Mips::BI__builtin_msa_addvi_h:
2425   case Mips::BI__builtin_msa_addvi_w:
2426   case Mips::BI__builtin_msa_addvi_d:
2427   case Mips::BI__builtin_msa_bclri_w:
2428   case Mips::BI__builtin_msa_bnegi_w:
2429   case Mips::BI__builtin_msa_bseti_w:
2430   case Mips::BI__builtin_msa_sat_s_w:
2431   case Mips::BI__builtin_msa_sat_u_w:
2432   case Mips::BI__builtin_msa_slli_w:
2433   case Mips::BI__builtin_msa_srai_w:
2434   case Mips::BI__builtin_msa_srari_w:
2435   case Mips::BI__builtin_msa_srli_w:
2436   case Mips::BI__builtin_msa_srlri_w:
2437   case Mips::BI__builtin_msa_subvi_b:
2438   case Mips::BI__builtin_msa_subvi_h:
2439   case Mips::BI__builtin_msa_subvi_w:
2440   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
2441   case Mips::BI__builtin_msa_binsli_w:
2442   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
2443   // These intrinsics take an unsigned 6 bit immediate.
2444   case Mips::BI__builtin_msa_bclri_d:
2445   case Mips::BI__builtin_msa_bnegi_d:
2446   case Mips::BI__builtin_msa_bseti_d:
2447   case Mips::BI__builtin_msa_sat_s_d:
2448   case Mips::BI__builtin_msa_sat_u_d:
2449   case Mips::BI__builtin_msa_slli_d:
2450   case Mips::BI__builtin_msa_srai_d:
2451   case Mips::BI__builtin_msa_srari_d:
2452   case Mips::BI__builtin_msa_srli_d:
2453   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
2454   case Mips::BI__builtin_msa_binsli_d:
2455   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
2456   // These intrinsics take a signed 5 bit immediate.
2457   case Mips::BI__builtin_msa_ceqi_b:
2458   case Mips::BI__builtin_msa_ceqi_h:
2459   case Mips::BI__builtin_msa_ceqi_w:
2460   case Mips::BI__builtin_msa_ceqi_d:
2461   case Mips::BI__builtin_msa_clti_s_b:
2462   case Mips::BI__builtin_msa_clti_s_h:
2463   case Mips::BI__builtin_msa_clti_s_w:
2464   case Mips::BI__builtin_msa_clti_s_d:
2465   case Mips::BI__builtin_msa_clei_s_b:
2466   case Mips::BI__builtin_msa_clei_s_h:
2467   case Mips::BI__builtin_msa_clei_s_w:
2468   case Mips::BI__builtin_msa_clei_s_d:
2469   case Mips::BI__builtin_msa_maxi_s_b:
2470   case Mips::BI__builtin_msa_maxi_s_h:
2471   case Mips::BI__builtin_msa_maxi_s_w:
2472   case Mips::BI__builtin_msa_maxi_s_d:
2473   case Mips::BI__builtin_msa_mini_s_b:
2474   case Mips::BI__builtin_msa_mini_s_h:
2475   case Mips::BI__builtin_msa_mini_s_w:
2476   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
2477   // These intrinsics take an unsigned 8 bit immediate.
2478   case Mips::BI__builtin_msa_andi_b:
2479   case Mips::BI__builtin_msa_nori_b:
2480   case Mips::BI__builtin_msa_ori_b:
2481   case Mips::BI__builtin_msa_shf_b:
2482   case Mips::BI__builtin_msa_shf_h:
2483   case Mips::BI__builtin_msa_shf_w:
2484   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
2485   case Mips::BI__builtin_msa_bseli_b:
2486   case Mips::BI__builtin_msa_bmnzi_b:
2487   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
2488   // df/n format
2489   // These intrinsics take an unsigned 4 bit immediate.
2490   case Mips::BI__builtin_msa_copy_s_b:
2491   case Mips::BI__builtin_msa_copy_u_b:
2492   case Mips::BI__builtin_msa_insve_b:
2493   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
2494   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
2495   // These intrinsics take an unsigned 3 bit immediate.
2496   case Mips::BI__builtin_msa_copy_s_h:
2497   case Mips::BI__builtin_msa_copy_u_h:
2498   case Mips::BI__builtin_msa_insve_h:
2499   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
2500   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
2501   // These intrinsics take an unsigned 2 bit immediate.
2502   case Mips::BI__builtin_msa_copy_s_w:
2503   case Mips::BI__builtin_msa_copy_u_w:
2504   case Mips::BI__builtin_msa_insve_w:
2505   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
2506   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
2507   // These intrinsics take an unsigned 1 bit immediate.
2508   case Mips::BI__builtin_msa_copy_s_d:
2509   case Mips::BI__builtin_msa_copy_u_d:
2510   case Mips::BI__builtin_msa_insve_d:
2511   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
2512   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
2513   // Memory offsets and immediate loads.
2514   // These intrinsics take a signed 10 bit immediate.
2515   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
2516   case Mips::BI__builtin_msa_ldi_h:
2517   case Mips::BI__builtin_msa_ldi_w:
2518   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
2519   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
2520   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
2521   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
2522   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
2523   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
2524   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
2525   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
2526   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
2527   }
2528 
2529   if (!m)
2530     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2531 
2532   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
2533          SemaBuiltinConstantArgMultiple(TheCall, i, m);
2534 }
2535 
2536 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2537   unsigned i = 0, l = 0, u = 0;
2538   bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
2539                       BuiltinID == PPC::BI__builtin_divdeu ||
2540                       BuiltinID == PPC::BI__builtin_bpermd;
2541   bool IsTarget64Bit = Context.getTargetInfo()
2542                               .getTypeWidth(Context
2543                                             .getTargetInfo()
2544                                             .getIntPtrType()) == 64;
2545   bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
2546                        BuiltinID == PPC::BI__builtin_divweu ||
2547                        BuiltinID == PPC::BI__builtin_divde ||
2548                        BuiltinID == PPC::BI__builtin_divdeu;
2549 
2550   if (Is64BitBltin && !IsTarget64Bit)
2551     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
2552            << TheCall->getSourceRange();
2553 
2554   if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
2555       (BuiltinID == PPC::BI__builtin_bpermd &&
2556        !Context.getTargetInfo().hasFeature("bpermd")))
2557     return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
2558            << TheCall->getSourceRange();
2559 
2560   auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool {
2561     if (!Context.getTargetInfo().hasFeature("vsx"))
2562       return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
2563              << TheCall->getSourceRange();
2564     return false;
2565   };
2566 
2567   switch (BuiltinID) {
2568   default: return false;
2569   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
2570   case PPC::BI__builtin_altivec_crypto_vshasigmad:
2571     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2572            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
2573   case PPC::BI__builtin_altivec_dss:
2574     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
2575   case PPC::BI__builtin_tbegin:
2576   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
2577   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
2578   case PPC::BI__builtin_tabortwc:
2579   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
2580   case PPC::BI__builtin_tabortwci:
2581   case PPC::BI__builtin_tabortdci:
2582     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
2583            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
2584   case PPC::BI__builtin_altivec_dst:
2585   case PPC::BI__builtin_altivec_dstt:
2586   case PPC::BI__builtin_altivec_dstst:
2587   case PPC::BI__builtin_altivec_dststt:
2588     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
2589   case PPC::BI__builtin_vsx_xxpermdi:
2590   case PPC::BI__builtin_vsx_xxsldwi:
2591     return SemaBuiltinVSX(TheCall);
2592   case PPC::BI__builtin_unpack_vector_int128:
2593     return SemaVSXCheck(TheCall) ||
2594            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
2595   case PPC::BI__builtin_pack_vector_int128:
2596     return SemaVSXCheck(TheCall);
2597   }
2598   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2599 }
2600 
2601 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
2602                                            CallExpr *TheCall) {
2603   if (BuiltinID == SystemZ::BI__builtin_tabort) {
2604     Expr *Arg = TheCall->getArg(0);
2605     llvm::APSInt AbortCode(32);
2606     if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
2607         AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
2608       return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
2609              << Arg->getSourceRange();
2610   }
2611 
2612   // For intrinsics which take an immediate value as part of the instruction,
2613   // range check them here.
2614   unsigned i = 0, l = 0, u = 0;
2615   switch (BuiltinID) {
2616   default: return false;
2617   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
2618   case SystemZ::BI__builtin_s390_verimb:
2619   case SystemZ::BI__builtin_s390_verimh:
2620   case SystemZ::BI__builtin_s390_verimf:
2621   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
2622   case SystemZ::BI__builtin_s390_vfaeb:
2623   case SystemZ::BI__builtin_s390_vfaeh:
2624   case SystemZ::BI__builtin_s390_vfaef:
2625   case SystemZ::BI__builtin_s390_vfaebs:
2626   case SystemZ::BI__builtin_s390_vfaehs:
2627   case SystemZ::BI__builtin_s390_vfaefs:
2628   case SystemZ::BI__builtin_s390_vfaezb:
2629   case SystemZ::BI__builtin_s390_vfaezh:
2630   case SystemZ::BI__builtin_s390_vfaezf:
2631   case SystemZ::BI__builtin_s390_vfaezbs:
2632   case SystemZ::BI__builtin_s390_vfaezhs:
2633   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
2634   case SystemZ::BI__builtin_s390_vfisb:
2635   case SystemZ::BI__builtin_s390_vfidb:
2636     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
2637            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
2638   case SystemZ::BI__builtin_s390_vftcisb:
2639   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
2640   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
2641   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
2642   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
2643   case SystemZ::BI__builtin_s390_vstrcb:
2644   case SystemZ::BI__builtin_s390_vstrch:
2645   case SystemZ::BI__builtin_s390_vstrcf:
2646   case SystemZ::BI__builtin_s390_vstrczb:
2647   case SystemZ::BI__builtin_s390_vstrczh:
2648   case SystemZ::BI__builtin_s390_vstrczf:
2649   case SystemZ::BI__builtin_s390_vstrcbs:
2650   case SystemZ::BI__builtin_s390_vstrchs:
2651   case SystemZ::BI__builtin_s390_vstrcfs:
2652   case SystemZ::BI__builtin_s390_vstrczbs:
2653   case SystemZ::BI__builtin_s390_vstrczhs:
2654   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
2655   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
2656   case SystemZ::BI__builtin_s390_vfminsb:
2657   case SystemZ::BI__builtin_s390_vfmaxsb:
2658   case SystemZ::BI__builtin_s390_vfmindb:
2659   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
2660   case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
2661   case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
2662   }
2663   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2664 }
2665 
2666 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
2667 /// This checks that the target supports __builtin_cpu_supports and
2668 /// that the string argument is constant and valid.
2669 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
2670   Expr *Arg = TheCall->getArg(0);
2671 
2672   // Check if the argument is a string literal.
2673   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
2674     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
2675            << Arg->getSourceRange();
2676 
2677   // Check the contents of the string.
2678   StringRef Feature =
2679       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
2680   if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
2681     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
2682            << Arg->getSourceRange();
2683   return false;
2684 }
2685 
2686 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
2687 /// This checks that the target supports __builtin_cpu_is and
2688 /// that the string argument is constant and valid.
2689 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
2690   Expr *Arg = TheCall->getArg(0);
2691 
2692   // Check if the argument is a string literal.
2693   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
2694     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
2695            << Arg->getSourceRange();
2696 
2697   // Check the contents of the string.
2698   StringRef Feature =
2699       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
2700   if (!S.Context.getTargetInfo().validateCpuIs(Feature))
2701     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
2702            << Arg->getSourceRange();
2703   return false;
2704 }
2705 
2706 // Check if the rounding mode is legal.
2707 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
2708   // Indicates if this instruction has rounding control or just SAE.
2709   bool HasRC = false;
2710 
2711   unsigned ArgNum = 0;
2712   switch (BuiltinID) {
2713   default:
2714     return false;
2715   case X86::BI__builtin_ia32_vcvttsd2si32:
2716   case X86::BI__builtin_ia32_vcvttsd2si64:
2717   case X86::BI__builtin_ia32_vcvttsd2usi32:
2718   case X86::BI__builtin_ia32_vcvttsd2usi64:
2719   case X86::BI__builtin_ia32_vcvttss2si32:
2720   case X86::BI__builtin_ia32_vcvttss2si64:
2721   case X86::BI__builtin_ia32_vcvttss2usi32:
2722   case X86::BI__builtin_ia32_vcvttss2usi64:
2723     ArgNum = 1;
2724     break;
2725   case X86::BI__builtin_ia32_maxpd512:
2726   case X86::BI__builtin_ia32_maxps512:
2727   case X86::BI__builtin_ia32_minpd512:
2728   case X86::BI__builtin_ia32_minps512:
2729     ArgNum = 2;
2730     break;
2731   case X86::BI__builtin_ia32_cvtps2pd512_mask:
2732   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
2733   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
2734   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
2735   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
2736   case X86::BI__builtin_ia32_cvttps2dq512_mask:
2737   case X86::BI__builtin_ia32_cvttps2qq512_mask:
2738   case X86::BI__builtin_ia32_cvttps2udq512_mask:
2739   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
2740   case X86::BI__builtin_ia32_exp2pd_mask:
2741   case X86::BI__builtin_ia32_exp2ps_mask:
2742   case X86::BI__builtin_ia32_getexppd512_mask:
2743   case X86::BI__builtin_ia32_getexpps512_mask:
2744   case X86::BI__builtin_ia32_rcp28pd_mask:
2745   case X86::BI__builtin_ia32_rcp28ps_mask:
2746   case X86::BI__builtin_ia32_rsqrt28pd_mask:
2747   case X86::BI__builtin_ia32_rsqrt28ps_mask:
2748   case X86::BI__builtin_ia32_vcomisd:
2749   case X86::BI__builtin_ia32_vcomiss:
2750   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
2751     ArgNum = 3;
2752     break;
2753   case X86::BI__builtin_ia32_cmppd512_mask:
2754   case X86::BI__builtin_ia32_cmpps512_mask:
2755   case X86::BI__builtin_ia32_cmpsd_mask:
2756   case X86::BI__builtin_ia32_cmpss_mask:
2757   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
2758   case X86::BI__builtin_ia32_getexpsd128_round_mask:
2759   case X86::BI__builtin_ia32_getexpss128_round_mask:
2760   case X86::BI__builtin_ia32_getmantpd512_mask:
2761   case X86::BI__builtin_ia32_getmantps512_mask:
2762   case X86::BI__builtin_ia32_maxsd_round_mask:
2763   case X86::BI__builtin_ia32_maxss_round_mask:
2764   case X86::BI__builtin_ia32_minsd_round_mask:
2765   case X86::BI__builtin_ia32_minss_round_mask:
2766   case X86::BI__builtin_ia32_rcp28sd_round_mask:
2767   case X86::BI__builtin_ia32_rcp28ss_round_mask:
2768   case X86::BI__builtin_ia32_reducepd512_mask:
2769   case X86::BI__builtin_ia32_reduceps512_mask:
2770   case X86::BI__builtin_ia32_rndscalepd_mask:
2771   case X86::BI__builtin_ia32_rndscaleps_mask:
2772   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
2773   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
2774     ArgNum = 4;
2775     break;
2776   case X86::BI__builtin_ia32_fixupimmpd512_mask:
2777   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2778   case X86::BI__builtin_ia32_fixupimmps512_mask:
2779   case X86::BI__builtin_ia32_fixupimmps512_maskz:
2780   case X86::BI__builtin_ia32_fixupimmsd_mask:
2781   case X86::BI__builtin_ia32_fixupimmsd_maskz:
2782   case X86::BI__builtin_ia32_fixupimmss_mask:
2783   case X86::BI__builtin_ia32_fixupimmss_maskz:
2784   case X86::BI__builtin_ia32_getmantsd_round_mask:
2785   case X86::BI__builtin_ia32_getmantss_round_mask:
2786   case X86::BI__builtin_ia32_rangepd512_mask:
2787   case X86::BI__builtin_ia32_rangeps512_mask:
2788   case X86::BI__builtin_ia32_rangesd128_round_mask:
2789   case X86::BI__builtin_ia32_rangess128_round_mask:
2790   case X86::BI__builtin_ia32_reducesd_mask:
2791   case X86::BI__builtin_ia32_reducess_mask:
2792   case X86::BI__builtin_ia32_rndscalesd_round_mask:
2793   case X86::BI__builtin_ia32_rndscaless_round_mask:
2794     ArgNum = 5;
2795     break;
2796   case X86::BI__builtin_ia32_vcvtsd2si64:
2797   case X86::BI__builtin_ia32_vcvtsd2si32:
2798   case X86::BI__builtin_ia32_vcvtsd2usi32:
2799   case X86::BI__builtin_ia32_vcvtsd2usi64:
2800   case X86::BI__builtin_ia32_vcvtss2si32:
2801   case X86::BI__builtin_ia32_vcvtss2si64:
2802   case X86::BI__builtin_ia32_vcvtss2usi32:
2803   case X86::BI__builtin_ia32_vcvtss2usi64:
2804   case X86::BI__builtin_ia32_sqrtpd512:
2805   case X86::BI__builtin_ia32_sqrtps512:
2806     ArgNum = 1;
2807     HasRC = true;
2808     break;
2809   case X86::BI__builtin_ia32_addpd512:
2810   case X86::BI__builtin_ia32_addps512:
2811   case X86::BI__builtin_ia32_divpd512:
2812   case X86::BI__builtin_ia32_divps512:
2813   case X86::BI__builtin_ia32_mulpd512:
2814   case X86::BI__builtin_ia32_mulps512:
2815   case X86::BI__builtin_ia32_subpd512:
2816   case X86::BI__builtin_ia32_subps512:
2817   case X86::BI__builtin_ia32_cvtsi2sd64:
2818   case X86::BI__builtin_ia32_cvtsi2ss32:
2819   case X86::BI__builtin_ia32_cvtsi2ss64:
2820   case X86::BI__builtin_ia32_cvtusi2sd64:
2821   case X86::BI__builtin_ia32_cvtusi2ss32:
2822   case X86::BI__builtin_ia32_cvtusi2ss64:
2823     ArgNum = 2;
2824     HasRC = true;
2825     break;
2826   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
2827   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
2828   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
2829   case X86::BI__builtin_ia32_cvtpd2dq512_mask:
2830   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
2831   case X86::BI__builtin_ia32_cvtpd2udq512_mask:
2832   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
2833   case X86::BI__builtin_ia32_cvtps2dq512_mask:
2834   case X86::BI__builtin_ia32_cvtps2qq512_mask:
2835   case X86::BI__builtin_ia32_cvtps2udq512_mask:
2836   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
2837   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
2838   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
2839   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
2840   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
2841     ArgNum = 3;
2842     HasRC = true;
2843     break;
2844   case X86::BI__builtin_ia32_addss_round_mask:
2845   case X86::BI__builtin_ia32_addsd_round_mask:
2846   case X86::BI__builtin_ia32_divss_round_mask:
2847   case X86::BI__builtin_ia32_divsd_round_mask:
2848   case X86::BI__builtin_ia32_mulss_round_mask:
2849   case X86::BI__builtin_ia32_mulsd_round_mask:
2850   case X86::BI__builtin_ia32_subss_round_mask:
2851   case X86::BI__builtin_ia32_subsd_round_mask:
2852   case X86::BI__builtin_ia32_scalefpd512_mask:
2853   case X86::BI__builtin_ia32_scalefps512_mask:
2854   case X86::BI__builtin_ia32_scalefsd_round_mask:
2855   case X86::BI__builtin_ia32_scalefss_round_mask:
2856   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
2857   case X86::BI__builtin_ia32_sqrtsd_round_mask:
2858   case X86::BI__builtin_ia32_sqrtss_round_mask:
2859   case X86::BI__builtin_ia32_vfmaddsd3_mask:
2860   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
2861   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
2862   case X86::BI__builtin_ia32_vfmaddss3_mask:
2863   case X86::BI__builtin_ia32_vfmaddss3_maskz:
2864   case X86::BI__builtin_ia32_vfmaddss3_mask3:
2865   case X86::BI__builtin_ia32_vfmaddpd512_mask:
2866   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
2867   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
2868   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
2869   case X86::BI__builtin_ia32_vfmaddps512_mask:
2870   case X86::BI__builtin_ia32_vfmaddps512_maskz:
2871   case X86::BI__builtin_ia32_vfmaddps512_mask3:
2872   case X86::BI__builtin_ia32_vfmsubps512_mask3:
2873   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
2874   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
2875   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
2876   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
2877   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
2878   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
2879   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
2880   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
2881     ArgNum = 4;
2882     HasRC = true;
2883     break;
2884   }
2885 
2886   llvm::APSInt Result;
2887 
2888   // We can't check the value of a dependent argument.
2889   Expr *Arg = TheCall->getArg(ArgNum);
2890   if (Arg->isTypeDependent() || Arg->isValueDependent())
2891     return false;
2892 
2893   // Check constant-ness first.
2894   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2895     return true;
2896 
2897   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
2898   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
2899   // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
2900   // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
2901   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
2902       Result == 8/*ROUND_NO_EXC*/ ||
2903       (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
2904       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
2905     return false;
2906 
2907   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
2908          << Arg->getSourceRange();
2909 }
2910 
2911 // Check if the gather/scatter scale is legal.
2912 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
2913                                              CallExpr *TheCall) {
2914   unsigned ArgNum = 0;
2915   switch (BuiltinID) {
2916   default:
2917     return false;
2918   case X86::BI__builtin_ia32_gatherpfdpd:
2919   case X86::BI__builtin_ia32_gatherpfdps:
2920   case X86::BI__builtin_ia32_gatherpfqpd:
2921   case X86::BI__builtin_ia32_gatherpfqps:
2922   case X86::BI__builtin_ia32_scatterpfdpd:
2923   case X86::BI__builtin_ia32_scatterpfdps:
2924   case X86::BI__builtin_ia32_scatterpfqpd:
2925   case X86::BI__builtin_ia32_scatterpfqps:
2926     ArgNum = 3;
2927     break;
2928   case X86::BI__builtin_ia32_gatherd_pd:
2929   case X86::BI__builtin_ia32_gatherd_pd256:
2930   case X86::BI__builtin_ia32_gatherq_pd:
2931   case X86::BI__builtin_ia32_gatherq_pd256:
2932   case X86::BI__builtin_ia32_gatherd_ps:
2933   case X86::BI__builtin_ia32_gatherd_ps256:
2934   case X86::BI__builtin_ia32_gatherq_ps:
2935   case X86::BI__builtin_ia32_gatherq_ps256:
2936   case X86::BI__builtin_ia32_gatherd_q:
2937   case X86::BI__builtin_ia32_gatherd_q256:
2938   case X86::BI__builtin_ia32_gatherq_q:
2939   case X86::BI__builtin_ia32_gatherq_q256:
2940   case X86::BI__builtin_ia32_gatherd_d:
2941   case X86::BI__builtin_ia32_gatherd_d256:
2942   case X86::BI__builtin_ia32_gatherq_d:
2943   case X86::BI__builtin_ia32_gatherq_d256:
2944   case X86::BI__builtin_ia32_gather3div2df:
2945   case X86::BI__builtin_ia32_gather3div2di:
2946   case X86::BI__builtin_ia32_gather3div4df:
2947   case X86::BI__builtin_ia32_gather3div4di:
2948   case X86::BI__builtin_ia32_gather3div4sf:
2949   case X86::BI__builtin_ia32_gather3div4si:
2950   case X86::BI__builtin_ia32_gather3div8sf:
2951   case X86::BI__builtin_ia32_gather3div8si:
2952   case X86::BI__builtin_ia32_gather3siv2df:
2953   case X86::BI__builtin_ia32_gather3siv2di:
2954   case X86::BI__builtin_ia32_gather3siv4df:
2955   case X86::BI__builtin_ia32_gather3siv4di:
2956   case X86::BI__builtin_ia32_gather3siv4sf:
2957   case X86::BI__builtin_ia32_gather3siv4si:
2958   case X86::BI__builtin_ia32_gather3siv8sf:
2959   case X86::BI__builtin_ia32_gather3siv8si:
2960   case X86::BI__builtin_ia32_gathersiv8df:
2961   case X86::BI__builtin_ia32_gathersiv16sf:
2962   case X86::BI__builtin_ia32_gatherdiv8df:
2963   case X86::BI__builtin_ia32_gatherdiv16sf:
2964   case X86::BI__builtin_ia32_gathersiv8di:
2965   case X86::BI__builtin_ia32_gathersiv16si:
2966   case X86::BI__builtin_ia32_gatherdiv8di:
2967   case X86::BI__builtin_ia32_gatherdiv16si:
2968   case X86::BI__builtin_ia32_scatterdiv2df:
2969   case X86::BI__builtin_ia32_scatterdiv2di:
2970   case X86::BI__builtin_ia32_scatterdiv4df:
2971   case X86::BI__builtin_ia32_scatterdiv4di:
2972   case X86::BI__builtin_ia32_scatterdiv4sf:
2973   case X86::BI__builtin_ia32_scatterdiv4si:
2974   case X86::BI__builtin_ia32_scatterdiv8sf:
2975   case X86::BI__builtin_ia32_scatterdiv8si:
2976   case X86::BI__builtin_ia32_scattersiv2df:
2977   case X86::BI__builtin_ia32_scattersiv2di:
2978   case X86::BI__builtin_ia32_scattersiv4df:
2979   case X86::BI__builtin_ia32_scattersiv4di:
2980   case X86::BI__builtin_ia32_scattersiv4sf:
2981   case X86::BI__builtin_ia32_scattersiv4si:
2982   case X86::BI__builtin_ia32_scattersiv8sf:
2983   case X86::BI__builtin_ia32_scattersiv8si:
2984   case X86::BI__builtin_ia32_scattersiv8df:
2985   case X86::BI__builtin_ia32_scattersiv16sf:
2986   case X86::BI__builtin_ia32_scatterdiv8df:
2987   case X86::BI__builtin_ia32_scatterdiv16sf:
2988   case X86::BI__builtin_ia32_scattersiv8di:
2989   case X86::BI__builtin_ia32_scattersiv16si:
2990   case X86::BI__builtin_ia32_scatterdiv8di:
2991   case X86::BI__builtin_ia32_scatterdiv16si:
2992     ArgNum = 4;
2993     break;
2994   }
2995 
2996   llvm::APSInt Result;
2997 
2998   // We can't check the value of a dependent argument.
2999   Expr *Arg = TheCall->getArg(ArgNum);
3000   if (Arg->isTypeDependent() || Arg->isValueDependent())
3001     return false;
3002 
3003   // Check constant-ness first.
3004   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3005     return true;
3006 
3007   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
3008     return false;
3009 
3010   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
3011          << Arg->getSourceRange();
3012 }
3013 
3014 static bool isX86_32Builtin(unsigned BuiltinID) {
3015   // These builtins only work on x86-32 targets.
3016   switch (BuiltinID) {
3017   case X86::BI__builtin_ia32_readeflags_u32:
3018   case X86::BI__builtin_ia32_writeeflags_u32:
3019     return true;
3020   }
3021 
3022   return false;
3023 }
3024 
3025 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3026   if (BuiltinID == X86::BI__builtin_cpu_supports)
3027     return SemaBuiltinCpuSupports(*this, TheCall);
3028 
3029   if (BuiltinID == X86::BI__builtin_cpu_is)
3030     return SemaBuiltinCpuIs(*this, TheCall);
3031 
3032   // Check for 32-bit only builtins on a 64-bit target.
3033   const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3034   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
3035     return Diag(TheCall->getCallee()->getBeginLoc(),
3036                 diag::err_32_bit_builtin_64_bit_tgt);
3037 
3038   // If the intrinsic has rounding or SAE make sure its valid.
3039   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
3040     return true;
3041 
3042   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
3043   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
3044     return true;
3045 
3046   // For intrinsics which take an immediate value as part of the instruction,
3047   // range check them here.
3048   int i = 0, l = 0, u = 0;
3049   switch (BuiltinID) {
3050   default:
3051     return false;
3052   case X86::BI__builtin_ia32_vec_ext_v2si:
3053   case X86::BI__builtin_ia32_vec_ext_v2di:
3054   case X86::BI__builtin_ia32_vextractf128_pd256:
3055   case X86::BI__builtin_ia32_vextractf128_ps256:
3056   case X86::BI__builtin_ia32_vextractf128_si256:
3057   case X86::BI__builtin_ia32_extract128i256:
3058   case X86::BI__builtin_ia32_extractf64x4_mask:
3059   case X86::BI__builtin_ia32_extracti64x4_mask:
3060   case X86::BI__builtin_ia32_extractf32x8_mask:
3061   case X86::BI__builtin_ia32_extracti32x8_mask:
3062   case X86::BI__builtin_ia32_extractf64x2_256_mask:
3063   case X86::BI__builtin_ia32_extracti64x2_256_mask:
3064   case X86::BI__builtin_ia32_extractf32x4_256_mask:
3065   case X86::BI__builtin_ia32_extracti32x4_256_mask:
3066     i = 1; l = 0; u = 1;
3067     break;
3068   case X86::BI__builtin_ia32_vec_set_v2di:
3069   case X86::BI__builtin_ia32_vinsertf128_pd256:
3070   case X86::BI__builtin_ia32_vinsertf128_ps256:
3071   case X86::BI__builtin_ia32_vinsertf128_si256:
3072   case X86::BI__builtin_ia32_insert128i256:
3073   case X86::BI__builtin_ia32_insertf32x8:
3074   case X86::BI__builtin_ia32_inserti32x8:
3075   case X86::BI__builtin_ia32_insertf64x4:
3076   case X86::BI__builtin_ia32_inserti64x4:
3077   case X86::BI__builtin_ia32_insertf64x2_256:
3078   case X86::BI__builtin_ia32_inserti64x2_256:
3079   case X86::BI__builtin_ia32_insertf32x4_256:
3080   case X86::BI__builtin_ia32_inserti32x4_256:
3081     i = 2; l = 0; u = 1;
3082     break;
3083   case X86::BI__builtin_ia32_vpermilpd:
3084   case X86::BI__builtin_ia32_vec_ext_v4hi:
3085   case X86::BI__builtin_ia32_vec_ext_v4si:
3086   case X86::BI__builtin_ia32_vec_ext_v4sf:
3087   case X86::BI__builtin_ia32_vec_ext_v4di:
3088   case X86::BI__builtin_ia32_extractf32x4_mask:
3089   case X86::BI__builtin_ia32_extracti32x4_mask:
3090   case X86::BI__builtin_ia32_extractf64x2_512_mask:
3091   case X86::BI__builtin_ia32_extracti64x2_512_mask:
3092     i = 1; l = 0; u = 3;
3093     break;
3094   case X86::BI_mm_prefetch:
3095   case X86::BI__builtin_ia32_vec_ext_v8hi:
3096   case X86::BI__builtin_ia32_vec_ext_v8si:
3097     i = 1; l = 0; u = 7;
3098     break;
3099   case X86::BI__builtin_ia32_sha1rnds4:
3100   case X86::BI__builtin_ia32_blendpd:
3101   case X86::BI__builtin_ia32_shufpd:
3102   case X86::BI__builtin_ia32_vec_set_v4hi:
3103   case X86::BI__builtin_ia32_vec_set_v4si:
3104   case X86::BI__builtin_ia32_vec_set_v4di:
3105   case X86::BI__builtin_ia32_shuf_f32x4_256:
3106   case X86::BI__builtin_ia32_shuf_f64x2_256:
3107   case X86::BI__builtin_ia32_shuf_i32x4_256:
3108   case X86::BI__builtin_ia32_shuf_i64x2_256:
3109   case X86::BI__builtin_ia32_insertf64x2_512:
3110   case X86::BI__builtin_ia32_inserti64x2_512:
3111   case X86::BI__builtin_ia32_insertf32x4:
3112   case X86::BI__builtin_ia32_inserti32x4:
3113     i = 2; l = 0; u = 3;
3114     break;
3115   case X86::BI__builtin_ia32_vpermil2pd:
3116   case X86::BI__builtin_ia32_vpermil2pd256:
3117   case X86::BI__builtin_ia32_vpermil2ps:
3118   case X86::BI__builtin_ia32_vpermil2ps256:
3119     i = 3; l = 0; u = 3;
3120     break;
3121   case X86::BI__builtin_ia32_cmpb128_mask:
3122   case X86::BI__builtin_ia32_cmpw128_mask:
3123   case X86::BI__builtin_ia32_cmpd128_mask:
3124   case X86::BI__builtin_ia32_cmpq128_mask:
3125   case X86::BI__builtin_ia32_cmpb256_mask:
3126   case X86::BI__builtin_ia32_cmpw256_mask:
3127   case X86::BI__builtin_ia32_cmpd256_mask:
3128   case X86::BI__builtin_ia32_cmpq256_mask:
3129   case X86::BI__builtin_ia32_cmpb512_mask:
3130   case X86::BI__builtin_ia32_cmpw512_mask:
3131   case X86::BI__builtin_ia32_cmpd512_mask:
3132   case X86::BI__builtin_ia32_cmpq512_mask:
3133   case X86::BI__builtin_ia32_ucmpb128_mask:
3134   case X86::BI__builtin_ia32_ucmpw128_mask:
3135   case X86::BI__builtin_ia32_ucmpd128_mask:
3136   case X86::BI__builtin_ia32_ucmpq128_mask:
3137   case X86::BI__builtin_ia32_ucmpb256_mask:
3138   case X86::BI__builtin_ia32_ucmpw256_mask:
3139   case X86::BI__builtin_ia32_ucmpd256_mask:
3140   case X86::BI__builtin_ia32_ucmpq256_mask:
3141   case X86::BI__builtin_ia32_ucmpb512_mask:
3142   case X86::BI__builtin_ia32_ucmpw512_mask:
3143   case X86::BI__builtin_ia32_ucmpd512_mask:
3144   case X86::BI__builtin_ia32_ucmpq512_mask:
3145   case X86::BI__builtin_ia32_vpcomub:
3146   case X86::BI__builtin_ia32_vpcomuw:
3147   case X86::BI__builtin_ia32_vpcomud:
3148   case X86::BI__builtin_ia32_vpcomuq:
3149   case X86::BI__builtin_ia32_vpcomb:
3150   case X86::BI__builtin_ia32_vpcomw:
3151   case X86::BI__builtin_ia32_vpcomd:
3152   case X86::BI__builtin_ia32_vpcomq:
3153   case X86::BI__builtin_ia32_vec_set_v8hi:
3154   case X86::BI__builtin_ia32_vec_set_v8si:
3155     i = 2; l = 0; u = 7;
3156     break;
3157   case X86::BI__builtin_ia32_vpermilpd256:
3158   case X86::BI__builtin_ia32_roundps:
3159   case X86::BI__builtin_ia32_roundpd:
3160   case X86::BI__builtin_ia32_roundps256:
3161   case X86::BI__builtin_ia32_roundpd256:
3162   case X86::BI__builtin_ia32_getmantpd128_mask:
3163   case X86::BI__builtin_ia32_getmantpd256_mask:
3164   case X86::BI__builtin_ia32_getmantps128_mask:
3165   case X86::BI__builtin_ia32_getmantps256_mask:
3166   case X86::BI__builtin_ia32_getmantpd512_mask:
3167   case X86::BI__builtin_ia32_getmantps512_mask:
3168   case X86::BI__builtin_ia32_vec_ext_v16qi:
3169   case X86::BI__builtin_ia32_vec_ext_v16hi:
3170     i = 1; l = 0; u = 15;
3171     break;
3172   case X86::BI__builtin_ia32_pblendd128:
3173   case X86::BI__builtin_ia32_blendps:
3174   case X86::BI__builtin_ia32_blendpd256:
3175   case X86::BI__builtin_ia32_shufpd256:
3176   case X86::BI__builtin_ia32_roundss:
3177   case X86::BI__builtin_ia32_roundsd:
3178   case X86::BI__builtin_ia32_rangepd128_mask:
3179   case X86::BI__builtin_ia32_rangepd256_mask:
3180   case X86::BI__builtin_ia32_rangepd512_mask:
3181   case X86::BI__builtin_ia32_rangeps128_mask:
3182   case X86::BI__builtin_ia32_rangeps256_mask:
3183   case X86::BI__builtin_ia32_rangeps512_mask:
3184   case X86::BI__builtin_ia32_getmantsd_round_mask:
3185   case X86::BI__builtin_ia32_getmantss_round_mask:
3186   case X86::BI__builtin_ia32_vec_set_v16qi:
3187   case X86::BI__builtin_ia32_vec_set_v16hi:
3188     i = 2; l = 0; u = 15;
3189     break;
3190   case X86::BI__builtin_ia32_vec_ext_v32qi:
3191     i = 1; l = 0; u = 31;
3192     break;
3193   case X86::BI__builtin_ia32_cmpps:
3194   case X86::BI__builtin_ia32_cmpss:
3195   case X86::BI__builtin_ia32_cmppd:
3196   case X86::BI__builtin_ia32_cmpsd:
3197   case X86::BI__builtin_ia32_cmpps256:
3198   case X86::BI__builtin_ia32_cmppd256:
3199   case X86::BI__builtin_ia32_cmpps128_mask:
3200   case X86::BI__builtin_ia32_cmppd128_mask:
3201   case X86::BI__builtin_ia32_cmpps256_mask:
3202   case X86::BI__builtin_ia32_cmppd256_mask:
3203   case X86::BI__builtin_ia32_cmpps512_mask:
3204   case X86::BI__builtin_ia32_cmppd512_mask:
3205   case X86::BI__builtin_ia32_cmpsd_mask:
3206   case X86::BI__builtin_ia32_cmpss_mask:
3207   case X86::BI__builtin_ia32_vec_set_v32qi:
3208     i = 2; l = 0; u = 31;
3209     break;
3210   case X86::BI__builtin_ia32_permdf256:
3211   case X86::BI__builtin_ia32_permdi256:
3212   case X86::BI__builtin_ia32_permdf512:
3213   case X86::BI__builtin_ia32_permdi512:
3214   case X86::BI__builtin_ia32_vpermilps:
3215   case X86::BI__builtin_ia32_vpermilps256:
3216   case X86::BI__builtin_ia32_vpermilpd512:
3217   case X86::BI__builtin_ia32_vpermilps512:
3218   case X86::BI__builtin_ia32_pshufd:
3219   case X86::BI__builtin_ia32_pshufd256:
3220   case X86::BI__builtin_ia32_pshufd512:
3221   case X86::BI__builtin_ia32_pshufhw:
3222   case X86::BI__builtin_ia32_pshufhw256:
3223   case X86::BI__builtin_ia32_pshufhw512:
3224   case X86::BI__builtin_ia32_pshuflw:
3225   case X86::BI__builtin_ia32_pshuflw256:
3226   case X86::BI__builtin_ia32_pshuflw512:
3227   case X86::BI__builtin_ia32_vcvtps2ph:
3228   case X86::BI__builtin_ia32_vcvtps2ph_mask:
3229   case X86::BI__builtin_ia32_vcvtps2ph256:
3230   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
3231   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
3232   case X86::BI__builtin_ia32_rndscaleps_128_mask:
3233   case X86::BI__builtin_ia32_rndscalepd_128_mask:
3234   case X86::BI__builtin_ia32_rndscaleps_256_mask:
3235   case X86::BI__builtin_ia32_rndscalepd_256_mask:
3236   case X86::BI__builtin_ia32_rndscaleps_mask:
3237   case X86::BI__builtin_ia32_rndscalepd_mask:
3238   case X86::BI__builtin_ia32_reducepd128_mask:
3239   case X86::BI__builtin_ia32_reducepd256_mask:
3240   case X86::BI__builtin_ia32_reducepd512_mask:
3241   case X86::BI__builtin_ia32_reduceps128_mask:
3242   case X86::BI__builtin_ia32_reduceps256_mask:
3243   case X86::BI__builtin_ia32_reduceps512_mask:
3244   case X86::BI__builtin_ia32_prold512:
3245   case X86::BI__builtin_ia32_prolq512:
3246   case X86::BI__builtin_ia32_prold128:
3247   case X86::BI__builtin_ia32_prold256:
3248   case X86::BI__builtin_ia32_prolq128:
3249   case X86::BI__builtin_ia32_prolq256:
3250   case X86::BI__builtin_ia32_prord512:
3251   case X86::BI__builtin_ia32_prorq512:
3252   case X86::BI__builtin_ia32_prord128:
3253   case X86::BI__builtin_ia32_prord256:
3254   case X86::BI__builtin_ia32_prorq128:
3255   case X86::BI__builtin_ia32_prorq256:
3256   case X86::BI__builtin_ia32_fpclasspd128_mask:
3257   case X86::BI__builtin_ia32_fpclasspd256_mask:
3258   case X86::BI__builtin_ia32_fpclassps128_mask:
3259   case X86::BI__builtin_ia32_fpclassps256_mask:
3260   case X86::BI__builtin_ia32_fpclassps512_mask:
3261   case X86::BI__builtin_ia32_fpclasspd512_mask:
3262   case X86::BI__builtin_ia32_fpclasssd_mask:
3263   case X86::BI__builtin_ia32_fpclassss_mask:
3264   case X86::BI__builtin_ia32_pslldqi128_byteshift:
3265   case X86::BI__builtin_ia32_pslldqi256_byteshift:
3266   case X86::BI__builtin_ia32_pslldqi512_byteshift:
3267   case X86::BI__builtin_ia32_psrldqi128_byteshift:
3268   case X86::BI__builtin_ia32_psrldqi256_byteshift:
3269   case X86::BI__builtin_ia32_psrldqi512_byteshift:
3270   case X86::BI__builtin_ia32_kshiftliqi:
3271   case X86::BI__builtin_ia32_kshiftlihi:
3272   case X86::BI__builtin_ia32_kshiftlisi:
3273   case X86::BI__builtin_ia32_kshiftlidi:
3274   case X86::BI__builtin_ia32_kshiftriqi:
3275   case X86::BI__builtin_ia32_kshiftrihi:
3276   case X86::BI__builtin_ia32_kshiftrisi:
3277   case X86::BI__builtin_ia32_kshiftridi:
3278     i = 1; l = 0; u = 255;
3279     break;
3280   case X86::BI__builtin_ia32_vperm2f128_pd256:
3281   case X86::BI__builtin_ia32_vperm2f128_ps256:
3282   case X86::BI__builtin_ia32_vperm2f128_si256:
3283   case X86::BI__builtin_ia32_permti256:
3284   case X86::BI__builtin_ia32_pblendw128:
3285   case X86::BI__builtin_ia32_pblendw256:
3286   case X86::BI__builtin_ia32_blendps256:
3287   case X86::BI__builtin_ia32_pblendd256:
3288   case X86::BI__builtin_ia32_palignr128:
3289   case X86::BI__builtin_ia32_palignr256:
3290   case X86::BI__builtin_ia32_palignr512:
3291   case X86::BI__builtin_ia32_alignq512:
3292   case X86::BI__builtin_ia32_alignd512:
3293   case X86::BI__builtin_ia32_alignd128:
3294   case X86::BI__builtin_ia32_alignd256:
3295   case X86::BI__builtin_ia32_alignq128:
3296   case X86::BI__builtin_ia32_alignq256:
3297   case X86::BI__builtin_ia32_vcomisd:
3298   case X86::BI__builtin_ia32_vcomiss:
3299   case X86::BI__builtin_ia32_shuf_f32x4:
3300   case X86::BI__builtin_ia32_shuf_f64x2:
3301   case X86::BI__builtin_ia32_shuf_i32x4:
3302   case X86::BI__builtin_ia32_shuf_i64x2:
3303   case X86::BI__builtin_ia32_shufpd512:
3304   case X86::BI__builtin_ia32_shufps:
3305   case X86::BI__builtin_ia32_shufps256:
3306   case X86::BI__builtin_ia32_shufps512:
3307   case X86::BI__builtin_ia32_dbpsadbw128:
3308   case X86::BI__builtin_ia32_dbpsadbw256:
3309   case X86::BI__builtin_ia32_dbpsadbw512:
3310   case X86::BI__builtin_ia32_vpshldd128:
3311   case X86::BI__builtin_ia32_vpshldd256:
3312   case X86::BI__builtin_ia32_vpshldd512:
3313   case X86::BI__builtin_ia32_vpshldq128:
3314   case X86::BI__builtin_ia32_vpshldq256:
3315   case X86::BI__builtin_ia32_vpshldq512:
3316   case X86::BI__builtin_ia32_vpshldw128:
3317   case X86::BI__builtin_ia32_vpshldw256:
3318   case X86::BI__builtin_ia32_vpshldw512:
3319   case X86::BI__builtin_ia32_vpshrdd128:
3320   case X86::BI__builtin_ia32_vpshrdd256:
3321   case X86::BI__builtin_ia32_vpshrdd512:
3322   case X86::BI__builtin_ia32_vpshrdq128:
3323   case X86::BI__builtin_ia32_vpshrdq256:
3324   case X86::BI__builtin_ia32_vpshrdq512:
3325   case X86::BI__builtin_ia32_vpshrdw128:
3326   case X86::BI__builtin_ia32_vpshrdw256:
3327   case X86::BI__builtin_ia32_vpshrdw512:
3328     i = 2; l = 0; u = 255;
3329     break;
3330   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3331   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3332   case X86::BI__builtin_ia32_fixupimmps512_mask:
3333   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3334   case X86::BI__builtin_ia32_fixupimmsd_mask:
3335   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3336   case X86::BI__builtin_ia32_fixupimmss_mask:
3337   case X86::BI__builtin_ia32_fixupimmss_maskz:
3338   case X86::BI__builtin_ia32_fixupimmpd128_mask:
3339   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
3340   case X86::BI__builtin_ia32_fixupimmpd256_mask:
3341   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
3342   case X86::BI__builtin_ia32_fixupimmps128_mask:
3343   case X86::BI__builtin_ia32_fixupimmps128_maskz:
3344   case X86::BI__builtin_ia32_fixupimmps256_mask:
3345   case X86::BI__builtin_ia32_fixupimmps256_maskz:
3346   case X86::BI__builtin_ia32_pternlogd512_mask:
3347   case X86::BI__builtin_ia32_pternlogd512_maskz:
3348   case X86::BI__builtin_ia32_pternlogq512_mask:
3349   case X86::BI__builtin_ia32_pternlogq512_maskz:
3350   case X86::BI__builtin_ia32_pternlogd128_mask:
3351   case X86::BI__builtin_ia32_pternlogd128_maskz:
3352   case X86::BI__builtin_ia32_pternlogd256_mask:
3353   case X86::BI__builtin_ia32_pternlogd256_maskz:
3354   case X86::BI__builtin_ia32_pternlogq128_mask:
3355   case X86::BI__builtin_ia32_pternlogq128_maskz:
3356   case X86::BI__builtin_ia32_pternlogq256_mask:
3357   case X86::BI__builtin_ia32_pternlogq256_maskz:
3358     i = 3; l = 0; u = 255;
3359     break;
3360   case X86::BI__builtin_ia32_gatherpfdpd:
3361   case X86::BI__builtin_ia32_gatherpfdps:
3362   case X86::BI__builtin_ia32_gatherpfqpd:
3363   case X86::BI__builtin_ia32_gatherpfqps:
3364   case X86::BI__builtin_ia32_scatterpfdpd:
3365   case X86::BI__builtin_ia32_scatterpfdps:
3366   case X86::BI__builtin_ia32_scatterpfqpd:
3367   case X86::BI__builtin_ia32_scatterpfqps:
3368     i = 4; l = 2; u = 3;
3369     break;
3370   case X86::BI__builtin_ia32_reducesd_mask:
3371   case X86::BI__builtin_ia32_reducess_mask:
3372   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3373   case X86::BI__builtin_ia32_rndscaless_round_mask:
3374     i = 4; l = 0; u = 255;
3375     break;
3376   }
3377 
3378   // Note that we don't force a hard error on the range check here, allowing
3379   // template-generated or macro-generated dead code to potentially have out-of-
3380   // range values. These need to code generate, but don't need to necessarily
3381   // make any sense. We use a warning that defaults to an error.
3382   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
3383 }
3384 
3385 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
3386 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
3387 /// Returns true when the format fits the function and the FormatStringInfo has
3388 /// been populated.
3389 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
3390                                FormatStringInfo *FSI) {
3391   FSI->HasVAListArg = Format->getFirstArg() == 0;
3392   FSI->FormatIdx = Format->getFormatIdx() - 1;
3393   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
3394 
3395   // The way the format attribute works in GCC, the implicit this argument
3396   // of member functions is counted. However, it doesn't appear in our own
3397   // lists, so decrement format_idx in that case.
3398   if (IsCXXMember) {
3399     if(FSI->FormatIdx == 0)
3400       return false;
3401     --FSI->FormatIdx;
3402     if (FSI->FirstDataArg != 0)
3403       --FSI->FirstDataArg;
3404   }
3405   return true;
3406 }
3407 
3408 /// Checks if a the given expression evaluates to null.
3409 ///
3410 /// Returns true if the value evaluates to null.
3411 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
3412   // If the expression has non-null type, it doesn't evaluate to null.
3413   if (auto nullability
3414         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
3415     if (*nullability == NullabilityKind::NonNull)
3416       return false;
3417   }
3418 
3419   // As a special case, transparent unions initialized with zero are
3420   // considered null for the purposes of the nonnull attribute.
3421   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
3422     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
3423       if (const CompoundLiteralExpr *CLE =
3424           dyn_cast<CompoundLiteralExpr>(Expr))
3425         if (const InitListExpr *ILE =
3426             dyn_cast<InitListExpr>(CLE->getInitializer()))
3427           Expr = ILE->getInit(0);
3428   }
3429 
3430   bool Result;
3431   return (!Expr->isValueDependent() &&
3432           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
3433           !Result);
3434 }
3435 
3436 static void CheckNonNullArgument(Sema &S,
3437                                  const Expr *ArgExpr,
3438                                  SourceLocation CallSiteLoc) {
3439   if (CheckNonNullExpr(S, ArgExpr))
3440     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
3441                           S.PDiag(diag::warn_null_arg)
3442                               << ArgExpr->getSourceRange());
3443 }
3444 
3445 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
3446   FormatStringInfo FSI;
3447   if ((GetFormatStringType(Format) == FST_NSString) &&
3448       getFormatStringInfo(Format, false, &FSI)) {
3449     Idx = FSI.FormatIdx;
3450     return true;
3451   }
3452   return false;
3453 }
3454 
3455 /// Diagnose use of %s directive in an NSString which is being passed
3456 /// as formatting string to formatting method.
3457 static void
3458 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
3459                                         const NamedDecl *FDecl,
3460                                         Expr **Args,
3461                                         unsigned NumArgs) {
3462   unsigned Idx = 0;
3463   bool Format = false;
3464   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
3465   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
3466     Idx = 2;
3467     Format = true;
3468   }
3469   else
3470     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
3471       if (S.GetFormatNSStringIdx(I, Idx)) {
3472         Format = true;
3473         break;
3474       }
3475     }
3476   if (!Format || NumArgs <= Idx)
3477     return;
3478   const Expr *FormatExpr = Args[Idx];
3479   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
3480     FormatExpr = CSCE->getSubExpr();
3481   const StringLiteral *FormatString;
3482   if (const ObjCStringLiteral *OSL =
3483       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
3484     FormatString = OSL->getString();
3485   else
3486     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
3487   if (!FormatString)
3488     return;
3489   if (S.FormatStringHasSArg(FormatString)) {
3490     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
3491       << "%s" << 1 << 1;
3492     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
3493       << FDecl->getDeclName();
3494   }
3495 }
3496 
3497 /// Determine whether the given type has a non-null nullability annotation.
3498 static bool isNonNullType(ASTContext &ctx, QualType type) {
3499   if (auto nullability = type->getNullability(ctx))
3500     return *nullability == NullabilityKind::NonNull;
3501 
3502   return false;
3503 }
3504 
3505 static void CheckNonNullArguments(Sema &S,
3506                                   const NamedDecl *FDecl,
3507                                   const FunctionProtoType *Proto,
3508                                   ArrayRef<const Expr *> Args,
3509                                   SourceLocation CallSiteLoc) {
3510   assert((FDecl || Proto) && "Need a function declaration or prototype");
3511 
3512   // Already checked by by constant evaluator.
3513   if (S.isConstantEvaluated())
3514     return;
3515   // Check the attributes attached to the method/function itself.
3516   llvm::SmallBitVector NonNullArgs;
3517   if (FDecl) {
3518     // Handle the nonnull attribute on the function/method declaration itself.
3519     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
3520       if (!NonNull->args_size()) {
3521         // Easy case: all pointer arguments are nonnull.
3522         for (const auto *Arg : Args)
3523           if (S.isValidPointerAttrType(Arg->getType()))
3524             CheckNonNullArgument(S, Arg, CallSiteLoc);
3525         return;
3526       }
3527 
3528       for (const ParamIdx &Idx : NonNull->args()) {
3529         unsigned IdxAST = Idx.getASTIndex();
3530         if (IdxAST >= Args.size())
3531           continue;
3532         if (NonNullArgs.empty())
3533           NonNullArgs.resize(Args.size());
3534         NonNullArgs.set(IdxAST);
3535       }
3536     }
3537   }
3538 
3539   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
3540     // Handle the nonnull attribute on the parameters of the
3541     // function/method.
3542     ArrayRef<ParmVarDecl*> parms;
3543     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
3544       parms = FD->parameters();
3545     else
3546       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
3547 
3548     unsigned ParamIndex = 0;
3549     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
3550          I != E; ++I, ++ParamIndex) {
3551       const ParmVarDecl *PVD = *I;
3552       if (PVD->hasAttr<NonNullAttr>() ||
3553           isNonNullType(S.Context, PVD->getType())) {
3554         if (NonNullArgs.empty())
3555           NonNullArgs.resize(Args.size());
3556 
3557         NonNullArgs.set(ParamIndex);
3558       }
3559     }
3560   } else {
3561     // If we have a non-function, non-method declaration but no
3562     // function prototype, try to dig out the function prototype.
3563     if (!Proto) {
3564       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
3565         QualType type = VD->getType().getNonReferenceType();
3566         if (auto pointerType = type->getAs<PointerType>())
3567           type = pointerType->getPointeeType();
3568         else if (auto blockType = type->getAs<BlockPointerType>())
3569           type = blockType->getPointeeType();
3570         // FIXME: data member pointers?
3571 
3572         // Dig out the function prototype, if there is one.
3573         Proto = type->getAs<FunctionProtoType>();
3574       }
3575     }
3576 
3577     // Fill in non-null argument information from the nullability
3578     // information on the parameter types (if we have them).
3579     if (Proto) {
3580       unsigned Index = 0;
3581       for (auto paramType : Proto->getParamTypes()) {
3582         if (isNonNullType(S.Context, paramType)) {
3583           if (NonNullArgs.empty())
3584             NonNullArgs.resize(Args.size());
3585 
3586           NonNullArgs.set(Index);
3587         }
3588 
3589         ++Index;
3590       }
3591     }
3592   }
3593 
3594   // Check for non-null arguments.
3595   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
3596        ArgIndex != ArgIndexEnd; ++ArgIndex) {
3597     if (NonNullArgs[ArgIndex])
3598       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
3599   }
3600 }
3601 
3602 /// Handles the checks for format strings, non-POD arguments to vararg
3603 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
3604 /// attributes.
3605 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
3606                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
3607                      bool IsMemberFunction, SourceLocation Loc,
3608                      SourceRange Range, VariadicCallType CallType) {
3609   // FIXME: We should check as much as we can in the template definition.
3610   if (CurContext->isDependentContext())
3611     return;
3612 
3613   // Printf and scanf checking.
3614   llvm::SmallBitVector CheckedVarArgs;
3615   if (FDecl) {
3616     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
3617       // Only create vector if there are format attributes.
3618       CheckedVarArgs.resize(Args.size());
3619 
3620       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
3621                            CheckedVarArgs);
3622     }
3623   }
3624 
3625   // Refuse POD arguments that weren't caught by the format string
3626   // checks above.
3627   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
3628   if (CallType != VariadicDoesNotApply &&
3629       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
3630     unsigned NumParams = Proto ? Proto->getNumParams()
3631                        : FDecl && isa<FunctionDecl>(FDecl)
3632                            ? cast<FunctionDecl>(FDecl)->getNumParams()
3633                        : FDecl && isa<ObjCMethodDecl>(FDecl)
3634                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
3635                        : 0;
3636 
3637     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
3638       // Args[ArgIdx] can be null in malformed code.
3639       if (const Expr *Arg = Args[ArgIdx]) {
3640         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
3641           checkVariadicArgument(Arg, CallType);
3642       }
3643     }
3644   }
3645 
3646   if (FDecl || Proto) {
3647     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
3648 
3649     // Type safety checking.
3650     if (FDecl) {
3651       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
3652         CheckArgumentWithTypeTag(I, Args, Loc);
3653     }
3654   }
3655 
3656   if (FD)
3657     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
3658 }
3659 
3660 /// CheckConstructorCall - Check a constructor call for correctness and safety
3661 /// properties not enforced by the C type system.
3662 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
3663                                 ArrayRef<const Expr *> Args,
3664                                 const FunctionProtoType *Proto,
3665                                 SourceLocation Loc) {
3666   VariadicCallType CallType =
3667     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
3668   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
3669             Loc, SourceRange(), CallType);
3670 }
3671 
3672 /// CheckFunctionCall - Check a direct function call for various correctness
3673 /// and safety properties not strictly enforced by the C type system.
3674 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
3675                              const FunctionProtoType *Proto) {
3676   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
3677                               isa<CXXMethodDecl>(FDecl);
3678   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
3679                           IsMemberOperatorCall;
3680   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
3681                                                   TheCall->getCallee());
3682   Expr** Args = TheCall->getArgs();
3683   unsigned NumArgs = TheCall->getNumArgs();
3684 
3685   Expr *ImplicitThis = nullptr;
3686   if (IsMemberOperatorCall) {
3687     // If this is a call to a member operator, hide the first argument
3688     // from checkCall.
3689     // FIXME: Our choice of AST representation here is less than ideal.
3690     ImplicitThis = Args[0];
3691     ++Args;
3692     --NumArgs;
3693   } else if (IsMemberFunction)
3694     ImplicitThis =
3695         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
3696 
3697   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
3698             IsMemberFunction, TheCall->getRParenLoc(),
3699             TheCall->getCallee()->getSourceRange(), CallType);
3700 
3701   IdentifierInfo *FnInfo = FDecl->getIdentifier();
3702   // None of the checks below are needed for functions that don't have
3703   // simple names (e.g., C++ conversion functions).
3704   if (!FnInfo)
3705     return false;
3706 
3707   CheckAbsoluteValueFunction(TheCall, FDecl);
3708   CheckMaxUnsignedZero(TheCall, FDecl);
3709 
3710   if (getLangOpts().ObjC)
3711     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
3712 
3713   unsigned CMId = FDecl->getMemoryFunctionKind();
3714   if (CMId == 0)
3715     return false;
3716 
3717   // Handle memory setting and copying functions.
3718   if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
3719     CheckStrlcpycatArguments(TheCall, FnInfo);
3720   else if (CMId == Builtin::BIstrncat)
3721     CheckStrncatArguments(TheCall, FnInfo);
3722   else
3723     CheckMemaccessArguments(TheCall, CMId, FnInfo);
3724 
3725   return false;
3726 }
3727 
3728 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
3729                                ArrayRef<const Expr *> Args) {
3730   VariadicCallType CallType =
3731       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
3732 
3733   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
3734             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
3735             CallType);
3736 
3737   return false;
3738 }
3739 
3740 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
3741                             const FunctionProtoType *Proto) {
3742   QualType Ty;
3743   if (const auto *V = dyn_cast<VarDecl>(NDecl))
3744     Ty = V->getType().getNonReferenceType();
3745   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
3746     Ty = F->getType().getNonReferenceType();
3747   else
3748     return false;
3749 
3750   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
3751       !Ty->isFunctionProtoType())
3752     return false;
3753 
3754   VariadicCallType CallType;
3755   if (!Proto || !Proto->isVariadic()) {
3756     CallType = VariadicDoesNotApply;
3757   } else if (Ty->isBlockPointerType()) {
3758     CallType = VariadicBlock;
3759   } else { // Ty->isFunctionPointerType()
3760     CallType = VariadicFunction;
3761   }
3762 
3763   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
3764             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
3765             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
3766             TheCall->getCallee()->getSourceRange(), CallType);
3767 
3768   return false;
3769 }
3770 
3771 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
3772 /// such as function pointers returned from functions.
3773 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
3774   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
3775                                                   TheCall->getCallee());
3776   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
3777             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
3778             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
3779             TheCall->getCallee()->getSourceRange(), CallType);
3780 
3781   return false;
3782 }
3783 
3784 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
3785   if (!llvm::isValidAtomicOrderingCABI(Ordering))
3786     return false;
3787 
3788   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
3789   switch (Op) {
3790   case AtomicExpr::AO__c11_atomic_init:
3791   case AtomicExpr::AO__opencl_atomic_init:
3792     llvm_unreachable("There is no ordering argument for an init");
3793 
3794   case AtomicExpr::AO__c11_atomic_load:
3795   case AtomicExpr::AO__opencl_atomic_load:
3796   case AtomicExpr::AO__atomic_load_n:
3797   case AtomicExpr::AO__atomic_load:
3798     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
3799            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
3800 
3801   case AtomicExpr::AO__c11_atomic_store:
3802   case AtomicExpr::AO__opencl_atomic_store:
3803   case AtomicExpr::AO__atomic_store:
3804   case AtomicExpr::AO__atomic_store_n:
3805     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
3806            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
3807            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
3808 
3809   default:
3810     return true;
3811   }
3812 }
3813 
3814 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
3815                                          AtomicExpr::AtomicOp Op) {
3816   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
3817   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3818   MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
3819   return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
3820                          DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
3821                          Op);
3822 }
3823 
3824 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
3825                                  SourceLocation RParenLoc, MultiExprArg Args,
3826                                  AtomicExpr::AtomicOp Op,
3827                                  AtomicArgumentOrder ArgOrder) {
3828   // All the non-OpenCL operations take one of the following forms.
3829   // The OpenCL operations take the __c11 forms with one extra argument for
3830   // synchronization scope.
3831   enum {
3832     // C    __c11_atomic_init(A *, C)
3833     Init,
3834 
3835     // C    __c11_atomic_load(A *, int)
3836     Load,
3837 
3838     // void __atomic_load(A *, CP, int)
3839     LoadCopy,
3840 
3841     // void __atomic_store(A *, CP, int)
3842     Copy,
3843 
3844     // C    __c11_atomic_add(A *, M, int)
3845     Arithmetic,
3846 
3847     // C    __atomic_exchange_n(A *, CP, int)
3848     Xchg,
3849 
3850     // void __atomic_exchange(A *, C *, CP, int)
3851     GNUXchg,
3852 
3853     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
3854     C11CmpXchg,
3855 
3856     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
3857     GNUCmpXchg
3858   } Form = Init;
3859 
3860   const unsigned NumForm = GNUCmpXchg + 1;
3861   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
3862   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
3863   // where:
3864   //   C is an appropriate type,
3865   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
3866   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
3867   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
3868   //   the int parameters are for orderings.
3869 
3870   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
3871       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
3872       "need to update code for modified forms");
3873   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
3874                     AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
3875                         AtomicExpr::AO__atomic_load,
3876                 "need to update code for modified C11 atomics");
3877   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
3878                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
3879   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
3880                Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
3881                IsOpenCL;
3882   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
3883              Op == AtomicExpr::AO__atomic_store_n ||
3884              Op == AtomicExpr::AO__atomic_exchange_n ||
3885              Op == AtomicExpr::AO__atomic_compare_exchange_n;
3886   bool IsAddSub = false;
3887 
3888   switch (Op) {
3889   case AtomicExpr::AO__c11_atomic_init:
3890   case AtomicExpr::AO__opencl_atomic_init:
3891     Form = Init;
3892     break;
3893 
3894   case AtomicExpr::AO__c11_atomic_load:
3895   case AtomicExpr::AO__opencl_atomic_load:
3896   case AtomicExpr::AO__atomic_load_n:
3897     Form = Load;
3898     break;
3899 
3900   case AtomicExpr::AO__atomic_load:
3901     Form = LoadCopy;
3902     break;
3903 
3904   case AtomicExpr::AO__c11_atomic_store:
3905   case AtomicExpr::AO__opencl_atomic_store:
3906   case AtomicExpr::AO__atomic_store:
3907   case AtomicExpr::AO__atomic_store_n:
3908     Form = Copy;
3909     break;
3910 
3911   case AtomicExpr::AO__c11_atomic_fetch_add:
3912   case AtomicExpr::AO__c11_atomic_fetch_sub:
3913   case AtomicExpr::AO__opencl_atomic_fetch_add:
3914   case AtomicExpr::AO__opencl_atomic_fetch_sub:
3915   case AtomicExpr::AO__atomic_fetch_add:
3916   case AtomicExpr::AO__atomic_fetch_sub:
3917   case AtomicExpr::AO__atomic_add_fetch:
3918   case AtomicExpr::AO__atomic_sub_fetch:
3919     IsAddSub = true;
3920     LLVM_FALLTHROUGH;
3921   case AtomicExpr::AO__c11_atomic_fetch_and:
3922   case AtomicExpr::AO__c11_atomic_fetch_or:
3923   case AtomicExpr::AO__c11_atomic_fetch_xor:
3924   case AtomicExpr::AO__opencl_atomic_fetch_and:
3925   case AtomicExpr::AO__opencl_atomic_fetch_or:
3926   case AtomicExpr::AO__opencl_atomic_fetch_xor:
3927   case AtomicExpr::AO__atomic_fetch_and:
3928   case AtomicExpr::AO__atomic_fetch_or:
3929   case AtomicExpr::AO__atomic_fetch_xor:
3930   case AtomicExpr::AO__atomic_fetch_nand:
3931   case AtomicExpr::AO__atomic_and_fetch:
3932   case AtomicExpr::AO__atomic_or_fetch:
3933   case AtomicExpr::AO__atomic_xor_fetch:
3934   case AtomicExpr::AO__atomic_nand_fetch:
3935   case AtomicExpr::AO__c11_atomic_fetch_min:
3936   case AtomicExpr::AO__c11_atomic_fetch_max:
3937   case AtomicExpr::AO__opencl_atomic_fetch_min:
3938   case AtomicExpr::AO__opencl_atomic_fetch_max:
3939   case AtomicExpr::AO__atomic_min_fetch:
3940   case AtomicExpr::AO__atomic_max_fetch:
3941   case AtomicExpr::AO__atomic_fetch_min:
3942   case AtomicExpr::AO__atomic_fetch_max:
3943     Form = Arithmetic;
3944     break;
3945 
3946   case AtomicExpr::AO__c11_atomic_exchange:
3947   case AtomicExpr::AO__opencl_atomic_exchange:
3948   case AtomicExpr::AO__atomic_exchange_n:
3949     Form = Xchg;
3950     break;
3951 
3952   case AtomicExpr::AO__atomic_exchange:
3953     Form = GNUXchg;
3954     break;
3955 
3956   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
3957   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
3958   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
3959   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
3960     Form = C11CmpXchg;
3961     break;
3962 
3963   case AtomicExpr::AO__atomic_compare_exchange:
3964   case AtomicExpr::AO__atomic_compare_exchange_n:
3965     Form = GNUCmpXchg;
3966     break;
3967   }
3968 
3969   unsigned AdjustedNumArgs = NumArgs[Form];
3970   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
3971     ++AdjustedNumArgs;
3972   // Check we have the right number of arguments.
3973   if (Args.size() < AdjustedNumArgs) {
3974     Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
3975         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
3976         << ExprRange;
3977     return ExprError();
3978   } else if (Args.size() > AdjustedNumArgs) {
3979     Diag(Args[AdjustedNumArgs]->getBeginLoc(),
3980          diag::err_typecheck_call_too_many_args)
3981         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
3982         << ExprRange;
3983     return ExprError();
3984   }
3985 
3986   // Inspect the first argument of the atomic operation.
3987   Expr *Ptr = Args[0];
3988   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
3989   if (ConvertedPtr.isInvalid())
3990     return ExprError();
3991 
3992   Ptr = ConvertedPtr.get();
3993   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
3994   if (!pointerType) {
3995     Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
3996         << Ptr->getType() << Ptr->getSourceRange();
3997     return ExprError();
3998   }
3999 
4000   // For a __c11 builtin, this should be a pointer to an _Atomic type.
4001   QualType AtomTy = pointerType->getPointeeType(); // 'A'
4002   QualType ValType = AtomTy; // 'C'
4003   if (IsC11) {
4004     if (!AtomTy->isAtomicType()) {
4005       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
4006           << Ptr->getType() << Ptr->getSourceRange();
4007       return ExprError();
4008     }
4009     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
4010         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
4011       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
4012           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
4013           << Ptr->getSourceRange();
4014       return ExprError();
4015     }
4016     ValType = AtomTy->castAs<AtomicType>()->getValueType();
4017   } else if (Form != Load && Form != LoadCopy) {
4018     if (ValType.isConstQualified()) {
4019       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
4020           << Ptr->getType() << Ptr->getSourceRange();
4021       return ExprError();
4022     }
4023   }
4024 
4025   // For an arithmetic operation, the implied arithmetic must be well-formed.
4026   if (Form == Arithmetic) {
4027     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
4028     if (IsAddSub && !ValType->isIntegerType()
4029         && !ValType->isPointerType()) {
4030       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4031           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4032       return ExprError();
4033     }
4034     if (!IsAddSub && !ValType->isIntegerType()) {
4035       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
4036           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4037       return ExprError();
4038     }
4039     if (IsC11 && ValType->isPointerType() &&
4040         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
4041                             diag::err_incomplete_type)) {
4042       return ExprError();
4043     }
4044   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
4045     // For __atomic_*_n operations, the value type must be a scalar integral or
4046     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
4047     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4048         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4049     return ExprError();
4050   }
4051 
4052   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
4053       !AtomTy->isScalarType()) {
4054     // For GNU atomics, require a trivially-copyable type. This is not part of
4055     // the GNU atomics specification, but we enforce it for sanity.
4056     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
4057         << Ptr->getType() << Ptr->getSourceRange();
4058     return ExprError();
4059   }
4060 
4061   switch (ValType.getObjCLifetime()) {
4062   case Qualifiers::OCL_None:
4063   case Qualifiers::OCL_ExplicitNone:
4064     // okay
4065     break;
4066 
4067   case Qualifiers::OCL_Weak:
4068   case Qualifiers::OCL_Strong:
4069   case Qualifiers::OCL_Autoreleasing:
4070     // FIXME: Can this happen? By this point, ValType should be known
4071     // to be trivially copyable.
4072     Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
4073         << ValType << Ptr->getSourceRange();
4074     return ExprError();
4075   }
4076 
4077   // All atomic operations have an overload which takes a pointer to a volatile
4078   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
4079   // into the result or the other operands. Similarly atomic_load takes a
4080   // pointer to a const 'A'.
4081   ValType.removeLocalVolatile();
4082   ValType.removeLocalConst();
4083   QualType ResultType = ValType;
4084   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
4085       Form == Init)
4086     ResultType = Context.VoidTy;
4087   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
4088     ResultType = Context.BoolTy;
4089 
4090   // The type of a parameter passed 'by value'. In the GNU atomics, such
4091   // arguments are actually passed as pointers.
4092   QualType ByValType = ValType; // 'CP'
4093   bool IsPassedByAddress = false;
4094   if (!IsC11 && !IsN) {
4095     ByValType = Ptr->getType();
4096     IsPassedByAddress = true;
4097   }
4098 
4099   SmallVector<Expr *, 5> APIOrderedArgs;
4100   if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
4101     APIOrderedArgs.push_back(Args[0]);
4102     switch (Form) {
4103     case Init:
4104     case Load:
4105       APIOrderedArgs.push_back(Args[1]); // Val1/Order
4106       break;
4107     case LoadCopy:
4108     case Copy:
4109     case Arithmetic:
4110     case Xchg:
4111       APIOrderedArgs.push_back(Args[2]); // Val1
4112       APIOrderedArgs.push_back(Args[1]); // Order
4113       break;
4114     case GNUXchg:
4115       APIOrderedArgs.push_back(Args[2]); // Val1
4116       APIOrderedArgs.push_back(Args[3]); // Val2
4117       APIOrderedArgs.push_back(Args[1]); // Order
4118       break;
4119     case C11CmpXchg:
4120       APIOrderedArgs.push_back(Args[2]); // Val1
4121       APIOrderedArgs.push_back(Args[4]); // Val2
4122       APIOrderedArgs.push_back(Args[1]); // Order
4123       APIOrderedArgs.push_back(Args[3]); // OrderFail
4124       break;
4125     case GNUCmpXchg:
4126       APIOrderedArgs.push_back(Args[2]); // Val1
4127       APIOrderedArgs.push_back(Args[4]); // Val2
4128       APIOrderedArgs.push_back(Args[5]); // Weak
4129       APIOrderedArgs.push_back(Args[1]); // Order
4130       APIOrderedArgs.push_back(Args[3]); // OrderFail
4131       break;
4132     }
4133   } else
4134     APIOrderedArgs.append(Args.begin(), Args.end());
4135 
4136   // The first argument's non-CV pointer type is used to deduce the type of
4137   // subsequent arguments, except for:
4138   //  - weak flag (always converted to bool)
4139   //  - memory order (always converted to int)
4140   //  - scope  (always converted to int)
4141   for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
4142     QualType Ty;
4143     if (i < NumVals[Form] + 1) {
4144       switch (i) {
4145       case 0:
4146         // The first argument is always a pointer. It has a fixed type.
4147         // It is always dereferenced, a nullptr is undefined.
4148         CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4149         // Nothing else to do: we already know all we want about this pointer.
4150         continue;
4151       case 1:
4152         // The second argument is the non-atomic operand. For arithmetic, this
4153         // is always passed by value, and for a compare_exchange it is always
4154         // passed by address. For the rest, GNU uses by-address and C11 uses
4155         // by-value.
4156         assert(Form != Load);
4157         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
4158           Ty = ValType;
4159         else if (Form == Copy || Form == Xchg) {
4160           if (IsPassedByAddress) {
4161             // The value pointer is always dereferenced, a nullptr is undefined.
4162             CheckNonNullArgument(*this, APIOrderedArgs[i],
4163                                  ExprRange.getBegin());
4164           }
4165           Ty = ByValType;
4166         } else if (Form == Arithmetic)
4167           Ty = Context.getPointerDiffType();
4168         else {
4169           Expr *ValArg = APIOrderedArgs[i];
4170           // The value pointer is always dereferenced, a nullptr is undefined.
4171           CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
4172           LangAS AS = LangAS::Default;
4173           // Keep address space of non-atomic pointer type.
4174           if (const PointerType *PtrTy =
4175                   ValArg->getType()->getAs<PointerType>()) {
4176             AS = PtrTy->getPointeeType().getAddressSpace();
4177           }
4178           Ty = Context.getPointerType(
4179               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
4180         }
4181         break;
4182       case 2:
4183         // The third argument to compare_exchange / GNU exchange is the desired
4184         // value, either by-value (for the C11 and *_n variant) or as a pointer.
4185         if (IsPassedByAddress)
4186           CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4187         Ty = ByValType;
4188         break;
4189       case 3:
4190         // The fourth argument to GNU compare_exchange is a 'weak' flag.
4191         Ty = Context.BoolTy;
4192         break;
4193       }
4194     } else {
4195       // The order(s) and scope are always converted to int.
4196       Ty = Context.IntTy;
4197     }
4198 
4199     InitializedEntity Entity =
4200         InitializedEntity::InitializeParameter(Context, Ty, false);
4201     ExprResult Arg = APIOrderedArgs[i];
4202     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4203     if (Arg.isInvalid())
4204       return true;
4205     APIOrderedArgs[i] = Arg.get();
4206   }
4207 
4208   // Permute the arguments into a 'consistent' order.
4209   SmallVector<Expr*, 5> SubExprs;
4210   SubExprs.push_back(Ptr);
4211   switch (Form) {
4212   case Init:
4213     // Note, AtomicExpr::getVal1() has a special case for this atomic.
4214     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4215     break;
4216   case Load:
4217     SubExprs.push_back(APIOrderedArgs[1]); // Order
4218     break;
4219   case LoadCopy:
4220   case Copy:
4221   case Arithmetic:
4222   case Xchg:
4223     SubExprs.push_back(APIOrderedArgs[2]); // Order
4224     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4225     break;
4226   case GNUXchg:
4227     // Note, AtomicExpr::getVal2() has a special case for this atomic.
4228     SubExprs.push_back(APIOrderedArgs[3]); // Order
4229     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4230     SubExprs.push_back(APIOrderedArgs[2]); // Val2
4231     break;
4232   case C11CmpXchg:
4233     SubExprs.push_back(APIOrderedArgs[3]); // Order
4234     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4235     SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
4236     SubExprs.push_back(APIOrderedArgs[2]); // Val2
4237     break;
4238   case GNUCmpXchg:
4239     SubExprs.push_back(APIOrderedArgs[4]); // Order
4240     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4241     SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
4242     SubExprs.push_back(APIOrderedArgs[2]); // Val2
4243     SubExprs.push_back(APIOrderedArgs[3]); // Weak
4244     break;
4245   }
4246 
4247   if (SubExprs.size() >= 2 && Form != Init) {
4248     llvm::APSInt Result(32);
4249     if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
4250         !isValidOrderingForOp(Result.getSExtValue(), Op))
4251       Diag(SubExprs[1]->getBeginLoc(),
4252            diag::warn_atomic_op_has_invalid_memory_order)
4253           << SubExprs[1]->getSourceRange();
4254   }
4255 
4256   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
4257     auto *Scope = Args[Args.size() - 1];
4258     llvm::APSInt Result(32);
4259     if (Scope->isIntegerConstantExpr(Result, Context) &&
4260         !ScopeModel->isValid(Result.getZExtValue())) {
4261       Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
4262           << Scope->getSourceRange();
4263     }
4264     SubExprs.push_back(Scope);
4265   }
4266 
4267   AtomicExpr *AE = new (Context)
4268       AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
4269 
4270   if ((Op == AtomicExpr::AO__c11_atomic_load ||
4271        Op == AtomicExpr::AO__c11_atomic_store ||
4272        Op == AtomicExpr::AO__opencl_atomic_load ||
4273        Op == AtomicExpr::AO__opencl_atomic_store ) &&
4274       Context.AtomicUsesUnsupportedLibcall(AE))
4275     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
4276         << ((Op == AtomicExpr::AO__c11_atomic_load ||
4277              Op == AtomicExpr::AO__opencl_atomic_load)
4278                 ? 0
4279                 : 1);
4280 
4281   return AE;
4282 }
4283 
4284 /// checkBuiltinArgument - Given a call to a builtin function, perform
4285 /// normal type-checking on the given argument, updating the call in
4286 /// place.  This is useful when a builtin function requires custom
4287 /// type-checking for some of its arguments but not necessarily all of
4288 /// them.
4289 ///
4290 /// Returns true on error.
4291 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
4292   FunctionDecl *Fn = E->getDirectCallee();
4293   assert(Fn && "builtin call without direct callee!");
4294 
4295   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
4296   InitializedEntity Entity =
4297     InitializedEntity::InitializeParameter(S.Context, Param);
4298 
4299   ExprResult Arg = E->getArg(0);
4300   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
4301   if (Arg.isInvalid())
4302     return true;
4303 
4304   E->setArg(ArgIndex, Arg.get());
4305   return false;
4306 }
4307 
4308 /// We have a call to a function like __sync_fetch_and_add, which is an
4309 /// overloaded function based on the pointer type of its first argument.
4310 /// The main BuildCallExpr routines have already promoted the types of
4311 /// arguments because all of these calls are prototyped as void(...).
4312 ///
4313 /// This function goes through and does final semantic checking for these
4314 /// builtins, as well as generating any warnings.
4315 ExprResult
4316 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
4317   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
4318   Expr *Callee = TheCall->getCallee();
4319   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
4320   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4321 
4322   // Ensure that we have at least one argument to do type inference from.
4323   if (TheCall->getNumArgs() < 1) {
4324     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
4325         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
4326     return ExprError();
4327   }
4328 
4329   // Inspect the first argument of the atomic builtin.  This should always be
4330   // a pointer type, whose element is an integral scalar or pointer type.
4331   // Because it is a pointer type, we don't have to worry about any implicit
4332   // casts here.
4333   // FIXME: We don't allow floating point scalars as input.
4334   Expr *FirstArg = TheCall->getArg(0);
4335   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
4336   if (FirstArgResult.isInvalid())
4337     return ExprError();
4338   FirstArg = FirstArgResult.get();
4339   TheCall->setArg(0, FirstArg);
4340 
4341   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
4342   if (!pointerType) {
4343     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
4344         << FirstArg->getType() << FirstArg->getSourceRange();
4345     return ExprError();
4346   }
4347 
4348   QualType ValType = pointerType->getPointeeType();
4349   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
4350       !ValType->isBlockPointerType()) {
4351     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
4352         << FirstArg->getType() << FirstArg->getSourceRange();
4353     return ExprError();
4354   }
4355 
4356   if (ValType.isConstQualified()) {
4357     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
4358         << FirstArg->getType() << FirstArg->getSourceRange();
4359     return ExprError();
4360   }
4361 
4362   switch (ValType.getObjCLifetime()) {
4363   case Qualifiers::OCL_None:
4364   case Qualifiers::OCL_ExplicitNone:
4365     // okay
4366     break;
4367 
4368   case Qualifiers::OCL_Weak:
4369   case Qualifiers::OCL_Strong:
4370   case Qualifiers::OCL_Autoreleasing:
4371     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
4372         << ValType << FirstArg->getSourceRange();
4373     return ExprError();
4374   }
4375 
4376   // Strip any qualifiers off ValType.
4377   ValType = ValType.getUnqualifiedType();
4378 
4379   // The majority of builtins return a value, but a few have special return
4380   // types, so allow them to override appropriately below.
4381   QualType ResultType = ValType;
4382 
4383   // We need to figure out which concrete builtin this maps onto.  For example,
4384   // __sync_fetch_and_add with a 2 byte object turns into
4385   // __sync_fetch_and_add_2.
4386 #define BUILTIN_ROW(x) \
4387   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
4388     Builtin::BI##x##_8, Builtin::BI##x##_16 }
4389 
4390   static const unsigned BuiltinIndices[][5] = {
4391     BUILTIN_ROW(__sync_fetch_and_add),
4392     BUILTIN_ROW(__sync_fetch_and_sub),
4393     BUILTIN_ROW(__sync_fetch_and_or),
4394     BUILTIN_ROW(__sync_fetch_and_and),
4395     BUILTIN_ROW(__sync_fetch_and_xor),
4396     BUILTIN_ROW(__sync_fetch_and_nand),
4397 
4398     BUILTIN_ROW(__sync_add_and_fetch),
4399     BUILTIN_ROW(__sync_sub_and_fetch),
4400     BUILTIN_ROW(__sync_and_and_fetch),
4401     BUILTIN_ROW(__sync_or_and_fetch),
4402     BUILTIN_ROW(__sync_xor_and_fetch),
4403     BUILTIN_ROW(__sync_nand_and_fetch),
4404 
4405     BUILTIN_ROW(__sync_val_compare_and_swap),
4406     BUILTIN_ROW(__sync_bool_compare_and_swap),
4407     BUILTIN_ROW(__sync_lock_test_and_set),
4408     BUILTIN_ROW(__sync_lock_release),
4409     BUILTIN_ROW(__sync_swap)
4410   };
4411 #undef BUILTIN_ROW
4412 
4413   // Determine the index of the size.
4414   unsigned SizeIndex;
4415   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
4416   case 1: SizeIndex = 0; break;
4417   case 2: SizeIndex = 1; break;
4418   case 4: SizeIndex = 2; break;
4419   case 8: SizeIndex = 3; break;
4420   case 16: SizeIndex = 4; break;
4421   default:
4422     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
4423         << FirstArg->getType() << FirstArg->getSourceRange();
4424     return ExprError();
4425   }
4426 
4427   // Each of these builtins has one pointer argument, followed by some number of
4428   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
4429   // that we ignore.  Find out which row of BuiltinIndices to read from as well
4430   // as the number of fixed args.
4431   unsigned BuiltinID = FDecl->getBuiltinID();
4432   unsigned BuiltinIndex, NumFixed = 1;
4433   bool WarnAboutSemanticsChange = false;
4434   switch (BuiltinID) {
4435   default: llvm_unreachable("Unknown overloaded atomic builtin!");
4436   case Builtin::BI__sync_fetch_and_add:
4437   case Builtin::BI__sync_fetch_and_add_1:
4438   case Builtin::BI__sync_fetch_and_add_2:
4439   case Builtin::BI__sync_fetch_and_add_4:
4440   case Builtin::BI__sync_fetch_and_add_8:
4441   case Builtin::BI__sync_fetch_and_add_16:
4442     BuiltinIndex = 0;
4443     break;
4444 
4445   case Builtin::BI__sync_fetch_and_sub:
4446   case Builtin::BI__sync_fetch_and_sub_1:
4447   case Builtin::BI__sync_fetch_and_sub_2:
4448   case Builtin::BI__sync_fetch_and_sub_4:
4449   case Builtin::BI__sync_fetch_and_sub_8:
4450   case Builtin::BI__sync_fetch_and_sub_16:
4451     BuiltinIndex = 1;
4452     break;
4453 
4454   case Builtin::BI__sync_fetch_and_or:
4455   case Builtin::BI__sync_fetch_and_or_1:
4456   case Builtin::BI__sync_fetch_and_or_2:
4457   case Builtin::BI__sync_fetch_and_or_4:
4458   case Builtin::BI__sync_fetch_and_or_8:
4459   case Builtin::BI__sync_fetch_and_or_16:
4460     BuiltinIndex = 2;
4461     break;
4462 
4463   case Builtin::BI__sync_fetch_and_and:
4464   case Builtin::BI__sync_fetch_and_and_1:
4465   case Builtin::BI__sync_fetch_and_and_2:
4466   case Builtin::BI__sync_fetch_and_and_4:
4467   case Builtin::BI__sync_fetch_and_and_8:
4468   case Builtin::BI__sync_fetch_and_and_16:
4469     BuiltinIndex = 3;
4470     break;
4471 
4472   case Builtin::BI__sync_fetch_and_xor:
4473   case Builtin::BI__sync_fetch_and_xor_1:
4474   case Builtin::BI__sync_fetch_and_xor_2:
4475   case Builtin::BI__sync_fetch_and_xor_4:
4476   case Builtin::BI__sync_fetch_and_xor_8:
4477   case Builtin::BI__sync_fetch_and_xor_16:
4478     BuiltinIndex = 4;
4479     break;
4480 
4481   case Builtin::BI__sync_fetch_and_nand:
4482   case Builtin::BI__sync_fetch_and_nand_1:
4483   case Builtin::BI__sync_fetch_and_nand_2:
4484   case Builtin::BI__sync_fetch_and_nand_4:
4485   case Builtin::BI__sync_fetch_and_nand_8:
4486   case Builtin::BI__sync_fetch_and_nand_16:
4487     BuiltinIndex = 5;
4488     WarnAboutSemanticsChange = true;
4489     break;
4490 
4491   case Builtin::BI__sync_add_and_fetch:
4492   case Builtin::BI__sync_add_and_fetch_1:
4493   case Builtin::BI__sync_add_and_fetch_2:
4494   case Builtin::BI__sync_add_and_fetch_4:
4495   case Builtin::BI__sync_add_and_fetch_8:
4496   case Builtin::BI__sync_add_and_fetch_16:
4497     BuiltinIndex = 6;
4498     break;
4499 
4500   case Builtin::BI__sync_sub_and_fetch:
4501   case Builtin::BI__sync_sub_and_fetch_1:
4502   case Builtin::BI__sync_sub_and_fetch_2:
4503   case Builtin::BI__sync_sub_and_fetch_4:
4504   case Builtin::BI__sync_sub_and_fetch_8:
4505   case Builtin::BI__sync_sub_and_fetch_16:
4506     BuiltinIndex = 7;
4507     break;
4508 
4509   case Builtin::BI__sync_and_and_fetch:
4510   case Builtin::BI__sync_and_and_fetch_1:
4511   case Builtin::BI__sync_and_and_fetch_2:
4512   case Builtin::BI__sync_and_and_fetch_4:
4513   case Builtin::BI__sync_and_and_fetch_8:
4514   case Builtin::BI__sync_and_and_fetch_16:
4515     BuiltinIndex = 8;
4516     break;
4517 
4518   case Builtin::BI__sync_or_and_fetch:
4519   case Builtin::BI__sync_or_and_fetch_1:
4520   case Builtin::BI__sync_or_and_fetch_2:
4521   case Builtin::BI__sync_or_and_fetch_4:
4522   case Builtin::BI__sync_or_and_fetch_8:
4523   case Builtin::BI__sync_or_and_fetch_16:
4524     BuiltinIndex = 9;
4525     break;
4526 
4527   case Builtin::BI__sync_xor_and_fetch:
4528   case Builtin::BI__sync_xor_and_fetch_1:
4529   case Builtin::BI__sync_xor_and_fetch_2:
4530   case Builtin::BI__sync_xor_and_fetch_4:
4531   case Builtin::BI__sync_xor_and_fetch_8:
4532   case Builtin::BI__sync_xor_and_fetch_16:
4533     BuiltinIndex = 10;
4534     break;
4535 
4536   case Builtin::BI__sync_nand_and_fetch:
4537   case Builtin::BI__sync_nand_and_fetch_1:
4538   case Builtin::BI__sync_nand_and_fetch_2:
4539   case Builtin::BI__sync_nand_and_fetch_4:
4540   case Builtin::BI__sync_nand_and_fetch_8:
4541   case Builtin::BI__sync_nand_and_fetch_16:
4542     BuiltinIndex = 11;
4543     WarnAboutSemanticsChange = true;
4544     break;
4545 
4546   case Builtin::BI__sync_val_compare_and_swap:
4547   case Builtin::BI__sync_val_compare_and_swap_1:
4548   case Builtin::BI__sync_val_compare_and_swap_2:
4549   case Builtin::BI__sync_val_compare_and_swap_4:
4550   case Builtin::BI__sync_val_compare_and_swap_8:
4551   case Builtin::BI__sync_val_compare_and_swap_16:
4552     BuiltinIndex = 12;
4553     NumFixed = 2;
4554     break;
4555 
4556   case Builtin::BI__sync_bool_compare_and_swap:
4557   case Builtin::BI__sync_bool_compare_and_swap_1:
4558   case Builtin::BI__sync_bool_compare_and_swap_2:
4559   case Builtin::BI__sync_bool_compare_and_swap_4:
4560   case Builtin::BI__sync_bool_compare_and_swap_8:
4561   case Builtin::BI__sync_bool_compare_and_swap_16:
4562     BuiltinIndex = 13;
4563     NumFixed = 2;
4564     ResultType = Context.BoolTy;
4565     break;
4566 
4567   case Builtin::BI__sync_lock_test_and_set:
4568   case Builtin::BI__sync_lock_test_and_set_1:
4569   case Builtin::BI__sync_lock_test_and_set_2:
4570   case Builtin::BI__sync_lock_test_and_set_4:
4571   case Builtin::BI__sync_lock_test_and_set_8:
4572   case Builtin::BI__sync_lock_test_and_set_16:
4573     BuiltinIndex = 14;
4574     break;
4575 
4576   case Builtin::BI__sync_lock_release:
4577   case Builtin::BI__sync_lock_release_1:
4578   case Builtin::BI__sync_lock_release_2:
4579   case Builtin::BI__sync_lock_release_4:
4580   case Builtin::BI__sync_lock_release_8:
4581   case Builtin::BI__sync_lock_release_16:
4582     BuiltinIndex = 15;
4583     NumFixed = 0;
4584     ResultType = Context.VoidTy;
4585     break;
4586 
4587   case Builtin::BI__sync_swap:
4588   case Builtin::BI__sync_swap_1:
4589   case Builtin::BI__sync_swap_2:
4590   case Builtin::BI__sync_swap_4:
4591   case Builtin::BI__sync_swap_8:
4592   case Builtin::BI__sync_swap_16:
4593     BuiltinIndex = 16;
4594     break;
4595   }
4596 
4597   // Now that we know how many fixed arguments we expect, first check that we
4598   // have at least that many.
4599   if (TheCall->getNumArgs() < 1+NumFixed) {
4600     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
4601         << 0 << 1 + NumFixed << TheCall->getNumArgs()
4602         << Callee->getSourceRange();
4603     return ExprError();
4604   }
4605 
4606   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
4607       << Callee->getSourceRange();
4608 
4609   if (WarnAboutSemanticsChange) {
4610     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
4611         << Callee->getSourceRange();
4612   }
4613 
4614   // Get the decl for the concrete builtin from this, we can tell what the
4615   // concrete integer type we should convert to is.
4616   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
4617   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
4618   FunctionDecl *NewBuiltinDecl;
4619   if (NewBuiltinID == BuiltinID)
4620     NewBuiltinDecl = FDecl;
4621   else {
4622     // Perform builtin lookup to avoid redeclaring it.
4623     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
4624     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
4625     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
4626     assert(Res.getFoundDecl());
4627     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
4628     if (!NewBuiltinDecl)
4629       return ExprError();
4630   }
4631 
4632   // The first argument --- the pointer --- has a fixed type; we
4633   // deduce the types of the rest of the arguments accordingly.  Walk
4634   // the remaining arguments, converting them to the deduced value type.
4635   for (unsigned i = 0; i != NumFixed; ++i) {
4636     ExprResult Arg = TheCall->getArg(i+1);
4637 
4638     // GCC does an implicit conversion to the pointer or integer ValType.  This
4639     // can fail in some cases (1i -> int**), check for this error case now.
4640     // Initialize the argument.
4641     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
4642                                                    ValType, /*consume*/ false);
4643     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4644     if (Arg.isInvalid())
4645       return ExprError();
4646 
4647     // Okay, we have something that *can* be converted to the right type.  Check
4648     // to see if there is a potentially weird extension going on here.  This can
4649     // happen when you do an atomic operation on something like an char* and
4650     // pass in 42.  The 42 gets converted to char.  This is even more strange
4651     // for things like 45.123 -> char, etc.
4652     // FIXME: Do this check.
4653     TheCall->setArg(i+1, Arg.get());
4654   }
4655 
4656   // Create a new DeclRefExpr to refer to the new decl.
4657   DeclRefExpr *NewDRE = DeclRefExpr::Create(
4658       Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
4659       /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
4660       DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
4661 
4662   // Set the callee in the CallExpr.
4663   // FIXME: This loses syntactic information.
4664   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
4665   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
4666                                               CK_BuiltinFnToFnPtr);
4667   TheCall->setCallee(PromotedCall.get());
4668 
4669   // Change the result type of the call to match the original value type. This
4670   // is arbitrary, but the codegen for these builtins ins design to handle it
4671   // gracefully.
4672   TheCall->setType(ResultType);
4673 
4674   return TheCallResult;
4675 }
4676 
4677 /// SemaBuiltinNontemporalOverloaded - We have a call to
4678 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
4679 /// overloaded function based on the pointer type of its last argument.
4680 ///
4681 /// This function goes through and does final semantic checking for these
4682 /// builtins.
4683 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
4684   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
4685   DeclRefExpr *DRE =
4686       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4687   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4688   unsigned BuiltinID = FDecl->getBuiltinID();
4689   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
4690           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
4691          "Unexpected nontemporal load/store builtin!");
4692   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
4693   unsigned numArgs = isStore ? 2 : 1;
4694 
4695   // Ensure that we have the proper number of arguments.
4696   if (checkArgCount(*this, TheCall, numArgs))
4697     return ExprError();
4698 
4699   // Inspect the last argument of the nontemporal builtin.  This should always
4700   // be a pointer type, from which we imply the type of the memory access.
4701   // Because it is a pointer type, we don't have to worry about any implicit
4702   // casts here.
4703   Expr *PointerArg = TheCall->getArg(numArgs - 1);
4704   ExprResult PointerArgResult =
4705       DefaultFunctionArrayLvalueConversion(PointerArg);
4706 
4707   if (PointerArgResult.isInvalid())
4708     return ExprError();
4709   PointerArg = PointerArgResult.get();
4710   TheCall->setArg(numArgs - 1, PointerArg);
4711 
4712   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
4713   if (!pointerType) {
4714     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
4715         << PointerArg->getType() << PointerArg->getSourceRange();
4716     return ExprError();
4717   }
4718 
4719   QualType ValType = pointerType->getPointeeType();
4720 
4721   // Strip any qualifiers off ValType.
4722   ValType = ValType.getUnqualifiedType();
4723   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
4724       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
4725       !ValType->isVectorType()) {
4726     Diag(DRE->getBeginLoc(),
4727          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
4728         << PointerArg->getType() << PointerArg->getSourceRange();
4729     return ExprError();
4730   }
4731 
4732   if (!isStore) {
4733     TheCall->setType(ValType);
4734     return TheCallResult;
4735   }
4736 
4737   ExprResult ValArg = TheCall->getArg(0);
4738   InitializedEntity Entity = InitializedEntity::InitializeParameter(
4739       Context, ValType, /*consume*/ false);
4740   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
4741   if (ValArg.isInvalid())
4742     return ExprError();
4743 
4744   TheCall->setArg(0, ValArg.get());
4745   TheCall->setType(Context.VoidTy);
4746   return TheCallResult;
4747 }
4748 
4749 /// CheckObjCString - Checks that the argument to the builtin
4750 /// CFString constructor is correct
4751 /// Note: It might also make sense to do the UTF-16 conversion here (would
4752 /// simplify the backend).
4753 bool Sema::CheckObjCString(Expr *Arg) {
4754   Arg = Arg->IgnoreParenCasts();
4755   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
4756 
4757   if (!Literal || !Literal->isAscii()) {
4758     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
4759         << Arg->getSourceRange();
4760     return true;
4761   }
4762 
4763   if (Literal->containsNonAsciiOrNull()) {
4764     StringRef String = Literal->getString();
4765     unsigned NumBytes = String.size();
4766     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
4767     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
4768     llvm::UTF16 *ToPtr = &ToBuf[0];
4769 
4770     llvm::ConversionResult Result =
4771         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
4772                                  ToPtr + NumBytes, llvm::strictConversion);
4773     // Check for conversion failure.
4774     if (Result != llvm::conversionOK)
4775       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
4776           << Arg->getSourceRange();
4777   }
4778   return false;
4779 }
4780 
4781 /// CheckObjCString - Checks that the format string argument to the os_log()
4782 /// and os_trace() functions is correct, and converts it to const char *.
4783 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
4784   Arg = Arg->IgnoreParenCasts();
4785   auto *Literal = dyn_cast<StringLiteral>(Arg);
4786   if (!Literal) {
4787     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
4788       Literal = ObjcLiteral->getString();
4789     }
4790   }
4791 
4792   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
4793     return ExprError(
4794         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
4795         << Arg->getSourceRange());
4796   }
4797 
4798   ExprResult Result(Literal);
4799   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
4800   InitializedEntity Entity =
4801       InitializedEntity::InitializeParameter(Context, ResultTy, false);
4802   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
4803   return Result;
4804 }
4805 
4806 /// Check that the user is calling the appropriate va_start builtin for the
4807 /// target and calling convention.
4808 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
4809   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
4810   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
4811   bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
4812                     TT.getArch() == llvm::Triple::aarch64_32);
4813   bool IsWindows = TT.isOSWindows();
4814   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
4815   if (IsX64 || IsAArch64) {
4816     CallingConv CC = CC_C;
4817     if (const FunctionDecl *FD = S.getCurFunctionDecl())
4818       CC = FD->getType()->castAs<FunctionType>()->getCallConv();
4819     if (IsMSVAStart) {
4820       // Don't allow this in System V ABI functions.
4821       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
4822         return S.Diag(Fn->getBeginLoc(),
4823                       diag::err_ms_va_start_used_in_sysv_function);
4824     } else {
4825       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
4826       // On x64 Windows, don't allow this in System V ABI functions.
4827       // (Yes, that means there's no corresponding way to support variadic
4828       // System V ABI functions on Windows.)
4829       if ((IsWindows && CC == CC_X86_64SysV) ||
4830           (!IsWindows && CC == CC_Win64))
4831         return S.Diag(Fn->getBeginLoc(),
4832                       diag::err_va_start_used_in_wrong_abi_function)
4833                << !IsWindows;
4834     }
4835     return false;
4836   }
4837 
4838   if (IsMSVAStart)
4839     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
4840   return false;
4841 }
4842 
4843 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
4844                                              ParmVarDecl **LastParam = nullptr) {
4845   // Determine whether the current function, block, or obj-c method is variadic
4846   // and get its parameter list.
4847   bool IsVariadic = false;
4848   ArrayRef<ParmVarDecl *> Params;
4849   DeclContext *Caller = S.CurContext;
4850   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
4851     IsVariadic = Block->isVariadic();
4852     Params = Block->parameters();
4853   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
4854     IsVariadic = FD->isVariadic();
4855     Params = FD->parameters();
4856   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
4857     IsVariadic = MD->isVariadic();
4858     // FIXME: This isn't correct for methods (results in bogus warning).
4859     Params = MD->parameters();
4860   } else if (isa<CapturedDecl>(Caller)) {
4861     // We don't support va_start in a CapturedDecl.
4862     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
4863     return true;
4864   } else {
4865     // This must be some other declcontext that parses exprs.
4866     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
4867     return true;
4868   }
4869 
4870   if (!IsVariadic) {
4871     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
4872     return true;
4873   }
4874 
4875   if (LastParam)
4876     *LastParam = Params.empty() ? nullptr : Params.back();
4877 
4878   return false;
4879 }
4880 
4881 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
4882 /// for validity.  Emit an error and return true on failure; return false
4883 /// on success.
4884 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
4885   Expr *Fn = TheCall->getCallee();
4886 
4887   if (checkVAStartABI(*this, BuiltinID, Fn))
4888     return true;
4889 
4890   if (TheCall->getNumArgs() > 2) {
4891     Diag(TheCall->getArg(2)->getBeginLoc(),
4892          diag::err_typecheck_call_too_many_args)
4893         << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4894         << Fn->getSourceRange()
4895         << SourceRange(TheCall->getArg(2)->getBeginLoc(),
4896                        (*(TheCall->arg_end() - 1))->getEndLoc());
4897     return true;
4898   }
4899 
4900   if (TheCall->getNumArgs() < 2) {
4901     return Diag(TheCall->getEndLoc(),
4902                 diag::err_typecheck_call_too_few_args_at_least)
4903            << 0 /*function call*/ << 2 << TheCall->getNumArgs();
4904   }
4905 
4906   // Type-check the first argument normally.
4907   if (checkBuiltinArgument(*this, TheCall, 0))
4908     return true;
4909 
4910   // Check that the current function is variadic, and get its last parameter.
4911   ParmVarDecl *LastParam;
4912   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
4913     return true;
4914 
4915   // Verify that the second argument to the builtin is the last argument of the
4916   // current function or method.
4917   bool SecondArgIsLastNamedArgument = false;
4918   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
4919 
4920   // These are valid if SecondArgIsLastNamedArgument is false after the next
4921   // block.
4922   QualType Type;
4923   SourceLocation ParamLoc;
4924   bool IsCRegister = false;
4925 
4926   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
4927     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
4928       SecondArgIsLastNamedArgument = PV == LastParam;
4929 
4930       Type = PV->getType();
4931       ParamLoc = PV->getLocation();
4932       IsCRegister =
4933           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
4934     }
4935   }
4936 
4937   if (!SecondArgIsLastNamedArgument)
4938     Diag(TheCall->getArg(1)->getBeginLoc(),
4939          diag::warn_second_arg_of_va_start_not_last_named_param);
4940   else if (IsCRegister || Type->isReferenceType() ||
4941            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
4942              // Promotable integers are UB, but enumerations need a bit of
4943              // extra checking to see what their promotable type actually is.
4944              if (!Type->isPromotableIntegerType())
4945                return false;
4946              if (!Type->isEnumeralType())
4947                return true;
4948              const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
4949              return !(ED &&
4950                       Context.typesAreCompatible(ED->getPromotionType(), Type));
4951            }()) {
4952     unsigned Reason = 0;
4953     if (Type->isReferenceType())  Reason = 1;
4954     else if (IsCRegister)         Reason = 2;
4955     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
4956     Diag(ParamLoc, diag::note_parameter_type) << Type;
4957   }
4958 
4959   TheCall->setType(Context.VoidTy);
4960   return false;
4961 }
4962 
4963 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
4964   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
4965   //                 const char *named_addr);
4966 
4967   Expr *Func = Call->getCallee();
4968 
4969   if (Call->getNumArgs() < 3)
4970     return Diag(Call->getEndLoc(),
4971                 diag::err_typecheck_call_too_few_args_at_least)
4972            << 0 /*function call*/ << 3 << Call->getNumArgs();
4973 
4974   // Type-check the first argument normally.
4975   if (checkBuiltinArgument(*this, Call, 0))
4976     return true;
4977 
4978   // Check that the current function is variadic.
4979   if (checkVAStartIsInVariadicFunction(*this, Func))
4980     return true;
4981 
4982   // __va_start on Windows does not validate the parameter qualifiers
4983 
4984   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
4985   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
4986 
4987   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
4988   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
4989 
4990   const QualType &ConstCharPtrTy =
4991       Context.getPointerType(Context.CharTy.withConst());
4992   if (!Arg1Ty->isPointerType() ||
4993       Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
4994     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
4995         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
4996         << 0                                      /* qualifier difference */
4997         << 3                                      /* parameter mismatch */
4998         << 2 << Arg1->getType() << ConstCharPtrTy;
4999 
5000   const QualType SizeTy = Context.getSizeType();
5001   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
5002     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5003         << Arg2->getType() << SizeTy << 1 /* different class */
5004         << 0                              /* qualifier difference */
5005         << 3                              /* parameter mismatch */
5006         << 3 << Arg2->getType() << SizeTy;
5007 
5008   return false;
5009 }
5010 
5011 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
5012 /// friends.  This is declared to take (...), so we have to check everything.
5013 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
5014   if (TheCall->getNumArgs() < 2)
5015     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5016            << 0 << 2 << TheCall->getNumArgs() /*function call*/;
5017   if (TheCall->getNumArgs() > 2)
5018     return Diag(TheCall->getArg(2)->getBeginLoc(),
5019                 diag::err_typecheck_call_too_many_args)
5020            << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5021            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5022                           (*(TheCall->arg_end() - 1))->getEndLoc());
5023 
5024   ExprResult OrigArg0 = TheCall->getArg(0);
5025   ExprResult OrigArg1 = TheCall->getArg(1);
5026 
5027   // Do standard promotions between the two arguments, returning their common
5028   // type.
5029   QualType Res = UsualArithmeticConversions(
5030       OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
5031   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
5032     return true;
5033 
5034   // Make sure any conversions are pushed back into the call; this is
5035   // type safe since unordered compare builtins are declared as "_Bool
5036   // foo(...)".
5037   TheCall->setArg(0, OrigArg0.get());
5038   TheCall->setArg(1, OrigArg1.get());
5039 
5040   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
5041     return false;
5042 
5043   // If the common type isn't a real floating type, then the arguments were
5044   // invalid for this operation.
5045   if (Res.isNull() || !Res->isRealFloatingType())
5046     return Diag(OrigArg0.get()->getBeginLoc(),
5047                 diag::err_typecheck_call_invalid_ordered_compare)
5048            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
5049            << SourceRange(OrigArg0.get()->getBeginLoc(),
5050                           OrigArg1.get()->getEndLoc());
5051 
5052   return false;
5053 }
5054 
5055 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
5056 /// __builtin_isnan and friends.  This is declared to take (...), so we have
5057 /// to check everything. We expect the last argument to be a floating point
5058 /// value.
5059 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
5060   if (TheCall->getNumArgs() < NumArgs)
5061     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5062            << 0 << NumArgs << TheCall->getNumArgs() /*function call*/;
5063   if (TheCall->getNumArgs() > NumArgs)
5064     return Diag(TheCall->getArg(NumArgs)->getBeginLoc(),
5065                 diag::err_typecheck_call_too_many_args)
5066            << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
5067            << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(),
5068                           (*(TheCall->arg_end() - 1))->getEndLoc());
5069 
5070   // __builtin_fpclassify is the only case where NumArgs != 1, so we can count
5071   // on all preceding parameters just being int.  Try all of those.
5072   for (unsigned i = 0; i < NumArgs - 1; ++i) {
5073     Expr *Arg = TheCall->getArg(i);
5074 
5075     if (Arg->isTypeDependent())
5076       return false;
5077 
5078     ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);
5079 
5080     if (Res.isInvalid())
5081       return true;
5082     TheCall->setArg(i, Res.get());
5083   }
5084 
5085   Expr *OrigArg = TheCall->getArg(NumArgs-1);
5086 
5087   if (OrigArg->isTypeDependent())
5088     return false;
5089 
5090   // Usual Unary Conversions will convert half to float, which we want for
5091   // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
5092   // type how it is, but do normal L->Rvalue conversions.
5093   if (Context.getTargetInfo().useFP16ConversionIntrinsics())
5094     OrigArg = UsualUnaryConversions(OrigArg).get();
5095   else
5096     OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
5097   TheCall->setArg(NumArgs - 1, OrigArg);
5098 
5099   // This operation requires a non-_Complex floating-point number.
5100   if (!OrigArg->getType()->isRealFloatingType())
5101     return Diag(OrigArg->getBeginLoc(),
5102                 diag::err_typecheck_call_invalid_unary_fp)
5103            << OrigArg->getType() << OrigArg->getSourceRange();
5104 
5105   return false;
5106 }
5107 
5108 // Customized Sema Checking for VSX builtins that have the following signature:
5109 // vector [...] builtinName(vector [...], vector [...], const int);
5110 // Which takes the same type of vectors (any legal vector type) for the first
5111 // two arguments and takes compile time constant for the third argument.
5112 // Example builtins are :
5113 // vector double vec_xxpermdi(vector double, vector double, int);
5114 // vector short vec_xxsldwi(vector short, vector short, int);
5115 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
5116   unsigned ExpectedNumArgs = 3;
5117   if (TheCall->getNumArgs() < ExpectedNumArgs)
5118     return Diag(TheCall->getEndLoc(),
5119                 diag::err_typecheck_call_too_few_args_at_least)
5120            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5121            << TheCall->getSourceRange();
5122 
5123   if (TheCall->getNumArgs() > ExpectedNumArgs)
5124     return Diag(TheCall->getEndLoc(),
5125                 diag::err_typecheck_call_too_many_args_at_most)
5126            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5127            << TheCall->getSourceRange();
5128 
5129   // Check the third argument is a compile time constant
5130   llvm::APSInt Value;
5131   if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
5132     return Diag(TheCall->getBeginLoc(),
5133                 diag::err_vsx_builtin_nonconstant_argument)
5134            << 3 /* argument index */ << TheCall->getDirectCallee()
5135            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5136                           TheCall->getArg(2)->getEndLoc());
5137 
5138   QualType Arg1Ty = TheCall->getArg(0)->getType();
5139   QualType Arg2Ty = TheCall->getArg(1)->getType();
5140 
5141   // Check the type of argument 1 and argument 2 are vectors.
5142   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
5143   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
5144       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
5145     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
5146            << TheCall->getDirectCallee()
5147            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5148                           TheCall->getArg(1)->getEndLoc());
5149   }
5150 
5151   // Check the first two arguments are the same type.
5152   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
5153     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
5154            << TheCall->getDirectCallee()
5155            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5156                           TheCall->getArg(1)->getEndLoc());
5157   }
5158 
5159   // When default clang type checking is turned off and the customized type
5160   // checking is used, the returning type of the function must be explicitly
5161   // set. Otherwise it is _Bool by default.
5162   TheCall->setType(Arg1Ty);
5163 
5164   return false;
5165 }
5166 
5167 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
5168 // This is declared to take (...), so we have to check everything.
5169 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
5170   if (TheCall->getNumArgs() < 2)
5171     return ExprError(Diag(TheCall->getEndLoc(),
5172                           diag::err_typecheck_call_too_few_args_at_least)
5173                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5174                      << TheCall->getSourceRange());
5175 
5176   // Determine which of the following types of shufflevector we're checking:
5177   // 1) unary, vector mask: (lhs, mask)
5178   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
5179   QualType resType = TheCall->getArg(0)->getType();
5180   unsigned numElements = 0;
5181 
5182   if (!TheCall->getArg(0)->isTypeDependent() &&
5183       !TheCall->getArg(1)->isTypeDependent()) {
5184     QualType LHSType = TheCall->getArg(0)->getType();
5185     QualType RHSType = TheCall->getArg(1)->getType();
5186 
5187     if (!LHSType->isVectorType() || !RHSType->isVectorType())
5188       return ExprError(
5189           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
5190           << TheCall->getDirectCallee()
5191           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5192                          TheCall->getArg(1)->getEndLoc()));
5193 
5194     numElements = LHSType->castAs<VectorType>()->getNumElements();
5195     unsigned numResElements = TheCall->getNumArgs() - 2;
5196 
5197     // Check to see if we have a call with 2 vector arguments, the unary shuffle
5198     // with mask.  If so, verify that RHS is an integer vector type with the
5199     // same number of elts as lhs.
5200     if (TheCall->getNumArgs() == 2) {
5201       if (!RHSType->hasIntegerRepresentation() ||
5202           RHSType->castAs<VectorType>()->getNumElements() != numElements)
5203         return ExprError(Diag(TheCall->getBeginLoc(),
5204                               diag::err_vec_builtin_incompatible_vector)
5205                          << TheCall->getDirectCallee()
5206                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
5207                                         TheCall->getArg(1)->getEndLoc()));
5208     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
5209       return ExprError(Diag(TheCall->getBeginLoc(),
5210                             diag::err_vec_builtin_incompatible_vector)
5211                        << TheCall->getDirectCallee()
5212                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5213                                       TheCall->getArg(1)->getEndLoc()));
5214     } else if (numElements != numResElements) {
5215       QualType eltType = LHSType->castAs<VectorType>()->getElementType();
5216       resType = Context.getVectorType(eltType, numResElements,
5217                                       VectorType::GenericVector);
5218     }
5219   }
5220 
5221   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
5222     if (TheCall->getArg(i)->isTypeDependent() ||
5223         TheCall->getArg(i)->isValueDependent())
5224       continue;
5225 
5226     llvm::APSInt Result(32);
5227     if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
5228       return ExprError(Diag(TheCall->getBeginLoc(),
5229                             diag::err_shufflevector_nonconstant_argument)
5230                        << TheCall->getArg(i)->getSourceRange());
5231 
5232     // Allow -1 which will be translated to undef in the IR.
5233     if (Result.isSigned() && Result.isAllOnesValue())
5234       continue;
5235 
5236     if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
5237       return ExprError(Diag(TheCall->getBeginLoc(),
5238                             diag::err_shufflevector_argument_too_large)
5239                        << TheCall->getArg(i)->getSourceRange());
5240   }
5241 
5242   SmallVector<Expr*, 32> exprs;
5243 
5244   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
5245     exprs.push_back(TheCall->getArg(i));
5246     TheCall->setArg(i, nullptr);
5247   }
5248 
5249   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
5250                                          TheCall->getCallee()->getBeginLoc(),
5251                                          TheCall->getRParenLoc());
5252 }
5253 
5254 /// SemaConvertVectorExpr - Handle __builtin_convertvector
5255 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
5256                                        SourceLocation BuiltinLoc,
5257                                        SourceLocation RParenLoc) {
5258   ExprValueKind VK = VK_RValue;
5259   ExprObjectKind OK = OK_Ordinary;
5260   QualType DstTy = TInfo->getType();
5261   QualType SrcTy = E->getType();
5262 
5263   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
5264     return ExprError(Diag(BuiltinLoc,
5265                           diag::err_convertvector_non_vector)
5266                      << E->getSourceRange());
5267   if (!DstTy->isVectorType() && !DstTy->isDependentType())
5268     return ExprError(Diag(BuiltinLoc,
5269                           diag::err_convertvector_non_vector_type));
5270 
5271   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
5272     unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
5273     unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
5274     if (SrcElts != DstElts)
5275       return ExprError(Diag(BuiltinLoc,
5276                             diag::err_convertvector_incompatible_vector)
5277                        << E->getSourceRange());
5278   }
5279 
5280   return new (Context)
5281       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5282 }
5283 
5284 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
5285 // This is declared to take (const void*, ...) and can take two
5286 // optional constant int args.
5287 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
5288   unsigned NumArgs = TheCall->getNumArgs();
5289 
5290   if (NumArgs > 3)
5291     return Diag(TheCall->getEndLoc(),
5292                 diag::err_typecheck_call_too_many_args_at_most)
5293            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
5294 
5295   // Argument 0 is checked for us and the remaining arguments must be
5296   // constant integers.
5297   for (unsigned i = 1; i != NumArgs; ++i)
5298     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
5299       return true;
5300 
5301   return false;
5302 }
5303 
5304 /// SemaBuiltinAssume - Handle __assume (MS Extension).
5305 // __assume does not evaluate its arguments, and should warn if its argument
5306 // has side effects.
5307 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
5308   Expr *Arg = TheCall->getArg(0);
5309   if (Arg->isInstantiationDependent()) return false;
5310 
5311   if (Arg->HasSideEffects(Context))
5312     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
5313         << Arg->getSourceRange()
5314         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
5315 
5316   return false;
5317 }
5318 
5319 /// Handle __builtin_alloca_with_align. This is declared
5320 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
5321 /// than 8.
5322 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
5323   // The alignment must be a constant integer.
5324   Expr *Arg = TheCall->getArg(1);
5325 
5326   // We can't check the value of a dependent argument.
5327   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
5328     if (const auto *UE =
5329             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
5330       if (UE->getKind() == UETT_AlignOf ||
5331           UE->getKind() == UETT_PreferredAlignOf)
5332         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
5333             << Arg->getSourceRange();
5334 
5335     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
5336 
5337     if (!Result.isPowerOf2())
5338       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5339              << Arg->getSourceRange();
5340 
5341     if (Result < Context.getCharWidth())
5342       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
5343              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
5344 
5345     if (Result > std::numeric_limits<int32_t>::max())
5346       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
5347              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
5348   }
5349 
5350   return false;
5351 }
5352 
5353 /// Handle __builtin_assume_aligned. This is declared
5354 /// as (const void*, size_t, ...) and can take one optional constant int arg.
5355 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
5356   unsigned NumArgs = TheCall->getNumArgs();
5357 
5358   if (NumArgs > 3)
5359     return Diag(TheCall->getEndLoc(),
5360                 diag::err_typecheck_call_too_many_args_at_most)
5361            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
5362 
5363   // The alignment must be a constant integer.
5364   Expr *Arg = TheCall->getArg(1);
5365 
5366   // We can't check the value of a dependent argument.
5367   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
5368     llvm::APSInt Result;
5369     if (SemaBuiltinConstantArg(TheCall, 1, Result))
5370       return true;
5371 
5372     if (!Result.isPowerOf2())
5373       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5374              << Arg->getSourceRange();
5375 
5376     // Alignment calculations can wrap around if it's greater than 2**29.
5377     unsigned MaximumAlignment = 536870912;
5378     if (Result > MaximumAlignment)
5379       Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
5380           << Arg->getSourceRange() << MaximumAlignment;
5381   }
5382 
5383   if (NumArgs > 2) {
5384     ExprResult Arg(TheCall->getArg(2));
5385     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5386       Context.getSizeType(), false);
5387     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5388     if (Arg.isInvalid()) return true;
5389     TheCall->setArg(2, Arg.get());
5390   }
5391 
5392   return false;
5393 }
5394 
5395 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
5396   unsigned BuiltinID =
5397       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
5398   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
5399 
5400   unsigned NumArgs = TheCall->getNumArgs();
5401   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
5402   if (NumArgs < NumRequiredArgs) {
5403     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5404            << 0 /* function call */ << NumRequiredArgs << NumArgs
5405            << TheCall->getSourceRange();
5406   }
5407   if (NumArgs >= NumRequiredArgs + 0x100) {
5408     return Diag(TheCall->getEndLoc(),
5409                 diag::err_typecheck_call_too_many_args_at_most)
5410            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
5411            << TheCall->getSourceRange();
5412   }
5413   unsigned i = 0;
5414 
5415   // For formatting call, check buffer arg.
5416   if (!IsSizeCall) {
5417     ExprResult Arg(TheCall->getArg(i));
5418     InitializedEntity Entity = InitializedEntity::InitializeParameter(
5419         Context, Context.VoidPtrTy, false);
5420     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5421     if (Arg.isInvalid())
5422       return true;
5423     TheCall->setArg(i, Arg.get());
5424     i++;
5425   }
5426 
5427   // Check string literal arg.
5428   unsigned FormatIdx = i;
5429   {
5430     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
5431     if (Arg.isInvalid())
5432       return true;
5433     TheCall->setArg(i, Arg.get());
5434     i++;
5435   }
5436 
5437   // Make sure variadic args are scalar.
5438   unsigned FirstDataArg = i;
5439   while (i < NumArgs) {
5440     ExprResult Arg = DefaultVariadicArgumentPromotion(
5441         TheCall->getArg(i), VariadicFunction, nullptr);
5442     if (Arg.isInvalid())
5443       return true;
5444     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
5445     if (ArgSize.getQuantity() >= 0x100) {
5446       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
5447              << i << (int)ArgSize.getQuantity() << 0xff
5448              << TheCall->getSourceRange();
5449     }
5450     TheCall->setArg(i, Arg.get());
5451     i++;
5452   }
5453 
5454   // Check formatting specifiers. NOTE: We're only doing this for the non-size
5455   // call to avoid duplicate diagnostics.
5456   if (!IsSizeCall) {
5457     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
5458     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
5459     bool Success = CheckFormatArguments(
5460         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
5461         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
5462         CheckedVarArgs);
5463     if (!Success)
5464       return true;
5465   }
5466 
5467   if (IsSizeCall) {
5468     TheCall->setType(Context.getSizeType());
5469   } else {
5470     TheCall->setType(Context.VoidPtrTy);
5471   }
5472   return false;
5473 }
5474 
5475 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
5476 /// TheCall is a constant expression.
5477 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
5478                                   llvm::APSInt &Result) {
5479   Expr *Arg = TheCall->getArg(ArgNum);
5480   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5481   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5482 
5483   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
5484 
5485   if (!Arg->isIntegerConstantExpr(Result, Context))
5486     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
5487            << FDecl->getDeclName() << Arg->getSourceRange();
5488 
5489   return false;
5490 }
5491 
5492 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
5493 /// TheCall is a constant expression in the range [Low, High].
5494 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
5495                                        int Low, int High, bool RangeIsError) {
5496   if (isConstantEvaluated())
5497     return false;
5498   llvm::APSInt Result;
5499 
5500   // We can't check the value of a dependent argument.
5501   Expr *Arg = TheCall->getArg(ArgNum);
5502   if (Arg->isTypeDependent() || Arg->isValueDependent())
5503     return false;
5504 
5505   // Check constant-ness first.
5506   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
5507     return true;
5508 
5509   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
5510     if (RangeIsError)
5511       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
5512              << Result.toString(10) << Low << High << Arg->getSourceRange();
5513     else
5514       // Defer the warning until we know if the code will be emitted so that
5515       // dead code can ignore this.
5516       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
5517                           PDiag(diag::warn_argument_invalid_range)
5518                               << Result.toString(10) << Low << High
5519                               << Arg->getSourceRange());
5520   }
5521 
5522   return false;
5523 }
5524 
5525 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
5526 /// TheCall is a constant expression is a multiple of Num..
5527 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
5528                                           unsigned Num) {
5529   llvm::APSInt Result;
5530 
5531   // We can't check the value of a dependent argument.
5532   Expr *Arg = TheCall->getArg(ArgNum);
5533   if (Arg->isTypeDependent() || Arg->isValueDependent())
5534     return false;
5535 
5536   // Check constant-ness first.
5537   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
5538     return true;
5539 
5540   if (Result.getSExtValue() % Num != 0)
5541     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
5542            << Num << Arg->getSourceRange();
5543 
5544   return false;
5545 }
5546 
5547 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
5548 /// constant expression representing a power of 2.
5549 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
5550   llvm::APSInt Result;
5551 
5552   // We can't check the value of a dependent argument.
5553   Expr *Arg = TheCall->getArg(ArgNum);
5554   if (Arg->isTypeDependent() || Arg->isValueDependent())
5555     return false;
5556 
5557   // Check constant-ness first.
5558   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
5559     return true;
5560 
5561   // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
5562   // and only if x is a power of 2.
5563   if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
5564     return false;
5565 
5566   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
5567          << Arg->getSourceRange();
5568 }
5569 
5570 static bool IsShiftedByte(llvm::APSInt Value) {
5571   if (Value.isNegative())
5572     return false;
5573 
5574   // Check if it's a shifted byte, by shifting it down
5575   while (true) {
5576     // If the value fits in the bottom byte, the check passes.
5577     if (Value < 0x100)
5578       return true;
5579 
5580     // Otherwise, if the value has _any_ bits in the bottom byte, the check
5581     // fails.
5582     if ((Value & 0xFF) != 0)
5583       return false;
5584 
5585     // If the bottom 8 bits are all 0, but something above that is nonzero,
5586     // then shifting the value right by 8 bits won't affect whether it's a
5587     // shifted byte or not. So do that, and go round again.
5588     Value >>= 8;
5589   }
5590 }
5591 
5592 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
5593 /// a constant expression representing an arbitrary byte value shifted left by
5594 /// a multiple of 8 bits.
5595 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum) {
5596   llvm::APSInt Result;
5597 
5598   // We can't check the value of a dependent argument.
5599   Expr *Arg = TheCall->getArg(ArgNum);
5600   if (Arg->isTypeDependent() || Arg->isValueDependent())
5601     return false;
5602 
5603   // Check constant-ness first.
5604   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
5605     return true;
5606 
5607   if (IsShiftedByte(Result))
5608     return false;
5609 
5610   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
5611          << Arg->getSourceRange();
5612 }
5613 
5614 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
5615 /// TheCall is a constant expression representing either a shifted byte value,
5616 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
5617 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
5618 /// Arm MVE intrinsics.
5619 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
5620                                                    int ArgNum) {
5621   llvm::APSInt Result;
5622 
5623   // We can't check the value of a dependent argument.
5624   Expr *Arg = TheCall->getArg(ArgNum);
5625   if (Arg->isTypeDependent() || Arg->isValueDependent())
5626     return false;
5627 
5628   // Check constant-ness first.
5629   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
5630     return true;
5631 
5632   // Check to see if it's in either of the required forms.
5633   if (IsShiftedByte(Result) ||
5634       (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
5635     return false;
5636 
5637   return Diag(TheCall->getBeginLoc(),
5638               diag::err_argument_not_shifted_byte_or_xxff)
5639          << Arg->getSourceRange();
5640 }
5641 
5642 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
5643 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
5644   if (BuiltinID == AArch64::BI__builtin_arm_irg) {
5645     if (checkArgCount(*this, TheCall, 2))
5646       return true;
5647     Expr *Arg0 = TheCall->getArg(0);
5648     Expr *Arg1 = TheCall->getArg(1);
5649 
5650     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
5651     if (FirstArg.isInvalid())
5652       return true;
5653     QualType FirstArgType = FirstArg.get()->getType();
5654     if (!FirstArgType->isAnyPointerType())
5655       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
5656                << "first" << FirstArgType << Arg0->getSourceRange();
5657     TheCall->setArg(0, FirstArg.get());
5658 
5659     ExprResult SecArg = DefaultLvalueConversion(Arg1);
5660     if (SecArg.isInvalid())
5661       return true;
5662     QualType SecArgType = SecArg.get()->getType();
5663     if (!SecArgType->isIntegerType())
5664       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
5665                << "second" << SecArgType << Arg1->getSourceRange();
5666 
5667     // Derive the return type from the pointer argument.
5668     TheCall->setType(FirstArgType);
5669     return false;
5670   }
5671 
5672   if (BuiltinID == AArch64::BI__builtin_arm_addg) {
5673     if (checkArgCount(*this, TheCall, 2))
5674       return true;
5675 
5676     Expr *Arg0 = TheCall->getArg(0);
5677     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
5678     if (FirstArg.isInvalid())
5679       return true;
5680     QualType FirstArgType = FirstArg.get()->getType();
5681     if (!FirstArgType->isAnyPointerType())
5682       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
5683                << "first" << FirstArgType << Arg0->getSourceRange();
5684     TheCall->setArg(0, FirstArg.get());
5685 
5686     // Derive the return type from the pointer argument.
5687     TheCall->setType(FirstArgType);
5688 
5689     // Second arg must be an constant in range [0,15]
5690     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
5691   }
5692 
5693   if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
5694     if (checkArgCount(*this, TheCall, 2))
5695       return true;
5696     Expr *Arg0 = TheCall->getArg(0);
5697     Expr *Arg1 = TheCall->getArg(1);
5698 
5699     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
5700     if (FirstArg.isInvalid())
5701       return true;
5702     QualType FirstArgType = FirstArg.get()->getType();
5703     if (!FirstArgType->isAnyPointerType())
5704       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
5705                << "first" << FirstArgType << Arg0->getSourceRange();
5706 
5707     QualType SecArgType = Arg1->getType();
5708     if (!SecArgType->isIntegerType())
5709       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
5710                << "second" << SecArgType << Arg1->getSourceRange();
5711     TheCall->setType(Context.IntTy);
5712     return false;
5713   }
5714 
5715   if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
5716       BuiltinID == AArch64::BI__builtin_arm_stg) {
5717     if (checkArgCount(*this, TheCall, 1))
5718       return true;
5719     Expr *Arg0 = TheCall->getArg(0);
5720     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
5721     if (FirstArg.isInvalid())
5722       return true;
5723 
5724     QualType FirstArgType = FirstArg.get()->getType();
5725     if (!FirstArgType->isAnyPointerType())
5726       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
5727                << "first" << FirstArgType << Arg0->getSourceRange();
5728     TheCall->setArg(0, FirstArg.get());
5729 
5730     // Derive the return type from the pointer argument.
5731     if (BuiltinID == AArch64::BI__builtin_arm_ldg)
5732       TheCall->setType(FirstArgType);
5733     return false;
5734   }
5735 
5736   if (BuiltinID == AArch64::BI__builtin_arm_subp) {
5737     Expr *ArgA = TheCall->getArg(0);
5738     Expr *ArgB = TheCall->getArg(1);
5739 
5740     ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
5741     ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
5742 
5743     if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
5744       return true;
5745 
5746     QualType ArgTypeA = ArgExprA.get()->getType();
5747     QualType ArgTypeB = ArgExprB.get()->getType();
5748 
5749     auto isNull = [&] (Expr *E) -> bool {
5750       return E->isNullPointerConstant(
5751                         Context, Expr::NPC_ValueDependentIsNotNull); };
5752 
5753     // argument should be either a pointer or null
5754     if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
5755       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
5756         << "first" << ArgTypeA << ArgA->getSourceRange();
5757 
5758     if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
5759       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
5760         << "second" << ArgTypeB << ArgB->getSourceRange();
5761 
5762     // Ensure Pointee types are compatible
5763     if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
5764         ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
5765       QualType pointeeA = ArgTypeA->getPointeeType();
5766       QualType pointeeB = ArgTypeB->getPointeeType();
5767       if (!Context.typesAreCompatible(
5768              Context.getCanonicalType(pointeeA).getUnqualifiedType(),
5769              Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
5770         return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
5771           << ArgTypeA <<  ArgTypeB << ArgA->getSourceRange()
5772           << ArgB->getSourceRange();
5773       }
5774     }
5775 
5776     // at least one argument should be pointer type
5777     if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
5778       return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
5779         <<  ArgTypeA << ArgTypeB << ArgA->getSourceRange();
5780 
5781     if (isNull(ArgA)) // adopt type of the other pointer
5782       ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
5783 
5784     if (isNull(ArgB))
5785       ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
5786 
5787     TheCall->setArg(0, ArgExprA.get());
5788     TheCall->setArg(1, ArgExprB.get());
5789     TheCall->setType(Context.LongLongTy);
5790     return false;
5791   }
5792   assert(false && "Unhandled ARM MTE intrinsic");
5793   return true;
5794 }
5795 
5796 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
5797 /// TheCall is an ARM/AArch64 special register string literal.
5798 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
5799                                     int ArgNum, unsigned ExpectedFieldNum,
5800                                     bool AllowName) {
5801   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
5802                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
5803                       BuiltinID == ARM::BI__builtin_arm_rsr ||
5804                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
5805                       BuiltinID == ARM::BI__builtin_arm_wsr ||
5806                       BuiltinID == ARM::BI__builtin_arm_wsrp;
5807   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
5808                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
5809                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
5810                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
5811                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
5812                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
5813   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
5814 
5815   // We can't check the value of a dependent argument.
5816   Expr *Arg = TheCall->getArg(ArgNum);
5817   if (Arg->isTypeDependent() || Arg->isValueDependent())
5818     return false;
5819 
5820   // Check if the argument is a string literal.
5821   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
5822     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
5823            << Arg->getSourceRange();
5824 
5825   // Check the type of special register given.
5826   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
5827   SmallVector<StringRef, 6> Fields;
5828   Reg.split(Fields, ":");
5829 
5830   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
5831     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
5832            << Arg->getSourceRange();
5833 
5834   // If the string is the name of a register then we cannot check that it is
5835   // valid here but if the string is of one the forms described in ACLE then we
5836   // can check that the supplied fields are integers and within the valid
5837   // ranges.
5838   if (Fields.size() > 1) {
5839     bool FiveFields = Fields.size() == 5;
5840 
5841     bool ValidString = true;
5842     if (IsARMBuiltin) {
5843       ValidString &= Fields[0].startswith_lower("cp") ||
5844                      Fields[0].startswith_lower("p");
5845       if (ValidString)
5846         Fields[0] =
5847           Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
5848 
5849       ValidString &= Fields[2].startswith_lower("c");
5850       if (ValidString)
5851         Fields[2] = Fields[2].drop_front(1);
5852 
5853       if (FiveFields) {
5854         ValidString &= Fields[3].startswith_lower("c");
5855         if (ValidString)
5856           Fields[3] = Fields[3].drop_front(1);
5857       }
5858     }
5859 
5860     SmallVector<int, 5> Ranges;
5861     if (FiveFields)
5862       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
5863     else
5864       Ranges.append({15, 7, 15});
5865 
5866     for (unsigned i=0; i<Fields.size(); ++i) {
5867       int IntField;
5868       ValidString &= !Fields[i].getAsInteger(10, IntField);
5869       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
5870     }
5871 
5872     if (!ValidString)
5873       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
5874              << Arg->getSourceRange();
5875   } else if (IsAArch64Builtin && Fields.size() == 1) {
5876     // If the register name is one of those that appear in the condition below
5877     // and the special register builtin being used is one of the write builtins,
5878     // then we require that the argument provided for writing to the register
5879     // is an integer constant expression. This is because it will be lowered to
5880     // an MSR (immediate) instruction, so we need to know the immediate at
5881     // compile time.
5882     if (TheCall->getNumArgs() != 2)
5883       return false;
5884 
5885     std::string RegLower = Reg.lower();
5886     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
5887         RegLower != "pan" && RegLower != "uao")
5888       return false;
5889 
5890     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
5891   }
5892 
5893   return false;
5894 }
5895 
5896 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
5897 /// This checks that the target supports __builtin_longjmp and
5898 /// that val is a constant 1.
5899 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
5900   if (!Context.getTargetInfo().hasSjLjLowering())
5901     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
5902            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
5903 
5904   Expr *Arg = TheCall->getArg(1);
5905   llvm::APSInt Result;
5906 
5907   // TODO: This is less than ideal. Overload this to take a value.
5908   if (SemaBuiltinConstantArg(TheCall, 1, Result))
5909     return true;
5910 
5911   if (Result != 1)
5912     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
5913            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
5914 
5915   return false;
5916 }
5917 
5918 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
5919 /// This checks that the target supports __builtin_setjmp.
5920 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
5921   if (!Context.getTargetInfo().hasSjLjLowering())
5922     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
5923            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
5924   return false;
5925 }
5926 
5927 namespace {
5928 
5929 class UncoveredArgHandler {
5930   enum { Unknown = -1, AllCovered = -2 };
5931 
5932   signed FirstUncoveredArg = Unknown;
5933   SmallVector<const Expr *, 4> DiagnosticExprs;
5934 
5935 public:
5936   UncoveredArgHandler() = default;
5937 
5938   bool hasUncoveredArg() const {
5939     return (FirstUncoveredArg >= 0);
5940   }
5941 
5942   unsigned getUncoveredArg() const {
5943     assert(hasUncoveredArg() && "no uncovered argument");
5944     return FirstUncoveredArg;
5945   }
5946 
5947   void setAllCovered() {
5948     // A string has been found with all arguments covered, so clear out
5949     // the diagnostics.
5950     DiagnosticExprs.clear();
5951     FirstUncoveredArg = AllCovered;
5952   }
5953 
5954   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
5955     assert(NewFirstUncoveredArg >= 0 && "Outside range");
5956 
5957     // Don't update if a previous string covers all arguments.
5958     if (FirstUncoveredArg == AllCovered)
5959       return;
5960 
5961     // UncoveredArgHandler tracks the highest uncovered argument index
5962     // and with it all the strings that match this index.
5963     if (NewFirstUncoveredArg == FirstUncoveredArg)
5964       DiagnosticExprs.push_back(StrExpr);
5965     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
5966       DiagnosticExprs.clear();
5967       DiagnosticExprs.push_back(StrExpr);
5968       FirstUncoveredArg = NewFirstUncoveredArg;
5969     }
5970   }
5971 
5972   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
5973 };
5974 
5975 enum StringLiteralCheckType {
5976   SLCT_NotALiteral,
5977   SLCT_UncheckedLiteral,
5978   SLCT_CheckedLiteral
5979 };
5980 
5981 } // namespace
5982 
5983 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
5984                                      BinaryOperatorKind BinOpKind,
5985                                      bool AddendIsRight) {
5986   unsigned BitWidth = Offset.getBitWidth();
5987   unsigned AddendBitWidth = Addend.getBitWidth();
5988   // There might be negative interim results.
5989   if (Addend.isUnsigned()) {
5990     Addend = Addend.zext(++AddendBitWidth);
5991     Addend.setIsSigned(true);
5992   }
5993   // Adjust the bit width of the APSInts.
5994   if (AddendBitWidth > BitWidth) {
5995     Offset = Offset.sext(AddendBitWidth);
5996     BitWidth = AddendBitWidth;
5997   } else if (BitWidth > AddendBitWidth) {
5998     Addend = Addend.sext(BitWidth);
5999   }
6000 
6001   bool Ov = false;
6002   llvm::APSInt ResOffset = Offset;
6003   if (BinOpKind == BO_Add)
6004     ResOffset = Offset.sadd_ov(Addend, Ov);
6005   else {
6006     assert(AddendIsRight && BinOpKind == BO_Sub &&
6007            "operator must be add or sub with addend on the right");
6008     ResOffset = Offset.ssub_ov(Addend, Ov);
6009   }
6010 
6011   // We add an offset to a pointer here so we should support an offset as big as
6012   // possible.
6013   if (Ov) {
6014     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
6015            "index (intermediate) result too big");
6016     Offset = Offset.sext(2 * BitWidth);
6017     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
6018     return;
6019   }
6020 
6021   Offset = ResOffset;
6022 }
6023 
6024 namespace {
6025 
6026 // This is a wrapper class around StringLiteral to support offsetted string
6027 // literals as format strings. It takes the offset into account when returning
6028 // the string and its length or the source locations to display notes correctly.
6029 class FormatStringLiteral {
6030   const StringLiteral *FExpr;
6031   int64_t Offset;
6032 
6033  public:
6034   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
6035       : FExpr(fexpr), Offset(Offset) {}
6036 
6037   StringRef getString() const {
6038     return FExpr->getString().drop_front(Offset);
6039   }
6040 
6041   unsigned getByteLength() const {
6042     return FExpr->getByteLength() - getCharByteWidth() * Offset;
6043   }
6044 
6045   unsigned getLength() const { return FExpr->getLength() - Offset; }
6046   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
6047 
6048   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
6049 
6050   QualType getType() const { return FExpr->getType(); }
6051 
6052   bool isAscii() const { return FExpr->isAscii(); }
6053   bool isWide() const { return FExpr->isWide(); }
6054   bool isUTF8() const { return FExpr->isUTF8(); }
6055   bool isUTF16() const { return FExpr->isUTF16(); }
6056   bool isUTF32() const { return FExpr->isUTF32(); }
6057   bool isPascal() const { return FExpr->isPascal(); }
6058 
6059   SourceLocation getLocationOfByte(
6060       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
6061       const TargetInfo &Target, unsigned *StartToken = nullptr,
6062       unsigned *StartTokenByteOffset = nullptr) const {
6063     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
6064                                     StartToken, StartTokenByteOffset);
6065   }
6066 
6067   SourceLocation getBeginLoc() const LLVM_READONLY {
6068     return FExpr->getBeginLoc().getLocWithOffset(Offset);
6069   }
6070 
6071   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
6072 };
6073 
6074 }  // namespace
6075 
6076 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
6077                               const Expr *OrigFormatExpr,
6078                               ArrayRef<const Expr *> Args,
6079                               bool HasVAListArg, unsigned format_idx,
6080                               unsigned firstDataArg,
6081                               Sema::FormatStringType Type,
6082                               bool inFunctionCall,
6083                               Sema::VariadicCallType CallType,
6084                               llvm::SmallBitVector &CheckedVarArgs,
6085                               UncoveredArgHandler &UncoveredArg,
6086                               bool IgnoreStringsWithoutSpecifiers);
6087 
6088 // Determine if an expression is a string literal or constant string.
6089 // If this function returns false on the arguments to a function expecting a
6090 // format string, we will usually need to emit a warning.
6091 // True string literals are then checked by CheckFormatString.
6092 static StringLiteralCheckType
6093 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
6094                       bool HasVAListArg, unsigned format_idx,
6095                       unsigned firstDataArg, Sema::FormatStringType Type,
6096                       Sema::VariadicCallType CallType, bool InFunctionCall,
6097                       llvm::SmallBitVector &CheckedVarArgs,
6098                       UncoveredArgHandler &UncoveredArg,
6099                       llvm::APSInt Offset,
6100                       bool IgnoreStringsWithoutSpecifiers = false) {
6101   if (S.isConstantEvaluated())
6102     return SLCT_NotALiteral;
6103  tryAgain:
6104   assert(Offset.isSigned() && "invalid offset");
6105 
6106   if (E->isTypeDependent() || E->isValueDependent())
6107     return SLCT_NotALiteral;
6108 
6109   E = E->IgnoreParenCasts();
6110 
6111   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
6112     // Technically -Wformat-nonliteral does not warn about this case.
6113     // The behavior of printf and friends in this case is implementation
6114     // dependent.  Ideally if the format string cannot be null then
6115     // it should have a 'nonnull' attribute in the function prototype.
6116     return SLCT_UncheckedLiteral;
6117 
6118   switch (E->getStmtClass()) {
6119   case Stmt::BinaryConditionalOperatorClass:
6120   case Stmt::ConditionalOperatorClass: {
6121     // The expression is a literal if both sub-expressions were, and it was
6122     // completely checked only if both sub-expressions were checked.
6123     const AbstractConditionalOperator *C =
6124         cast<AbstractConditionalOperator>(E);
6125 
6126     // Determine whether it is necessary to check both sub-expressions, for
6127     // example, because the condition expression is a constant that can be
6128     // evaluated at compile time.
6129     bool CheckLeft = true, CheckRight = true;
6130 
6131     bool Cond;
6132     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
6133                                                  S.isConstantEvaluated())) {
6134       if (Cond)
6135         CheckRight = false;
6136       else
6137         CheckLeft = false;
6138     }
6139 
6140     // We need to maintain the offsets for the right and the left hand side
6141     // separately to check if every possible indexed expression is a valid
6142     // string literal. They might have different offsets for different string
6143     // literals in the end.
6144     StringLiteralCheckType Left;
6145     if (!CheckLeft)
6146       Left = SLCT_UncheckedLiteral;
6147     else {
6148       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
6149                                    HasVAListArg, format_idx, firstDataArg,
6150                                    Type, CallType, InFunctionCall,
6151                                    CheckedVarArgs, UncoveredArg, Offset,
6152                                    IgnoreStringsWithoutSpecifiers);
6153       if (Left == SLCT_NotALiteral || !CheckRight) {
6154         return Left;
6155       }
6156     }
6157 
6158     StringLiteralCheckType Right = checkFormatStringExpr(
6159         S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
6160         Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6161         IgnoreStringsWithoutSpecifiers);
6162 
6163     return (CheckLeft && Left < Right) ? Left : Right;
6164   }
6165 
6166   case Stmt::ImplicitCastExprClass:
6167     E = cast<ImplicitCastExpr>(E)->getSubExpr();
6168     goto tryAgain;
6169 
6170   case Stmt::OpaqueValueExprClass:
6171     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
6172       E = src;
6173       goto tryAgain;
6174     }
6175     return SLCT_NotALiteral;
6176 
6177   case Stmt::PredefinedExprClass:
6178     // While __func__, etc., are technically not string literals, they
6179     // cannot contain format specifiers and thus are not a security
6180     // liability.
6181     return SLCT_UncheckedLiteral;
6182 
6183   case Stmt::DeclRefExprClass: {
6184     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6185 
6186     // As an exception, do not flag errors for variables binding to
6187     // const string literals.
6188     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
6189       bool isConstant = false;
6190       QualType T = DR->getType();
6191 
6192       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
6193         isConstant = AT->getElementType().isConstant(S.Context);
6194       } else if (const PointerType *PT = T->getAs<PointerType>()) {
6195         isConstant = T.isConstant(S.Context) &&
6196                      PT->getPointeeType().isConstant(S.Context);
6197       } else if (T->isObjCObjectPointerType()) {
6198         // In ObjC, there is usually no "const ObjectPointer" type,
6199         // so don't check if the pointee type is constant.
6200         isConstant = T.isConstant(S.Context);
6201       }
6202 
6203       if (isConstant) {
6204         if (const Expr *Init = VD->getAnyInitializer()) {
6205           // Look through initializers like const char c[] = { "foo" }
6206           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
6207             if (InitList->isStringLiteralInit())
6208               Init = InitList->getInit(0)->IgnoreParenImpCasts();
6209           }
6210           return checkFormatStringExpr(S, Init, Args,
6211                                        HasVAListArg, format_idx,
6212                                        firstDataArg, Type, CallType,
6213                                        /*InFunctionCall*/ false, CheckedVarArgs,
6214                                        UncoveredArg, Offset);
6215         }
6216       }
6217 
6218       // For vprintf* functions (i.e., HasVAListArg==true), we add a
6219       // special check to see if the format string is a function parameter
6220       // of the function calling the printf function.  If the function
6221       // has an attribute indicating it is a printf-like function, then we
6222       // should suppress warnings concerning non-literals being used in a call
6223       // to a vprintf function.  For example:
6224       //
6225       // void
6226       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
6227       //      va_list ap;
6228       //      va_start(ap, fmt);
6229       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
6230       //      ...
6231       // }
6232       if (HasVAListArg) {
6233         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
6234           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
6235             int PVIndex = PV->getFunctionScopeIndex() + 1;
6236             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
6237               // adjust for implicit parameter
6238               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6239                 if (MD->isInstance())
6240                   ++PVIndex;
6241               // We also check if the formats are compatible.
6242               // We can't pass a 'scanf' string to a 'printf' function.
6243               if (PVIndex == PVFormat->getFormatIdx() &&
6244                   Type == S.GetFormatStringType(PVFormat))
6245                 return SLCT_UncheckedLiteral;
6246             }
6247           }
6248         }
6249       }
6250     }
6251 
6252     return SLCT_NotALiteral;
6253   }
6254 
6255   case Stmt::CallExprClass:
6256   case Stmt::CXXMemberCallExprClass: {
6257     const CallExpr *CE = cast<CallExpr>(E);
6258     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
6259       bool IsFirst = true;
6260       StringLiteralCheckType CommonResult;
6261       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
6262         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
6263         StringLiteralCheckType Result = checkFormatStringExpr(
6264             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
6265             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6266             IgnoreStringsWithoutSpecifiers);
6267         if (IsFirst) {
6268           CommonResult = Result;
6269           IsFirst = false;
6270         }
6271       }
6272       if (!IsFirst)
6273         return CommonResult;
6274 
6275       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
6276         unsigned BuiltinID = FD->getBuiltinID();
6277         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
6278             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
6279           const Expr *Arg = CE->getArg(0);
6280           return checkFormatStringExpr(S, Arg, Args,
6281                                        HasVAListArg, format_idx,
6282                                        firstDataArg, Type, CallType,
6283                                        InFunctionCall, CheckedVarArgs,
6284                                        UncoveredArg, Offset,
6285                                        IgnoreStringsWithoutSpecifiers);
6286         }
6287       }
6288     }
6289 
6290     return SLCT_NotALiteral;
6291   }
6292   case Stmt::ObjCMessageExprClass: {
6293     const auto *ME = cast<ObjCMessageExpr>(E);
6294     if (const auto *MD = ME->getMethodDecl()) {
6295       if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
6296         // As a special case heuristic, if we're using the method -[NSBundle
6297         // localizedStringForKey:value:table:], ignore any key strings that lack
6298         // format specifiers. The idea is that if the key doesn't have any
6299         // format specifiers then its probably just a key to map to the
6300         // localized strings. If it does have format specifiers though, then its
6301         // likely that the text of the key is the format string in the
6302         // programmer's language, and should be checked.
6303         const ObjCInterfaceDecl *IFace;
6304         if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
6305             IFace->getIdentifier()->isStr("NSBundle") &&
6306             MD->getSelector().isKeywordSelector(
6307                 {"localizedStringForKey", "value", "table"})) {
6308           IgnoreStringsWithoutSpecifiers = true;
6309         }
6310 
6311         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
6312         return checkFormatStringExpr(
6313             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
6314             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6315             IgnoreStringsWithoutSpecifiers);
6316       }
6317     }
6318 
6319     return SLCT_NotALiteral;
6320   }
6321   case Stmt::ObjCStringLiteralClass:
6322   case Stmt::StringLiteralClass: {
6323     const StringLiteral *StrE = nullptr;
6324 
6325     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
6326       StrE = ObjCFExpr->getString();
6327     else
6328       StrE = cast<StringLiteral>(E);
6329 
6330     if (StrE) {
6331       if (Offset.isNegative() || Offset > StrE->getLength()) {
6332         // TODO: It would be better to have an explicit warning for out of
6333         // bounds literals.
6334         return SLCT_NotALiteral;
6335       }
6336       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
6337       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
6338                         firstDataArg, Type, InFunctionCall, CallType,
6339                         CheckedVarArgs, UncoveredArg,
6340                         IgnoreStringsWithoutSpecifiers);
6341       return SLCT_CheckedLiteral;
6342     }
6343 
6344     return SLCT_NotALiteral;
6345   }
6346   case Stmt::BinaryOperatorClass: {
6347     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
6348 
6349     // A string literal + an int offset is still a string literal.
6350     if (BinOp->isAdditiveOp()) {
6351       Expr::EvalResult LResult, RResult;
6352 
6353       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
6354           LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
6355       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
6356           RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
6357 
6358       if (LIsInt != RIsInt) {
6359         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
6360 
6361         if (LIsInt) {
6362           if (BinOpKind == BO_Add) {
6363             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
6364             E = BinOp->getRHS();
6365             goto tryAgain;
6366           }
6367         } else {
6368           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
6369           E = BinOp->getLHS();
6370           goto tryAgain;
6371         }
6372       }
6373     }
6374 
6375     return SLCT_NotALiteral;
6376   }
6377   case Stmt::UnaryOperatorClass: {
6378     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
6379     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
6380     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
6381       Expr::EvalResult IndexResult;
6382       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
6383                                        Expr::SE_NoSideEffects,
6384                                        S.isConstantEvaluated())) {
6385         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
6386                    /*RHS is int*/ true);
6387         E = ASE->getBase();
6388         goto tryAgain;
6389       }
6390     }
6391 
6392     return SLCT_NotALiteral;
6393   }
6394 
6395   default:
6396     return SLCT_NotALiteral;
6397   }
6398 }
6399 
6400 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
6401   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
6402       .Case("scanf", FST_Scanf)
6403       .Cases("printf", "printf0", FST_Printf)
6404       .Cases("NSString", "CFString", FST_NSString)
6405       .Case("strftime", FST_Strftime)
6406       .Case("strfmon", FST_Strfmon)
6407       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
6408       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
6409       .Case("os_trace", FST_OSLog)
6410       .Case("os_log", FST_OSLog)
6411       .Default(FST_Unknown);
6412 }
6413 
6414 /// CheckFormatArguments - Check calls to printf and scanf (and similar
6415 /// functions) for correct use of format strings.
6416 /// Returns true if a format string has been fully checked.
6417 bool Sema::CheckFormatArguments(const FormatAttr *Format,
6418                                 ArrayRef<const Expr *> Args,
6419                                 bool IsCXXMember,
6420                                 VariadicCallType CallType,
6421                                 SourceLocation Loc, SourceRange Range,
6422                                 llvm::SmallBitVector &CheckedVarArgs) {
6423   FormatStringInfo FSI;
6424   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
6425     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
6426                                 FSI.FirstDataArg, GetFormatStringType(Format),
6427                                 CallType, Loc, Range, CheckedVarArgs);
6428   return false;
6429 }
6430 
6431 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
6432                                 bool HasVAListArg, unsigned format_idx,
6433                                 unsigned firstDataArg, FormatStringType Type,
6434                                 VariadicCallType CallType,
6435                                 SourceLocation Loc, SourceRange Range,
6436                                 llvm::SmallBitVector &CheckedVarArgs) {
6437   // CHECK: printf/scanf-like function is called with no format string.
6438   if (format_idx >= Args.size()) {
6439     Diag(Loc, diag::warn_missing_format_string) << Range;
6440     return false;
6441   }
6442 
6443   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
6444 
6445   // CHECK: format string is not a string literal.
6446   //
6447   // Dynamically generated format strings are difficult to
6448   // automatically vet at compile time.  Requiring that format strings
6449   // are string literals: (1) permits the checking of format strings by
6450   // the compiler and thereby (2) can practically remove the source of
6451   // many format string exploits.
6452 
6453   // Format string can be either ObjC string (e.g. @"%d") or
6454   // C string (e.g. "%d")
6455   // ObjC string uses the same format specifiers as C string, so we can use
6456   // the same format string checking logic for both ObjC and C strings.
6457   UncoveredArgHandler UncoveredArg;
6458   StringLiteralCheckType CT =
6459       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
6460                             format_idx, firstDataArg, Type, CallType,
6461                             /*IsFunctionCall*/ true, CheckedVarArgs,
6462                             UncoveredArg,
6463                             /*no string offset*/ llvm::APSInt(64, false) = 0);
6464 
6465   // Generate a diagnostic where an uncovered argument is detected.
6466   if (UncoveredArg.hasUncoveredArg()) {
6467     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
6468     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
6469     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
6470   }
6471 
6472   if (CT != SLCT_NotALiteral)
6473     // Literal format string found, check done!
6474     return CT == SLCT_CheckedLiteral;
6475 
6476   // Strftime is particular as it always uses a single 'time' argument,
6477   // so it is safe to pass a non-literal string.
6478   if (Type == FST_Strftime)
6479     return false;
6480 
6481   // Do not emit diag when the string param is a macro expansion and the
6482   // format is either NSString or CFString. This is a hack to prevent
6483   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
6484   // which are usually used in place of NS and CF string literals.
6485   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
6486   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
6487     return false;
6488 
6489   // If there are no arguments specified, warn with -Wformat-security, otherwise
6490   // warn only with -Wformat-nonliteral.
6491   if (Args.size() == firstDataArg) {
6492     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
6493       << OrigFormatExpr->getSourceRange();
6494     switch (Type) {
6495     default:
6496       break;
6497     case FST_Kprintf:
6498     case FST_FreeBSDKPrintf:
6499     case FST_Printf:
6500       Diag(FormatLoc, diag::note_format_security_fixit)
6501         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
6502       break;
6503     case FST_NSString:
6504       Diag(FormatLoc, diag::note_format_security_fixit)
6505         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
6506       break;
6507     }
6508   } else {
6509     Diag(FormatLoc, diag::warn_format_nonliteral)
6510       << OrigFormatExpr->getSourceRange();
6511   }
6512   return false;
6513 }
6514 
6515 namespace {
6516 
6517 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
6518 protected:
6519   Sema &S;
6520   const FormatStringLiteral *FExpr;
6521   const Expr *OrigFormatExpr;
6522   const Sema::FormatStringType FSType;
6523   const unsigned FirstDataArg;
6524   const unsigned NumDataArgs;
6525   const char *Beg; // Start of format string.
6526   const bool HasVAListArg;
6527   ArrayRef<const Expr *> Args;
6528   unsigned FormatIdx;
6529   llvm::SmallBitVector CoveredArgs;
6530   bool usesPositionalArgs = false;
6531   bool atFirstArg = true;
6532   bool inFunctionCall;
6533   Sema::VariadicCallType CallType;
6534   llvm::SmallBitVector &CheckedVarArgs;
6535   UncoveredArgHandler &UncoveredArg;
6536 
6537 public:
6538   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
6539                      const Expr *origFormatExpr,
6540                      const Sema::FormatStringType type, unsigned firstDataArg,
6541                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
6542                      ArrayRef<const Expr *> Args, unsigned formatIdx,
6543                      bool inFunctionCall, Sema::VariadicCallType callType,
6544                      llvm::SmallBitVector &CheckedVarArgs,
6545                      UncoveredArgHandler &UncoveredArg)
6546       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
6547         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
6548         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
6549         inFunctionCall(inFunctionCall), CallType(callType),
6550         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
6551     CoveredArgs.resize(numDataArgs);
6552     CoveredArgs.reset();
6553   }
6554 
6555   void DoneProcessing();
6556 
6557   void HandleIncompleteSpecifier(const char *startSpecifier,
6558                                  unsigned specifierLen) override;
6559 
6560   void HandleInvalidLengthModifier(
6561                            const analyze_format_string::FormatSpecifier &FS,
6562                            const analyze_format_string::ConversionSpecifier &CS,
6563                            const char *startSpecifier, unsigned specifierLen,
6564                            unsigned DiagID);
6565 
6566   void HandleNonStandardLengthModifier(
6567                     const analyze_format_string::FormatSpecifier &FS,
6568                     const char *startSpecifier, unsigned specifierLen);
6569 
6570   void HandleNonStandardConversionSpecifier(
6571                     const analyze_format_string::ConversionSpecifier &CS,
6572                     const char *startSpecifier, unsigned specifierLen);
6573 
6574   void HandlePosition(const char *startPos, unsigned posLen) override;
6575 
6576   void HandleInvalidPosition(const char *startSpecifier,
6577                              unsigned specifierLen,
6578                              analyze_format_string::PositionContext p) override;
6579 
6580   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
6581 
6582   void HandleNullChar(const char *nullCharacter) override;
6583 
6584   template <typename Range>
6585   static void
6586   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
6587                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
6588                        bool IsStringLocation, Range StringRange,
6589                        ArrayRef<FixItHint> Fixit = None);
6590 
6591 protected:
6592   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
6593                                         const char *startSpec,
6594                                         unsigned specifierLen,
6595                                         const char *csStart, unsigned csLen);
6596 
6597   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
6598                                          const char *startSpec,
6599                                          unsigned specifierLen);
6600 
6601   SourceRange getFormatStringRange();
6602   CharSourceRange getSpecifierRange(const char *startSpecifier,
6603                                     unsigned specifierLen);
6604   SourceLocation getLocationOfByte(const char *x);
6605 
6606   const Expr *getDataArg(unsigned i) const;
6607 
6608   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
6609                     const analyze_format_string::ConversionSpecifier &CS,
6610                     const char *startSpecifier, unsigned specifierLen,
6611                     unsigned argIndex);
6612 
6613   template <typename Range>
6614   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
6615                             bool IsStringLocation, Range StringRange,
6616                             ArrayRef<FixItHint> Fixit = None);
6617 };
6618 
6619 } // namespace
6620 
6621 SourceRange CheckFormatHandler::getFormatStringRange() {
6622   return OrigFormatExpr->getSourceRange();
6623 }
6624 
6625 CharSourceRange CheckFormatHandler::
6626 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
6627   SourceLocation Start = getLocationOfByte(startSpecifier);
6628   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
6629 
6630   // Advance the end SourceLocation by one due to half-open ranges.
6631   End = End.getLocWithOffset(1);
6632 
6633   return CharSourceRange::getCharRange(Start, End);
6634 }
6635 
6636 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
6637   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
6638                                   S.getLangOpts(), S.Context.getTargetInfo());
6639 }
6640 
6641 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
6642                                                    unsigned specifierLen){
6643   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
6644                        getLocationOfByte(startSpecifier),
6645                        /*IsStringLocation*/true,
6646                        getSpecifierRange(startSpecifier, specifierLen));
6647 }
6648 
6649 void CheckFormatHandler::HandleInvalidLengthModifier(
6650     const analyze_format_string::FormatSpecifier &FS,
6651     const analyze_format_string::ConversionSpecifier &CS,
6652     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
6653   using namespace analyze_format_string;
6654 
6655   const LengthModifier &LM = FS.getLengthModifier();
6656   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
6657 
6658   // See if we know how to fix this length modifier.
6659   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
6660   if (FixedLM) {
6661     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
6662                          getLocationOfByte(LM.getStart()),
6663                          /*IsStringLocation*/true,
6664                          getSpecifierRange(startSpecifier, specifierLen));
6665 
6666     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
6667       << FixedLM->toString()
6668       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
6669 
6670   } else {
6671     FixItHint Hint;
6672     if (DiagID == diag::warn_format_nonsensical_length)
6673       Hint = FixItHint::CreateRemoval(LMRange);
6674 
6675     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
6676                          getLocationOfByte(LM.getStart()),
6677                          /*IsStringLocation*/true,
6678                          getSpecifierRange(startSpecifier, specifierLen),
6679                          Hint);
6680   }
6681 }
6682 
6683 void CheckFormatHandler::HandleNonStandardLengthModifier(
6684     const analyze_format_string::FormatSpecifier &FS,
6685     const char *startSpecifier, unsigned specifierLen) {
6686   using namespace analyze_format_string;
6687 
6688   const LengthModifier &LM = FS.getLengthModifier();
6689   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
6690 
6691   // See if we know how to fix this length modifier.
6692   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
6693   if (FixedLM) {
6694     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
6695                            << LM.toString() << 0,
6696                          getLocationOfByte(LM.getStart()),
6697                          /*IsStringLocation*/true,
6698                          getSpecifierRange(startSpecifier, specifierLen));
6699 
6700     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
6701       << FixedLM->toString()
6702       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
6703 
6704   } else {
6705     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
6706                            << LM.toString() << 0,
6707                          getLocationOfByte(LM.getStart()),
6708                          /*IsStringLocation*/true,
6709                          getSpecifierRange(startSpecifier, specifierLen));
6710   }
6711 }
6712 
6713 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
6714     const analyze_format_string::ConversionSpecifier &CS,
6715     const char *startSpecifier, unsigned specifierLen) {
6716   using namespace analyze_format_string;
6717 
6718   // See if we know how to fix this conversion specifier.
6719   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
6720   if (FixedCS) {
6721     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
6722                           << CS.toString() << /*conversion specifier*/1,
6723                          getLocationOfByte(CS.getStart()),
6724                          /*IsStringLocation*/true,
6725                          getSpecifierRange(startSpecifier, specifierLen));
6726 
6727     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
6728     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
6729       << FixedCS->toString()
6730       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
6731   } else {
6732     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
6733                           << CS.toString() << /*conversion specifier*/1,
6734                          getLocationOfByte(CS.getStart()),
6735                          /*IsStringLocation*/true,
6736                          getSpecifierRange(startSpecifier, specifierLen));
6737   }
6738 }
6739 
6740 void CheckFormatHandler::HandlePosition(const char *startPos,
6741                                         unsigned posLen) {
6742   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
6743                                getLocationOfByte(startPos),
6744                                /*IsStringLocation*/true,
6745                                getSpecifierRange(startPos, posLen));
6746 }
6747 
6748 void
6749 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
6750                                      analyze_format_string::PositionContext p) {
6751   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
6752                          << (unsigned) p,
6753                        getLocationOfByte(startPos), /*IsStringLocation*/true,
6754                        getSpecifierRange(startPos, posLen));
6755 }
6756 
6757 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
6758                                             unsigned posLen) {
6759   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
6760                                getLocationOfByte(startPos),
6761                                /*IsStringLocation*/true,
6762                                getSpecifierRange(startPos, posLen));
6763 }
6764 
6765 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
6766   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
6767     // The presence of a null character is likely an error.
6768     EmitFormatDiagnostic(
6769       S.PDiag(diag::warn_printf_format_string_contains_null_char),
6770       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
6771       getFormatStringRange());
6772   }
6773 }
6774 
6775 // Note that this may return NULL if there was an error parsing or building
6776 // one of the argument expressions.
6777 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
6778   return Args[FirstDataArg + i];
6779 }
6780 
6781 void CheckFormatHandler::DoneProcessing() {
6782   // Does the number of data arguments exceed the number of
6783   // format conversions in the format string?
6784   if (!HasVAListArg) {
6785       // Find any arguments that weren't covered.
6786     CoveredArgs.flip();
6787     signed notCoveredArg = CoveredArgs.find_first();
6788     if (notCoveredArg >= 0) {
6789       assert((unsigned)notCoveredArg < NumDataArgs);
6790       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
6791     } else {
6792       UncoveredArg.setAllCovered();
6793     }
6794   }
6795 }
6796 
6797 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
6798                                    const Expr *ArgExpr) {
6799   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
6800          "Invalid state");
6801 
6802   if (!ArgExpr)
6803     return;
6804 
6805   SourceLocation Loc = ArgExpr->getBeginLoc();
6806 
6807   if (S.getSourceManager().isInSystemMacro(Loc))
6808     return;
6809 
6810   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
6811   for (auto E : DiagnosticExprs)
6812     PDiag << E->getSourceRange();
6813 
6814   CheckFormatHandler::EmitFormatDiagnostic(
6815                                   S, IsFunctionCall, DiagnosticExprs[0],
6816                                   PDiag, Loc, /*IsStringLocation*/false,
6817                                   DiagnosticExprs[0]->getSourceRange());
6818 }
6819 
6820 bool
6821 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
6822                                                      SourceLocation Loc,
6823                                                      const char *startSpec,
6824                                                      unsigned specifierLen,
6825                                                      const char *csStart,
6826                                                      unsigned csLen) {
6827   bool keepGoing = true;
6828   if (argIndex < NumDataArgs) {
6829     // Consider the argument coverered, even though the specifier doesn't
6830     // make sense.
6831     CoveredArgs.set(argIndex);
6832   }
6833   else {
6834     // If argIndex exceeds the number of data arguments we
6835     // don't issue a warning because that is just a cascade of warnings (and
6836     // they may have intended '%%' anyway). We don't want to continue processing
6837     // the format string after this point, however, as we will like just get
6838     // gibberish when trying to match arguments.
6839     keepGoing = false;
6840   }
6841 
6842   StringRef Specifier(csStart, csLen);
6843 
6844   // If the specifier in non-printable, it could be the first byte of a UTF-8
6845   // sequence. In that case, print the UTF-8 code point. If not, print the byte
6846   // hex value.
6847   std::string CodePointStr;
6848   if (!llvm::sys::locale::isPrint(*csStart)) {
6849     llvm::UTF32 CodePoint;
6850     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
6851     const llvm::UTF8 *E =
6852         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
6853     llvm::ConversionResult Result =
6854         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
6855 
6856     if (Result != llvm::conversionOK) {
6857       unsigned char FirstChar = *csStart;
6858       CodePoint = (llvm::UTF32)FirstChar;
6859     }
6860 
6861     llvm::raw_string_ostream OS(CodePointStr);
6862     if (CodePoint < 256)
6863       OS << "\\x" << llvm::format("%02x", CodePoint);
6864     else if (CodePoint <= 0xFFFF)
6865       OS << "\\u" << llvm::format("%04x", CodePoint);
6866     else
6867       OS << "\\U" << llvm::format("%08x", CodePoint);
6868     OS.flush();
6869     Specifier = CodePointStr;
6870   }
6871 
6872   EmitFormatDiagnostic(
6873       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
6874       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
6875 
6876   return keepGoing;
6877 }
6878 
6879 void
6880 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
6881                                                       const char *startSpec,
6882                                                       unsigned specifierLen) {
6883   EmitFormatDiagnostic(
6884     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
6885     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
6886 }
6887 
6888 bool
6889 CheckFormatHandler::CheckNumArgs(
6890   const analyze_format_string::FormatSpecifier &FS,
6891   const analyze_format_string::ConversionSpecifier &CS,
6892   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
6893 
6894   if (argIndex >= NumDataArgs) {
6895     PartialDiagnostic PDiag = FS.usesPositionalArg()
6896       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
6897            << (argIndex+1) << NumDataArgs)
6898       : S.PDiag(diag::warn_printf_insufficient_data_args);
6899     EmitFormatDiagnostic(
6900       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
6901       getSpecifierRange(startSpecifier, specifierLen));
6902 
6903     // Since more arguments than conversion tokens are given, by extension
6904     // all arguments are covered, so mark this as so.
6905     UncoveredArg.setAllCovered();
6906     return false;
6907   }
6908   return true;
6909 }
6910 
6911 template<typename Range>
6912 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
6913                                               SourceLocation Loc,
6914                                               bool IsStringLocation,
6915                                               Range StringRange,
6916                                               ArrayRef<FixItHint> FixIt) {
6917   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
6918                        Loc, IsStringLocation, StringRange, FixIt);
6919 }
6920 
6921 /// If the format string is not within the function call, emit a note
6922 /// so that the function call and string are in diagnostic messages.
6923 ///
6924 /// \param InFunctionCall if true, the format string is within the function
6925 /// call and only one diagnostic message will be produced.  Otherwise, an
6926 /// extra note will be emitted pointing to location of the format string.
6927 ///
6928 /// \param ArgumentExpr the expression that is passed as the format string
6929 /// argument in the function call.  Used for getting locations when two
6930 /// diagnostics are emitted.
6931 ///
6932 /// \param PDiag the callee should already have provided any strings for the
6933 /// diagnostic message.  This function only adds locations and fixits
6934 /// to diagnostics.
6935 ///
6936 /// \param Loc primary location for diagnostic.  If two diagnostics are
6937 /// required, one will be at Loc and a new SourceLocation will be created for
6938 /// the other one.
6939 ///
6940 /// \param IsStringLocation if true, Loc points to the format string should be
6941 /// used for the note.  Otherwise, Loc points to the argument list and will
6942 /// be used with PDiag.
6943 ///
6944 /// \param StringRange some or all of the string to highlight.  This is
6945 /// templated so it can accept either a CharSourceRange or a SourceRange.
6946 ///
6947 /// \param FixIt optional fix it hint for the format string.
6948 template <typename Range>
6949 void CheckFormatHandler::EmitFormatDiagnostic(
6950     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
6951     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
6952     Range StringRange, ArrayRef<FixItHint> FixIt) {
6953   if (InFunctionCall) {
6954     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
6955     D << StringRange;
6956     D << FixIt;
6957   } else {
6958     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
6959       << ArgumentExpr->getSourceRange();
6960 
6961     const Sema::SemaDiagnosticBuilder &Note =
6962       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
6963              diag::note_format_string_defined);
6964 
6965     Note << StringRange;
6966     Note << FixIt;
6967   }
6968 }
6969 
6970 //===--- CHECK: Printf format string checking ------------------------------===//
6971 
6972 namespace {
6973 
6974 class CheckPrintfHandler : public CheckFormatHandler {
6975 public:
6976   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
6977                      const Expr *origFormatExpr,
6978                      const Sema::FormatStringType type, unsigned firstDataArg,
6979                      unsigned numDataArgs, bool isObjC, const char *beg,
6980                      bool hasVAListArg, ArrayRef<const Expr *> Args,
6981                      unsigned formatIdx, bool inFunctionCall,
6982                      Sema::VariadicCallType CallType,
6983                      llvm::SmallBitVector &CheckedVarArgs,
6984                      UncoveredArgHandler &UncoveredArg)
6985       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6986                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
6987                            inFunctionCall, CallType, CheckedVarArgs,
6988                            UncoveredArg) {}
6989 
6990   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
6991 
6992   /// Returns true if '%@' specifiers are allowed in the format string.
6993   bool allowsObjCArg() const {
6994     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
6995            FSType == Sema::FST_OSTrace;
6996   }
6997 
6998   bool HandleInvalidPrintfConversionSpecifier(
6999                                       const analyze_printf::PrintfSpecifier &FS,
7000                                       const char *startSpecifier,
7001                                       unsigned specifierLen) override;
7002 
7003   void handleInvalidMaskType(StringRef MaskType) override;
7004 
7005   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
7006                              const char *startSpecifier,
7007                              unsigned specifierLen) override;
7008   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7009                        const char *StartSpecifier,
7010                        unsigned SpecifierLen,
7011                        const Expr *E);
7012 
7013   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
7014                     const char *startSpecifier, unsigned specifierLen);
7015   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
7016                            const analyze_printf::OptionalAmount &Amt,
7017                            unsigned type,
7018                            const char *startSpecifier, unsigned specifierLen);
7019   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7020                   const analyze_printf::OptionalFlag &flag,
7021                   const char *startSpecifier, unsigned specifierLen);
7022   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
7023                          const analyze_printf::OptionalFlag &ignoredFlag,
7024                          const analyze_printf::OptionalFlag &flag,
7025                          const char *startSpecifier, unsigned specifierLen);
7026   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
7027                            const Expr *E);
7028 
7029   void HandleEmptyObjCModifierFlag(const char *startFlag,
7030                                    unsigned flagLen) override;
7031 
7032   void HandleInvalidObjCModifierFlag(const char *startFlag,
7033                                             unsigned flagLen) override;
7034 
7035   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
7036                                            const char *flagsEnd,
7037                                            const char *conversionPosition)
7038                                              override;
7039 };
7040 
7041 } // namespace
7042 
7043 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
7044                                       const analyze_printf::PrintfSpecifier &FS,
7045                                       const char *startSpecifier,
7046                                       unsigned specifierLen) {
7047   const analyze_printf::PrintfConversionSpecifier &CS =
7048     FS.getConversionSpecifier();
7049 
7050   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
7051                                           getLocationOfByte(CS.getStart()),
7052                                           startSpecifier, specifierLen,
7053                                           CS.getStart(), CS.getLength());
7054 }
7055 
7056 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
7057   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
7058 }
7059 
7060 bool CheckPrintfHandler::HandleAmount(
7061                                const analyze_format_string::OptionalAmount &Amt,
7062                                unsigned k, const char *startSpecifier,
7063                                unsigned specifierLen) {
7064   if (Amt.hasDataArgument()) {
7065     if (!HasVAListArg) {
7066       unsigned argIndex = Amt.getArgIndex();
7067       if (argIndex >= NumDataArgs) {
7068         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
7069                                << k,
7070                              getLocationOfByte(Amt.getStart()),
7071                              /*IsStringLocation*/true,
7072                              getSpecifierRange(startSpecifier, specifierLen));
7073         // Don't do any more checking.  We will just emit
7074         // spurious errors.
7075         return false;
7076       }
7077 
7078       // Type check the data argument.  It should be an 'int'.
7079       // Although not in conformance with C99, we also allow the argument to be
7080       // an 'unsigned int' as that is a reasonably safe case.  GCC also
7081       // doesn't emit a warning for that case.
7082       CoveredArgs.set(argIndex);
7083       const Expr *Arg = getDataArg(argIndex);
7084       if (!Arg)
7085         return false;
7086 
7087       QualType T = Arg->getType();
7088 
7089       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
7090       assert(AT.isValid());
7091 
7092       if (!AT.matchesType(S.Context, T)) {
7093         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
7094                                << k << AT.getRepresentativeTypeName(S.Context)
7095                                << T << Arg->getSourceRange(),
7096                              getLocationOfByte(Amt.getStart()),
7097                              /*IsStringLocation*/true,
7098                              getSpecifierRange(startSpecifier, specifierLen));
7099         // Don't do any more checking.  We will just emit
7100         // spurious errors.
7101         return false;
7102       }
7103     }
7104   }
7105   return true;
7106 }
7107 
7108 void CheckPrintfHandler::HandleInvalidAmount(
7109                                       const analyze_printf::PrintfSpecifier &FS,
7110                                       const analyze_printf::OptionalAmount &Amt,
7111                                       unsigned type,
7112                                       const char *startSpecifier,
7113                                       unsigned specifierLen) {
7114   const analyze_printf::PrintfConversionSpecifier &CS =
7115     FS.getConversionSpecifier();
7116 
7117   FixItHint fixit =
7118     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
7119       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
7120                                  Amt.getConstantLength()))
7121       : FixItHint();
7122 
7123   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
7124                          << type << CS.toString(),
7125                        getLocationOfByte(Amt.getStart()),
7126                        /*IsStringLocation*/true,
7127                        getSpecifierRange(startSpecifier, specifierLen),
7128                        fixit);
7129 }
7130 
7131 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7132                                     const analyze_printf::OptionalFlag &flag,
7133                                     const char *startSpecifier,
7134                                     unsigned specifierLen) {
7135   // Warn about pointless flag with a fixit removal.
7136   const analyze_printf::PrintfConversionSpecifier &CS =
7137     FS.getConversionSpecifier();
7138   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
7139                          << flag.toString() << CS.toString(),
7140                        getLocationOfByte(flag.getPosition()),
7141                        /*IsStringLocation*/true,
7142                        getSpecifierRange(startSpecifier, specifierLen),
7143                        FixItHint::CreateRemoval(
7144                          getSpecifierRange(flag.getPosition(), 1)));
7145 }
7146 
7147 void CheckPrintfHandler::HandleIgnoredFlag(
7148                                 const analyze_printf::PrintfSpecifier &FS,
7149                                 const analyze_printf::OptionalFlag &ignoredFlag,
7150                                 const analyze_printf::OptionalFlag &flag,
7151                                 const char *startSpecifier,
7152                                 unsigned specifierLen) {
7153   // Warn about ignored flag with a fixit removal.
7154   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
7155                          << ignoredFlag.toString() << flag.toString(),
7156                        getLocationOfByte(ignoredFlag.getPosition()),
7157                        /*IsStringLocation*/true,
7158                        getSpecifierRange(startSpecifier, specifierLen),
7159                        FixItHint::CreateRemoval(
7160                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
7161 }
7162 
7163 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
7164                                                      unsigned flagLen) {
7165   // Warn about an empty flag.
7166   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
7167                        getLocationOfByte(startFlag),
7168                        /*IsStringLocation*/true,
7169                        getSpecifierRange(startFlag, flagLen));
7170 }
7171 
7172 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
7173                                                        unsigned flagLen) {
7174   // Warn about an invalid flag.
7175   auto Range = getSpecifierRange(startFlag, flagLen);
7176   StringRef flag(startFlag, flagLen);
7177   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
7178                       getLocationOfByte(startFlag),
7179                       /*IsStringLocation*/true,
7180                       Range, FixItHint::CreateRemoval(Range));
7181 }
7182 
7183 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
7184     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
7185     // Warn about using '[...]' without a '@' conversion.
7186     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
7187     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
7188     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
7189                          getLocationOfByte(conversionPosition),
7190                          /*IsStringLocation*/true,
7191                          Range, FixItHint::CreateRemoval(Range));
7192 }
7193 
7194 // Determines if the specified is a C++ class or struct containing
7195 // a member with the specified name and kind (e.g. a CXXMethodDecl named
7196 // "c_str()").
7197 template<typename MemberKind>
7198 static llvm::SmallPtrSet<MemberKind*, 1>
7199 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
7200   const RecordType *RT = Ty->getAs<RecordType>();
7201   llvm::SmallPtrSet<MemberKind*, 1> Results;
7202 
7203   if (!RT)
7204     return Results;
7205   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
7206   if (!RD || !RD->getDefinition())
7207     return Results;
7208 
7209   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
7210                  Sema::LookupMemberName);
7211   R.suppressDiagnostics();
7212 
7213   // We just need to include all members of the right kind turned up by the
7214   // filter, at this point.
7215   if (S.LookupQualifiedName(R, RT->getDecl()))
7216     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7217       NamedDecl *decl = (*I)->getUnderlyingDecl();
7218       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
7219         Results.insert(FK);
7220     }
7221   return Results;
7222 }
7223 
7224 /// Check if we could call '.c_str()' on an object.
7225 ///
7226 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
7227 /// allow the call, or if it would be ambiguous).
7228 bool Sema::hasCStrMethod(const Expr *E) {
7229   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7230 
7231   MethodSet Results =
7232       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
7233   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7234        MI != ME; ++MI)
7235     if ((*MI)->getMinRequiredArguments() == 0)
7236       return true;
7237   return false;
7238 }
7239 
7240 // Check if a (w)string was passed when a (w)char* was needed, and offer a
7241 // better diagnostic if so. AT is assumed to be valid.
7242 // Returns true when a c_str() conversion method is found.
7243 bool CheckPrintfHandler::checkForCStrMembers(
7244     const analyze_printf::ArgType &AT, const Expr *E) {
7245   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7246 
7247   MethodSet Results =
7248       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
7249 
7250   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7251        MI != ME; ++MI) {
7252     const CXXMethodDecl *Method = *MI;
7253     if (Method->getMinRequiredArguments() == 0 &&
7254         AT.matchesType(S.Context, Method->getReturnType())) {
7255       // FIXME: Suggest parens if the expression needs them.
7256       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
7257       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
7258           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
7259       return true;
7260     }
7261   }
7262 
7263   return false;
7264 }
7265 
7266 bool
7267 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
7268                                             &FS,
7269                                           const char *startSpecifier,
7270                                           unsigned specifierLen) {
7271   using namespace analyze_format_string;
7272   using namespace analyze_printf;
7273 
7274   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
7275 
7276   if (FS.consumesDataArgument()) {
7277     if (atFirstArg) {
7278         atFirstArg = false;
7279         usesPositionalArgs = FS.usesPositionalArg();
7280     }
7281     else if (usesPositionalArgs != FS.usesPositionalArg()) {
7282       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
7283                                         startSpecifier, specifierLen);
7284       return false;
7285     }
7286   }
7287 
7288   // First check if the field width, precision, and conversion specifier
7289   // have matching data arguments.
7290   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
7291                     startSpecifier, specifierLen)) {
7292     return false;
7293   }
7294 
7295   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
7296                     startSpecifier, specifierLen)) {
7297     return false;
7298   }
7299 
7300   if (!CS.consumesDataArgument()) {
7301     // FIXME: Technically specifying a precision or field width here
7302     // makes no sense.  Worth issuing a warning at some point.
7303     return true;
7304   }
7305 
7306   // Consume the argument.
7307   unsigned argIndex = FS.getArgIndex();
7308   if (argIndex < NumDataArgs) {
7309     // The check to see if the argIndex is valid will come later.
7310     // We set the bit here because we may exit early from this
7311     // function if we encounter some other error.
7312     CoveredArgs.set(argIndex);
7313   }
7314 
7315   // FreeBSD kernel extensions.
7316   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
7317       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
7318     // We need at least two arguments.
7319     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
7320       return false;
7321 
7322     // Claim the second argument.
7323     CoveredArgs.set(argIndex + 1);
7324 
7325     // Type check the first argument (int for %b, pointer for %D)
7326     const Expr *Ex = getDataArg(argIndex);
7327     const analyze_printf::ArgType &AT =
7328       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
7329         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
7330     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
7331       EmitFormatDiagnostic(
7332           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7333               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
7334               << false << Ex->getSourceRange(),
7335           Ex->getBeginLoc(), /*IsStringLocation*/ false,
7336           getSpecifierRange(startSpecifier, specifierLen));
7337 
7338     // Type check the second argument (char * for both %b and %D)
7339     Ex = getDataArg(argIndex + 1);
7340     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
7341     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
7342       EmitFormatDiagnostic(
7343           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7344               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
7345               << false << Ex->getSourceRange(),
7346           Ex->getBeginLoc(), /*IsStringLocation*/ false,
7347           getSpecifierRange(startSpecifier, specifierLen));
7348 
7349      return true;
7350   }
7351 
7352   // Check for using an Objective-C specific conversion specifier
7353   // in a non-ObjC literal.
7354   if (!allowsObjCArg() && CS.isObjCArg()) {
7355     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7356                                                   specifierLen);
7357   }
7358 
7359   // %P can only be used with os_log.
7360   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
7361     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7362                                                   specifierLen);
7363   }
7364 
7365   // %n is not allowed with os_log.
7366   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
7367     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
7368                          getLocationOfByte(CS.getStart()),
7369                          /*IsStringLocation*/ false,
7370                          getSpecifierRange(startSpecifier, specifierLen));
7371 
7372     return true;
7373   }
7374 
7375   // Only scalars are allowed for os_trace.
7376   if (FSType == Sema::FST_OSTrace &&
7377       (CS.getKind() == ConversionSpecifier::PArg ||
7378        CS.getKind() == ConversionSpecifier::sArg ||
7379        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
7380     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7381                                                   specifierLen);
7382   }
7383 
7384   // Check for use of public/private annotation outside of os_log().
7385   if (FSType != Sema::FST_OSLog) {
7386     if (FS.isPublic().isSet()) {
7387       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
7388                                << "public",
7389                            getLocationOfByte(FS.isPublic().getPosition()),
7390                            /*IsStringLocation*/ false,
7391                            getSpecifierRange(startSpecifier, specifierLen));
7392     }
7393     if (FS.isPrivate().isSet()) {
7394       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
7395                                << "private",
7396                            getLocationOfByte(FS.isPrivate().getPosition()),
7397                            /*IsStringLocation*/ false,
7398                            getSpecifierRange(startSpecifier, specifierLen));
7399     }
7400   }
7401 
7402   // Check for invalid use of field width
7403   if (!FS.hasValidFieldWidth()) {
7404     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
7405         startSpecifier, specifierLen);
7406   }
7407 
7408   // Check for invalid use of precision
7409   if (!FS.hasValidPrecision()) {
7410     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
7411         startSpecifier, specifierLen);
7412   }
7413 
7414   // Precision is mandatory for %P specifier.
7415   if (CS.getKind() == ConversionSpecifier::PArg &&
7416       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
7417     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
7418                          getLocationOfByte(startSpecifier),
7419                          /*IsStringLocation*/ false,
7420                          getSpecifierRange(startSpecifier, specifierLen));
7421   }
7422 
7423   // Check each flag does not conflict with any other component.
7424   if (!FS.hasValidThousandsGroupingPrefix())
7425     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
7426   if (!FS.hasValidLeadingZeros())
7427     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
7428   if (!FS.hasValidPlusPrefix())
7429     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
7430   if (!FS.hasValidSpacePrefix())
7431     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
7432   if (!FS.hasValidAlternativeForm())
7433     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
7434   if (!FS.hasValidLeftJustified())
7435     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
7436 
7437   // Check that flags are not ignored by another flag
7438   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
7439     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
7440         startSpecifier, specifierLen);
7441   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
7442     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
7443             startSpecifier, specifierLen);
7444 
7445   // Check the length modifier is valid with the given conversion specifier.
7446   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
7447                                  S.getLangOpts()))
7448     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7449                                 diag::warn_format_nonsensical_length);
7450   else if (!FS.hasStandardLengthModifier())
7451     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
7452   else if (!FS.hasStandardLengthConversionCombination())
7453     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7454                                 diag::warn_format_non_standard_conversion_spec);
7455 
7456   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
7457     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
7458 
7459   // The remaining checks depend on the data arguments.
7460   if (HasVAListArg)
7461     return true;
7462 
7463   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
7464     return false;
7465 
7466   const Expr *Arg = getDataArg(argIndex);
7467   if (!Arg)
7468     return true;
7469 
7470   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
7471 }
7472 
7473 static bool requiresParensToAddCast(const Expr *E) {
7474   // FIXME: We should have a general way to reason about operator
7475   // precedence and whether parens are actually needed here.
7476   // Take care of a few common cases where they aren't.
7477   const Expr *Inside = E->IgnoreImpCasts();
7478   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
7479     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
7480 
7481   switch (Inside->getStmtClass()) {
7482   case Stmt::ArraySubscriptExprClass:
7483   case Stmt::CallExprClass:
7484   case Stmt::CharacterLiteralClass:
7485   case Stmt::CXXBoolLiteralExprClass:
7486   case Stmt::DeclRefExprClass:
7487   case Stmt::FloatingLiteralClass:
7488   case Stmt::IntegerLiteralClass:
7489   case Stmt::MemberExprClass:
7490   case Stmt::ObjCArrayLiteralClass:
7491   case Stmt::ObjCBoolLiteralExprClass:
7492   case Stmt::ObjCBoxedExprClass:
7493   case Stmt::ObjCDictionaryLiteralClass:
7494   case Stmt::ObjCEncodeExprClass:
7495   case Stmt::ObjCIvarRefExprClass:
7496   case Stmt::ObjCMessageExprClass:
7497   case Stmt::ObjCPropertyRefExprClass:
7498   case Stmt::ObjCStringLiteralClass:
7499   case Stmt::ObjCSubscriptRefExprClass:
7500   case Stmt::ParenExprClass:
7501   case Stmt::StringLiteralClass:
7502   case Stmt::UnaryOperatorClass:
7503     return false;
7504   default:
7505     return true;
7506   }
7507 }
7508 
7509 static std::pair<QualType, StringRef>
7510 shouldNotPrintDirectly(const ASTContext &Context,
7511                        QualType IntendedTy,
7512                        const Expr *E) {
7513   // Use a 'while' to peel off layers of typedefs.
7514   QualType TyTy = IntendedTy;
7515   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
7516     StringRef Name = UserTy->getDecl()->getName();
7517     QualType CastTy = llvm::StringSwitch<QualType>(Name)
7518       .Case("CFIndex", Context.getNSIntegerType())
7519       .Case("NSInteger", Context.getNSIntegerType())
7520       .Case("NSUInteger", Context.getNSUIntegerType())
7521       .Case("SInt32", Context.IntTy)
7522       .Case("UInt32", Context.UnsignedIntTy)
7523       .Default(QualType());
7524 
7525     if (!CastTy.isNull())
7526       return std::make_pair(CastTy, Name);
7527 
7528     TyTy = UserTy->desugar();
7529   }
7530 
7531   // Strip parens if necessary.
7532   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
7533     return shouldNotPrintDirectly(Context,
7534                                   PE->getSubExpr()->getType(),
7535                                   PE->getSubExpr());
7536 
7537   // If this is a conditional expression, then its result type is constructed
7538   // via usual arithmetic conversions and thus there might be no necessary
7539   // typedef sugar there.  Recurse to operands to check for NSInteger &
7540   // Co. usage condition.
7541   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
7542     QualType TrueTy, FalseTy;
7543     StringRef TrueName, FalseName;
7544 
7545     std::tie(TrueTy, TrueName) =
7546       shouldNotPrintDirectly(Context,
7547                              CO->getTrueExpr()->getType(),
7548                              CO->getTrueExpr());
7549     std::tie(FalseTy, FalseName) =
7550       shouldNotPrintDirectly(Context,
7551                              CO->getFalseExpr()->getType(),
7552                              CO->getFalseExpr());
7553 
7554     if (TrueTy == FalseTy)
7555       return std::make_pair(TrueTy, TrueName);
7556     else if (TrueTy.isNull())
7557       return std::make_pair(FalseTy, FalseName);
7558     else if (FalseTy.isNull())
7559       return std::make_pair(TrueTy, TrueName);
7560   }
7561 
7562   return std::make_pair(QualType(), StringRef());
7563 }
7564 
7565 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
7566 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
7567 /// type do not count.
7568 static bool
7569 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
7570   QualType From = ICE->getSubExpr()->getType();
7571   QualType To = ICE->getType();
7572   // It's an integer promotion if the destination type is the promoted
7573   // source type.
7574   if (ICE->getCastKind() == CK_IntegralCast &&
7575       From->isPromotableIntegerType() &&
7576       S.Context.getPromotedIntegerType(From) == To)
7577     return true;
7578   // Look through vector types, since we do default argument promotion for
7579   // those in OpenCL.
7580   if (const auto *VecTy = From->getAs<ExtVectorType>())
7581     From = VecTy->getElementType();
7582   if (const auto *VecTy = To->getAs<ExtVectorType>())
7583     To = VecTy->getElementType();
7584   // It's a floating promotion if the source type is a lower rank.
7585   return ICE->getCastKind() == CK_FloatingCast &&
7586          S.Context.getFloatingTypeOrder(From, To) < 0;
7587 }
7588 
7589 bool
7590 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7591                                     const char *StartSpecifier,
7592                                     unsigned SpecifierLen,
7593                                     const Expr *E) {
7594   using namespace analyze_format_string;
7595   using namespace analyze_printf;
7596 
7597   // Now type check the data expression that matches the
7598   // format specifier.
7599   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
7600   if (!AT.isValid())
7601     return true;
7602 
7603   QualType ExprTy = E->getType();
7604   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
7605     ExprTy = TET->getUnderlyingExpr()->getType();
7606   }
7607 
7608   // Diagnose attempts to print a boolean value as a character. Unlike other
7609   // -Wformat diagnostics, this is fine from a type perspective, but it still
7610   // doesn't make sense.
7611   if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
7612       E->isKnownToHaveBooleanValue()) {
7613     const CharSourceRange &CSR =
7614         getSpecifierRange(StartSpecifier, SpecifierLen);
7615     SmallString<4> FSString;
7616     llvm::raw_svector_ostream os(FSString);
7617     FS.toString(os);
7618     EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
7619                              << FSString,
7620                          E->getExprLoc(), false, CSR);
7621     return true;
7622   }
7623 
7624   analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
7625   if (Match == analyze_printf::ArgType::Match)
7626     return true;
7627 
7628   // Look through argument promotions for our error message's reported type.
7629   // This includes the integral and floating promotions, but excludes array
7630   // and function pointer decay (seeing that an argument intended to be a
7631   // string has type 'char [6]' is probably more confusing than 'char *') and
7632   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
7633   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
7634     if (isArithmeticArgumentPromotion(S, ICE)) {
7635       E = ICE->getSubExpr();
7636       ExprTy = E->getType();
7637 
7638       // Check if we didn't match because of an implicit cast from a 'char'
7639       // or 'short' to an 'int'.  This is done because printf is a varargs
7640       // function.
7641       if (ICE->getType() == S.Context.IntTy ||
7642           ICE->getType() == S.Context.UnsignedIntTy) {
7643         // All further checking is done on the subexpression
7644         const analyze_printf::ArgType::MatchKind ImplicitMatch =
7645             AT.matchesType(S.Context, ExprTy);
7646         if (ImplicitMatch == analyze_printf::ArgType::Match)
7647           return true;
7648         if (ImplicitMatch == ArgType::NoMatchPedantic ||
7649             ImplicitMatch == ArgType::NoMatchTypeConfusion)
7650           Match = ImplicitMatch;
7651       }
7652     }
7653   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
7654     // Special case for 'a', which has type 'int' in C.
7655     // Note, however, that we do /not/ want to treat multibyte constants like
7656     // 'MooV' as characters! This form is deprecated but still exists.
7657     if (ExprTy == S.Context.IntTy)
7658       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
7659         ExprTy = S.Context.CharTy;
7660   }
7661 
7662   // Look through enums to their underlying type.
7663   bool IsEnum = false;
7664   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
7665     ExprTy = EnumTy->getDecl()->getIntegerType();
7666     IsEnum = true;
7667   }
7668 
7669   // %C in an Objective-C context prints a unichar, not a wchar_t.
7670   // If the argument is an integer of some kind, believe the %C and suggest
7671   // a cast instead of changing the conversion specifier.
7672   QualType IntendedTy = ExprTy;
7673   if (isObjCContext() &&
7674       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
7675     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
7676         !ExprTy->isCharType()) {
7677       // 'unichar' is defined as a typedef of unsigned short, but we should
7678       // prefer using the typedef if it is visible.
7679       IntendedTy = S.Context.UnsignedShortTy;
7680 
7681       // While we are here, check if the value is an IntegerLiteral that happens
7682       // to be within the valid range.
7683       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
7684         const llvm::APInt &V = IL->getValue();
7685         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
7686           return true;
7687       }
7688 
7689       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
7690                           Sema::LookupOrdinaryName);
7691       if (S.LookupName(Result, S.getCurScope())) {
7692         NamedDecl *ND = Result.getFoundDecl();
7693         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
7694           if (TD->getUnderlyingType() == IntendedTy)
7695             IntendedTy = S.Context.getTypedefType(TD);
7696       }
7697     }
7698   }
7699 
7700   // Special-case some of Darwin's platform-independence types by suggesting
7701   // casts to primitive types that are known to be large enough.
7702   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
7703   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
7704     QualType CastTy;
7705     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
7706     if (!CastTy.isNull()) {
7707       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
7708       // (long in ASTContext). Only complain to pedants.
7709       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
7710           (AT.isSizeT() || AT.isPtrdiffT()) &&
7711           AT.matchesType(S.Context, CastTy))
7712         Match = ArgType::NoMatchPedantic;
7713       IntendedTy = CastTy;
7714       ShouldNotPrintDirectly = true;
7715     }
7716   }
7717 
7718   // We may be able to offer a FixItHint if it is a supported type.
7719   PrintfSpecifier fixedFS = FS;
7720   bool Success =
7721       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
7722 
7723   if (Success) {
7724     // Get the fix string from the fixed format specifier
7725     SmallString<16> buf;
7726     llvm::raw_svector_ostream os(buf);
7727     fixedFS.toString(os);
7728 
7729     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
7730 
7731     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
7732       unsigned Diag;
7733       switch (Match) {
7734       case ArgType::Match: llvm_unreachable("expected non-matching");
7735       case ArgType::NoMatchPedantic:
7736         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
7737         break;
7738       case ArgType::NoMatchTypeConfusion:
7739         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
7740         break;
7741       case ArgType::NoMatch:
7742         Diag = diag::warn_format_conversion_argument_type_mismatch;
7743         break;
7744       }
7745 
7746       // In this case, the specifier is wrong and should be changed to match
7747       // the argument.
7748       EmitFormatDiagnostic(S.PDiag(Diag)
7749                                << AT.getRepresentativeTypeName(S.Context)
7750                                << IntendedTy << IsEnum << E->getSourceRange(),
7751                            E->getBeginLoc(),
7752                            /*IsStringLocation*/ false, SpecRange,
7753                            FixItHint::CreateReplacement(SpecRange, os.str()));
7754     } else {
7755       // The canonical type for formatting this value is different from the
7756       // actual type of the expression. (This occurs, for example, with Darwin's
7757       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
7758       // should be printed as 'long' for 64-bit compatibility.)
7759       // Rather than emitting a normal format/argument mismatch, we want to
7760       // add a cast to the recommended type (and correct the format string
7761       // if necessary).
7762       SmallString<16> CastBuf;
7763       llvm::raw_svector_ostream CastFix(CastBuf);
7764       CastFix << "(";
7765       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
7766       CastFix << ")";
7767 
7768       SmallVector<FixItHint,4> Hints;
7769       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
7770         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
7771 
7772       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
7773         // If there's already a cast present, just replace it.
7774         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
7775         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
7776 
7777       } else if (!requiresParensToAddCast(E)) {
7778         // If the expression has high enough precedence,
7779         // just write the C-style cast.
7780         Hints.push_back(
7781             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
7782       } else {
7783         // Otherwise, add parens around the expression as well as the cast.
7784         CastFix << "(";
7785         Hints.push_back(
7786             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
7787 
7788         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
7789         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
7790       }
7791 
7792       if (ShouldNotPrintDirectly) {
7793         // The expression has a type that should not be printed directly.
7794         // We extract the name from the typedef because we don't want to show
7795         // the underlying type in the diagnostic.
7796         StringRef Name;
7797         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
7798           Name = TypedefTy->getDecl()->getName();
7799         else
7800           Name = CastTyName;
7801         unsigned Diag = Match == ArgType::NoMatchPedantic
7802                             ? diag::warn_format_argument_needs_cast_pedantic
7803                             : diag::warn_format_argument_needs_cast;
7804         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
7805                                            << E->getSourceRange(),
7806                              E->getBeginLoc(), /*IsStringLocation=*/false,
7807                              SpecRange, Hints);
7808       } else {
7809         // In this case, the expression could be printed using a different
7810         // specifier, but we've decided that the specifier is probably correct
7811         // and we should cast instead. Just use the normal warning message.
7812         EmitFormatDiagnostic(
7813             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7814                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
7815                 << E->getSourceRange(),
7816             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
7817       }
7818     }
7819   } else {
7820     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
7821                                                    SpecifierLen);
7822     // Since the warning for passing non-POD types to variadic functions
7823     // was deferred until now, we emit a warning for non-POD
7824     // arguments here.
7825     switch (S.isValidVarArgType(ExprTy)) {
7826     case Sema::VAK_Valid:
7827     case Sema::VAK_ValidInCXX11: {
7828       unsigned Diag;
7829       switch (Match) {
7830       case ArgType::Match: llvm_unreachable("expected non-matching");
7831       case ArgType::NoMatchPedantic:
7832         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
7833         break;
7834       case ArgType::NoMatchTypeConfusion:
7835         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
7836         break;
7837       case ArgType::NoMatch:
7838         Diag = diag::warn_format_conversion_argument_type_mismatch;
7839         break;
7840       }
7841 
7842       EmitFormatDiagnostic(
7843           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
7844                         << IsEnum << CSR << E->getSourceRange(),
7845           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
7846       break;
7847     }
7848     case Sema::VAK_Undefined:
7849     case Sema::VAK_MSVCUndefined:
7850       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
7851                                << S.getLangOpts().CPlusPlus11 << ExprTy
7852                                << CallType
7853                                << AT.getRepresentativeTypeName(S.Context) << CSR
7854                                << E->getSourceRange(),
7855                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
7856       checkForCStrMembers(AT, E);
7857       break;
7858 
7859     case Sema::VAK_Invalid:
7860       if (ExprTy->isObjCObjectType())
7861         EmitFormatDiagnostic(
7862             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
7863                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
7864                 << AT.getRepresentativeTypeName(S.Context) << CSR
7865                 << E->getSourceRange(),
7866             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
7867       else
7868         // FIXME: If this is an initializer list, suggest removing the braces
7869         // or inserting a cast to the target type.
7870         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
7871             << isa<InitListExpr>(E) << ExprTy << CallType
7872             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
7873       break;
7874     }
7875 
7876     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
7877            "format string specifier index out of range");
7878     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
7879   }
7880 
7881   return true;
7882 }
7883 
7884 //===--- CHECK: Scanf format string checking ------------------------------===//
7885 
7886 namespace {
7887 
7888 class CheckScanfHandler : public CheckFormatHandler {
7889 public:
7890   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
7891                     const Expr *origFormatExpr, Sema::FormatStringType type,
7892                     unsigned firstDataArg, unsigned numDataArgs,
7893                     const char *beg, bool hasVAListArg,
7894                     ArrayRef<const Expr *> Args, unsigned formatIdx,
7895                     bool inFunctionCall, Sema::VariadicCallType CallType,
7896                     llvm::SmallBitVector &CheckedVarArgs,
7897                     UncoveredArgHandler &UncoveredArg)
7898       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7899                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
7900                            inFunctionCall, CallType, CheckedVarArgs,
7901                            UncoveredArg) {}
7902 
7903   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
7904                             const char *startSpecifier,
7905                             unsigned specifierLen) override;
7906 
7907   bool HandleInvalidScanfConversionSpecifier(
7908           const analyze_scanf::ScanfSpecifier &FS,
7909           const char *startSpecifier,
7910           unsigned specifierLen) override;
7911 
7912   void HandleIncompleteScanList(const char *start, const char *end) override;
7913 };
7914 
7915 } // namespace
7916 
7917 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
7918                                                  const char *end) {
7919   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
7920                        getLocationOfByte(end), /*IsStringLocation*/true,
7921                        getSpecifierRange(start, end - start));
7922 }
7923 
7924 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
7925                                         const analyze_scanf::ScanfSpecifier &FS,
7926                                         const char *startSpecifier,
7927                                         unsigned specifierLen) {
7928   const analyze_scanf::ScanfConversionSpecifier &CS =
7929     FS.getConversionSpecifier();
7930 
7931   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
7932                                           getLocationOfByte(CS.getStart()),
7933                                           startSpecifier, specifierLen,
7934                                           CS.getStart(), CS.getLength());
7935 }
7936 
7937 bool CheckScanfHandler::HandleScanfSpecifier(
7938                                        const analyze_scanf::ScanfSpecifier &FS,
7939                                        const char *startSpecifier,
7940                                        unsigned specifierLen) {
7941   using namespace analyze_scanf;
7942   using namespace analyze_format_string;
7943 
7944   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
7945 
7946   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
7947   // be used to decide if we are using positional arguments consistently.
7948   if (FS.consumesDataArgument()) {
7949     if (atFirstArg) {
7950       atFirstArg = false;
7951       usesPositionalArgs = FS.usesPositionalArg();
7952     }
7953     else if (usesPositionalArgs != FS.usesPositionalArg()) {
7954       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
7955                                         startSpecifier, specifierLen);
7956       return false;
7957     }
7958   }
7959 
7960   // Check if the field with is non-zero.
7961   const OptionalAmount &Amt = FS.getFieldWidth();
7962   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
7963     if (Amt.getConstantAmount() == 0) {
7964       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
7965                                                    Amt.getConstantLength());
7966       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
7967                            getLocationOfByte(Amt.getStart()),
7968                            /*IsStringLocation*/true, R,
7969                            FixItHint::CreateRemoval(R));
7970     }
7971   }
7972 
7973   if (!FS.consumesDataArgument()) {
7974     // FIXME: Technically specifying a precision or field width here
7975     // makes no sense.  Worth issuing a warning at some point.
7976     return true;
7977   }
7978 
7979   // Consume the argument.
7980   unsigned argIndex = FS.getArgIndex();
7981   if (argIndex < NumDataArgs) {
7982       // The check to see if the argIndex is valid will come later.
7983       // We set the bit here because we may exit early from this
7984       // function if we encounter some other error.
7985     CoveredArgs.set(argIndex);
7986   }
7987 
7988   // Check the length modifier is valid with the given conversion specifier.
7989   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
7990                                  S.getLangOpts()))
7991     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7992                                 diag::warn_format_nonsensical_length);
7993   else if (!FS.hasStandardLengthModifier())
7994     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
7995   else if (!FS.hasStandardLengthConversionCombination())
7996     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7997                                 diag::warn_format_non_standard_conversion_spec);
7998 
7999   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8000     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8001 
8002   // The remaining checks depend on the data arguments.
8003   if (HasVAListArg)
8004     return true;
8005 
8006   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8007     return false;
8008 
8009   // Check that the argument type matches the format specifier.
8010   const Expr *Ex = getDataArg(argIndex);
8011   if (!Ex)
8012     return true;
8013 
8014   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
8015 
8016   if (!AT.isValid()) {
8017     return true;
8018   }
8019 
8020   analyze_format_string::ArgType::MatchKind Match =
8021       AT.matchesType(S.Context, Ex->getType());
8022   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
8023   if (Match == analyze_format_string::ArgType::Match)
8024     return true;
8025 
8026   ScanfSpecifier fixedFS = FS;
8027   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
8028                                  S.getLangOpts(), S.Context);
8029 
8030   unsigned Diag =
8031       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
8032                : diag::warn_format_conversion_argument_type_mismatch;
8033 
8034   if (Success) {
8035     // Get the fix string from the fixed format specifier.
8036     SmallString<128> buf;
8037     llvm::raw_svector_ostream os(buf);
8038     fixedFS.toString(os);
8039 
8040     EmitFormatDiagnostic(
8041         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
8042                       << Ex->getType() << false << Ex->getSourceRange(),
8043         Ex->getBeginLoc(),
8044         /*IsStringLocation*/ false,
8045         getSpecifierRange(startSpecifier, specifierLen),
8046         FixItHint::CreateReplacement(
8047             getSpecifierRange(startSpecifier, specifierLen), os.str()));
8048   } else {
8049     EmitFormatDiagnostic(S.PDiag(Diag)
8050                              << AT.getRepresentativeTypeName(S.Context)
8051                              << Ex->getType() << false << Ex->getSourceRange(),
8052                          Ex->getBeginLoc(),
8053                          /*IsStringLocation*/ false,
8054                          getSpecifierRange(startSpecifier, specifierLen));
8055   }
8056 
8057   return true;
8058 }
8059 
8060 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
8061                               const Expr *OrigFormatExpr,
8062                               ArrayRef<const Expr *> Args,
8063                               bool HasVAListArg, unsigned format_idx,
8064                               unsigned firstDataArg,
8065                               Sema::FormatStringType Type,
8066                               bool inFunctionCall,
8067                               Sema::VariadicCallType CallType,
8068                               llvm::SmallBitVector &CheckedVarArgs,
8069                               UncoveredArgHandler &UncoveredArg,
8070                               bool IgnoreStringsWithoutSpecifiers) {
8071   // CHECK: is the format string a wide literal?
8072   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
8073     CheckFormatHandler::EmitFormatDiagnostic(
8074         S, inFunctionCall, Args[format_idx],
8075         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
8076         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8077     return;
8078   }
8079 
8080   // Str - The format string.  NOTE: this is NOT null-terminated!
8081   StringRef StrRef = FExpr->getString();
8082   const char *Str = StrRef.data();
8083   // Account for cases where the string literal is truncated in a declaration.
8084   const ConstantArrayType *T =
8085     S.Context.getAsConstantArrayType(FExpr->getType());
8086   assert(T && "String literal not of constant array type!");
8087   size_t TypeSize = T->getSize().getZExtValue();
8088   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8089   const unsigned numDataArgs = Args.size() - firstDataArg;
8090 
8091   if (IgnoreStringsWithoutSpecifiers &&
8092       !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
8093           Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
8094     return;
8095 
8096   // Emit a warning if the string literal is truncated and does not contain an
8097   // embedded null character.
8098   if (TypeSize <= StrRef.size() &&
8099       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
8100     CheckFormatHandler::EmitFormatDiagnostic(
8101         S, inFunctionCall, Args[format_idx],
8102         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
8103         FExpr->getBeginLoc(),
8104         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
8105     return;
8106   }
8107 
8108   // CHECK: empty format string?
8109   if (StrLen == 0 && numDataArgs > 0) {
8110     CheckFormatHandler::EmitFormatDiagnostic(
8111         S, inFunctionCall, Args[format_idx],
8112         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
8113         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8114     return;
8115   }
8116 
8117   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
8118       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
8119       Type == Sema::FST_OSTrace) {
8120     CheckPrintfHandler H(
8121         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
8122         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
8123         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
8124         CheckedVarArgs, UncoveredArg);
8125 
8126     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
8127                                                   S.getLangOpts(),
8128                                                   S.Context.getTargetInfo(),
8129                                             Type == Sema::FST_FreeBSDKPrintf))
8130       H.DoneProcessing();
8131   } else if (Type == Sema::FST_Scanf) {
8132     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
8133                         numDataArgs, Str, HasVAListArg, Args, format_idx,
8134                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
8135 
8136     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
8137                                                  S.getLangOpts(),
8138                                                  S.Context.getTargetInfo()))
8139       H.DoneProcessing();
8140   } // TODO: handle other formats
8141 }
8142 
8143 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
8144   // Str - The format string.  NOTE: this is NOT null-terminated!
8145   StringRef StrRef = FExpr->getString();
8146   const char *Str = StrRef.data();
8147   // Account for cases where the string literal is truncated in a declaration.
8148   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
8149   assert(T && "String literal not of constant array type!");
8150   size_t TypeSize = T->getSize().getZExtValue();
8151   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8152   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
8153                                                          getLangOpts(),
8154                                                          Context.getTargetInfo());
8155 }
8156 
8157 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
8158 
8159 // Returns the related absolute value function that is larger, of 0 if one
8160 // does not exist.
8161 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
8162   switch (AbsFunction) {
8163   default:
8164     return 0;
8165 
8166   case Builtin::BI__builtin_abs:
8167     return Builtin::BI__builtin_labs;
8168   case Builtin::BI__builtin_labs:
8169     return Builtin::BI__builtin_llabs;
8170   case Builtin::BI__builtin_llabs:
8171     return 0;
8172 
8173   case Builtin::BI__builtin_fabsf:
8174     return Builtin::BI__builtin_fabs;
8175   case Builtin::BI__builtin_fabs:
8176     return Builtin::BI__builtin_fabsl;
8177   case Builtin::BI__builtin_fabsl:
8178     return 0;
8179 
8180   case Builtin::BI__builtin_cabsf:
8181     return Builtin::BI__builtin_cabs;
8182   case Builtin::BI__builtin_cabs:
8183     return Builtin::BI__builtin_cabsl;
8184   case Builtin::BI__builtin_cabsl:
8185     return 0;
8186 
8187   case Builtin::BIabs:
8188     return Builtin::BIlabs;
8189   case Builtin::BIlabs:
8190     return Builtin::BIllabs;
8191   case Builtin::BIllabs:
8192     return 0;
8193 
8194   case Builtin::BIfabsf:
8195     return Builtin::BIfabs;
8196   case Builtin::BIfabs:
8197     return Builtin::BIfabsl;
8198   case Builtin::BIfabsl:
8199     return 0;
8200 
8201   case Builtin::BIcabsf:
8202    return Builtin::BIcabs;
8203   case Builtin::BIcabs:
8204     return Builtin::BIcabsl;
8205   case Builtin::BIcabsl:
8206     return 0;
8207   }
8208 }
8209 
8210 // Returns the argument type of the absolute value function.
8211 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
8212                                              unsigned AbsType) {
8213   if (AbsType == 0)
8214     return QualType();
8215 
8216   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
8217   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
8218   if (Error != ASTContext::GE_None)
8219     return QualType();
8220 
8221   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
8222   if (!FT)
8223     return QualType();
8224 
8225   if (FT->getNumParams() != 1)
8226     return QualType();
8227 
8228   return FT->getParamType(0);
8229 }
8230 
8231 // Returns the best absolute value function, or zero, based on type and
8232 // current absolute value function.
8233 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
8234                                    unsigned AbsFunctionKind) {
8235   unsigned BestKind = 0;
8236   uint64_t ArgSize = Context.getTypeSize(ArgType);
8237   for (unsigned Kind = AbsFunctionKind; Kind != 0;
8238        Kind = getLargerAbsoluteValueFunction(Kind)) {
8239     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
8240     if (Context.getTypeSize(ParamType) >= ArgSize) {
8241       if (BestKind == 0)
8242         BestKind = Kind;
8243       else if (Context.hasSameType(ParamType, ArgType)) {
8244         BestKind = Kind;
8245         break;
8246       }
8247     }
8248   }
8249   return BestKind;
8250 }
8251 
8252 enum AbsoluteValueKind {
8253   AVK_Integer,
8254   AVK_Floating,
8255   AVK_Complex
8256 };
8257 
8258 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
8259   if (T->isIntegralOrEnumerationType())
8260     return AVK_Integer;
8261   if (T->isRealFloatingType())
8262     return AVK_Floating;
8263   if (T->isAnyComplexType())
8264     return AVK_Complex;
8265 
8266   llvm_unreachable("Type not integer, floating, or complex");
8267 }
8268 
8269 // Changes the absolute value function to a different type.  Preserves whether
8270 // the function is a builtin.
8271 static unsigned changeAbsFunction(unsigned AbsKind,
8272                                   AbsoluteValueKind ValueKind) {
8273   switch (ValueKind) {
8274   case AVK_Integer:
8275     switch (AbsKind) {
8276     default:
8277       return 0;
8278     case Builtin::BI__builtin_fabsf:
8279     case Builtin::BI__builtin_fabs:
8280     case Builtin::BI__builtin_fabsl:
8281     case Builtin::BI__builtin_cabsf:
8282     case Builtin::BI__builtin_cabs:
8283     case Builtin::BI__builtin_cabsl:
8284       return Builtin::BI__builtin_abs;
8285     case Builtin::BIfabsf:
8286     case Builtin::BIfabs:
8287     case Builtin::BIfabsl:
8288     case Builtin::BIcabsf:
8289     case Builtin::BIcabs:
8290     case Builtin::BIcabsl:
8291       return Builtin::BIabs;
8292     }
8293   case AVK_Floating:
8294     switch (AbsKind) {
8295     default:
8296       return 0;
8297     case Builtin::BI__builtin_abs:
8298     case Builtin::BI__builtin_labs:
8299     case Builtin::BI__builtin_llabs:
8300     case Builtin::BI__builtin_cabsf:
8301     case Builtin::BI__builtin_cabs:
8302     case Builtin::BI__builtin_cabsl:
8303       return Builtin::BI__builtin_fabsf;
8304     case Builtin::BIabs:
8305     case Builtin::BIlabs:
8306     case Builtin::BIllabs:
8307     case Builtin::BIcabsf:
8308     case Builtin::BIcabs:
8309     case Builtin::BIcabsl:
8310       return Builtin::BIfabsf;
8311     }
8312   case AVK_Complex:
8313     switch (AbsKind) {
8314     default:
8315       return 0;
8316     case Builtin::BI__builtin_abs:
8317     case Builtin::BI__builtin_labs:
8318     case Builtin::BI__builtin_llabs:
8319     case Builtin::BI__builtin_fabsf:
8320     case Builtin::BI__builtin_fabs:
8321     case Builtin::BI__builtin_fabsl:
8322       return Builtin::BI__builtin_cabsf;
8323     case Builtin::BIabs:
8324     case Builtin::BIlabs:
8325     case Builtin::BIllabs:
8326     case Builtin::BIfabsf:
8327     case Builtin::BIfabs:
8328     case Builtin::BIfabsl:
8329       return Builtin::BIcabsf;
8330     }
8331   }
8332   llvm_unreachable("Unable to convert function");
8333 }
8334 
8335 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
8336   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
8337   if (!FnInfo)
8338     return 0;
8339 
8340   switch (FDecl->getBuiltinID()) {
8341   default:
8342     return 0;
8343   case Builtin::BI__builtin_abs:
8344   case Builtin::BI__builtin_fabs:
8345   case Builtin::BI__builtin_fabsf:
8346   case Builtin::BI__builtin_fabsl:
8347   case Builtin::BI__builtin_labs:
8348   case Builtin::BI__builtin_llabs:
8349   case Builtin::BI__builtin_cabs:
8350   case Builtin::BI__builtin_cabsf:
8351   case Builtin::BI__builtin_cabsl:
8352   case Builtin::BIabs:
8353   case Builtin::BIlabs:
8354   case Builtin::BIllabs:
8355   case Builtin::BIfabs:
8356   case Builtin::BIfabsf:
8357   case Builtin::BIfabsl:
8358   case Builtin::BIcabs:
8359   case Builtin::BIcabsf:
8360   case Builtin::BIcabsl:
8361     return FDecl->getBuiltinID();
8362   }
8363   llvm_unreachable("Unknown Builtin type");
8364 }
8365 
8366 // If the replacement is valid, emit a note with replacement function.
8367 // Additionally, suggest including the proper header if not already included.
8368 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
8369                             unsigned AbsKind, QualType ArgType) {
8370   bool EmitHeaderHint = true;
8371   const char *HeaderName = nullptr;
8372   const char *FunctionName = nullptr;
8373   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
8374     FunctionName = "std::abs";
8375     if (ArgType->isIntegralOrEnumerationType()) {
8376       HeaderName = "cstdlib";
8377     } else if (ArgType->isRealFloatingType()) {
8378       HeaderName = "cmath";
8379     } else {
8380       llvm_unreachable("Invalid Type");
8381     }
8382 
8383     // Lookup all std::abs
8384     if (NamespaceDecl *Std = S.getStdNamespace()) {
8385       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
8386       R.suppressDiagnostics();
8387       S.LookupQualifiedName(R, Std);
8388 
8389       for (const auto *I : R) {
8390         const FunctionDecl *FDecl = nullptr;
8391         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
8392           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
8393         } else {
8394           FDecl = dyn_cast<FunctionDecl>(I);
8395         }
8396         if (!FDecl)
8397           continue;
8398 
8399         // Found std::abs(), check that they are the right ones.
8400         if (FDecl->getNumParams() != 1)
8401           continue;
8402 
8403         // Check that the parameter type can handle the argument.
8404         QualType ParamType = FDecl->getParamDecl(0)->getType();
8405         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
8406             S.Context.getTypeSize(ArgType) <=
8407                 S.Context.getTypeSize(ParamType)) {
8408           // Found a function, don't need the header hint.
8409           EmitHeaderHint = false;
8410           break;
8411         }
8412       }
8413     }
8414   } else {
8415     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
8416     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
8417 
8418     if (HeaderName) {
8419       DeclarationName DN(&S.Context.Idents.get(FunctionName));
8420       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
8421       R.suppressDiagnostics();
8422       S.LookupName(R, S.getCurScope());
8423 
8424       if (R.isSingleResult()) {
8425         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
8426         if (FD && FD->getBuiltinID() == AbsKind) {
8427           EmitHeaderHint = false;
8428         } else {
8429           return;
8430         }
8431       } else if (!R.empty()) {
8432         return;
8433       }
8434     }
8435   }
8436 
8437   S.Diag(Loc, diag::note_replace_abs_function)
8438       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
8439 
8440   if (!HeaderName)
8441     return;
8442 
8443   if (!EmitHeaderHint)
8444     return;
8445 
8446   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
8447                                                     << FunctionName;
8448 }
8449 
8450 template <std::size_t StrLen>
8451 static bool IsStdFunction(const FunctionDecl *FDecl,
8452                           const char (&Str)[StrLen]) {
8453   if (!FDecl)
8454     return false;
8455   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
8456     return false;
8457   if (!FDecl->isInStdNamespace())
8458     return false;
8459 
8460   return true;
8461 }
8462 
8463 // Warn when using the wrong abs() function.
8464 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
8465                                       const FunctionDecl *FDecl) {
8466   if (Call->getNumArgs() != 1)
8467     return;
8468 
8469   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
8470   bool IsStdAbs = IsStdFunction(FDecl, "abs");
8471   if (AbsKind == 0 && !IsStdAbs)
8472     return;
8473 
8474   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
8475   QualType ParamType = Call->getArg(0)->getType();
8476 
8477   // Unsigned types cannot be negative.  Suggest removing the absolute value
8478   // function call.
8479   if (ArgType->isUnsignedIntegerType()) {
8480     const char *FunctionName =
8481         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
8482     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
8483     Diag(Call->getExprLoc(), diag::note_remove_abs)
8484         << FunctionName
8485         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
8486     return;
8487   }
8488 
8489   // Taking the absolute value of a pointer is very suspicious, they probably
8490   // wanted to index into an array, dereference a pointer, call a function, etc.
8491   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
8492     unsigned DiagType = 0;
8493     if (ArgType->isFunctionType())
8494       DiagType = 1;
8495     else if (ArgType->isArrayType())
8496       DiagType = 2;
8497 
8498     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
8499     return;
8500   }
8501 
8502   // std::abs has overloads which prevent most of the absolute value problems
8503   // from occurring.
8504   if (IsStdAbs)
8505     return;
8506 
8507   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
8508   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
8509 
8510   // The argument and parameter are the same kind.  Check if they are the right
8511   // size.
8512   if (ArgValueKind == ParamValueKind) {
8513     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
8514       return;
8515 
8516     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
8517     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
8518         << FDecl << ArgType << ParamType;
8519 
8520     if (NewAbsKind == 0)
8521       return;
8522 
8523     emitReplacement(*this, Call->getExprLoc(),
8524                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
8525     return;
8526   }
8527 
8528   // ArgValueKind != ParamValueKind
8529   // The wrong type of absolute value function was used.  Attempt to find the
8530   // proper one.
8531   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
8532   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
8533   if (NewAbsKind == 0)
8534     return;
8535 
8536   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
8537       << FDecl << ParamValueKind << ArgValueKind;
8538 
8539   emitReplacement(*this, Call->getExprLoc(),
8540                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
8541 }
8542 
8543 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
8544 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
8545                                 const FunctionDecl *FDecl) {
8546   if (!Call || !FDecl) return;
8547 
8548   // Ignore template specializations and macros.
8549   if (inTemplateInstantiation()) return;
8550   if (Call->getExprLoc().isMacroID()) return;
8551 
8552   // Only care about the one template argument, two function parameter std::max
8553   if (Call->getNumArgs() != 2) return;
8554   if (!IsStdFunction(FDecl, "max")) return;
8555   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
8556   if (!ArgList) return;
8557   if (ArgList->size() != 1) return;
8558 
8559   // Check that template type argument is unsigned integer.
8560   const auto& TA = ArgList->get(0);
8561   if (TA.getKind() != TemplateArgument::Type) return;
8562   QualType ArgType = TA.getAsType();
8563   if (!ArgType->isUnsignedIntegerType()) return;
8564 
8565   // See if either argument is a literal zero.
8566   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
8567     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
8568     if (!MTE) return false;
8569     const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
8570     if (!Num) return false;
8571     if (Num->getValue() != 0) return false;
8572     return true;
8573   };
8574 
8575   const Expr *FirstArg = Call->getArg(0);
8576   const Expr *SecondArg = Call->getArg(1);
8577   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
8578   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
8579 
8580   // Only warn when exactly one argument is zero.
8581   if (IsFirstArgZero == IsSecondArgZero) return;
8582 
8583   SourceRange FirstRange = FirstArg->getSourceRange();
8584   SourceRange SecondRange = SecondArg->getSourceRange();
8585 
8586   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
8587 
8588   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
8589       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
8590 
8591   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
8592   SourceRange RemovalRange;
8593   if (IsFirstArgZero) {
8594     RemovalRange = SourceRange(FirstRange.getBegin(),
8595                                SecondRange.getBegin().getLocWithOffset(-1));
8596   } else {
8597     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
8598                                SecondRange.getEnd());
8599   }
8600 
8601   Diag(Call->getExprLoc(), diag::note_remove_max_call)
8602         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
8603         << FixItHint::CreateRemoval(RemovalRange);
8604 }
8605 
8606 //===--- CHECK: Standard memory functions ---------------------------------===//
8607 
8608 /// Takes the expression passed to the size_t parameter of functions
8609 /// such as memcmp, strncat, etc and warns if it's a comparison.
8610 ///
8611 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
8612 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
8613                                            IdentifierInfo *FnName,
8614                                            SourceLocation FnLoc,
8615                                            SourceLocation RParenLoc) {
8616   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
8617   if (!Size)
8618     return false;
8619 
8620   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
8621   if (!Size->isComparisonOp() && !Size->isLogicalOp())
8622     return false;
8623 
8624   SourceRange SizeRange = Size->getSourceRange();
8625   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
8626       << SizeRange << FnName;
8627   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
8628       << FnName
8629       << FixItHint::CreateInsertion(
8630              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
8631       << FixItHint::CreateRemoval(RParenLoc);
8632   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
8633       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
8634       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
8635                                     ")");
8636 
8637   return true;
8638 }
8639 
8640 /// Determine whether the given type is or contains a dynamic class type
8641 /// (e.g., whether it has a vtable).
8642 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
8643                                                      bool &IsContained) {
8644   // Look through array types while ignoring qualifiers.
8645   const Type *Ty = T->getBaseElementTypeUnsafe();
8646   IsContained = false;
8647 
8648   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
8649   RD = RD ? RD->getDefinition() : nullptr;
8650   if (!RD || RD->isInvalidDecl())
8651     return nullptr;
8652 
8653   if (RD->isDynamicClass())
8654     return RD;
8655 
8656   // Check all the fields.  If any bases were dynamic, the class is dynamic.
8657   // It's impossible for a class to transitively contain itself by value, so
8658   // infinite recursion is impossible.
8659   for (auto *FD : RD->fields()) {
8660     bool SubContained;
8661     if (const CXXRecordDecl *ContainedRD =
8662             getContainedDynamicClass(FD->getType(), SubContained)) {
8663       IsContained = true;
8664       return ContainedRD;
8665     }
8666   }
8667 
8668   return nullptr;
8669 }
8670 
8671 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
8672   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
8673     if (Unary->getKind() == UETT_SizeOf)
8674       return Unary;
8675   return nullptr;
8676 }
8677 
8678 /// If E is a sizeof expression, returns its argument expression,
8679 /// otherwise returns NULL.
8680 static const Expr *getSizeOfExprArg(const Expr *E) {
8681   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
8682     if (!SizeOf->isArgumentType())
8683       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
8684   return nullptr;
8685 }
8686 
8687 /// If E is a sizeof expression, returns its argument type.
8688 static QualType getSizeOfArgType(const Expr *E) {
8689   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
8690     return SizeOf->getTypeOfArgument();
8691   return QualType();
8692 }
8693 
8694 namespace {
8695 
8696 struct SearchNonTrivialToInitializeField
8697     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
8698   using Super =
8699       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
8700 
8701   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
8702 
8703   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
8704                      SourceLocation SL) {
8705     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
8706       asDerived().visitArray(PDIK, AT, SL);
8707       return;
8708     }
8709 
8710     Super::visitWithKind(PDIK, FT, SL);
8711   }
8712 
8713   void visitARCStrong(QualType FT, SourceLocation SL) {
8714     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
8715   }
8716   void visitARCWeak(QualType FT, SourceLocation SL) {
8717     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
8718   }
8719   void visitStruct(QualType FT, SourceLocation SL) {
8720     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
8721       visit(FD->getType(), FD->getLocation());
8722   }
8723   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
8724                   const ArrayType *AT, SourceLocation SL) {
8725     visit(getContext().getBaseElementType(AT), SL);
8726   }
8727   void visitTrivial(QualType FT, SourceLocation SL) {}
8728 
8729   static void diag(QualType RT, const Expr *E, Sema &S) {
8730     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
8731   }
8732 
8733   ASTContext &getContext() { return S.getASTContext(); }
8734 
8735   const Expr *E;
8736   Sema &S;
8737 };
8738 
8739 struct SearchNonTrivialToCopyField
8740     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
8741   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
8742 
8743   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
8744 
8745   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
8746                      SourceLocation SL) {
8747     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
8748       asDerived().visitArray(PCK, AT, SL);
8749       return;
8750     }
8751 
8752     Super::visitWithKind(PCK, FT, SL);
8753   }
8754 
8755   void visitARCStrong(QualType FT, SourceLocation SL) {
8756     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
8757   }
8758   void visitARCWeak(QualType FT, SourceLocation SL) {
8759     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
8760   }
8761   void visitStruct(QualType FT, SourceLocation SL) {
8762     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
8763       visit(FD->getType(), FD->getLocation());
8764   }
8765   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
8766                   SourceLocation SL) {
8767     visit(getContext().getBaseElementType(AT), SL);
8768   }
8769   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
8770                 SourceLocation SL) {}
8771   void visitTrivial(QualType FT, SourceLocation SL) {}
8772   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
8773 
8774   static void diag(QualType RT, const Expr *E, Sema &S) {
8775     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
8776   }
8777 
8778   ASTContext &getContext() { return S.getASTContext(); }
8779 
8780   const Expr *E;
8781   Sema &S;
8782 };
8783 
8784 }
8785 
8786 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
8787 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
8788   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
8789 
8790   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
8791     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
8792       return false;
8793 
8794     return doesExprLikelyComputeSize(BO->getLHS()) ||
8795            doesExprLikelyComputeSize(BO->getRHS());
8796   }
8797 
8798   return getAsSizeOfExpr(SizeofExpr) != nullptr;
8799 }
8800 
8801 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
8802 ///
8803 /// \code
8804 ///   #define MACRO 0
8805 ///   foo(MACRO);
8806 ///   foo(0);
8807 /// \endcode
8808 ///
8809 /// This should return true for the first call to foo, but not for the second
8810 /// (regardless of whether foo is a macro or function).
8811 static bool isArgumentExpandedFromMacro(SourceManager &SM,
8812                                         SourceLocation CallLoc,
8813                                         SourceLocation ArgLoc) {
8814   if (!CallLoc.isMacroID())
8815     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
8816 
8817   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
8818          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
8819 }
8820 
8821 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
8822 /// last two arguments transposed.
8823 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
8824   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
8825     return;
8826 
8827   const Expr *SizeArg =
8828     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
8829 
8830   auto isLiteralZero = [](const Expr *E) {
8831     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
8832   };
8833 
8834   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
8835   SourceLocation CallLoc = Call->getRParenLoc();
8836   SourceManager &SM = S.getSourceManager();
8837   if (isLiteralZero(SizeArg) &&
8838       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
8839 
8840     SourceLocation DiagLoc = SizeArg->getExprLoc();
8841 
8842     // Some platforms #define bzero to __builtin_memset. See if this is the
8843     // case, and if so, emit a better diagnostic.
8844     if (BId == Builtin::BIbzero ||
8845         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
8846                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
8847       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
8848       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
8849     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
8850       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
8851       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
8852     }
8853     return;
8854   }
8855 
8856   // If the second argument to a memset is a sizeof expression and the third
8857   // isn't, this is also likely an error. This should catch
8858   // 'memset(buf, sizeof(buf), 0xff)'.
8859   if (BId == Builtin::BImemset &&
8860       doesExprLikelyComputeSize(Call->getArg(1)) &&
8861       !doesExprLikelyComputeSize(Call->getArg(2))) {
8862     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
8863     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
8864     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
8865     return;
8866   }
8867 }
8868 
8869 /// Check for dangerous or invalid arguments to memset().
8870 ///
8871 /// This issues warnings on known problematic, dangerous or unspecified
8872 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
8873 /// function calls.
8874 ///
8875 /// \param Call The call expression to diagnose.
8876 void Sema::CheckMemaccessArguments(const CallExpr *Call,
8877                                    unsigned BId,
8878                                    IdentifierInfo *FnName) {
8879   assert(BId != 0);
8880 
8881   // It is possible to have a non-standard definition of memset.  Validate
8882   // we have enough arguments, and if not, abort further checking.
8883   unsigned ExpectedNumArgs =
8884       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
8885   if (Call->getNumArgs() < ExpectedNumArgs)
8886     return;
8887 
8888   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
8889                       BId == Builtin::BIstrndup ? 1 : 2);
8890   unsigned LenArg =
8891       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
8892   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
8893 
8894   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
8895                                      Call->getBeginLoc(), Call->getRParenLoc()))
8896     return;
8897 
8898   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
8899   CheckMemaccessSize(*this, BId, Call);
8900 
8901   // We have special checking when the length is a sizeof expression.
8902   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
8903   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
8904   llvm::FoldingSetNodeID SizeOfArgID;
8905 
8906   // Although widely used, 'bzero' is not a standard function. Be more strict
8907   // with the argument types before allowing diagnostics and only allow the
8908   // form bzero(ptr, sizeof(...)).
8909   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
8910   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
8911     return;
8912 
8913   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
8914     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
8915     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
8916 
8917     QualType DestTy = Dest->getType();
8918     QualType PointeeTy;
8919     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
8920       PointeeTy = DestPtrTy->getPointeeType();
8921 
8922       // Never warn about void type pointers. This can be used to suppress
8923       // false positives.
8924       if (PointeeTy->isVoidType())
8925         continue;
8926 
8927       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
8928       // actually comparing the expressions for equality. Because computing the
8929       // expression IDs can be expensive, we only do this if the diagnostic is
8930       // enabled.
8931       if (SizeOfArg &&
8932           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
8933                            SizeOfArg->getExprLoc())) {
8934         // We only compute IDs for expressions if the warning is enabled, and
8935         // cache the sizeof arg's ID.
8936         if (SizeOfArgID == llvm::FoldingSetNodeID())
8937           SizeOfArg->Profile(SizeOfArgID, Context, true);
8938         llvm::FoldingSetNodeID DestID;
8939         Dest->Profile(DestID, Context, true);
8940         if (DestID == SizeOfArgID) {
8941           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
8942           //       over sizeof(src) as well.
8943           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
8944           StringRef ReadableName = FnName->getName();
8945 
8946           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
8947             if (UnaryOp->getOpcode() == UO_AddrOf)
8948               ActionIdx = 1; // If its an address-of operator, just remove it.
8949           if (!PointeeTy->isIncompleteType() &&
8950               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
8951             ActionIdx = 2; // If the pointee's size is sizeof(char),
8952                            // suggest an explicit length.
8953 
8954           // If the function is defined as a builtin macro, do not show macro
8955           // expansion.
8956           SourceLocation SL = SizeOfArg->getExprLoc();
8957           SourceRange DSR = Dest->getSourceRange();
8958           SourceRange SSR = SizeOfArg->getSourceRange();
8959           SourceManager &SM = getSourceManager();
8960 
8961           if (SM.isMacroArgExpansion(SL)) {
8962             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
8963             SL = SM.getSpellingLoc(SL);
8964             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
8965                              SM.getSpellingLoc(DSR.getEnd()));
8966             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
8967                              SM.getSpellingLoc(SSR.getEnd()));
8968           }
8969 
8970           DiagRuntimeBehavior(SL, SizeOfArg,
8971                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
8972                                 << ReadableName
8973                                 << PointeeTy
8974                                 << DestTy
8975                                 << DSR
8976                                 << SSR);
8977           DiagRuntimeBehavior(SL, SizeOfArg,
8978                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
8979                                 << ActionIdx
8980                                 << SSR);
8981 
8982           break;
8983         }
8984       }
8985 
8986       // Also check for cases where the sizeof argument is the exact same
8987       // type as the memory argument, and where it points to a user-defined
8988       // record type.
8989       if (SizeOfArgTy != QualType()) {
8990         if (PointeeTy->isRecordType() &&
8991             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
8992           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
8993                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
8994                                 << FnName << SizeOfArgTy << ArgIdx
8995                                 << PointeeTy << Dest->getSourceRange()
8996                                 << LenExpr->getSourceRange());
8997           break;
8998         }
8999       }
9000     } else if (DestTy->isArrayType()) {
9001       PointeeTy = DestTy;
9002     }
9003 
9004     if (PointeeTy == QualType())
9005       continue;
9006 
9007     // Always complain about dynamic classes.
9008     bool IsContained;
9009     if (const CXXRecordDecl *ContainedRD =
9010             getContainedDynamicClass(PointeeTy, IsContained)) {
9011 
9012       unsigned OperationType = 0;
9013       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
9014       // "overwritten" if we're warning about the destination for any call
9015       // but memcmp; otherwise a verb appropriate to the call.
9016       if (ArgIdx != 0 || IsCmp) {
9017         if (BId == Builtin::BImemcpy)
9018           OperationType = 1;
9019         else if(BId == Builtin::BImemmove)
9020           OperationType = 2;
9021         else if (IsCmp)
9022           OperationType = 3;
9023       }
9024 
9025       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9026                           PDiag(diag::warn_dyn_class_memaccess)
9027                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
9028                               << IsContained << ContainedRD << OperationType
9029                               << Call->getCallee()->getSourceRange());
9030     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
9031              BId != Builtin::BImemset)
9032       DiagRuntimeBehavior(
9033         Dest->getExprLoc(), Dest,
9034         PDiag(diag::warn_arc_object_memaccess)
9035           << ArgIdx << FnName << PointeeTy
9036           << Call->getCallee()->getSourceRange());
9037     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
9038       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
9039           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
9040         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9041                             PDiag(diag::warn_cstruct_memaccess)
9042                                 << ArgIdx << FnName << PointeeTy << 0);
9043         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
9044       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
9045                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
9046         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9047                             PDiag(diag::warn_cstruct_memaccess)
9048                                 << ArgIdx << FnName << PointeeTy << 1);
9049         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
9050       } else {
9051         continue;
9052       }
9053     } else
9054       continue;
9055 
9056     DiagRuntimeBehavior(
9057       Dest->getExprLoc(), Dest,
9058       PDiag(diag::note_bad_memaccess_silence)
9059         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
9060     break;
9061   }
9062 }
9063 
9064 // A little helper routine: ignore addition and subtraction of integer literals.
9065 // This intentionally does not ignore all integer constant expressions because
9066 // we don't want to remove sizeof().
9067 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
9068   Ex = Ex->IgnoreParenCasts();
9069 
9070   while (true) {
9071     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
9072     if (!BO || !BO->isAdditiveOp())
9073       break;
9074 
9075     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
9076     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
9077 
9078     if (isa<IntegerLiteral>(RHS))
9079       Ex = LHS;
9080     else if (isa<IntegerLiteral>(LHS))
9081       Ex = RHS;
9082     else
9083       break;
9084   }
9085 
9086   return Ex;
9087 }
9088 
9089 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
9090                                                       ASTContext &Context) {
9091   // Only handle constant-sized or VLAs, but not flexible members.
9092   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
9093     // Only issue the FIXIT for arrays of size > 1.
9094     if (CAT->getSize().getSExtValue() <= 1)
9095       return false;
9096   } else if (!Ty->isVariableArrayType()) {
9097     return false;
9098   }
9099   return true;
9100 }
9101 
9102 // Warn if the user has made the 'size' argument to strlcpy or strlcat
9103 // be the size of the source, instead of the destination.
9104 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
9105                                     IdentifierInfo *FnName) {
9106 
9107   // Don't crash if the user has the wrong number of arguments
9108   unsigned NumArgs = Call->getNumArgs();
9109   if ((NumArgs != 3) && (NumArgs != 4))
9110     return;
9111 
9112   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
9113   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
9114   const Expr *CompareWithSrc = nullptr;
9115 
9116   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
9117                                      Call->getBeginLoc(), Call->getRParenLoc()))
9118     return;
9119 
9120   // Look for 'strlcpy(dst, x, sizeof(x))'
9121   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
9122     CompareWithSrc = Ex;
9123   else {
9124     // Look for 'strlcpy(dst, x, strlen(x))'
9125     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
9126       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
9127           SizeCall->getNumArgs() == 1)
9128         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
9129     }
9130   }
9131 
9132   if (!CompareWithSrc)
9133     return;
9134 
9135   // Determine if the argument to sizeof/strlen is equal to the source
9136   // argument.  In principle there's all kinds of things you could do
9137   // here, for instance creating an == expression and evaluating it with
9138   // EvaluateAsBooleanCondition, but this uses a more direct technique:
9139   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
9140   if (!SrcArgDRE)
9141     return;
9142 
9143   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
9144   if (!CompareWithSrcDRE ||
9145       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
9146     return;
9147 
9148   const Expr *OriginalSizeArg = Call->getArg(2);
9149   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
9150       << OriginalSizeArg->getSourceRange() << FnName;
9151 
9152   // Output a FIXIT hint if the destination is an array (rather than a
9153   // pointer to an array).  This could be enhanced to handle some
9154   // pointers if we know the actual size, like if DstArg is 'array+2'
9155   // we could say 'sizeof(array)-2'.
9156   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
9157   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
9158     return;
9159 
9160   SmallString<128> sizeString;
9161   llvm::raw_svector_ostream OS(sizeString);
9162   OS << "sizeof(";
9163   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9164   OS << ")";
9165 
9166   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
9167       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
9168                                       OS.str());
9169 }
9170 
9171 /// Check if two expressions refer to the same declaration.
9172 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
9173   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
9174     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
9175       return D1->getDecl() == D2->getDecl();
9176   return false;
9177 }
9178 
9179 static const Expr *getStrlenExprArg(const Expr *E) {
9180   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
9181     const FunctionDecl *FD = CE->getDirectCallee();
9182     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
9183       return nullptr;
9184     return CE->getArg(0)->IgnoreParenCasts();
9185   }
9186   return nullptr;
9187 }
9188 
9189 // Warn on anti-patterns as the 'size' argument to strncat.
9190 // The correct size argument should look like following:
9191 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
9192 void Sema::CheckStrncatArguments(const CallExpr *CE,
9193                                  IdentifierInfo *FnName) {
9194   // Don't crash if the user has the wrong number of arguments.
9195   if (CE->getNumArgs() < 3)
9196     return;
9197   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
9198   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
9199   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
9200 
9201   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
9202                                      CE->getRParenLoc()))
9203     return;
9204 
9205   // Identify common expressions, which are wrongly used as the size argument
9206   // to strncat and may lead to buffer overflows.
9207   unsigned PatternType = 0;
9208   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
9209     // - sizeof(dst)
9210     if (referToTheSameDecl(SizeOfArg, DstArg))
9211       PatternType = 1;
9212     // - sizeof(src)
9213     else if (referToTheSameDecl(SizeOfArg, SrcArg))
9214       PatternType = 2;
9215   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
9216     if (BE->getOpcode() == BO_Sub) {
9217       const Expr *L = BE->getLHS()->IgnoreParenCasts();
9218       const Expr *R = BE->getRHS()->IgnoreParenCasts();
9219       // - sizeof(dst) - strlen(dst)
9220       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
9221           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
9222         PatternType = 1;
9223       // - sizeof(src) - (anything)
9224       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
9225         PatternType = 2;
9226     }
9227   }
9228 
9229   if (PatternType == 0)
9230     return;
9231 
9232   // Generate the diagnostic.
9233   SourceLocation SL = LenArg->getBeginLoc();
9234   SourceRange SR = LenArg->getSourceRange();
9235   SourceManager &SM = getSourceManager();
9236 
9237   // If the function is defined as a builtin macro, do not show macro expansion.
9238   if (SM.isMacroArgExpansion(SL)) {
9239     SL = SM.getSpellingLoc(SL);
9240     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
9241                      SM.getSpellingLoc(SR.getEnd()));
9242   }
9243 
9244   // Check if the destination is an array (rather than a pointer to an array).
9245   QualType DstTy = DstArg->getType();
9246   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
9247                                                                     Context);
9248   if (!isKnownSizeArray) {
9249     if (PatternType == 1)
9250       Diag(SL, diag::warn_strncat_wrong_size) << SR;
9251     else
9252       Diag(SL, diag::warn_strncat_src_size) << SR;
9253     return;
9254   }
9255 
9256   if (PatternType == 1)
9257     Diag(SL, diag::warn_strncat_large_size) << SR;
9258   else
9259     Diag(SL, diag::warn_strncat_src_size) << SR;
9260 
9261   SmallString<128> sizeString;
9262   llvm::raw_svector_ostream OS(sizeString);
9263   OS << "sizeof(";
9264   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9265   OS << ") - ";
9266   OS << "strlen(";
9267   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9268   OS << ") - 1";
9269 
9270   Diag(SL, diag::note_strncat_wrong_size)
9271     << FixItHint::CreateReplacement(SR, OS.str());
9272 }
9273 
9274 void
9275 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
9276                          SourceLocation ReturnLoc,
9277                          bool isObjCMethod,
9278                          const AttrVec *Attrs,
9279                          const FunctionDecl *FD) {
9280   // Check if the return value is null but should not be.
9281   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
9282        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
9283       CheckNonNullExpr(*this, RetValExp))
9284     Diag(ReturnLoc, diag::warn_null_ret)
9285       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
9286 
9287   // C++11 [basic.stc.dynamic.allocation]p4:
9288   //   If an allocation function declared with a non-throwing
9289   //   exception-specification fails to allocate storage, it shall return
9290   //   a null pointer. Any other allocation function that fails to allocate
9291   //   storage shall indicate failure only by throwing an exception [...]
9292   if (FD) {
9293     OverloadedOperatorKind Op = FD->getOverloadedOperator();
9294     if (Op == OO_New || Op == OO_Array_New) {
9295       const FunctionProtoType *Proto
9296         = FD->getType()->castAs<FunctionProtoType>();
9297       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
9298           CheckNonNullExpr(*this, RetValExp))
9299         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
9300           << FD << getLangOpts().CPlusPlus11;
9301     }
9302   }
9303 }
9304 
9305 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
9306 
9307 /// Check for comparisons of floating point operands using != and ==.
9308 /// Issue a warning if these are no self-comparisons, as they are not likely
9309 /// to do what the programmer intended.
9310 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
9311   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
9312   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
9313 
9314   // Special case: check for x == x (which is OK).
9315   // Do not emit warnings for such cases.
9316   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
9317     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
9318       if (DRL->getDecl() == DRR->getDecl())
9319         return;
9320 
9321   // Special case: check for comparisons against literals that can be exactly
9322   //  represented by APFloat.  In such cases, do not emit a warning.  This
9323   //  is a heuristic: often comparison against such literals are used to
9324   //  detect if a value in a variable has not changed.  This clearly can
9325   //  lead to false negatives.
9326   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
9327     if (FLL->isExact())
9328       return;
9329   } else
9330     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
9331       if (FLR->isExact())
9332         return;
9333 
9334   // Check for comparisons with builtin types.
9335   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
9336     if (CL->getBuiltinCallee())
9337       return;
9338 
9339   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
9340     if (CR->getBuiltinCallee())
9341       return;
9342 
9343   // Emit the diagnostic.
9344   Diag(Loc, diag::warn_floatingpoint_eq)
9345     << LHS->getSourceRange() << RHS->getSourceRange();
9346 }
9347 
9348 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
9349 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
9350 
9351 namespace {
9352 
9353 /// Structure recording the 'active' range of an integer-valued
9354 /// expression.
9355 struct IntRange {
9356   /// The number of bits active in the int.
9357   unsigned Width;
9358 
9359   /// True if the int is known not to have negative values.
9360   bool NonNegative;
9361 
9362   IntRange(unsigned Width, bool NonNegative)
9363       : Width(Width), NonNegative(NonNegative) {}
9364 
9365   /// Returns the range of the bool type.
9366   static IntRange forBoolType() {
9367     return IntRange(1, true);
9368   }
9369 
9370   /// Returns the range of an opaque value of the given integral type.
9371   static IntRange forValueOfType(ASTContext &C, QualType T) {
9372     return forValueOfCanonicalType(C,
9373                           T->getCanonicalTypeInternal().getTypePtr());
9374   }
9375 
9376   /// Returns the range of an opaque value of a canonical integral type.
9377   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
9378     assert(T->isCanonicalUnqualified());
9379 
9380     if (const VectorType *VT = dyn_cast<VectorType>(T))
9381       T = VT->getElementType().getTypePtr();
9382     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
9383       T = CT->getElementType().getTypePtr();
9384     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
9385       T = AT->getValueType().getTypePtr();
9386 
9387     if (!C.getLangOpts().CPlusPlus) {
9388       // For enum types in C code, use the underlying datatype.
9389       if (const EnumType *ET = dyn_cast<EnumType>(T))
9390         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
9391     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
9392       // For enum types in C++, use the known bit width of the enumerators.
9393       EnumDecl *Enum = ET->getDecl();
9394       // In C++11, enums can have a fixed underlying type. Use this type to
9395       // compute the range.
9396       if (Enum->isFixed()) {
9397         return IntRange(C.getIntWidth(QualType(T, 0)),
9398                         !ET->isSignedIntegerOrEnumerationType());
9399       }
9400 
9401       unsigned NumPositive = Enum->getNumPositiveBits();
9402       unsigned NumNegative = Enum->getNumNegativeBits();
9403 
9404       if (NumNegative == 0)
9405         return IntRange(NumPositive, true/*NonNegative*/);
9406       else
9407         return IntRange(std::max(NumPositive + 1, NumNegative),
9408                         false/*NonNegative*/);
9409     }
9410 
9411     const BuiltinType *BT = cast<BuiltinType>(T);
9412     assert(BT->isInteger());
9413 
9414     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
9415   }
9416 
9417   /// Returns the "target" range of a canonical integral type, i.e.
9418   /// the range of values expressible in the type.
9419   ///
9420   /// This matches forValueOfCanonicalType except that enums have the
9421   /// full range of their type, not the range of their enumerators.
9422   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
9423     assert(T->isCanonicalUnqualified());
9424 
9425     if (const VectorType *VT = dyn_cast<VectorType>(T))
9426       T = VT->getElementType().getTypePtr();
9427     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
9428       T = CT->getElementType().getTypePtr();
9429     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
9430       T = AT->getValueType().getTypePtr();
9431     if (const EnumType *ET = dyn_cast<EnumType>(T))
9432       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
9433 
9434     const BuiltinType *BT = cast<BuiltinType>(T);
9435     assert(BT->isInteger());
9436 
9437     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
9438   }
9439 
9440   /// Returns the supremum of two ranges: i.e. their conservative merge.
9441   static IntRange join(IntRange L, IntRange R) {
9442     return IntRange(std::max(L.Width, R.Width),
9443                     L.NonNegative && R.NonNegative);
9444   }
9445 
9446   /// Returns the infinum of two ranges: i.e. their aggressive merge.
9447   static IntRange meet(IntRange L, IntRange R) {
9448     return IntRange(std::min(L.Width, R.Width),
9449                     L.NonNegative || R.NonNegative);
9450   }
9451 };
9452 
9453 } // namespace
9454 
9455 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
9456                               unsigned MaxWidth) {
9457   if (value.isSigned() && value.isNegative())
9458     return IntRange(value.getMinSignedBits(), false);
9459 
9460   if (value.getBitWidth() > MaxWidth)
9461     value = value.trunc(MaxWidth);
9462 
9463   // isNonNegative() just checks the sign bit without considering
9464   // signedness.
9465   return IntRange(value.getActiveBits(), true);
9466 }
9467 
9468 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
9469                               unsigned MaxWidth) {
9470   if (result.isInt())
9471     return GetValueRange(C, result.getInt(), MaxWidth);
9472 
9473   if (result.isVector()) {
9474     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
9475     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
9476       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
9477       R = IntRange::join(R, El);
9478     }
9479     return R;
9480   }
9481 
9482   if (result.isComplexInt()) {
9483     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
9484     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
9485     return IntRange::join(R, I);
9486   }
9487 
9488   // This can happen with lossless casts to intptr_t of "based" lvalues.
9489   // Assume it might use arbitrary bits.
9490   // FIXME: The only reason we need to pass the type in here is to get
9491   // the sign right on this one case.  It would be nice if APValue
9492   // preserved this.
9493   assert(result.isLValue() || result.isAddrLabelDiff());
9494   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
9495 }
9496 
9497 static QualType GetExprType(const Expr *E) {
9498   QualType Ty = E->getType();
9499   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
9500     Ty = AtomicRHS->getValueType();
9501   return Ty;
9502 }
9503 
9504 /// Pseudo-evaluate the given integer expression, estimating the
9505 /// range of values it might take.
9506 ///
9507 /// \param MaxWidth - the width to which the value will be truncated
9508 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
9509                              bool InConstantContext) {
9510   E = E->IgnoreParens();
9511 
9512   // Try a full evaluation first.
9513   Expr::EvalResult result;
9514   if (E->EvaluateAsRValue(result, C, InConstantContext))
9515     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
9516 
9517   // I think we only want to look through implicit casts here; if the
9518   // user has an explicit widening cast, we should treat the value as
9519   // being of the new, wider type.
9520   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
9521     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
9522       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext);
9523 
9524     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
9525 
9526     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
9527                          CE->getCastKind() == CK_BooleanToSignedIntegral;
9528 
9529     // Assume that non-integer casts can span the full range of the type.
9530     if (!isIntegerCast)
9531       return OutputTypeRange;
9532 
9533     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
9534                                      std::min(MaxWidth, OutputTypeRange.Width),
9535                                      InConstantContext);
9536 
9537     // Bail out if the subexpr's range is as wide as the cast type.
9538     if (SubRange.Width >= OutputTypeRange.Width)
9539       return OutputTypeRange;
9540 
9541     // Otherwise, we take the smaller width, and we're non-negative if
9542     // either the output type or the subexpr is.
9543     return IntRange(SubRange.Width,
9544                     SubRange.NonNegative || OutputTypeRange.NonNegative);
9545   }
9546 
9547   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
9548     // If we can fold the condition, just take that operand.
9549     bool CondResult;
9550     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
9551       return GetExprRange(C,
9552                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
9553                           MaxWidth, InConstantContext);
9554 
9555     // Otherwise, conservatively merge.
9556     IntRange L =
9557         GetExprRange(C, CO->getTrueExpr(), MaxWidth, InConstantContext);
9558     IntRange R =
9559         GetExprRange(C, CO->getFalseExpr(), MaxWidth, InConstantContext);
9560     return IntRange::join(L, R);
9561   }
9562 
9563   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
9564     switch (BO->getOpcode()) {
9565     case BO_Cmp:
9566       llvm_unreachable("builtin <=> should have class type");
9567 
9568     // Boolean-valued operations are single-bit and positive.
9569     case BO_LAnd:
9570     case BO_LOr:
9571     case BO_LT:
9572     case BO_GT:
9573     case BO_LE:
9574     case BO_GE:
9575     case BO_EQ:
9576     case BO_NE:
9577       return IntRange::forBoolType();
9578 
9579     // The type of the assignments is the type of the LHS, so the RHS
9580     // is not necessarily the same type.
9581     case BO_MulAssign:
9582     case BO_DivAssign:
9583     case BO_RemAssign:
9584     case BO_AddAssign:
9585     case BO_SubAssign:
9586     case BO_XorAssign:
9587     case BO_OrAssign:
9588       // TODO: bitfields?
9589       return IntRange::forValueOfType(C, GetExprType(E));
9590 
9591     // Simple assignments just pass through the RHS, which will have
9592     // been coerced to the LHS type.
9593     case BO_Assign:
9594       // TODO: bitfields?
9595       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
9596 
9597     // Operations with opaque sources are black-listed.
9598     case BO_PtrMemD:
9599     case BO_PtrMemI:
9600       return IntRange::forValueOfType(C, GetExprType(E));
9601 
9602     // Bitwise-and uses the *infinum* of the two source ranges.
9603     case BO_And:
9604     case BO_AndAssign:
9605       return IntRange::meet(
9606           GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext),
9607           GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext));
9608 
9609     // Left shift gets black-listed based on a judgement call.
9610     case BO_Shl:
9611       // ...except that we want to treat '1 << (blah)' as logically
9612       // positive.  It's an important idiom.
9613       if (IntegerLiteral *I
9614             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
9615         if (I->getValue() == 1) {
9616           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
9617           return IntRange(R.Width, /*NonNegative*/ true);
9618         }
9619       }
9620       LLVM_FALLTHROUGH;
9621 
9622     case BO_ShlAssign:
9623       return IntRange::forValueOfType(C, GetExprType(E));
9624 
9625     // Right shift by a constant can narrow its left argument.
9626     case BO_Shr:
9627     case BO_ShrAssign: {
9628       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext);
9629 
9630       // If the shift amount is a positive constant, drop the width by
9631       // that much.
9632       llvm::APSInt shift;
9633       if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
9634           shift.isNonNegative()) {
9635         unsigned zext = shift.getZExtValue();
9636         if (zext >= L.Width)
9637           L.Width = (L.NonNegative ? 0 : 1);
9638         else
9639           L.Width -= zext;
9640       }
9641 
9642       return L;
9643     }
9644 
9645     // Comma acts as its right operand.
9646     case BO_Comma:
9647       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
9648 
9649     // Black-list pointer subtractions.
9650     case BO_Sub:
9651       if (BO->getLHS()->getType()->isPointerType())
9652         return IntRange::forValueOfType(C, GetExprType(E));
9653       break;
9654 
9655     // The width of a division result is mostly determined by the size
9656     // of the LHS.
9657     case BO_Div: {
9658       // Don't 'pre-truncate' the operands.
9659       unsigned opWidth = C.getIntWidth(GetExprType(E));
9660       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext);
9661 
9662       // If the divisor is constant, use that.
9663       llvm::APSInt divisor;
9664       if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
9665         unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
9666         if (log2 >= L.Width)
9667           L.Width = (L.NonNegative ? 0 : 1);
9668         else
9669           L.Width = std::min(L.Width - log2, MaxWidth);
9670         return L;
9671       }
9672 
9673       // Otherwise, just use the LHS's width.
9674       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext);
9675       return IntRange(L.Width, L.NonNegative && R.NonNegative);
9676     }
9677 
9678     // The result of a remainder can't be larger than the result of
9679     // either side.
9680     case BO_Rem: {
9681       // Don't 'pre-truncate' the operands.
9682       unsigned opWidth = C.getIntWidth(GetExprType(E));
9683       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext);
9684       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext);
9685 
9686       IntRange meet = IntRange::meet(L, R);
9687       meet.Width = std::min(meet.Width, MaxWidth);
9688       return meet;
9689     }
9690 
9691     // The default behavior is okay for these.
9692     case BO_Mul:
9693     case BO_Add:
9694     case BO_Xor:
9695     case BO_Or:
9696       break;
9697     }
9698 
9699     // The default case is to treat the operation as if it were closed
9700     // on the narrowest type that encompasses both operands.
9701     IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext);
9702     IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
9703     return IntRange::join(L, R);
9704   }
9705 
9706   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
9707     switch (UO->getOpcode()) {
9708     // Boolean-valued operations are white-listed.
9709     case UO_LNot:
9710       return IntRange::forBoolType();
9711 
9712     // Operations with opaque sources are black-listed.
9713     case UO_Deref:
9714     case UO_AddrOf: // should be impossible
9715       return IntRange::forValueOfType(C, GetExprType(E));
9716 
9717     default:
9718       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext);
9719     }
9720   }
9721 
9722   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
9723     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext);
9724 
9725   if (const auto *BitField = E->getSourceBitField())
9726     return IntRange(BitField->getBitWidthValue(C),
9727                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
9728 
9729   return IntRange::forValueOfType(C, GetExprType(E));
9730 }
9731 
9732 static IntRange GetExprRange(ASTContext &C, const Expr *E,
9733                              bool InConstantContext) {
9734   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext);
9735 }
9736 
9737 /// Checks whether the given value, which currently has the given
9738 /// source semantics, has the same value when coerced through the
9739 /// target semantics.
9740 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
9741                                  const llvm::fltSemantics &Src,
9742                                  const llvm::fltSemantics &Tgt) {
9743   llvm::APFloat truncated = value;
9744 
9745   bool ignored;
9746   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
9747   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
9748 
9749   return truncated.bitwiseIsEqual(value);
9750 }
9751 
9752 /// Checks whether the given value, which currently has the given
9753 /// source semantics, has the same value when coerced through the
9754 /// target semantics.
9755 ///
9756 /// The value might be a vector of floats (or a complex number).
9757 static bool IsSameFloatAfterCast(const APValue &value,
9758                                  const llvm::fltSemantics &Src,
9759                                  const llvm::fltSemantics &Tgt) {
9760   if (value.isFloat())
9761     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
9762 
9763   if (value.isVector()) {
9764     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
9765       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
9766         return false;
9767     return true;
9768   }
9769 
9770   assert(value.isComplexFloat());
9771   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
9772           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
9773 }
9774 
9775 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
9776                                        bool IsListInit = false);
9777 
9778 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
9779   // Suppress cases where we are comparing against an enum constant.
9780   if (const DeclRefExpr *DR =
9781       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
9782     if (isa<EnumConstantDecl>(DR->getDecl()))
9783       return true;
9784 
9785   // Suppress cases where the value is expanded from a macro, unless that macro
9786   // is how a language represents a boolean literal. This is the case in both C
9787   // and Objective-C.
9788   SourceLocation BeginLoc = E->getBeginLoc();
9789   if (BeginLoc.isMacroID()) {
9790     StringRef MacroName = Lexer::getImmediateMacroName(
9791         BeginLoc, S.getSourceManager(), S.getLangOpts());
9792     return MacroName != "YES" && MacroName != "NO" &&
9793            MacroName != "true" && MacroName != "false";
9794   }
9795 
9796   return false;
9797 }
9798 
9799 static bool isKnownToHaveUnsignedValue(Expr *E) {
9800   return E->getType()->isIntegerType() &&
9801          (!E->getType()->isSignedIntegerType() ||
9802           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
9803 }
9804 
9805 namespace {
9806 /// The promoted range of values of a type. In general this has the
9807 /// following structure:
9808 ///
9809 ///     |-----------| . . . |-----------|
9810 ///     ^           ^       ^           ^
9811 ///    Min       HoleMin  HoleMax      Max
9812 ///
9813 /// ... where there is only a hole if a signed type is promoted to unsigned
9814 /// (in which case Min and Max are the smallest and largest representable
9815 /// values).
9816 struct PromotedRange {
9817   // Min, or HoleMax if there is a hole.
9818   llvm::APSInt PromotedMin;
9819   // Max, or HoleMin if there is a hole.
9820   llvm::APSInt PromotedMax;
9821 
9822   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
9823     if (R.Width == 0)
9824       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
9825     else if (R.Width >= BitWidth && !Unsigned) {
9826       // Promotion made the type *narrower*. This happens when promoting
9827       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
9828       // Treat all values of 'signed int' as being in range for now.
9829       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
9830       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
9831     } else {
9832       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
9833                         .extOrTrunc(BitWidth);
9834       PromotedMin.setIsUnsigned(Unsigned);
9835 
9836       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
9837                         .extOrTrunc(BitWidth);
9838       PromotedMax.setIsUnsigned(Unsigned);
9839     }
9840   }
9841 
9842   // Determine whether this range is contiguous (has no hole).
9843   bool isContiguous() const { return PromotedMin <= PromotedMax; }
9844 
9845   // Where a constant value is within the range.
9846   enum ComparisonResult {
9847     LT = 0x1,
9848     LE = 0x2,
9849     GT = 0x4,
9850     GE = 0x8,
9851     EQ = 0x10,
9852     NE = 0x20,
9853     InRangeFlag = 0x40,
9854 
9855     Less = LE | LT | NE,
9856     Min = LE | InRangeFlag,
9857     InRange = InRangeFlag,
9858     Max = GE | InRangeFlag,
9859     Greater = GE | GT | NE,
9860 
9861     OnlyValue = LE | GE | EQ | InRangeFlag,
9862     InHole = NE
9863   };
9864 
9865   ComparisonResult compare(const llvm::APSInt &Value) const {
9866     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
9867            Value.isUnsigned() == PromotedMin.isUnsigned());
9868     if (!isContiguous()) {
9869       assert(Value.isUnsigned() && "discontiguous range for signed compare");
9870       if (Value.isMinValue()) return Min;
9871       if (Value.isMaxValue()) return Max;
9872       if (Value >= PromotedMin) return InRange;
9873       if (Value <= PromotedMax) return InRange;
9874       return InHole;
9875     }
9876 
9877     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
9878     case -1: return Less;
9879     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
9880     case 1:
9881       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
9882       case -1: return InRange;
9883       case 0: return Max;
9884       case 1: return Greater;
9885       }
9886     }
9887 
9888     llvm_unreachable("impossible compare result");
9889   }
9890 
9891   static llvm::Optional<StringRef>
9892   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
9893     if (Op == BO_Cmp) {
9894       ComparisonResult LTFlag = LT, GTFlag = GT;
9895       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
9896 
9897       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
9898       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
9899       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
9900       return llvm::None;
9901     }
9902 
9903     ComparisonResult TrueFlag, FalseFlag;
9904     if (Op == BO_EQ) {
9905       TrueFlag = EQ;
9906       FalseFlag = NE;
9907     } else if (Op == BO_NE) {
9908       TrueFlag = NE;
9909       FalseFlag = EQ;
9910     } else {
9911       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
9912         TrueFlag = LT;
9913         FalseFlag = GE;
9914       } else {
9915         TrueFlag = GT;
9916         FalseFlag = LE;
9917       }
9918       if (Op == BO_GE || Op == BO_LE)
9919         std::swap(TrueFlag, FalseFlag);
9920     }
9921     if (R & TrueFlag)
9922       return StringRef("true");
9923     if (R & FalseFlag)
9924       return StringRef("false");
9925     return llvm::None;
9926   }
9927 };
9928 }
9929 
9930 static bool HasEnumType(Expr *E) {
9931   // Strip off implicit integral promotions.
9932   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
9933     if (ICE->getCastKind() != CK_IntegralCast &&
9934         ICE->getCastKind() != CK_NoOp)
9935       break;
9936     E = ICE->getSubExpr();
9937   }
9938 
9939   return E->getType()->isEnumeralType();
9940 }
9941 
9942 static int classifyConstantValue(Expr *Constant) {
9943   // The values of this enumeration are used in the diagnostics
9944   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
9945   enum ConstantValueKind {
9946     Miscellaneous = 0,
9947     LiteralTrue,
9948     LiteralFalse
9949   };
9950   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
9951     return BL->getValue() ? ConstantValueKind::LiteralTrue
9952                           : ConstantValueKind::LiteralFalse;
9953   return ConstantValueKind::Miscellaneous;
9954 }
9955 
9956 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
9957                                         Expr *Constant, Expr *Other,
9958                                         const llvm::APSInt &Value,
9959                                         bool RhsConstant) {
9960   if (S.inTemplateInstantiation())
9961     return false;
9962 
9963   Expr *OriginalOther = Other;
9964 
9965   Constant = Constant->IgnoreParenImpCasts();
9966   Other = Other->IgnoreParenImpCasts();
9967 
9968   // Suppress warnings on tautological comparisons between values of the same
9969   // enumeration type. There are only two ways we could warn on this:
9970   //  - If the constant is outside the range of representable values of
9971   //    the enumeration. In such a case, we should warn about the cast
9972   //    to enumeration type, not about the comparison.
9973   //  - If the constant is the maximum / minimum in-range value. For an
9974   //    enumeratin type, such comparisons can be meaningful and useful.
9975   if (Constant->getType()->isEnumeralType() &&
9976       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
9977     return false;
9978 
9979   // TODO: Investigate using GetExprRange() to get tighter bounds
9980   // on the bit ranges.
9981   QualType OtherT = Other->getType();
9982   if (const auto *AT = OtherT->getAs<AtomicType>())
9983     OtherT = AT->getValueType();
9984   IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
9985 
9986   // Special case for ObjC BOOL on targets where its a typedef for a signed char
9987   // (Namely, macOS).
9988   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
9989                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
9990                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
9991 
9992   // Whether we're treating Other as being a bool because of the form of
9993   // expression despite it having another type (typically 'int' in C).
9994   bool OtherIsBooleanDespiteType =
9995       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
9996   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
9997     OtherRange = IntRange::forBoolType();
9998 
9999   // Determine the promoted range of the other type and see if a comparison of
10000   // the constant against that range is tautological.
10001   PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
10002                                    Value.isUnsigned());
10003   auto Cmp = OtherPromotedRange.compare(Value);
10004   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
10005   if (!Result)
10006     return false;
10007 
10008   // Suppress the diagnostic for an in-range comparison if the constant comes
10009   // from a macro or enumerator. We don't want to diagnose
10010   //
10011   //   some_long_value <= INT_MAX
10012   //
10013   // when sizeof(int) == sizeof(long).
10014   bool InRange = Cmp & PromotedRange::InRangeFlag;
10015   if (InRange && IsEnumConstOrFromMacro(S, Constant))
10016     return false;
10017 
10018   // If this is a comparison to an enum constant, include that
10019   // constant in the diagnostic.
10020   const EnumConstantDecl *ED = nullptr;
10021   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
10022     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
10023 
10024   // Should be enough for uint128 (39 decimal digits)
10025   SmallString<64> PrettySourceValue;
10026   llvm::raw_svector_ostream OS(PrettySourceValue);
10027   if (ED) {
10028     OS << '\'' << *ED << "' (" << Value << ")";
10029   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
10030                Constant->IgnoreParenImpCasts())) {
10031     OS << (BL->getValue() ? "YES" : "NO");
10032   } else {
10033     OS << Value;
10034   }
10035 
10036   if (IsObjCSignedCharBool) {
10037     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
10038                           S.PDiag(diag::warn_tautological_compare_objc_bool)
10039                               << OS.str() << *Result);
10040     return true;
10041   }
10042 
10043   // FIXME: We use a somewhat different formatting for the in-range cases and
10044   // cases involving boolean values for historical reasons. We should pick a
10045   // consistent way of presenting these diagnostics.
10046   if (!InRange || Other->isKnownToHaveBooleanValue()) {
10047 
10048     S.DiagRuntimeBehavior(
10049         E->getOperatorLoc(), E,
10050         S.PDiag(!InRange ? diag::warn_out_of_range_compare
10051                          : diag::warn_tautological_bool_compare)
10052             << OS.str() << classifyConstantValue(Constant) << OtherT
10053             << OtherIsBooleanDespiteType << *Result
10054             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
10055   } else {
10056     unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
10057                         ? (HasEnumType(OriginalOther)
10058                                ? diag::warn_unsigned_enum_always_true_comparison
10059                                : diag::warn_unsigned_always_true_comparison)
10060                         : diag::warn_tautological_constant_compare;
10061 
10062     S.Diag(E->getOperatorLoc(), Diag)
10063         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
10064         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
10065   }
10066 
10067   return true;
10068 }
10069 
10070 /// Analyze the operands of the given comparison.  Implements the
10071 /// fallback case from AnalyzeComparison.
10072 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
10073   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10074   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10075 }
10076 
10077 /// Implements -Wsign-compare.
10078 ///
10079 /// \param E the binary operator to check for warnings
10080 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
10081   // The type the comparison is being performed in.
10082   QualType T = E->getLHS()->getType();
10083 
10084   // Only analyze comparison operators where both sides have been converted to
10085   // the same type.
10086   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
10087     return AnalyzeImpConvsInComparison(S, E);
10088 
10089   // Don't analyze value-dependent comparisons directly.
10090   if (E->isValueDependent())
10091     return AnalyzeImpConvsInComparison(S, E);
10092 
10093   Expr *LHS = E->getLHS();
10094   Expr *RHS = E->getRHS();
10095 
10096   if (T->isIntegralType(S.Context)) {
10097     llvm::APSInt RHSValue;
10098     llvm::APSInt LHSValue;
10099 
10100     bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
10101     bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
10102 
10103     // We don't care about expressions whose result is a constant.
10104     if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
10105       return AnalyzeImpConvsInComparison(S, E);
10106 
10107     // We only care about expressions where just one side is literal
10108     if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
10109       // Is the constant on the RHS or LHS?
10110       const bool RhsConstant = IsRHSIntegralLiteral;
10111       Expr *Const = RhsConstant ? RHS : LHS;
10112       Expr *Other = RhsConstant ? LHS : RHS;
10113       const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
10114 
10115       // Check whether an integer constant comparison results in a value
10116       // of 'true' or 'false'.
10117       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
10118         return AnalyzeImpConvsInComparison(S, E);
10119     }
10120   }
10121 
10122   if (!T->hasUnsignedIntegerRepresentation()) {
10123     // We don't do anything special if this isn't an unsigned integral
10124     // comparison:  we're only interested in integral comparisons, and
10125     // signed comparisons only happen in cases we don't care to warn about.
10126     return AnalyzeImpConvsInComparison(S, E);
10127   }
10128 
10129   LHS = LHS->IgnoreParenImpCasts();
10130   RHS = RHS->IgnoreParenImpCasts();
10131 
10132   if (!S.getLangOpts().CPlusPlus) {
10133     // Avoid warning about comparison of integers with different signs when
10134     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
10135     // the type of `E`.
10136     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
10137       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10138     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
10139       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10140   }
10141 
10142   // Check to see if one of the (unmodified) operands is of different
10143   // signedness.
10144   Expr *signedOperand, *unsignedOperand;
10145   if (LHS->getType()->hasSignedIntegerRepresentation()) {
10146     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
10147            "unsigned comparison between two signed integer expressions?");
10148     signedOperand = LHS;
10149     unsignedOperand = RHS;
10150   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
10151     signedOperand = RHS;
10152     unsignedOperand = LHS;
10153   } else {
10154     return AnalyzeImpConvsInComparison(S, E);
10155   }
10156 
10157   // Otherwise, calculate the effective range of the signed operand.
10158   IntRange signedRange =
10159       GetExprRange(S.Context, signedOperand, S.isConstantEvaluated());
10160 
10161   // Go ahead and analyze implicit conversions in the operands.  Note
10162   // that we skip the implicit conversions on both sides.
10163   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
10164   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
10165 
10166   // If the signed range is non-negative, -Wsign-compare won't fire.
10167   if (signedRange.NonNegative)
10168     return;
10169 
10170   // For (in)equality comparisons, if the unsigned operand is a
10171   // constant which cannot collide with a overflowed signed operand,
10172   // then reinterpreting the signed operand as unsigned will not
10173   // change the result of the comparison.
10174   if (E->isEqualityOp()) {
10175     unsigned comparisonWidth = S.Context.getIntWidth(T);
10176     IntRange unsignedRange =
10177         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated());
10178 
10179     // We should never be unable to prove that the unsigned operand is
10180     // non-negative.
10181     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
10182 
10183     if (unsignedRange.Width < comparisonWidth)
10184       return;
10185   }
10186 
10187   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
10188                         S.PDiag(diag::warn_mixed_sign_comparison)
10189                             << LHS->getType() << RHS->getType()
10190                             << LHS->getSourceRange() << RHS->getSourceRange());
10191 }
10192 
10193 /// Analyzes an attempt to assign the given value to a bitfield.
10194 ///
10195 /// Returns true if there was something fishy about the attempt.
10196 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
10197                                       SourceLocation InitLoc) {
10198   assert(Bitfield->isBitField());
10199   if (Bitfield->isInvalidDecl())
10200     return false;
10201 
10202   // White-list bool bitfields.
10203   QualType BitfieldType = Bitfield->getType();
10204   if (BitfieldType->isBooleanType())
10205      return false;
10206 
10207   if (BitfieldType->isEnumeralType()) {
10208     EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
10209     // If the underlying enum type was not explicitly specified as an unsigned
10210     // type and the enum contain only positive values, MSVC++ will cause an
10211     // inconsistency by storing this as a signed type.
10212     if (S.getLangOpts().CPlusPlus11 &&
10213         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
10214         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
10215         BitfieldEnumDecl->getNumNegativeBits() == 0) {
10216       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
10217         << BitfieldEnumDecl->getNameAsString();
10218     }
10219   }
10220 
10221   if (Bitfield->getType()->isBooleanType())
10222     return false;
10223 
10224   // Ignore value- or type-dependent expressions.
10225   if (Bitfield->getBitWidth()->isValueDependent() ||
10226       Bitfield->getBitWidth()->isTypeDependent() ||
10227       Init->isValueDependent() ||
10228       Init->isTypeDependent())
10229     return false;
10230 
10231   Expr *OriginalInit = Init->IgnoreParenImpCasts();
10232   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
10233 
10234   Expr::EvalResult Result;
10235   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
10236                                    Expr::SE_AllowSideEffects)) {
10237     // The RHS is not constant.  If the RHS has an enum type, make sure the
10238     // bitfield is wide enough to hold all the values of the enum without
10239     // truncation.
10240     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
10241       EnumDecl *ED = EnumTy->getDecl();
10242       bool SignedBitfield = BitfieldType->isSignedIntegerType();
10243 
10244       // Enum types are implicitly signed on Windows, so check if there are any
10245       // negative enumerators to see if the enum was intended to be signed or
10246       // not.
10247       bool SignedEnum = ED->getNumNegativeBits() > 0;
10248 
10249       // Check for surprising sign changes when assigning enum values to a
10250       // bitfield of different signedness.  If the bitfield is signed and we
10251       // have exactly the right number of bits to store this unsigned enum,
10252       // suggest changing the enum to an unsigned type. This typically happens
10253       // on Windows where unfixed enums always use an underlying type of 'int'.
10254       unsigned DiagID = 0;
10255       if (SignedEnum && !SignedBitfield) {
10256         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
10257       } else if (SignedBitfield && !SignedEnum &&
10258                  ED->getNumPositiveBits() == FieldWidth) {
10259         DiagID = diag::warn_signed_bitfield_enum_conversion;
10260       }
10261 
10262       if (DiagID) {
10263         S.Diag(InitLoc, DiagID) << Bitfield << ED;
10264         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
10265         SourceRange TypeRange =
10266             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
10267         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
10268             << SignedEnum << TypeRange;
10269       }
10270 
10271       // Compute the required bitwidth. If the enum has negative values, we need
10272       // one more bit than the normal number of positive bits to represent the
10273       // sign bit.
10274       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
10275                                                   ED->getNumNegativeBits())
10276                                        : ED->getNumPositiveBits();
10277 
10278       // Check the bitwidth.
10279       if (BitsNeeded > FieldWidth) {
10280         Expr *WidthExpr = Bitfield->getBitWidth();
10281         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
10282             << Bitfield << ED;
10283         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
10284             << BitsNeeded << ED << WidthExpr->getSourceRange();
10285       }
10286     }
10287 
10288     return false;
10289   }
10290 
10291   llvm::APSInt Value = Result.Val.getInt();
10292 
10293   unsigned OriginalWidth = Value.getBitWidth();
10294 
10295   if (!Value.isSigned() || Value.isNegative())
10296     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
10297       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
10298         OriginalWidth = Value.getMinSignedBits();
10299 
10300   if (OriginalWidth <= FieldWidth)
10301     return false;
10302 
10303   // Compute the value which the bitfield will contain.
10304   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
10305   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
10306 
10307   // Check whether the stored value is equal to the original value.
10308   TruncatedValue = TruncatedValue.extend(OriginalWidth);
10309   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
10310     return false;
10311 
10312   // Special-case bitfields of width 1: booleans are naturally 0/1, and
10313   // therefore don't strictly fit into a signed bitfield of width 1.
10314   if (FieldWidth == 1 && Value == 1)
10315     return false;
10316 
10317   std::string PrettyValue = Value.toString(10);
10318   std::string PrettyTrunc = TruncatedValue.toString(10);
10319 
10320   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
10321     << PrettyValue << PrettyTrunc << OriginalInit->getType()
10322     << Init->getSourceRange();
10323 
10324   return true;
10325 }
10326 
10327 /// Analyze the given simple or compound assignment for warning-worthy
10328 /// operations.
10329 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
10330   // Just recurse on the LHS.
10331   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10332 
10333   // We want to recurse on the RHS as normal unless we're assigning to
10334   // a bitfield.
10335   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
10336     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
10337                                   E->getOperatorLoc())) {
10338       // Recurse, ignoring any implicit conversions on the RHS.
10339       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
10340                                         E->getOperatorLoc());
10341     }
10342   }
10343 
10344   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10345 
10346   // Diagnose implicitly sequentially-consistent atomic assignment.
10347   if (E->getLHS()->getType()->isAtomicType())
10348     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
10349 }
10350 
10351 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
10352 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
10353                             SourceLocation CContext, unsigned diag,
10354                             bool pruneControlFlow = false) {
10355   if (pruneControlFlow) {
10356     S.DiagRuntimeBehavior(E->getExprLoc(), E,
10357                           S.PDiag(diag)
10358                               << SourceType << T << E->getSourceRange()
10359                               << SourceRange(CContext));
10360     return;
10361   }
10362   S.Diag(E->getExprLoc(), diag)
10363     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
10364 }
10365 
10366 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
10367 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
10368                             SourceLocation CContext,
10369                             unsigned diag, bool pruneControlFlow = false) {
10370   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
10371 }
10372 
10373 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
10374   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
10375       S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
10376 }
10377 
10378 static void adornObjCBoolConversionDiagWithTernaryFixit(
10379     Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
10380   Expr *Ignored = SourceExpr->IgnoreImplicit();
10381   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
10382     Ignored = OVE->getSourceExpr();
10383   bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
10384                      isa<BinaryOperator>(Ignored) ||
10385                      isa<CXXOperatorCallExpr>(Ignored);
10386   SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
10387   if (NeedsParens)
10388     Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
10389             << FixItHint::CreateInsertion(EndLoc, ")");
10390   Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
10391 }
10392 
10393 /// Diagnose an implicit cast from a floating point value to an integer value.
10394 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
10395                                     SourceLocation CContext) {
10396   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
10397   const bool PruneWarnings = S.inTemplateInstantiation();
10398 
10399   Expr *InnerE = E->IgnoreParenImpCasts();
10400   // We also want to warn on, e.g., "int i = -1.234"
10401   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
10402     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
10403       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
10404 
10405   const bool IsLiteral =
10406       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
10407 
10408   llvm::APFloat Value(0.0);
10409   bool IsConstant =
10410     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
10411   if (!IsConstant) {
10412     if (isObjCSignedCharBool(S, T)) {
10413       return adornObjCBoolConversionDiagWithTernaryFixit(
10414           S, E,
10415           S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
10416               << E->getType());
10417     }
10418 
10419     return DiagnoseImpCast(S, E, T, CContext,
10420                            diag::warn_impcast_float_integer, PruneWarnings);
10421   }
10422 
10423   bool isExact = false;
10424 
10425   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
10426                             T->hasUnsignedIntegerRepresentation());
10427   llvm::APFloat::opStatus Result = Value.convertToInteger(
10428       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
10429 
10430   // FIXME: Force the precision of the source value down so we don't print
10431   // digits which are usually useless (we don't really care here if we
10432   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
10433   // would automatically print the shortest representation, but it's a bit
10434   // tricky to implement.
10435   SmallString<16> PrettySourceValue;
10436   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
10437   precision = (precision * 59 + 195) / 196;
10438   Value.toString(PrettySourceValue, precision);
10439 
10440   if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
10441     return adornObjCBoolConversionDiagWithTernaryFixit(
10442         S, E,
10443         S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
10444             << PrettySourceValue);
10445   }
10446 
10447   if (Result == llvm::APFloat::opOK && isExact) {
10448     if (IsLiteral) return;
10449     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
10450                            PruneWarnings);
10451   }
10452 
10453   // Conversion of a floating-point value to a non-bool integer where the
10454   // integral part cannot be represented by the integer type is undefined.
10455   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
10456     return DiagnoseImpCast(
10457         S, E, T, CContext,
10458         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
10459                   : diag::warn_impcast_float_to_integer_out_of_range,
10460         PruneWarnings);
10461 
10462   unsigned DiagID = 0;
10463   if (IsLiteral) {
10464     // Warn on floating point literal to integer.
10465     DiagID = diag::warn_impcast_literal_float_to_integer;
10466   } else if (IntegerValue == 0) {
10467     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
10468       return DiagnoseImpCast(S, E, T, CContext,
10469                              diag::warn_impcast_float_integer, PruneWarnings);
10470     }
10471     // Warn on non-zero to zero conversion.
10472     DiagID = diag::warn_impcast_float_to_integer_zero;
10473   } else {
10474     if (IntegerValue.isUnsigned()) {
10475       if (!IntegerValue.isMaxValue()) {
10476         return DiagnoseImpCast(S, E, T, CContext,
10477                                diag::warn_impcast_float_integer, PruneWarnings);
10478       }
10479     } else {  // IntegerValue.isSigned()
10480       if (!IntegerValue.isMaxSignedValue() &&
10481           !IntegerValue.isMinSignedValue()) {
10482         return DiagnoseImpCast(S, E, T, CContext,
10483                                diag::warn_impcast_float_integer, PruneWarnings);
10484       }
10485     }
10486     // Warn on evaluatable floating point expression to integer conversion.
10487     DiagID = diag::warn_impcast_float_to_integer;
10488   }
10489 
10490   SmallString<16> PrettyTargetValue;
10491   if (IsBool)
10492     PrettyTargetValue = Value.isZero() ? "false" : "true";
10493   else
10494     IntegerValue.toString(PrettyTargetValue);
10495 
10496   if (PruneWarnings) {
10497     S.DiagRuntimeBehavior(E->getExprLoc(), E,
10498                           S.PDiag(DiagID)
10499                               << E->getType() << T.getUnqualifiedType()
10500                               << PrettySourceValue << PrettyTargetValue
10501                               << E->getSourceRange() << SourceRange(CContext));
10502   } else {
10503     S.Diag(E->getExprLoc(), DiagID)
10504         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
10505         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
10506   }
10507 }
10508 
10509 /// Analyze the given compound assignment for the possible losing of
10510 /// floating-point precision.
10511 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
10512   assert(isa<CompoundAssignOperator>(E) &&
10513          "Must be compound assignment operation");
10514   // Recurse on the LHS and RHS in here
10515   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10516   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10517 
10518   if (E->getLHS()->getType()->isAtomicType())
10519     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
10520 
10521   // Now check the outermost expression
10522   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
10523   const auto *RBT = cast<CompoundAssignOperator>(E)
10524                         ->getComputationResultType()
10525                         ->getAs<BuiltinType>();
10526 
10527   // The below checks assume source is floating point.
10528   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
10529 
10530   // If source is floating point but target is an integer.
10531   if (ResultBT->isInteger())
10532     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
10533                            E->getExprLoc(), diag::warn_impcast_float_integer);
10534 
10535   if (!ResultBT->isFloatingPoint())
10536     return;
10537 
10538   // If both source and target are floating points, warn about losing precision.
10539   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
10540       QualType(ResultBT, 0), QualType(RBT, 0));
10541   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
10542     // warn about dropping FP rank.
10543     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
10544                     diag::warn_impcast_float_result_precision);
10545 }
10546 
10547 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
10548                                       IntRange Range) {
10549   if (!Range.Width) return "0";
10550 
10551   llvm::APSInt ValueInRange = Value;
10552   ValueInRange.setIsSigned(!Range.NonNegative);
10553   ValueInRange = ValueInRange.trunc(Range.Width);
10554   return ValueInRange.toString(10);
10555 }
10556 
10557 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
10558   if (!isa<ImplicitCastExpr>(Ex))
10559     return false;
10560 
10561   Expr *InnerE = Ex->IgnoreParenImpCasts();
10562   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
10563   const Type *Source =
10564     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
10565   if (Target->isDependentType())
10566     return false;
10567 
10568   const BuiltinType *FloatCandidateBT =
10569     dyn_cast<BuiltinType>(ToBool ? Source : Target);
10570   const Type *BoolCandidateType = ToBool ? Target : Source;
10571 
10572   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
10573           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
10574 }
10575 
10576 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
10577                                              SourceLocation CC) {
10578   unsigned NumArgs = TheCall->getNumArgs();
10579   for (unsigned i = 0; i < NumArgs; ++i) {
10580     Expr *CurrA = TheCall->getArg(i);
10581     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
10582       continue;
10583 
10584     bool IsSwapped = ((i > 0) &&
10585         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
10586     IsSwapped |= ((i < (NumArgs - 1)) &&
10587         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
10588     if (IsSwapped) {
10589       // Warn on this floating-point to bool conversion.
10590       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
10591                       CurrA->getType(), CC,
10592                       diag::warn_impcast_floating_point_to_bool);
10593     }
10594   }
10595 }
10596 
10597 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
10598                                    SourceLocation CC) {
10599   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
10600                         E->getExprLoc()))
10601     return;
10602 
10603   // Don't warn on functions which have return type nullptr_t.
10604   if (isa<CallExpr>(E))
10605     return;
10606 
10607   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
10608   const Expr::NullPointerConstantKind NullKind =
10609       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
10610   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
10611     return;
10612 
10613   // Return if target type is a safe conversion.
10614   if (T->isAnyPointerType() || T->isBlockPointerType() ||
10615       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
10616     return;
10617 
10618   SourceLocation Loc = E->getSourceRange().getBegin();
10619 
10620   // Venture through the macro stacks to get to the source of macro arguments.
10621   // The new location is a better location than the complete location that was
10622   // passed in.
10623   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
10624   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
10625 
10626   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
10627   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
10628     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
10629         Loc, S.SourceMgr, S.getLangOpts());
10630     if (MacroName == "NULL")
10631       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
10632   }
10633 
10634   // Only warn if the null and context location are in the same macro expansion.
10635   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
10636     return;
10637 
10638   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
10639       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
10640       << FixItHint::CreateReplacement(Loc,
10641                                       S.getFixItZeroLiteralForType(T, Loc));
10642 }
10643 
10644 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
10645                                   ObjCArrayLiteral *ArrayLiteral);
10646 
10647 static void
10648 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
10649                            ObjCDictionaryLiteral *DictionaryLiteral);
10650 
10651 /// Check a single element within a collection literal against the
10652 /// target element type.
10653 static void checkObjCCollectionLiteralElement(Sema &S,
10654                                               QualType TargetElementType,
10655                                               Expr *Element,
10656                                               unsigned ElementKind) {
10657   // Skip a bitcast to 'id' or qualified 'id'.
10658   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
10659     if (ICE->getCastKind() == CK_BitCast &&
10660         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
10661       Element = ICE->getSubExpr();
10662   }
10663 
10664   QualType ElementType = Element->getType();
10665   ExprResult ElementResult(Element);
10666   if (ElementType->getAs<ObjCObjectPointerType>() &&
10667       S.CheckSingleAssignmentConstraints(TargetElementType,
10668                                          ElementResult,
10669                                          false, false)
10670         != Sema::Compatible) {
10671     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
10672         << ElementType << ElementKind << TargetElementType
10673         << Element->getSourceRange();
10674   }
10675 
10676   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
10677     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
10678   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
10679     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
10680 }
10681 
10682 /// Check an Objective-C array literal being converted to the given
10683 /// target type.
10684 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
10685                                   ObjCArrayLiteral *ArrayLiteral) {
10686   if (!S.NSArrayDecl)
10687     return;
10688 
10689   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
10690   if (!TargetObjCPtr)
10691     return;
10692 
10693   if (TargetObjCPtr->isUnspecialized() ||
10694       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
10695         != S.NSArrayDecl->getCanonicalDecl())
10696     return;
10697 
10698   auto TypeArgs = TargetObjCPtr->getTypeArgs();
10699   if (TypeArgs.size() != 1)
10700     return;
10701 
10702   QualType TargetElementType = TypeArgs[0];
10703   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
10704     checkObjCCollectionLiteralElement(S, TargetElementType,
10705                                       ArrayLiteral->getElement(I),
10706                                       0);
10707   }
10708 }
10709 
10710 /// Check an Objective-C dictionary literal being converted to the given
10711 /// target type.
10712 static void
10713 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
10714                            ObjCDictionaryLiteral *DictionaryLiteral) {
10715   if (!S.NSDictionaryDecl)
10716     return;
10717 
10718   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
10719   if (!TargetObjCPtr)
10720     return;
10721 
10722   if (TargetObjCPtr->isUnspecialized() ||
10723       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
10724         != S.NSDictionaryDecl->getCanonicalDecl())
10725     return;
10726 
10727   auto TypeArgs = TargetObjCPtr->getTypeArgs();
10728   if (TypeArgs.size() != 2)
10729     return;
10730 
10731   QualType TargetKeyType = TypeArgs[0];
10732   QualType TargetObjectType = TypeArgs[1];
10733   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
10734     auto Element = DictionaryLiteral->getKeyValueElement(I);
10735     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
10736     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
10737   }
10738 }
10739 
10740 // Helper function to filter out cases for constant width constant conversion.
10741 // Don't warn on char array initialization or for non-decimal values.
10742 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
10743                                           SourceLocation CC) {
10744   // If initializing from a constant, and the constant starts with '0',
10745   // then it is a binary, octal, or hexadecimal.  Allow these constants
10746   // to fill all the bits, even if there is a sign change.
10747   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
10748     const char FirstLiteralCharacter =
10749         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
10750     if (FirstLiteralCharacter == '0')
10751       return false;
10752   }
10753 
10754   // If the CC location points to a '{', and the type is char, then assume
10755   // assume it is an array initialization.
10756   if (CC.isValid() && T->isCharType()) {
10757     const char FirstContextCharacter =
10758         S.getSourceManager().getCharacterData(CC)[0];
10759     if (FirstContextCharacter == '{')
10760       return false;
10761   }
10762 
10763   return true;
10764 }
10765 
10766 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
10767   const auto *IL = dyn_cast<IntegerLiteral>(E);
10768   if (!IL) {
10769     if (auto *UO = dyn_cast<UnaryOperator>(E)) {
10770       if (UO->getOpcode() == UO_Minus)
10771         return dyn_cast<IntegerLiteral>(UO->getSubExpr());
10772     }
10773   }
10774 
10775   return IL;
10776 }
10777 
10778 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
10779   E = E->IgnoreParenImpCasts();
10780   SourceLocation ExprLoc = E->getExprLoc();
10781 
10782   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
10783     BinaryOperator::Opcode Opc = BO->getOpcode();
10784     Expr::EvalResult Result;
10785     // Do not diagnose unsigned shifts.
10786     if (Opc == BO_Shl) {
10787       const auto *LHS = getIntegerLiteral(BO->getLHS());
10788       const auto *RHS = getIntegerLiteral(BO->getRHS());
10789       if (LHS && LHS->getValue() == 0)
10790         S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
10791       else if (!E->isValueDependent() && LHS && RHS &&
10792                RHS->getValue().isNonNegative() &&
10793                E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
10794         S.Diag(ExprLoc, diag::warn_left_shift_always)
10795             << (Result.Val.getInt() != 0);
10796       else if (E->getType()->isSignedIntegerType())
10797         S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
10798     }
10799   }
10800 
10801   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
10802     const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
10803     const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
10804     if (!LHS || !RHS)
10805       return;
10806     if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
10807         (RHS->getValue() == 0 || RHS->getValue() == 1))
10808       // Do not diagnose common idioms.
10809       return;
10810     if (LHS->getValue() != 0 && RHS->getValue() != 0)
10811       S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
10812   }
10813 }
10814 
10815 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
10816                                     SourceLocation CC,
10817                                     bool *ICContext = nullptr,
10818                                     bool IsListInit = false) {
10819   if (E->isTypeDependent() || E->isValueDependent()) return;
10820 
10821   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
10822   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
10823   if (Source == Target) return;
10824   if (Target->isDependentType()) return;
10825 
10826   // If the conversion context location is invalid don't complain. We also
10827   // don't want to emit a warning if the issue occurs from the expansion of
10828   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
10829   // delay this check as long as possible. Once we detect we are in that
10830   // scenario, we just return.
10831   if (CC.isInvalid())
10832     return;
10833 
10834   if (Source->isAtomicType())
10835     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
10836 
10837   // Diagnose implicit casts to bool.
10838   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
10839     if (isa<StringLiteral>(E))
10840       // Warn on string literal to bool.  Checks for string literals in logical
10841       // and expressions, for instance, assert(0 && "error here"), are
10842       // prevented by a check in AnalyzeImplicitConversions().
10843       return DiagnoseImpCast(S, E, T, CC,
10844                              diag::warn_impcast_string_literal_to_bool);
10845     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
10846         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
10847       // This covers the literal expressions that evaluate to Objective-C
10848       // objects.
10849       return DiagnoseImpCast(S, E, T, CC,
10850                              diag::warn_impcast_objective_c_literal_to_bool);
10851     }
10852     if (Source->isPointerType() || Source->canDecayToPointerType()) {
10853       // Warn on pointer to bool conversion that is always true.
10854       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
10855                                      SourceRange(CC));
10856     }
10857   }
10858 
10859   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
10860   // is a typedef for signed char (macOS), then that constant value has to be 1
10861   // or 0.
10862   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
10863     Expr::EvalResult Result;
10864     if (E->EvaluateAsInt(Result, S.getASTContext(),
10865                          Expr::SE_AllowSideEffects)) {
10866       if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
10867         adornObjCBoolConversionDiagWithTernaryFixit(
10868             S, E,
10869             S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
10870                 << Result.Val.getInt().toString(10));
10871       }
10872       return;
10873     }
10874   }
10875 
10876   // Check implicit casts from Objective-C collection literals to specialized
10877   // collection types, e.g., NSArray<NSString *> *.
10878   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
10879     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
10880   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
10881     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
10882 
10883   // Strip vector types.
10884   if (isa<VectorType>(Source)) {
10885     if (!isa<VectorType>(Target)) {
10886       if (S.SourceMgr.isInSystemMacro(CC))
10887         return;
10888       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
10889     }
10890 
10891     // If the vector cast is cast between two vectors of the same size, it is
10892     // a bitcast, not a conversion.
10893     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
10894       return;
10895 
10896     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
10897     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
10898   }
10899   if (auto VecTy = dyn_cast<VectorType>(Target))
10900     Target = VecTy->getElementType().getTypePtr();
10901 
10902   // Strip complex types.
10903   if (isa<ComplexType>(Source)) {
10904     if (!isa<ComplexType>(Target)) {
10905       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
10906         return;
10907 
10908       return DiagnoseImpCast(S, E, T, CC,
10909                              S.getLangOpts().CPlusPlus
10910                                  ? diag::err_impcast_complex_scalar
10911                                  : diag::warn_impcast_complex_scalar);
10912     }
10913 
10914     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
10915     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
10916   }
10917 
10918   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
10919   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
10920 
10921   // If the source is floating point...
10922   if (SourceBT && SourceBT->isFloatingPoint()) {
10923     // ...and the target is floating point...
10924     if (TargetBT && TargetBT->isFloatingPoint()) {
10925       // ...then warn if we're dropping FP rank.
10926 
10927       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
10928           QualType(SourceBT, 0), QualType(TargetBT, 0));
10929       if (Order > 0) {
10930         // Don't warn about float constants that are precisely
10931         // representable in the target type.
10932         Expr::EvalResult result;
10933         if (E->EvaluateAsRValue(result, S.Context)) {
10934           // Value might be a float, a float vector, or a float complex.
10935           if (IsSameFloatAfterCast(result.Val,
10936                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
10937                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
10938             return;
10939         }
10940 
10941         if (S.SourceMgr.isInSystemMacro(CC))
10942           return;
10943 
10944         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
10945       }
10946       // ... or possibly if we're increasing rank, too
10947       else if (Order < 0) {
10948         if (S.SourceMgr.isInSystemMacro(CC))
10949           return;
10950 
10951         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
10952       }
10953       return;
10954     }
10955 
10956     // If the target is integral, always warn.
10957     if (TargetBT && TargetBT->isInteger()) {
10958       if (S.SourceMgr.isInSystemMacro(CC))
10959         return;
10960 
10961       DiagnoseFloatingImpCast(S, E, T, CC);
10962     }
10963 
10964     // Detect the case where a call result is converted from floating-point to
10965     // to bool, and the final argument to the call is converted from bool, to
10966     // discover this typo:
10967     //
10968     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
10969     //
10970     // FIXME: This is an incredibly special case; is there some more general
10971     // way to detect this class of misplaced-parentheses bug?
10972     if (Target->isBooleanType() && isa<CallExpr>(E)) {
10973       // Check last argument of function call to see if it is an
10974       // implicit cast from a type matching the type the result
10975       // is being cast to.
10976       CallExpr *CEx = cast<CallExpr>(E);
10977       if (unsigned NumArgs = CEx->getNumArgs()) {
10978         Expr *LastA = CEx->getArg(NumArgs - 1);
10979         Expr *InnerE = LastA->IgnoreParenImpCasts();
10980         if (isa<ImplicitCastExpr>(LastA) &&
10981             InnerE->getType()->isBooleanType()) {
10982           // Warn on this floating-point to bool conversion
10983           DiagnoseImpCast(S, E, T, CC,
10984                           diag::warn_impcast_floating_point_to_bool);
10985         }
10986       }
10987     }
10988     return;
10989   }
10990 
10991   // Valid casts involving fixed point types should be accounted for here.
10992   if (Source->isFixedPointType()) {
10993     if (Target->isUnsaturatedFixedPointType()) {
10994       Expr::EvalResult Result;
10995       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
10996                                   S.isConstantEvaluated())) {
10997         APFixedPoint Value = Result.Val.getFixedPoint();
10998         APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
10999         APFixedPoint MinVal = S.Context.getFixedPointMin(T);
11000         if (Value > MaxVal || Value < MinVal) {
11001           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11002                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11003                                     << Value.toString() << T
11004                                     << E->getSourceRange()
11005                                     << clang::SourceRange(CC));
11006           return;
11007         }
11008       }
11009     } else if (Target->isIntegerType()) {
11010       Expr::EvalResult Result;
11011       if (!S.isConstantEvaluated() &&
11012           E->EvaluateAsFixedPoint(Result, S.Context,
11013                                   Expr::SE_AllowSideEffects)) {
11014         APFixedPoint FXResult = Result.Val.getFixedPoint();
11015 
11016         bool Overflowed;
11017         llvm::APSInt IntResult = FXResult.convertToInt(
11018             S.Context.getIntWidth(T),
11019             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
11020 
11021         if (Overflowed) {
11022           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11023                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11024                                     << FXResult.toString() << T
11025                                     << E->getSourceRange()
11026                                     << clang::SourceRange(CC));
11027           return;
11028         }
11029       }
11030     }
11031   } else if (Target->isUnsaturatedFixedPointType()) {
11032     if (Source->isIntegerType()) {
11033       Expr::EvalResult Result;
11034       if (!S.isConstantEvaluated() &&
11035           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
11036         llvm::APSInt Value = Result.Val.getInt();
11037 
11038         bool Overflowed;
11039         APFixedPoint IntResult = APFixedPoint::getFromIntValue(
11040             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
11041 
11042         if (Overflowed) {
11043           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11044                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11045                                     << Value.toString(/*Radix=*/10) << T
11046                                     << E->getSourceRange()
11047                                     << clang::SourceRange(CC));
11048           return;
11049         }
11050       }
11051     }
11052   }
11053 
11054   // If we are casting an integer type to a floating point type without
11055   // initialization-list syntax, we might lose accuracy if the floating
11056   // point type has a narrower significand than the integer type.
11057   if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
11058       TargetBT->isFloatingType() && !IsListInit) {
11059     // Determine the number of precision bits in the source integer type.
11060     IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated());
11061     unsigned int SourcePrecision = SourceRange.Width;
11062 
11063     // Determine the number of precision bits in the
11064     // target floating point type.
11065     unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
11066         S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
11067 
11068     if (SourcePrecision > 0 && TargetPrecision > 0 &&
11069         SourcePrecision > TargetPrecision) {
11070 
11071       llvm::APSInt SourceInt;
11072       if (E->isIntegerConstantExpr(SourceInt, S.Context)) {
11073         // If the source integer is a constant, convert it to the target
11074         // floating point type. Issue a warning if the value changes
11075         // during the whole conversion.
11076         llvm::APFloat TargetFloatValue(
11077             S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
11078         llvm::APFloat::opStatus ConversionStatus =
11079             TargetFloatValue.convertFromAPInt(
11080                 SourceInt, SourceBT->isSignedInteger(),
11081                 llvm::APFloat::rmNearestTiesToEven);
11082 
11083         if (ConversionStatus != llvm::APFloat::opOK) {
11084           std::string PrettySourceValue = SourceInt.toString(10);
11085           SmallString<32> PrettyTargetValue;
11086           TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
11087 
11088           S.DiagRuntimeBehavior(
11089               E->getExprLoc(), E,
11090               S.PDiag(diag::warn_impcast_integer_float_precision_constant)
11091                   << PrettySourceValue << PrettyTargetValue << E->getType() << T
11092                   << E->getSourceRange() << clang::SourceRange(CC));
11093         }
11094       } else {
11095         // Otherwise, the implicit conversion may lose precision.
11096         DiagnoseImpCast(S, E, T, CC,
11097                         diag::warn_impcast_integer_float_precision);
11098       }
11099     }
11100   }
11101 
11102   DiagnoseNullConversion(S, E, T, CC);
11103 
11104   S.DiscardMisalignedMemberAddress(Target, E);
11105 
11106   if (Target->isBooleanType())
11107     DiagnoseIntInBoolContext(S, E);
11108 
11109   if (!Source->isIntegerType() || !Target->isIntegerType())
11110     return;
11111 
11112   // TODO: remove this early return once the false positives for constant->bool
11113   // in templates, macros, etc, are reduced or removed.
11114   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
11115     return;
11116 
11117   if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
11118       !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
11119     return adornObjCBoolConversionDiagWithTernaryFixit(
11120         S, E,
11121         S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
11122             << E->getType());
11123   }
11124 
11125   IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated());
11126   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
11127 
11128   if (SourceRange.Width > TargetRange.Width) {
11129     // If the source is a constant, use a default-on diagnostic.
11130     // TODO: this should happen for bitfield stores, too.
11131     Expr::EvalResult Result;
11132     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
11133                          S.isConstantEvaluated())) {
11134       llvm::APSInt Value(32);
11135       Value = Result.Val.getInt();
11136 
11137       if (S.SourceMgr.isInSystemMacro(CC))
11138         return;
11139 
11140       std::string PrettySourceValue = Value.toString(10);
11141       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
11142 
11143       S.DiagRuntimeBehavior(
11144           E->getExprLoc(), E,
11145           S.PDiag(diag::warn_impcast_integer_precision_constant)
11146               << PrettySourceValue << PrettyTargetValue << E->getType() << T
11147               << E->getSourceRange() << clang::SourceRange(CC));
11148       return;
11149     }
11150 
11151     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
11152     if (S.SourceMgr.isInSystemMacro(CC))
11153       return;
11154 
11155     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
11156       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
11157                              /* pruneControlFlow */ true);
11158     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
11159   }
11160 
11161   if (TargetRange.Width > SourceRange.Width) {
11162     if (auto *UO = dyn_cast<UnaryOperator>(E))
11163       if (UO->getOpcode() == UO_Minus)
11164         if (Source->isUnsignedIntegerType()) {
11165           if (Target->isUnsignedIntegerType())
11166             return DiagnoseImpCast(S, E, T, CC,
11167                                    diag::warn_impcast_high_order_zero_bits);
11168           if (Target->isSignedIntegerType())
11169             return DiagnoseImpCast(S, E, T, CC,
11170                                    diag::warn_impcast_nonnegative_result);
11171         }
11172   }
11173 
11174   if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
11175       SourceRange.NonNegative && Source->isSignedIntegerType()) {
11176     // Warn when doing a signed to signed conversion, warn if the positive
11177     // source value is exactly the width of the target type, which will
11178     // cause a negative value to be stored.
11179 
11180     Expr::EvalResult Result;
11181     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
11182         !S.SourceMgr.isInSystemMacro(CC)) {
11183       llvm::APSInt Value = Result.Val.getInt();
11184       if (isSameWidthConstantConversion(S, E, T, CC)) {
11185         std::string PrettySourceValue = Value.toString(10);
11186         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
11187 
11188         S.DiagRuntimeBehavior(
11189             E->getExprLoc(), E,
11190             S.PDiag(diag::warn_impcast_integer_precision_constant)
11191                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
11192                 << E->getSourceRange() << clang::SourceRange(CC));
11193         return;
11194       }
11195     }
11196 
11197     // Fall through for non-constants to give a sign conversion warning.
11198   }
11199 
11200   if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
11201       (!TargetRange.NonNegative && SourceRange.NonNegative &&
11202        SourceRange.Width == TargetRange.Width)) {
11203     if (S.SourceMgr.isInSystemMacro(CC))
11204       return;
11205 
11206     unsigned DiagID = diag::warn_impcast_integer_sign;
11207 
11208     // Traditionally, gcc has warned about this under -Wsign-compare.
11209     // We also want to warn about it in -Wconversion.
11210     // So if -Wconversion is off, use a completely identical diagnostic
11211     // in the sign-compare group.
11212     // The conditional-checking code will
11213     if (ICContext) {
11214       DiagID = diag::warn_impcast_integer_sign_conditional;
11215       *ICContext = true;
11216     }
11217 
11218     return DiagnoseImpCast(S, E, T, CC, DiagID);
11219   }
11220 
11221   // Diagnose conversions between different enumeration types.
11222   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
11223   // type, to give us better diagnostics.
11224   QualType SourceType = E->getType();
11225   if (!S.getLangOpts().CPlusPlus) {
11226     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11227       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
11228         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
11229         SourceType = S.Context.getTypeDeclType(Enum);
11230         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
11231       }
11232   }
11233 
11234   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
11235     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
11236       if (SourceEnum->getDecl()->hasNameForLinkage() &&
11237           TargetEnum->getDecl()->hasNameForLinkage() &&
11238           SourceEnum != TargetEnum) {
11239         if (S.SourceMgr.isInSystemMacro(CC))
11240           return;
11241 
11242         return DiagnoseImpCast(S, E, SourceType, T, CC,
11243                                diag::warn_impcast_different_enum_types);
11244       }
11245 }
11246 
11247 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
11248                                      SourceLocation CC, QualType T);
11249 
11250 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
11251                                     SourceLocation CC, bool &ICContext) {
11252   E = E->IgnoreParenImpCasts();
11253 
11254   if (isa<ConditionalOperator>(E))
11255     return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
11256 
11257   AnalyzeImplicitConversions(S, E, CC);
11258   if (E->getType() != T)
11259     return CheckImplicitConversion(S, E, T, CC, &ICContext);
11260 }
11261 
11262 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
11263                                      SourceLocation CC, QualType T) {
11264   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
11265 
11266   bool Suspicious = false;
11267   CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
11268   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
11269 
11270   if (T->isBooleanType())
11271     DiagnoseIntInBoolContext(S, E);
11272 
11273   // If -Wconversion would have warned about either of the candidates
11274   // for a signedness conversion to the context type...
11275   if (!Suspicious) return;
11276 
11277   // ...but it's currently ignored...
11278   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
11279     return;
11280 
11281   // ...then check whether it would have warned about either of the
11282   // candidates for a signedness conversion to the condition type.
11283   if (E->getType() == T) return;
11284 
11285   Suspicious = false;
11286   CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
11287                           E->getType(), CC, &Suspicious);
11288   if (!Suspicious)
11289     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
11290                             E->getType(), CC, &Suspicious);
11291 }
11292 
11293 /// Check conversion of given expression to boolean.
11294 /// Input argument E is a logical expression.
11295 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
11296   if (S.getLangOpts().Bool)
11297     return;
11298   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
11299     return;
11300   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
11301 }
11302 
11303 /// AnalyzeImplicitConversions - Find and report any interesting
11304 /// implicit conversions in the given expression.  There are a couple
11305 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
11306 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
11307                                        bool IsListInit/*= false*/) {
11308   QualType T = OrigE->getType();
11309   Expr *E = OrigE->IgnoreParenImpCasts();
11310 
11311   // Propagate whether we are in a C++ list initialization expression.
11312   // If so, we do not issue warnings for implicit int-float conversion
11313   // precision loss, because C++11 narrowing already handles it.
11314   IsListInit =
11315       IsListInit || (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
11316 
11317   if (E->isTypeDependent() || E->isValueDependent())
11318     return;
11319 
11320   if (const auto *UO = dyn_cast<UnaryOperator>(E))
11321     if (UO->getOpcode() == UO_Not &&
11322         UO->getSubExpr()->isKnownToHaveBooleanValue())
11323       S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
11324           << OrigE->getSourceRange() << T->isBooleanType()
11325           << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
11326 
11327   // For conditional operators, we analyze the arguments as if they
11328   // were being fed directly into the output.
11329   if (isa<ConditionalOperator>(E)) {
11330     ConditionalOperator *CO = cast<ConditionalOperator>(E);
11331     CheckConditionalOperator(S, CO, CC, T);
11332     return;
11333   }
11334 
11335   // Check implicit argument conversions for function calls.
11336   if (CallExpr *Call = dyn_cast<CallExpr>(E))
11337     CheckImplicitArgumentConversions(S, Call, CC);
11338 
11339   // Go ahead and check any implicit conversions we might have skipped.
11340   // The non-canonical typecheck is just an optimization;
11341   // CheckImplicitConversion will filter out dead implicit conversions.
11342   if (E->getType() != T)
11343     CheckImplicitConversion(S, E, T, CC, nullptr, IsListInit);
11344 
11345   // Now continue drilling into this expression.
11346 
11347   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
11348     // The bound subexpressions in a PseudoObjectExpr are not reachable
11349     // as transitive children.
11350     // FIXME: Use a more uniform representation for this.
11351     for (auto *SE : POE->semantics())
11352       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
11353         AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC, IsListInit);
11354   }
11355 
11356   // Skip past explicit casts.
11357   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
11358     E = CE->getSubExpr()->IgnoreParenImpCasts();
11359     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
11360       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
11361     return AnalyzeImplicitConversions(S, E, CC, IsListInit);
11362   }
11363 
11364   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11365     // Do a somewhat different check with comparison operators.
11366     if (BO->isComparisonOp())
11367       return AnalyzeComparison(S, BO);
11368 
11369     // And with simple assignments.
11370     if (BO->getOpcode() == BO_Assign)
11371       return AnalyzeAssignment(S, BO);
11372     // And with compound assignments.
11373     if (BO->isAssignmentOp())
11374       return AnalyzeCompoundAssignment(S, BO);
11375   }
11376 
11377   // These break the otherwise-useful invariant below.  Fortunately,
11378   // we don't really need to recurse into them, because any internal
11379   // expressions should have been analyzed already when they were
11380   // built into statements.
11381   if (isa<StmtExpr>(E)) return;
11382 
11383   // Don't descend into unevaluated contexts.
11384   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
11385 
11386   // Now just recurse over the expression's children.
11387   CC = E->getExprLoc();
11388   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
11389   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
11390   for (Stmt *SubStmt : E->children()) {
11391     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
11392     if (!ChildExpr)
11393       continue;
11394 
11395     if (IsLogicalAndOperator &&
11396         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
11397       // Ignore checking string literals that are in logical and operators.
11398       // This is a common pattern for asserts.
11399       continue;
11400     AnalyzeImplicitConversions(S, ChildExpr, CC, IsListInit);
11401   }
11402 
11403   if (BO && BO->isLogicalOp()) {
11404     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
11405     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
11406       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
11407 
11408     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
11409     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
11410       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
11411   }
11412 
11413   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
11414     if (U->getOpcode() == UO_LNot) {
11415       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
11416     } else if (U->getOpcode() != UO_AddrOf) {
11417       if (U->getSubExpr()->getType()->isAtomicType())
11418         S.Diag(U->getSubExpr()->getBeginLoc(),
11419                diag::warn_atomic_implicit_seq_cst);
11420     }
11421   }
11422 }
11423 
11424 /// Diagnose integer type and any valid implicit conversion to it.
11425 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
11426   // Taking into account implicit conversions,
11427   // allow any integer.
11428   if (!E->getType()->isIntegerType()) {
11429     S.Diag(E->getBeginLoc(),
11430            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
11431     return true;
11432   }
11433   // Potentially emit standard warnings for implicit conversions if enabled
11434   // using -Wconversion.
11435   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
11436   return false;
11437 }
11438 
11439 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
11440 // Returns true when emitting a warning about taking the address of a reference.
11441 static bool CheckForReference(Sema &SemaRef, const Expr *E,
11442                               const PartialDiagnostic &PD) {
11443   E = E->IgnoreParenImpCasts();
11444 
11445   const FunctionDecl *FD = nullptr;
11446 
11447   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11448     if (!DRE->getDecl()->getType()->isReferenceType())
11449       return false;
11450   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
11451     if (!M->getMemberDecl()->getType()->isReferenceType())
11452       return false;
11453   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
11454     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
11455       return false;
11456     FD = Call->getDirectCallee();
11457   } else {
11458     return false;
11459   }
11460 
11461   SemaRef.Diag(E->getExprLoc(), PD);
11462 
11463   // If possible, point to location of function.
11464   if (FD) {
11465     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
11466   }
11467 
11468   return true;
11469 }
11470 
11471 // Returns true if the SourceLocation is expanded from any macro body.
11472 // Returns false if the SourceLocation is invalid, is from not in a macro
11473 // expansion, or is from expanded from a top-level macro argument.
11474 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
11475   if (Loc.isInvalid())
11476     return false;
11477 
11478   while (Loc.isMacroID()) {
11479     if (SM.isMacroBodyExpansion(Loc))
11480       return true;
11481     Loc = SM.getImmediateMacroCallerLoc(Loc);
11482   }
11483 
11484   return false;
11485 }
11486 
11487 /// Diagnose pointers that are always non-null.
11488 /// \param E the expression containing the pointer
11489 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
11490 /// compared to a null pointer
11491 /// \param IsEqual True when the comparison is equal to a null pointer
11492 /// \param Range Extra SourceRange to highlight in the diagnostic
11493 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
11494                                         Expr::NullPointerConstantKind NullKind,
11495                                         bool IsEqual, SourceRange Range) {
11496   if (!E)
11497     return;
11498 
11499   // Don't warn inside macros.
11500   if (E->getExprLoc().isMacroID()) {
11501     const SourceManager &SM = getSourceManager();
11502     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
11503         IsInAnyMacroBody(SM, Range.getBegin()))
11504       return;
11505   }
11506   E = E->IgnoreImpCasts();
11507 
11508   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
11509 
11510   if (isa<CXXThisExpr>(E)) {
11511     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
11512                                 : diag::warn_this_bool_conversion;
11513     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
11514     return;
11515   }
11516 
11517   bool IsAddressOf = false;
11518 
11519   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
11520     if (UO->getOpcode() != UO_AddrOf)
11521       return;
11522     IsAddressOf = true;
11523     E = UO->getSubExpr();
11524   }
11525 
11526   if (IsAddressOf) {
11527     unsigned DiagID = IsCompare
11528                           ? diag::warn_address_of_reference_null_compare
11529                           : diag::warn_address_of_reference_bool_conversion;
11530     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
11531                                          << IsEqual;
11532     if (CheckForReference(*this, E, PD)) {
11533       return;
11534     }
11535   }
11536 
11537   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
11538     bool IsParam = isa<NonNullAttr>(NonnullAttr);
11539     std::string Str;
11540     llvm::raw_string_ostream S(Str);
11541     E->printPretty(S, nullptr, getPrintingPolicy());
11542     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
11543                                 : diag::warn_cast_nonnull_to_bool;
11544     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
11545       << E->getSourceRange() << Range << IsEqual;
11546     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
11547   };
11548 
11549   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
11550   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
11551     if (auto *Callee = Call->getDirectCallee()) {
11552       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
11553         ComplainAboutNonnullParamOrCall(A);
11554         return;
11555       }
11556     }
11557   }
11558 
11559   // Expect to find a single Decl.  Skip anything more complicated.
11560   ValueDecl *D = nullptr;
11561   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
11562     D = R->getDecl();
11563   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
11564     D = M->getMemberDecl();
11565   }
11566 
11567   // Weak Decls can be null.
11568   if (!D || D->isWeak())
11569     return;
11570 
11571   // Check for parameter decl with nonnull attribute
11572   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
11573     if (getCurFunction() &&
11574         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
11575       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
11576         ComplainAboutNonnullParamOrCall(A);
11577         return;
11578       }
11579 
11580       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
11581         // Skip function template not specialized yet.
11582         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
11583           return;
11584         auto ParamIter = llvm::find(FD->parameters(), PV);
11585         assert(ParamIter != FD->param_end());
11586         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
11587 
11588         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
11589           if (!NonNull->args_size()) {
11590               ComplainAboutNonnullParamOrCall(NonNull);
11591               return;
11592           }
11593 
11594           for (const ParamIdx &ArgNo : NonNull->args()) {
11595             if (ArgNo.getASTIndex() == ParamNo) {
11596               ComplainAboutNonnullParamOrCall(NonNull);
11597               return;
11598             }
11599           }
11600         }
11601       }
11602     }
11603   }
11604 
11605   QualType T = D->getType();
11606   const bool IsArray = T->isArrayType();
11607   const bool IsFunction = T->isFunctionType();
11608 
11609   // Address of function is used to silence the function warning.
11610   if (IsAddressOf && IsFunction) {
11611     return;
11612   }
11613 
11614   // Found nothing.
11615   if (!IsAddressOf && !IsFunction && !IsArray)
11616     return;
11617 
11618   // Pretty print the expression for the diagnostic.
11619   std::string Str;
11620   llvm::raw_string_ostream S(Str);
11621   E->printPretty(S, nullptr, getPrintingPolicy());
11622 
11623   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
11624                               : diag::warn_impcast_pointer_to_bool;
11625   enum {
11626     AddressOf,
11627     FunctionPointer,
11628     ArrayPointer
11629   } DiagType;
11630   if (IsAddressOf)
11631     DiagType = AddressOf;
11632   else if (IsFunction)
11633     DiagType = FunctionPointer;
11634   else if (IsArray)
11635     DiagType = ArrayPointer;
11636   else
11637     llvm_unreachable("Could not determine diagnostic.");
11638   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
11639                                 << Range << IsEqual;
11640 
11641   if (!IsFunction)
11642     return;
11643 
11644   // Suggest '&' to silence the function warning.
11645   Diag(E->getExprLoc(), diag::note_function_warning_silence)
11646       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
11647 
11648   // Check to see if '()' fixit should be emitted.
11649   QualType ReturnType;
11650   UnresolvedSet<4> NonTemplateOverloads;
11651   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
11652   if (ReturnType.isNull())
11653     return;
11654 
11655   if (IsCompare) {
11656     // There are two cases here.  If there is null constant, the only suggest
11657     // for a pointer return type.  If the null is 0, then suggest if the return
11658     // type is a pointer or an integer type.
11659     if (!ReturnType->isPointerType()) {
11660       if (NullKind == Expr::NPCK_ZeroExpression ||
11661           NullKind == Expr::NPCK_ZeroLiteral) {
11662         if (!ReturnType->isIntegerType())
11663           return;
11664       } else {
11665         return;
11666       }
11667     }
11668   } else { // !IsCompare
11669     // For function to bool, only suggest if the function pointer has bool
11670     // return type.
11671     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
11672       return;
11673   }
11674   Diag(E->getExprLoc(), diag::note_function_to_function_call)
11675       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
11676 }
11677 
11678 /// Diagnoses "dangerous" implicit conversions within the given
11679 /// expression (which is a full expression).  Implements -Wconversion
11680 /// and -Wsign-compare.
11681 ///
11682 /// \param CC the "context" location of the implicit conversion, i.e.
11683 ///   the most location of the syntactic entity requiring the implicit
11684 ///   conversion
11685 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
11686   // Don't diagnose in unevaluated contexts.
11687   if (isUnevaluatedContext())
11688     return;
11689 
11690   // Don't diagnose for value- or type-dependent expressions.
11691   if (E->isTypeDependent() || E->isValueDependent())
11692     return;
11693 
11694   // Check for array bounds violations in cases where the check isn't triggered
11695   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
11696   // ArraySubscriptExpr is on the RHS of a variable initialization.
11697   CheckArrayAccess(E);
11698 
11699   // This is not the right CC for (e.g.) a variable initialization.
11700   AnalyzeImplicitConversions(*this, E, CC);
11701 }
11702 
11703 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
11704 /// Input argument E is a logical expression.
11705 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
11706   ::CheckBoolLikeConversion(*this, E, CC);
11707 }
11708 
11709 /// Diagnose when expression is an integer constant expression and its evaluation
11710 /// results in integer overflow
11711 void Sema::CheckForIntOverflow (Expr *E) {
11712   // Use a work list to deal with nested struct initializers.
11713   SmallVector<Expr *, 2> Exprs(1, E);
11714 
11715   do {
11716     Expr *OriginalE = Exprs.pop_back_val();
11717     Expr *E = OriginalE->IgnoreParenCasts();
11718 
11719     if (isa<BinaryOperator>(E)) {
11720       E->EvaluateForOverflow(Context);
11721       continue;
11722     }
11723 
11724     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
11725       Exprs.append(InitList->inits().begin(), InitList->inits().end());
11726     else if (isa<ObjCBoxedExpr>(OriginalE))
11727       E->EvaluateForOverflow(Context);
11728     else if (auto Call = dyn_cast<CallExpr>(E))
11729       Exprs.append(Call->arg_begin(), Call->arg_end());
11730     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
11731       Exprs.append(Message->arg_begin(), Message->arg_end());
11732   } while (!Exprs.empty());
11733 }
11734 
11735 namespace {
11736 
11737 /// Visitor for expressions which looks for unsequenced operations on the
11738 /// same object.
11739 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
11740   using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
11741 
11742   /// A tree of sequenced regions within an expression. Two regions are
11743   /// unsequenced if one is an ancestor or a descendent of the other. When we
11744   /// finish processing an expression with sequencing, such as a comma
11745   /// expression, we fold its tree nodes into its parent, since they are
11746   /// unsequenced with respect to nodes we will visit later.
11747   class SequenceTree {
11748     struct Value {
11749       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
11750       unsigned Parent : 31;
11751       unsigned Merged : 1;
11752     };
11753     SmallVector<Value, 8> Values;
11754 
11755   public:
11756     /// A region within an expression which may be sequenced with respect
11757     /// to some other region.
11758     class Seq {
11759       friend class SequenceTree;
11760 
11761       unsigned Index;
11762 
11763       explicit Seq(unsigned N) : Index(N) {}
11764 
11765     public:
11766       Seq() : Index(0) {}
11767     };
11768 
11769     SequenceTree() { Values.push_back(Value(0)); }
11770     Seq root() const { return Seq(0); }
11771 
11772     /// Create a new sequence of operations, which is an unsequenced
11773     /// subset of \p Parent. This sequence of operations is sequenced with
11774     /// respect to other children of \p Parent.
11775     Seq allocate(Seq Parent) {
11776       Values.push_back(Value(Parent.Index));
11777       return Seq(Values.size() - 1);
11778     }
11779 
11780     /// Merge a sequence of operations into its parent.
11781     void merge(Seq S) {
11782       Values[S.Index].Merged = true;
11783     }
11784 
11785     /// Determine whether two operations are unsequenced. This operation
11786     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
11787     /// should have been merged into its parent as appropriate.
11788     bool isUnsequenced(Seq Cur, Seq Old) {
11789       unsigned C = representative(Cur.Index);
11790       unsigned Target = representative(Old.Index);
11791       while (C >= Target) {
11792         if (C == Target)
11793           return true;
11794         C = Values[C].Parent;
11795       }
11796       return false;
11797     }
11798 
11799   private:
11800     /// Pick a representative for a sequence.
11801     unsigned representative(unsigned K) {
11802       if (Values[K].Merged)
11803         // Perform path compression as we go.
11804         return Values[K].Parent = representative(Values[K].Parent);
11805       return K;
11806     }
11807   };
11808 
11809   /// An object for which we can track unsequenced uses.
11810   using Object = const NamedDecl *;
11811 
11812   /// Different flavors of object usage which we track. We only track the
11813   /// least-sequenced usage of each kind.
11814   enum UsageKind {
11815     /// A read of an object. Multiple unsequenced reads are OK.
11816     UK_Use,
11817 
11818     /// A modification of an object which is sequenced before the value
11819     /// computation of the expression, such as ++n in C++.
11820     UK_ModAsValue,
11821 
11822     /// A modification of an object which is not sequenced before the value
11823     /// computation of the expression, such as n++.
11824     UK_ModAsSideEffect,
11825 
11826     UK_Count = UK_ModAsSideEffect + 1
11827   };
11828 
11829   /// Bundle together a sequencing region and the expression corresponding
11830   /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
11831   struct Usage {
11832     const Expr *UsageExpr;
11833     SequenceTree::Seq Seq;
11834 
11835     Usage() : UsageExpr(nullptr), Seq() {}
11836   };
11837 
11838   struct UsageInfo {
11839     Usage Uses[UK_Count];
11840 
11841     /// Have we issued a diagnostic for this object already?
11842     bool Diagnosed;
11843 
11844     UsageInfo() : Uses(), Diagnosed(false) {}
11845   };
11846   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
11847 
11848   Sema &SemaRef;
11849 
11850   /// Sequenced regions within the expression.
11851   SequenceTree Tree;
11852 
11853   /// Declaration modifications and references which we have seen.
11854   UsageInfoMap UsageMap;
11855 
11856   /// The region we are currently within.
11857   SequenceTree::Seq Region;
11858 
11859   /// Filled in with declarations which were modified as a side-effect
11860   /// (that is, post-increment operations).
11861   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
11862 
11863   /// Expressions to check later. We defer checking these to reduce
11864   /// stack usage.
11865   SmallVectorImpl<const Expr *> &WorkList;
11866 
11867   /// RAII object wrapping the visitation of a sequenced subexpression of an
11868   /// expression. At the end of this process, the side-effects of the evaluation
11869   /// become sequenced with respect to the value computation of the result, so
11870   /// we downgrade any UK_ModAsSideEffect within the evaluation to
11871   /// UK_ModAsValue.
11872   struct SequencedSubexpression {
11873     SequencedSubexpression(SequenceChecker &Self)
11874       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
11875       Self.ModAsSideEffect = &ModAsSideEffect;
11876     }
11877 
11878     ~SequencedSubexpression() {
11879       for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
11880         // Add a new usage with usage kind UK_ModAsValue, and then restore
11881         // the previous usage with UK_ModAsSideEffect (thus clearing it if
11882         // the previous one was empty).
11883         UsageInfo &UI = Self.UsageMap[M.first];
11884         auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
11885         Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
11886         SideEffectUsage = M.second;
11887       }
11888       Self.ModAsSideEffect = OldModAsSideEffect;
11889     }
11890 
11891     SequenceChecker &Self;
11892     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
11893     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
11894   };
11895 
11896   /// RAII object wrapping the visitation of a subexpression which we might
11897   /// choose to evaluate as a constant. If any subexpression is evaluated and
11898   /// found to be non-constant, this allows us to suppress the evaluation of
11899   /// the outer expression.
11900   class EvaluationTracker {
11901   public:
11902     EvaluationTracker(SequenceChecker &Self)
11903         : Self(Self), Prev(Self.EvalTracker) {
11904       Self.EvalTracker = this;
11905     }
11906 
11907     ~EvaluationTracker() {
11908       Self.EvalTracker = Prev;
11909       if (Prev)
11910         Prev->EvalOK &= EvalOK;
11911     }
11912 
11913     bool evaluate(const Expr *E, bool &Result) {
11914       if (!EvalOK || E->isValueDependent())
11915         return false;
11916       EvalOK = E->EvaluateAsBooleanCondition(
11917           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
11918       return EvalOK;
11919     }
11920 
11921   private:
11922     SequenceChecker &Self;
11923     EvaluationTracker *Prev;
11924     bool EvalOK = true;
11925   } *EvalTracker = nullptr;
11926 
11927   /// Find the object which is produced by the specified expression,
11928   /// if any.
11929   Object getObject(const Expr *E, bool Mod) const {
11930     E = E->IgnoreParenCasts();
11931     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
11932       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
11933         return getObject(UO->getSubExpr(), Mod);
11934     } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11935       if (BO->getOpcode() == BO_Comma)
11936         return getObject(BO->getRHS(), Mod);
11937       if (Mod && BO->isAssignmentOp())
11938         return getObject(BO->getLHS(), Mod);
11939     } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
11940       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
11941       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
11942         return ME->getMemberDecl();
11943     } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11944       // FIXME: If this is a reference, map through to its value.
11945       return DRE->getDecl();
11946     return nullptr;
11947   }
11948 
11949   /// Note that an object \p O was modified or used by an expression
11950   /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
11951   /// the object \p O as obtained via the \p UsageMap.
11952   void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
11953     // Get the old usage for the given object and usage kind.
11954     Usage &U = UI.Uses[UK];
11955     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
11956       // If we have a modification as side effect and are in a sequenced
11957       // subexpression, save the old Usage so that we can restore it later
11958       // in SequencedSubexpression::~SequencedSubexpression.
11959       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
11960         ModAsSideEffect->push_back(std::make_pair(O, U));
11961       // Then record the new usage with the current sequencing region.
11962       U.UsageExpr = UsageExpr;
11963       U.Seq = Region;
11964     }
11965   }
11966 
11967   /// Check whether a modification or use of an object \p O in an expression
11968   /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
11969   /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
11970   /// \p IsModMod is true when we are checking for a mod-mod unsequenced
11971   /// usage and false we are checking for a mod-use unsequenced usage.
11972   void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
11973                   UsageKind OtherKind, bool IsModMod) {
11974     if (UI.Diagnosed)
11975       return;
11976 
11977     const Usage &U = UI.Uses[OtherKind];
11978     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
11979       return;
11980 
11981     const Expr *Mod = U.UsageExpr;
11982     const Expr *ModOrUse = UsageExpr;
11983     if (OtherKind == UK_Use)
11984       std::swap(Mod, ModOrUse);
11985 
11986     SemaRef.DiagRuntimeBehavior(
11987         Mod->getExprLoc(), {Mod, ModOrUse},
11988         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
11989                                : diag::warn_unsequenced_mod_use)
11990             << O << SourceRange(ModOrUse->getExprLoc()));
11991     UI.Diagnosed = true;
11992   }
11993 
11994   // A note on note{Pre, Post}{Use, Mod}:
11995   //
11996   // (It helps to follow the algorithm with an expression such as
11997   //  "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
11998   //  operations before C++17 and both are well-defined in C++17).
11999   //
12000   // When visiting a node which uses/modify an object we first call notePreUse
12001   // or notePreMod before visiting its sub-expression(s). At this point the
12002   // children of the current node have not yet been visited and so the eventual
12003   // uses/modifications resulting from the children of the current node have not
12004   // been recorded yet.
12005   //
12006   // We then visit the children of the current node. After that notePostUse or
12007   // notePostMod is called. These will 1) detect an unsequenced modification
12008   // as side effect (as in "k++ + k") and 2) add a new usage with the
12009   // appropriate usage kind.
12010   //
12011   // We also have to be careful that some operation sequences modification as
12012   // side effect as well (for example: || or ,). To account for this we wrap
12013   // the visitation of such a sub-expression (for example: the LHS of || or ,)
12014   // with SequencedSubexpression. SequencedSubexpression is an RAII object
12015   // which record usages which are modifications as side effect, and then
12016   // downgrade them (or more accurately restore the previous usage which was a
12017   // modification as side effect) when exiting the scope of the sequenced
12018   // subexpression.
12019 
12020   void notePreUse(Object O, const Expr *UseExpr) {
12021     UsageInfo &UI = UsageMap[O];
12022     // Uses conflict with other modifications.
12023     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
12024   }
12025 
12026   void notePostUse(Object O, const Expr *UseExpr) {
12027     UsageInfo &UI = UsageMap[O];
12028     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
12029                /*IsModMod=*/false);
12030     addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
12031   }
12032 
12033   void notePreMod(Object O, const Expr *ModExpr) {
12034     UsageInfo &UI = UsageMap[O];
12035     // Modifications conflict with other modifications and with uses.
12036     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
12037     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
12038   }
12039 
12040   void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
12041     UsageInfo &UI = UsageMap[O];
12042     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
12043                /*IsModMod=*/true);
12044     addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
12045   }
12046 
12047 public:
12048   SequenceChecker(Sema &S, const Expr *E,
12049                   SmallVectorImpl<const Expr *> &WorkList)
12050       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
12051     Visit(E);
12052     // Silence a -Wunused-private-field since WorkList is now unused.
12053     // TODO: Evaluate if it can be used, and if not remove it.
12054     (void)this->WorkList;
12055   }
12056 
12057   void VisitStmt(const Stmt *S) {
12058     // Skip all statements which aren't expressions for now.
12059   }
12060 
12061   void VisitExpr(const Expr *E) {
12062     // By default, just recurse to evaluated subexpressions.
12063     Base::VisitStmt(E);
12064   }
12065 
12066   void VisitCastExpr(const CastExpr *E) {
12067     Object O = Object();
12068     if (E->getCastKind() == CK_LValueToRValue)
12069       O = getObject(E->getSubExpr(), false);
12070 
12071     if (O)
12072       notePreUse(O, E);
12073     VisitExpr(E);
12074     if (O)
12075       notePostUse(O, E);
12076   }
12077 
12078   void VisitSequencedExpressions(const Expr *SequencedBefore,
12079                                  const Expr *SequencedAfter) {
12080     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
12081     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
12082     SequenceTree::Seq OldRegion = Region;
12083 
12084     {
12085       SequencedSubexpression SeqBefore(*this);
12086       Region = BeforeRegion;
12087       Visit(SequencedBefore);
12088     }
12089 
12090     Region = AfterRegion;
12091     Visit(SequencedAfter);
12092 
12093     Region = OldRegion;
12094 
12095     Tree.merge(BeforeRegion);
12096     Tree.merge(AfterRegion);
12097   }
12098 
12099   void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
12100     // C++17 [expr.sub]p1:
12101     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
12102     //   expression E1 is sequenced before the expression E2.
12103     if (SemaRef.getLangOpts().CPlusPlus17)
12104       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
12105     else {
12106       Visit(ASE->getLHS());
12107       Visit(ASE->getRHS());
12108     }
12109   }
12110 
12111   void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
12112   void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
12113   void VisitBinPtrMem(const BinaryOperator *BO) {
12114     // C++17 [expr.mptr.oper]p4:
12115     //  Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
12116     //  the expression E1 is sequenced before the expression E2.
12117     if (SemaRef.getLangOpts().CPlusPlus17)
12118       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12119     else {
12120       Visit(BO->getLHS());
12121       Visit(BO->getRHS());
12122     }
12123   }
12124 
12125   void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
12126   void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
12127   void VisitBinShlShr(const BinaryOperator *BO) {
12128     // C++17 [expr.shift]p4:
12129     //  The expression E1 is sequenced before the expression E2.
12130     if (SemaRef.getLangOpts().CPlusPlus17)
12131       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12132     else {
12133       Visit(BO->getLHS());
12134       Visit(BO->getRHS());
12135     }
12136   }
12137 
12138   void VisitBinComma(const BinaryOperator *BO) {
12139     // C++11 [expr.comma]p1:
12140     //   Every value computation and side effect associated with the left
12141     //   expression is sequenced before every value computation and side
12142     //   effect associated with the right expression.
12143     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12144   }
12145 
12146   void VisitBinAssign(const BinaryOperator *BO) {
12147     SequenceTree::Seq RHSRegion;
12148     SequenceTree::Seq LHSRegion;
12149     if (SemaRef.getLangOpts().CPlusPlus17) {
12150       RHSRegion = Tree.allocate(Region);
12151       LHSRegion = Tree.allocate(Region);
12152     } else {
12153       RHSRegion = Region;
12154       LHSRegion = Region;
12155     }
12156     SequenceTree::Seq OldRegion = Region;
12157 
12158     // C++11 [expr.ass]p1:
12159     //  [...] the assignment is sequenced after the value computation
12160     //  of the right and left operands, [...]
12161     //
12162     // so check it before inspecting the operands and update the
12163     // map afterwards.
12164     Object O = getObject(BO->getLHS(), /*Mod=*/true);
12165     if (O)
12166       notePreMod(O, BO);
12167 
12168     if (SemaRef.getLangOpts().CPlusPlus17) {
12169       // C++17 [expr.ass]p1:
12170       //  [...] The right operand is sequenced before the left operand. [...]
12171       {
12172         SequencedSubexpression SeqBefore(*this);
12173         Region = RHSRegion;
12174         Visit(BO->getRHS());
12175       }
12176 
12177       Region = LHSRegion;
12178       Visit(BO->getLHS());
12179 
12180       if (O && isa<CompoundAssignOperator>(BO))
12181         notePostUse(O, BO);
12182 
12183     } else {
12184       // C++11 does not specify any sequencing between the LHS and RHS.
12185       Region = LHSRegion;
12186       Visit(BO->getLHS());
12187 
12188       if (O && isa<CompoundAssignOperator>(BO))
12189         notePostUse(O, BO);
12190 
12191       Region = RHSRegion;
12192       Visit(BO->getRHS());
12193     }
12194 
12195     // C++11 [expr.ass]p1:
12196     //  the assignment is sequenced [...] before the value computation of the
12197     //  assignment expression.
12198     // C11 6.5.16/3 has no such rule.
12199     Region = OldRegion;
12200     if (O)
12201       notePostMod(O, BO,
12202                   SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12203                                                   : UK_ModAsSideEffect);
12204     if (SemaRef.getLangOpts().CPlusPlus17) {
12205       Tree.merge(RHSRegion);
12206       Tree.merge(LHSRegion);
12207     }
12208   }
12209 
12210   void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
12211     VisitBinAssign(CAO);
12212   }
12213 
12214   void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12215   void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12216   void VisitUnaryPreIncDec(const UnaryOperator *UO) {
12217     Object O = getObject(UO->getSubExpr(), true);
12218     if (!O)
12219       return VisitExpr(UO);
12220 
12221     notePreMod(O, UO);
12222     Visit(UO->getSubExpr());
12223     // C++11 [expr.pre.incr]p1:
12224     //   the expression ++x is equivalent to x+=1
12225     notePostMod(O, UO,
12226                 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12227                                                 : UK_ModAsSideEffect);
12228   }
12229 
12230   void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12231   void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12232   void VisitUnaryPostIncDec(const UnaryOperator *UO) {
12233     Object O = getObject(UO->getSubExpr(), true);
12234     if (!O)
12235       return VisitExpr(UO);
12236 
12237     notePreMod(O, UO);
12238     Visit(UO->getSubExpr());
12239     notePostMod(O, UO, UK_ModAsSideEffect);
12240   }
12241 
12242   void VisitBinLOr(const BinaryOperator *BO) {
12243     // C++11 [expr.log.or]p2:
12244     //  If the second expression is evaluated, every value computation and
12245     //  side effect associated with the first expression is sequenced before
12246     //  every value computation and side effect associated with the
12247     //  second expression.
12248     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
12249     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
12250     SequenceTree::Seq OldRegion = Region;
12251 
12252     EvaluationTracker Eval(*this);
12253     {
12254       SequencedSubexpression Sequenced(*this);
12255       Region = LHSRegion;
12256       Visit(BO->getLHS());
12257     }
12258 
12259     // C++11 [expr.log.or]p1:
12260     //  [...] the second operand is not evaluated if the first operand
12261     //  evaluates to true.
12262     bool EvalResult = false;
12263     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
12264     bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
12265     if (ShouldVisitRHS) {
12266       Region = RHSRegion;
12267       Visit(BO->getRHS());
12268     }
12269 
12270     Region = OldRegion;
12271     Tree.merge(LHSRegion);
12272     Tree.merge(RHSRegion);
12273   }
12274 
12275   void VisitBinLAnd(const BinaryOperator *BO) {
12276     // C++11 [expr.log.and]p2:
12277     //  If the second expression is evaluated, every value computation and
12278     //  side effect associated with the first expression is sequenced before
12279     //  every value computation and side effect associated with the
12280     //  second expression.
12281     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
12282     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
12283     SequenceTree::Seq OldRegion = Region;
12284 
12285     EvaluationTracker Eval(*this);
12286     {
12287       SequencedSubexpression Sequenced(*this);
12288       Region = LHSRegion;
12289       Visit(BO->getLHS());
12290     }
12291 
12292     // C++11 [expr.log.and]p1:
12293     //  [...] the second operand is not evaluated if the first operand is false.
12294     bool EvalResult = false;
12295     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
12296     bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
12297     if (ShouldVisitRHS) {
12298       Region = RHSRegion;
12299       Visit(BO->getRHS());
12300     }
12301 
12302     Region = OldRegion;
12303     Tree.merge(LHSRegion);
12304     Tree.merge(RHSRegion);
12305   }
12306 
12307   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
12308     // C++11 [expr.cond]p1:
12309     //  [...] Every value computation and side effect associated with the first
12310     //  expression is sequenced before every value computation and side effect
12311     //  associated with the second or third expression.
12312     SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
12313 
12314     // No sequencing is specified between the true and false expression.
12315     // However since exactly one of both is going to be evaluated we can
12316     // consider them to be sequenced. This is needed to avoid warning on
12317     // something like "x ? y+= 1 : y += 2;" in the case where we will visit
12318     // both the true and false expressions because we can't evaluate x.
12319     // This will still allow us to detect an expression like (pre C++17)
12320     // "(x ? y += 1 : y += 2) = y".
12321     //
12322     // We don't wrap the visitation of the true and false expression with
12323     // SequencedSubexpression because we don't want to downgrade modifications
12324     // as side effect in the true and false expressions after the visition
12325     // is done. (for example in the expression "(x ? y++ : y++) + y" we should
12326     // not warn between the two "y++", but we should warn between the "y++"
12327     // and the "y".
12328     SequenceTree::Seq TrueRegion = Tree.allocate(Region);
12329     SequenceTree::Seq FalseRegion = Tree.allocate(Region);
12330     SequenceTree::Seq OldRegion = Region;
12331 
12332     EvaluationTracker Eval(*this);
12333     {
12334       SequencedSubexpression Sequenced(*this);
12335       Region = ConditionRegion;
12336       Visit(CO->getCond());
12337     }
12338 
12339     // C++11 [expr.cond]p1:
12340     // [...] The first expression is contextually converted to bool (Clause 4).
12341     // It is evaluated and if it is true, the result of the conditional
12342     // expression is the value of the second expression, otherwise that of the
12343     // third expression. Only one of the second and third expressions is
12344     // evaluated. [...]
12345     bool EvalResult = false;
12346     bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
12347     bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
12348     bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
12349     if (ShouldVisitTrueExpr) {
12350       Region = TrueRegion;
12351       Visit(CO->getTrueExpr());
12352     }
12353     if (ShouldVisitFalseExpr) {
12354       Region = FalseRegion;
12355       Visit(CO->getFalseExpr());
12356     }
12357 
12358     Region = OldRegion;
12359     Tree.merge(ConditionRegion);
12360     Tree.merge(TrueRegion);
12361     Tree.merge(FalseRegion);
12362   }
12363 
12364   void VisitCallExpr(const CallExpr *CE) {
12365     // C++11 [intro.execution]p15:
12366     //   When calling a function [...], every value computation and side effect
12367     //   associated with any argument expression, or with the postfix expression
12368     //   designating the called function, is sequenced before execution of every
12369     //   expression or statement in the body of the function [and thus before
12370     //   the value computation of its result].
12371     SequencedSubexpression Sequenced(*this);
12372     SemaRef.runWithSufficientStackSpace(CE->getExprLoc(),
12373                                         [&] { Base::VisitCallExpr(CE); });
12374 
12375     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
12376   }
12377 
12378   void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
12379     // This is a call, so all subexpressions are sequenced before the result.
12380     SequencedSubexpression Sequenced(*this);
12381 
12382     if (!CCE->isListInitialization())
12383       return VisitExpr(CCE);
12384 
12385     // In C++11, list initializations are sequenced.
12386     SmallVector<SequenceTree::Seq, 32> Elts;
12387     SequenceTree::Seq Parent = Region;
12388     for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
12389                                               E = CCE->arg_end();
12390          I != E; ++I) {
12391       Region = Tree.allocate(Parent);
12392       Elts.push_back(Region);
12393       Visit(*I);
12394     }
12395 
12396     // Forget that the initializers are sequenced.
12397     Region = Parent;
12398     for (unsigned I = 0; I < Elts.size(); ++I)
12399       Tree.merge(Elts[I]);
12400   }
12401 
12402   void VisitInitListExpr(const InitListExpr *ILE) {
12403     if (!SemaRef.getLangOpts().CPlusPlus11)
12404       return VisitExpr(ILE);
12405 
12406     // In C++11, list initializations are sequenced.
12407     SmallVector<SequenceTree::Seq, 32> Elts;
12408     SequenceTree::Seq Parent = Region;
12409     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
12410       const Expr *E = ILE->getInit(I);
12411       if (!E)
12412         continue;
12413       Region = Tree.allocate(Parent);
12414       Elts.push_back(Region);
12415       Visit(E);
12416     }
12417 
12418     // Forget that the initializers are sequenced.
12419     Region = Parent;
12420     for (unsigned I = 0; I < Elts.size(); ++I)
12421       Tree.merge(Elts[I]);
12422   }
12423 };
12424 
12425 } // namespace
12426 
12427 void Sema::CheckUnsequencedOperations(const Expr *E) {
12428   SmallVector<const Expr *, 8> WorkList;
12429   WorkList.push_back(E);
12430   while (!WorkList.empty()) {
12431     const Expr *Item = WorkList.pop_back_val();
12432     SequenceChecker(*this, Item, WorkList);
12433   }
12434 }
12435 
12436 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
12437                               bool IsConstexpr) {
12438   llvm::SaveAndRestore<bool> ConstantContext(
12439       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
12440   CheckImplicitConversions(E, CheckLoc);
12441   if (!E->isInstantiationDependent())
12442     CheckUnsequencedOperations(E);
12443   if (!IsConstexpr && !E->isValueDependent())
12444     CheckForIntOverflow(E);
12445   DiagnoseMisalignedMembers();
12446 }
12447 
12448 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
12449                                        FieldDecl *BitField,
12450                                        Expr *Init) {
12451   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
12452 }
12453 
12454 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
12455                                          SourceLocation Loc) {
12456   if (!PType->isVariablyModifiedType())
12457     return;
12458   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
12459     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
12460     return;
12461   }
12462   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
12463     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
12464     return;
12465   }
12466   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
12467     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
12468     return;
12469   }
12470 
12471   const ArrayType *AT = S.Context.getAsArrayType(PType);
12472   if (!AT)
12473     return;
12474 
12475   if (AT->getSizeModifier() != ArrayType::Star) {
12476     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
12477     return;
12478   }
12479 
12480   S.Diag(Loc, diag::err_array_star_in_function_definition);
12481 }
12482 
12483 /// CheckParmsForFunctionDef - Check that the parameters of the given
12484 /// function are appropriate for the definition of a function. This
12485 /// takes care of any checks that cannot be performed on the
12486 /// declaration itself, e.g., that the types of each of the function
12487 /// parameters are complete.
12488 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
12489                                     bool CheckParameterNames) {
12490   bool HasInvalidParm = false;
12491   for (ParmVarDecl *Param : Parameters) {
12492     // C99 6.7.5.3p4: the parameters in a parameter type list in a
12493     // function declarator that is part of a function definition of
12494     // that function shall not have incomplete type.
12495     //
12496     // This is also C++ [dcl.fct]p6.
12497     if (!Param->isInvalidDecl() &&
12498         RequireCompleteType(Param->getLocation(), Param->getType(),
12499                             diag::err_typecheck_decl_incomplete_type)) {
12500       Param->setInvalidDecl();
12501       HasInvalidParm = true;
12502     }
12503 
12504     // C99 6.9.1p5: If the declarator includes a parameter type list, the
12505     // declaration of each parameter shall include an identifier.
12506     if (CheckParameterNames &&
12507         Param->getIdentifier() == nullptr &&
12508         !Param->isImplicit() &&
12509         !getLangOpts().CPlusPlus)
12510       Diag(Param->getLocation(), diag::err_parameter_name_omitted);
12511 
12512     // C99 6.7.5.3p12:
12513     //   If the function declarator is not part of a definition of that
12514     //   function, parameters may have incomplete type and may use the [*]
12515     //   notation in their sequences of declarator specifiers to specify
12516     //   variable length array types.
12517     QualType PType = Param->getOriginalType();
12518     // FIXME: This diagnostic should point the '[*]' if source-location
12519     // information is added for it.
12520     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
12521 
12522     // If the parameter is a c++ class type and it has to be destructed in the
12523     // callee function, declare the destructor so that it can be called by the
12524     // callee function. Do not perform any direct access check on the dtor here.
12525     if (!Param->isInvalidDecl()) {
12526       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
12527         if (!ClassDecl->isInvalidDecl() &&
12528             !ClassDecl->hasIrrelevantDestructor() &&
12529             !ClassDecl->isDependentContext() &&
12530             ClassDecl->isParamDestroyedInCallee()) {
12531           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
12532           MarkFunctionReferenced(Param->getLocation(), Destructor);
12533           DiagnoseUseOfDecl(Destructor, Param->getLocation());
12534         }
12535       }
12536     }
12537 
12538     // Parameters with the pass_object_size attribute only need to be marked
12539     // constant at function definitions. Because we lack information about
12540     // whether we're on a declaration or definition when we're instantiating the
12541     // attribute, we need to check for constness here.
12542     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
12543       if (!Param->getType().isConstQualified())
12544         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
12545             << Attr->getSpelling() << 1;
12546 
12547     // Check for parameter names shadowing fields from the class.
12548     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
12549       // The owning context for the parameter should be the function, but we
12550       // want to see if this function's declaration context is a record.
12551       DeclContext *DC = Param->getDeclContext();
12552       if (DC && DC->isFunctionOrMethod()) {
12553         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
12554           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
12555                                      RD, /*DeclIsField*/ false);
12556       }
12557     }
12558   }
12559 
12560   return HasInvalidParm;
12561 }
12562 
12563 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr
12564 /// or MemberExpr.
12565 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
12566                               ASTContext &Context) {
12567   if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
12568     return Context.getDeclAlign(DRE->getDecl());
12569 
12570   if (const auto *ME = dyn_cast<MemberExpr>(E))
12571     return Context.getDeclAlign(ME->getMemberDecl());
12572 
12573   return TypeAlign;
12574 }
12575 
12576 /// CheckCastAlign - Implements -Wcast-align, which warns when a
12577 /// pointer cast increases the alignment requirements.
12578 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
12579   // This is actually a lot of work to potentially be doing on every
12580   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
12581   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
12582     return;
12583 
12584   // Ignore dependent types.
12585   if (T->isDependentType() || Op->getType()->isDependentType())
12586     return;
12587 
12588   // Require that the destination be a pointer type.
12589   const PointerType *DestPtr = T->getAs<PointerType>();
12590   if (!DestPtr) return;
12591 
12592   // If the destination has alignment 1, we're done.
12593   QualType DestPointee = DestPtr->getPointeeType();
12594   if (DestPointee->isIncompleteType()) return;
12595   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
12596   if (DestAlign.isOne()) return;
12597 
12598   // Require that the source be a pointer type.
12599   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
12600   if (!SrcPtr) return;
12601   QualType SrcPointee = SrcPtr->getPointeeType();
12602 
12603   // Whitelist casts from cv void*.  We already implicitly
12604   // whitelisted casts to cv void*, since they have alignment 1.
12605   // Also whitelist casts involving incomplete types, which implicitly
12606   // includes 'void'.
12607   if (SrcPointee->isIncompleteType()) return;
12608 
12609   CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
12610 
12611   if (auto *CE = dyn_cast<CastExpr>(Op)) {
12612     if (CE->getCastKind() == CK_ArrayToPointerDecay)
12613       SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
12614   } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
12615     if (UO->getOpcode() == UO_AddrOf)
12616       SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
12617   }
12618 
12619   if (SrcAlign >= DestAlign) return;
12620 
12621   Diag(TRange.getBegin(), diag::warn_cast_align)
12622     << Op->getType() << T
12623     << static_cast<unsigned>(SrcAlign.getQuantity())
12624     << static_cast<unsigned>(DestAlign.getQuantity())
12625     << TRange << Op->getSourceRange();
12626 }
12627 
12628 /// Check whether this array fits the idiom of a size-one tail padded
12629 /// array member of a struct.
12630 ///
12631 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
12632 /// commonly used to emulate flexible arrays in C89 code.
12633 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
12634                                     const NamedDecl *ND) {
12635   if (Size != 1 || !ND) return false;
12636 
12637   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
12638   if (!FD) return false;
12639 
12640   // Don't consider sizes resulting from macro expansions or template argument
12641   // substitution to form C89 tail-padded arrays.
12642 
12643   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
12644   while (TInfo) {
12645     TypeLoc TL = TInfo->getTypeLoc();
12646     // Look through typedefs.
12647     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
12648       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
12649       TInfo = TDL->getTypeSourceInfo();
12650       continue;
12651     }
12652     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
12653       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
12654       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
12655         return false;
12656     }
12657     break;
12658   }
12659 
12660   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
12661   if (!RD) return false;
12662   if (RD->isUnion()) return false;
12663   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
12664     if (!CRD->isStandardLayout()) return false;
12665   }
12666 
12667   // See if this is the last field decl in the record.
12668   const Decl *D = FD;
12669   while ((D = D->getNextDeclInContext()))
12670     if (isa<FieldDecl>(D))
12671       return false;
12672   return true;
12673 }
12674 
12675 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
12676                             const ArraySubscriptExpr *ASE,
12677                             bool AllowOnePastEnd, bool IndexNegated) {
12678   // Already diagnosed by the constant evaluator.
12679   if (isConstantEvaluated())
12680     return;
12681 
12682   IndexExpr = IndexExpr->IgnoreParenImpCasts();
12683   if (IndexExpr->isValueDependent())
12684     return;
12685 
12686   const Type *EffectiveType =
12687       BaseExpr->getType()->getPointeeOrArrayElementType();
12688   BaseExpr = BaseExpr->IgnoreParenCasts();
12689   const ConstantArrayType *ArrayTy =
12690       Context.getAsConstantArrayType(BaseExpr->getType());
12691 
12692   if (!ArrayTy)
12693     return;
12694 
12695   const Type *BaseType = ArrayTy->getElementType().getTypePtr();
12696   if (EffectiveType->isDependentType() || BaseType->isDependentType())
12697     return;
12698 
12699   Expr::EvalResult Result;
12700   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
12701     return;
12702 
12703   llvm::APSInt index = Result.Val.getInt();
12704   if (IndexNegated)
12705     index = -index;
12706 
12707   const NamedDecl *ND = nullptr;
12708   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
12709     ND = DRE->getDecl();
12710   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
12711     ND = ME->getMemberDecl();
12712 
12713   if (index.isUnsigned() || !index.isNegative()) {
12714     // It is possible that the type of the base expression after
12715     // IgnoreParenCasts is incomplete, even though the type of the base
12716     // expression before IgnoreParenCasts is complete (see PR39746 for an
12717     // example). In this case we have no information about whether the array
12718     // access exceeds the array bounds. However we can still diagnose an array
12719     // access which precedes the array bounds.
12720     if (BaseType->isIncompleteType())
12721       return;
12722 
12723     llvm::APInt size = ArrayTy->getSize();
12724     if (!size.isStrictlyPositive())
12725       return;
12726 
12727     if (BaseType != EffectiveType) {
12728       // Make sure we're comparing apples to apples when comparing index to size
12729       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
12730       uint64_t array_typesize = Context.getTypeSize(BaseType);
12731       // Handle ptrarith_typesize being zero, such as when casting to void*
12732       if (!ptrarith_typesize) ptrarith_typesize = 1;
12733       if (ptrarith_typesize != array_typesize) {
12734         // There's a cast to a different size type involved
12735         uint64_t ratio = array_typesize / ptrarith_typesize;
12736         // TODO: Be smarter about handling cases where array_typesize is not a
12737         // multiple of ptrarith_typesize
12738         if (ptrarith_typesize * ratio == array_typesize)
12739           size *= llvm::APInt(size.getBitWidth(), ratio);
12740       }
12741     }
12742 
12743     if (size.getBitWidth() > index.getBitWidth())
12744       index = index.zext(size.getBitWidth());
12745     else if (size.getBitWidth() < index.getBitWidth())
12746       size = size.zext(index.getBitWidth());
12747 
12748     // For array subscripting the index must be less than size, but for pointer
12749     // arithmetic also allow the index (offset) to be equal to size since
12750     // computing the next address after the end of the array is legal and
12751     // commonly done e.g. in C++ iterators and range-based for loops.
12752     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
12753       return;
12754 
12755     // Also don't warn for arrays of size 1 which are members of some
12756     // structure. These are often used to approximate flexible arrays in C89
12757     // code.
12758     if (IsTailPaddedMemberArray(*this, size, ND))
12759       return;
12760 
12761     // Suppress the warning if the subscript expression (as identified by the
12762     // ']' location) and the index expression are both from macro expansions
12763     // within a system header.
12764     if (ASE) {
12765       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
12766           ASE->getRBracketLoc());
12767       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
12768         SourceLocation IndexLoc =
12769             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
12770         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
12771           return;
12772       }
12773     }
12774 
12775     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
12776     if (ASE)
12777       DiagID = diag::warn_array_index_exceeds_bounds;
12778 
12779     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
12780                         PDiag(DiagID) << index.toString(10, true)
12781                                       << size.toString(10, true)
12782                                       << (unsigned)size.getLimitedValue(~0U)
12783                                       << IndexExpr->getSourceRange());
12784   } else {
12785     unsigned DiagID = diag::warn_array_index_precedes_bounds;
12786     if (!ASE) {
12787       DiagID = diag::warn_ptr_arith_precedes_bounds;
12788       if (index.isNegative()) index = -index;
12789     }
12790 
12791     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
12792                         PDiag(DiagID) << index.toString(10, true)
12793                                       << IndexExpr->getSourceRange());
12794   }
12795 
12796   if (!ND) {
12797     // Try harder to find a NamedDecl to point at in the note.
12798     while (const ArraySubscriptExpr *ASE =
12799            dyn_cast<ArraySubscriptExpr>(BaseExpr))
12800       BaseExpr = ASE->getBase()->IgnoreParenCasts();
12801     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
12802       ND = DRE->getDecl();
12803     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
12804       ND = ME->getMemberDecl();
12805   }
12806 
12807   if (ND)
12808     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
12809                         PDiag(diag::note_array_declared_here)
12810                             << ND->getDeclName());
12811 }
12812 
12813 void Sema::CheckArrayAccess(const Expr *expr) {
12814   int AllowOnePastEnd = 0;
12815   while (expr) {
12816     expr = expr->IgnoreParenImpCasts();
12817     switch (expr->getStmtClass()) {
12818       case Stmt::ArraySubscriptExprClass: {
12819         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
12820         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
12821                          AllowOnePastEnd > 0);
12822         expr = ASE->getBase();
12823         break;
12824       }
12825       case Stmt::MemberExprClass: {
12826         expr = cast<MemberExpr>(expr)->getBase();
12827         break;
12828       }
12829       case Stmt::OMPArraySectionExprClass: {
12830         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
12831         if (ASE->getLowerBound())
12832           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
12833                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
12834         return;
12835       }
12836       case Stmt::UnaryOperatorClass: {
12837         // Only unwrap the * and & unary operators
12838         const UnaryOperator *UO = cast<UnaryOperator>(expr);
12839         expr = UO->getSubExpr();
12840         switch (UO->getOpcode()) {
12841           case UO_AddrOf:
12842             AllowOnePastEnd++;
12843             break;
12844           case UO_Deref:
12845             AllowOnePastEnd--;
12846             break;
12847           default:
12848             return;
12849         }
12850         break;
12851       }
12852       case Stmt::ConditionalOperatorClass: {
12853         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
12854         if (const Expr *lhs = cond->getLHS())
12855           CheckArrayAccess(lhs);
12856         if (const Expr *rhs = cond->getRHS())
12857           CheckArrayAccess(rhs);
12858         return;
12859       }
12860       case Stmt::CXXOperatorCallExprClass: {
12861         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
12862         for (const auto *Arg : OCE->arguments())
12863           CheckArrayAccess(Arg);
12864         return;
12865       }
12866       default:
12867         return;
12868     }
12869   }
12870 }
12871 
12872 //===--- CHECK: Objective-C retain cycles ----------------------------------//
12873 
12874 namespace {
12875 
12876 struct RetainCycleOwner {
12877   VarDecl *Variable = nullptr;
12878   SourceRange Range;
12879   SourceLocation Loc;
12880   bool Indirect = false;
12881 
12882   RetainCycleOwner() = default;
12883 
12884   void setLocsFrom(Expr *e) {
12885     Loc = e->getExprLoc();
12886     Range = e->getSourceRange();
12887   }
12888 };
12889 
12890 } // namespace
12891 
12892 /// Consider whether capturing the given variable can possibly lead to
12893 /// a retain cycle.
12894 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
12895   // In ARC, it's captured strongly iff the variable has __strong
12896   // lifetime.  In MRR, it's captured strongly if the variable is
12897   // __block and has an appropriate type.
12898   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
12899     return false;
12900 
12901   owner.Variable = var;
12902   if (ref)
12903     owner.setLocsFrom(ref);
12904   return true;
12905 }
12906 
12907 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
12908   while (true) {
12909     e = e->IgnoreParens();
12910     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
12911       switch (cast->getCastKind()) {
12912       case CK_BitCast:
12913       case CK_LValueBitCast:
12914       case CK_LValueToRValue:
12915       case CK_ARCReclaimReturnedObject:
12916         e = cast->getSubExpr();
12917         continue;
12918 
12919       default:
12920         return false;
12921       }
12922     }
12923 
12924     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
12925       ObjCIvarDecl *ivar = ref->getDecl();
12926       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
12927         return false;
12928 
12929       // Try to find a retain cycle in the base.
12930       if (!findRetainCycleOwner(S, ref->getBase(), owner))
12931         return false;
12932 
12933       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
12934       owner.Indirect = true;
12935       return true;
12936     }
12937 
12938     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
12939       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
12940       if (!var) return false;
12941       return considerVariable(var, ref, owner);
12942     }
12943 
12944     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
12945       if (member->isArrow()) return false;
12946 
12947       // Don't count this as an indirect ownership.
12948       e = member->getBase();
12949       continue;
12950     }
12951 
12952     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
12953       // Only pay attention to pseudo-objects on property references.
12954       ObjCPropertyRefExpr *pre
12955         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
12956                                               ->IgnoreParens());
12957       if (!pre) return false;
12958       if (pre->isImplicitProperty()) return false;
12959       ObjCPropertyDecl *property = pre->getExplicitProperty();
12960       if (!property->isRetaining() &&
12961           !(property->getPropertyIvarDecl() &&
12962             property->getPropertyIvarDecl()->getType()
12963               .getObjCLifetime() == Qualifiers::OCL_Strong))
12964           return false;
12965 
12966       owner.Indirect = true;
12967       if (pre->isSuperReceiver()) {
12968         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
12969         if (!owner.Variable)
12970           return false;
12971         owner.Loc = pre->getLocation();
12972         owner.Range = pre->getSourceRange();
12973         return true;
12974       }
12975       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
12976                               ->getSourceExpr());
12977       continue;
12978     }
12979 
12980     // Array ivars?
12981 
12982     return false;
12983   }
12984 }
12985 
12986 namespace {
12987 
12988   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
12989     ASTContext &Context;
12990     VarDecl *Variable;
12991     Expr *Capturer = nullptr;
12992     bool VarWillBeReased = false;
12993 
12994     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
12995         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
12996           Context(Context), Variable(variable) {}
12997 
12998     void VisitDeclRefExpr(DeclRefExpr *ref) {
12999       if (ref->getDecl() == Variable && !Capturer)
13000         Capturer = ref;
13001     }
13002 
13003     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
13004       if (Capturer) return;
13005       Visit(ref->getBase());
13006       if (Capturer && ref->isFreeIvar())
13007         Capturer = ref;
13008     }
13009 
13010     void VisitBlockExpr(BlockExpr *block) {
13011       // Look inside nested blocks
13012       if (block->getBlockDecl()->capturesVariable(Variable))
13013         Visit(block->getBlockDecl()->getBody());
13014     }
13015 
13016     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
13017       if (Capturer) return;
13018       if (OVE->getSourceExpr())
13019         Visit(OVE->getSourceExpr());
13020     }
13021 
13022     void VisitBinaryOperator(BinaryOperator *BinOp) {
13023       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
13024         return;
13025       Expr *LHS = BinOp->getLHS();
13026       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
13027         if (DRE->getDecl() != Variable)
13028           return;
13029         if (Expr *RHS = BinOp->getRHS()) {
13030           RHS = RHS->IgnoreParenCasts();
13031           llvm::APSInt Value;
13032           VarWillBeReased =
13033             (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
13034         }
13035       }
13036     }
13037   };
13038 
13039 } // namespace
13040 
13041 /// Check whether the given argument is a block which captures a
13042 /// variable.
13043 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
13044   assert(owner.Variable && owner.Loc.isValid());
13045 
13046   e = e->IgnoreParenCasts();
13047 
13048   // Look through [^{...} copy] and Block_copy(^{...}).
13049   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
13050     Selector Cmd = ME->getSelector();
13051     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
13052       e = ME->getInstanceReceiver();
13053       if (!e)
13054         return nullptr;
13055       e = e->IgnoreParenCasts();
13056     }
13057   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
13058     if (CE->getNumArgs() == 1) {
13059       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
13060       if (Fn) {
13061         const IdentifierInfo *FnI = Fn->getIdentifier();
13062         if (FnI && FnI->isStr("_Block_copy")) {
13063           e = CE->getArg(0)->IgnoreParenCasts();
13064         }
13065       }
13066     }
13067   }
13068 
13069   BlockExpr *block = dyn_cast<BlockExpr>(e);
13070   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
13071     return nullptr;
13072 
13073   FindCaptureVisitor visitor(S.Context, owner.Variable);
13074   visitor.Visit(block->getBlockDecl()->getBody());
13075   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
13076 }
13077 
13078 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
13079                                 RetainCycleOwner &owner) {
13080   assert(capturer);
13081   assert(owner.Variable && owner.Loc.isValid());
13082 
13083   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
13084     << owner.Variable << capturer->getSourceRange();
13085   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
13086     << owner.Indirect << owner.Range;
13087 }
13088 
13089 /// Check for a keyword selector that starts with the word 'add' or
13090 /// 'set'.
13091 static bool isSetterLikeSelector(Selector sel) {
13092   if (sel.isUnarySelector()) return false;
13093 
13094   StringRef str = sel.getNameForSlot(0);
13095   while (!str.empty() && str.front() == '_') str = str.substr(1);
13096   if (str.startswith("set"))
13097     str = str.substr(3);
13098   else if (str.startswith("add")) {
13099     // Specially whitelist 'addOperationWithBlock:'.
13100     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
13101       return false;
13102     str = str.substr(3);
13103   }
13104   else
13105     return false;
13106 
13107   if (str.empty()) return true;
13108   return !isLowercase(str.front());
13109 }
13110 
13111 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
13112                                                     ObjCMessageExpr *Message) {
13113   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
13114                                                 Message->getReceiverInterface(),
13115                                                 NSAPI::ClassId_NSMutableArray);
13116   if (!IsMutableArray) {
13117     return None;
13118   }
13119 
13120   Selector Sel = Message->getSelector();
13121 
13122   Optional<NSAPI::NSArrayMethodKind> MKOpt =
13123     S.NSAPIObj->getNSArrayMethodKind(Sel);
13124   if (!MKOpt) {
13125     return None;
13126   }
13127 
13128   NSAPI::NSArrayMethodKind MK = *MKOpt;
13129 
13130   switch (MK) {
13131     case NSAPI::NSMutableArr_addObject:
13132     case NSAPI::NSMutableArr_insertObjectAtIndex:
13133     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
13134       return 0;
13135     case NSAPI::NSMutableArr_replaceObjectAtIndex:
13136       return 1;
13137 
13138     default:
13139       return None;
13140   }
13141 
13142   return None;
13143 }
13144 
13145 static
13146 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
13147                                                   ObjCMessageExpr *Message) {
13148   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
13149                                             Message->getReceiverInterface(),
13150                                             NSAPI::ClassId_NSMutableDictionary);
13151   if (!IsMutableDictionary) {
13152     return None;
13153   }
13154 
13155   Selector Sel = Message->getSelector();
13156 
13157   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
13158     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
13159   if (!MKOpt) {
13160     return None;
13161   }
13162 
13163   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
13164 
13165   switch (MK) {
13166     case NSAPI::NSMutableDict_setObjectForKey:
13167     case NSAPI::NSMutableDict_setValueForKey:
13168     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
13169       return 0;
13170 
13171     default:
13172       return None;
13173   }
13174 
13175   return None;
13176 }
13177 
13178 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
13179   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
13180                                                 Message->getReceiverInterface(),
13181                                                 NSAPI::ClassId_NSMutableSet);
13182 
13183   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
13184                                             Message->getReceiverInterface(),
13185                                             NSAPI::ClassId_NSMutableOrderedSet);
13186   if (!IsMutableSet && !IsMutableOrderedSet) {
13187     return None;
13188   }
13189 
13190   Selector Sel = Message->getSelector();
13191 
13192   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
13193   if (!MKOpt) {
13194     return None;
13195   }
13196 
13197   NSAPI::NSSetMethodKind MK = *MKOpt;
13198 
13199   switch (MK) {
13200     case NSAPI::NSMutableSet_addObject:
13201     case NSAPI::NSOrderedSet_setObjectAtIndex:
13202     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
13203     case NSAPI::NSOrderedSet_insertObjectAtIndex:
13204       return 0;
13205     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
13206       return 1;
13207   }
13208 
13209   return None;
13210 }
13211 
13212 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
13213   if (!Message->isInstanceMessage()) {
13214     return;
13215   }
13216 
13217   Optional<int> ArgOpt;
13218 
13219   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
13220       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
13221       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
13222     return;
13223   }
13224 
13225   int ArgIndex = *ArgOpt;
13226 
13227   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
13228   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
13229     Arg = OE->getSourceExpr()->IgnoreImpCasts();
13230   }
13231 
13232   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
13233     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
13234       if (ArgRE->isObjCSelfExpr()) {
13235         Diag(Message->getSourceRange().getBegin(),
13236              diag::warn_objc_circular_container)
13237           << ArgRE->getDecl() << StringRef("'super'");
13238       }
13239     }
13240   } else {
13241     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
13242 
13243     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
13244       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
13245     }
13246 
13247     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
13248       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
13249         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
13250           ValueDecl *Decl = ReceiverRE->getDecl();
13251           Diag(Message->getSourceRange().getBegin(),
13252                diag::warn_objc_circular_container)
13253             << Decl << Decl;
13254           if (!ArgRE->isObjCSelfExpr()) {
13255             Diag(Decl->getLocation(),
13256                  diag::note_objc_circular_container_declared_here)
13257               << Decl;
13258           }
13259         }
13260       }
13261     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
13262       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
13263         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
13264           ObjCIvarDecl *Decl = IvarRE->getDecl();
13265           Diag(Message->getSourceRange().getBegin(),
13266                diag::warn_objc_circular_container)
13267             << Decl << Decl;
13268           Diag(Decl->getLocation(),
13269                diag::note_objc_circular_container_declared_here)
13270             << Decl;
13271         }
13272       }
13273     }
13274   }
13275 }
13276 
13277 /// Check a message send to see if it's likely to cause a retain cycle.
13278 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
13279   // Only check instance methods whose selector looks like a setter.
13280   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
13281     return;
13282 
13283   // Try to find a variable that the receiver is strongly owned by.
13284   RetainCycleOwner owner;
13285   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
13286     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
13287       return;
13288   } else {
13289     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
13290     owner.Variable = getCurMethodDecl()->getSelfDecl();
13291     owner.Loc = msg->getSuperLoc();
13292     owner.Range = msg->getSuperLoc();
13293   }
13294 
13295   // Check whether the receiver is captured by any of the arguments.
13296   const ObjCMethodDecl *MD = msg->getMethodDecl();
13297   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
13298     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
13299       // noescape blocks should not be retained by the method.
13300       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
13301         continue;
13302       return diagnoseRetainCycle(*this, capturer, owner);
13303     }
13304   }
13305 }
13306 
13307 /// Check a property assign to see if it's likely to cause a retain cycle.
13308 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
13309   RetainCycleOwner owner;
13310   if (!findRetainCycleOwner(*this, receiver, owner))
13311     return;
13312 
13313   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
13314     diagnoseRetainCycle(*this, capturer, owner);
13315 }
13316 
13317 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
13318   RetainCycleOwner Owner;
13319   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
13320     return;
13321 
13322   // Because we don't have an expression for the variable, we have to set the
13323   // location explicitly here.
13324   Owner.Loc = Var->getLocation();
13325   Owner.Range = Var->getSourceRange();
13326 
13327   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
13328     diagnoseRetainCycle(*this, Capturer, Owner);
13329 }
13330 
13331 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
13332                                      Expr *RHS, bool isProperty) {
13333   // Check if RHS is an Objective-C object literal, which also can get
13334   // immediately zapped in a weak reference.  Note that we explicitly
13335   // allow ObjCStringLiterals, since those are designed to never really die.
13336   RHS = RHS->IgnoreParenImpCasts();
13337 
13338   // This enum needs to match with the 'select' in
13339   // warn_objc_arc_literal_assign (off-by-1).
13340   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
13341   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
13342     return false;
13343 
13344   S.Diag(Loc, diag::warn_arc_literal_assign)
13345     << (unsigned) Kind
13346     << (isProperty ? 0 : 1)
13347     << RHS->getSourceRange();
13348 
13349   return true;
13350 }
13351 
13352 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
13353                                     Qualifiers::ObjCLifetime LT,
13354                                     Expr *RHS, bool isProperty) {
13355   // Strip off any implicit cast added to get to the one ARC-specific.
13356   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
13357     if (cast->getCastKind() == CK_ARCConsumeObject) {
13358       S.Diag(Loc, diag::warn_arc_retained_assign)
13359         << (LT == Qualifiers::OCL_ExplicitNone)
13360         << (isProperty ? 0 : 1)
13361         << RHS->getSourceRange();
13362       return true;
13363     }
13364     RHS = cast->getSubExpr();
13365   }
13366 
13367   if (LT == Qualifiers::OCL_Weak &&
13368       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
13369     return true;
13370 
13371   return false;
13372 }
13373 
13374 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
13375                               QualType LHS, Expr *RHS) {
13376   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
13377 
13378   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
13379     return false;
13380 
13381   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
13382     return true;
13383 
13384   return false;
13385 }
13386 
13387 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
13388                               Expr *LHS, Expr *RHS) {
13389   QualType LHSType;
13390   // PropertyRef on LHS type need be directly obtained from
13391   // its declaration as it has a PseudoType.
13392   ObjCPropertyRefExpr *PRE
13393     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
13394   if (PRE && !PRE->isImplicitProperty()) {
13395     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
13396     if (PD)
13397       LHSType = PD->getType();
13398   }
13399 
13400   if (LHSType.isNull())
13401     LHSType = LHS->getType();
13402 
13403   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
13404 
13405   if (LT == Qualifiers::OCL_Weak) {
13406     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
13407       getCurFunction()->markSafeWeakUse(LHS);
13408   }
13409 
13410   if (checkUnsafeAssigns(Loc, LHSType, RHS))
13411     return;
13412 
13413   // FIXME. Check for other life times.
13414   if (LT != Qualifiers::OCL_None)
13415     return;
13416 
13417   if (PRE) {
13418     if (PRE->isImplicitProperty())
13419       return;
13420     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
13421     if (!PD)
13422       return;
13423 
13424     unsigned Attributes = PD->getPropertyAttributes();
13425     if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
13426       // when 'assign' attribute was not explicitly specified
13427       // by user, ignore it and rely on property type itself
13428       // for lifetime info.
13429       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
13430       if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
13431           LHSType->isObjCRetainableType())
13432         return;
13433 
13434       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
13435         if (cast->getCastKind() == CK_ARCConsumeObject) {
13436           Diag(Loc, diag::warn_arc_retained_property_assign)
13437           << RHS->getSourceRange();
13438           return;
13439         }
13440         RHS = cast->getSubExpr();
13441       }
13442     }
13443     else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
13444       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
13445         return;
13446     }
13447   }
13448 }
13449 
13450 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
13451 
13452 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
13453                                         SourceLocation StmtLoc,
13454                                         const NullStmt *Body) {
13455   // Do not warn if the body is a macro that expands to nothing, e.g:
13456   //
13457   // #define CALL(x)
13458   // if (condition)
13459   //   CALL(0);
13460   if (Body->hasLeadingEmptyMacro())
13461     return false;
13462 
13463   // Get line numbers of statement and body.
13464   bool StmtLineInvalid;
13465   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
13466                                                       &StmtLineInvalid);
13467   if (StmtLineInvalid)
13468     return false;
13469 
13470   bool BodyLineInvalid;
13471   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
13472                                                       &BodyLineInvalid);
13473   if (BodyLineInvalid)
13474     return false;
13475 
13476   // Warn if null statement and body are on the same line.
13477   if (StmtLine != BodyLine)
13478     return false;
13479 
13480   return true;
13481 }
13482 
13483 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
13484                                  const Stmt *Body,
13485                                  unsigned DiagID) {
13486   // Since this is a syntactic check, don't emit diagnostic for template
13487   // instantiations, this just adds noise.
13488   if (CurrentInstantiationScope)
13489     return;
13490 
13491   // The body should be a null statement.
13492   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
13493   if (!NBody)
13494     return;
13495 
13496   // Do the usual checks.
13497   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
13498     return;
13499 
13500   Diag(NBody->getSemiLoc(), DiagID);
13501   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
13502 }
13503 
13504 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
13505                                  const Stmt *PossibleBody) {
13506   assert(!CurrentInstantiationScope); // Ensured by caller
13507 
13508   SourceLocation StmtLoc;
13509   const Stmt *Body;
13510   unsigned DiagID;
13511   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
13512     StmtLoc = FS->getRParenLoc();
13513     Body = FS->getBody();
13514     DiagID = diag::warn_empty_for_body;
13515   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
13516     StmtLoc = WS->getCond()->getSourceRange().getEnd();
13517     Body = WS->getBody();
13518     DiagID = diag::warn_empty_while_body;
13519   } else
13520     return; // Neither `for' nor `while'.
13521 
13522   // The body should be a null statement.
13523   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
13524   if (!NBody)
13525     return;
13526 
13527   // Skip expensive checks if diagnostic is disabled.
13528   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
13529     return;
13530 
13531   // Do the usual checks.
13532   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
13533     return;
13534 
13535   // `for(...);' and `while(...);' are popular idioms, so in order to keep
13536   // noise level low, emit diagnostics only if for/while is followed by a
13537   // CompoundStmt, e.g.:
13538   //    for (int i = 0; i < n; i++);
13539   //    {
13540   //      a(i);
13541   //    }
13542   // or if for/while is followed by a statement with more indentation
13543   // than for/while itself:
13544   //    for (int i = 0; i < n; i++);
13545   //      a(i);
13546   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
13547   if (!ProbableTypo) {
13548     bool BodyColInvalid;
13549     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
13550         PossibleBody->getBeginLoc(), &BodyColInvalid);
13551     if (BodyColInvalid)
13552       return;
13553 
13554     bool StmtColInvalid;
13555     unsigned StmtCol =
13556         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
13557     if (StmtColInvalid)
13558       return;
13559 
13560     if (BodyCol > StmtCol)
13561       ProbableTypo = true;
13562   }
13563 
13564   if (ProbableTypo) {
13565     Diag(NBody->getSemiLoc(), DiagID);
13566     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
13567   }
13568 }
13569 
13570 //===--- CHECK: Warn on self move with std::move. -------------------------===//
13571 
13572 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
13573 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
13574                              SourceLocation OpLoc) {
13575   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
13576     return;
13577 
13578   if (inTemplateInstantiation())
13579     return;
13580 
13581   // Strip parens and casts away.
13582   LHSExpr = LHSExpr->IgnoreParenImpCasts();
13583   RHSExpr = RHSExpr->IgnoreParenImpCasts();
13584 
13585   // Check for a call expression
13586   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
13587   if (!CE || CE->getNumArgs() != 1)
13588     return;
13589 
13590   // Check for a call to std::move
13591   if (!CE->isCallToStdMove())
13592     return;
13593 
13594   // Get argument from std::move
13595   RHSExpr = CE->getArg(0);
13596 
13597   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
13598   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
13599 
13600   // Two DeclRefExpr's, check that the decls are the same.
13601   if (LHSDeclRef && RHSDeclRef) {
13602     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
13603       return;
13604     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
13605         RHSDeclRef->getDecl()->getCanonicalDecl())
13606       return;
13607 
13608     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
13609                                         << LHSExpr->getSourceRange()
13610                                         << RHSExpr->getSourceRange();
13611     return;
13612   }
13613 
13614   // Member variables require a different approach to check for self moves.
13615   // MemberExpr's are the same if every nested MemberExpr refers to the same
13616   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
13617   // the base Expr's are CXXThisExpr's.
13618   const Expr *LHSBase = LHSExpr;
13619   const Expr *RHSBase = RHSExpr;
13620   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
13621   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
13622   if (!LHSME || !RHSME)
13623     return;
13624 
13625   while (LHSME && RHSME) {
13626     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
13627         RHSME->getMemberDecl()->getCanonicalDecl())
13628       return;
13629 
13630     LHSBase = LHSME->getBase();
13631     RHSBase = RHSME->getBase();
13632     LHSME = dyn_cast<MemberExpr>(LHSBase);
13633     RHSME = dyn_cast<MemberExpr>(RHSBase);
13634   }
13635 
13636   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
13637   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
13638   if (LHSDeclRef && RHSDeclRef) {
13639     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
13640       return;
13641     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
13642         RHSDeclRef->getDecl()->getCanonicalDecl())
13643       return;
13644 
13645     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
13646                                         << LHSExpr->getSourceRange()
13647                                         << RHSExpr->getSourceRange();
13648     return;
13649   }
13650 
13651   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
13652     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
13653                                         << LHSExpr->getSourceRange()
13654                                         << RHSExpr->getSourceRange();
13655 }
13656 
13657 //===--- Layout compatibility ----------------------------------------------//
13658 
13659 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
13660 
13661 /// Check if two enumeration types are layout-compatible.
13662 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
13663   // C++11 [dcl.enum] p8:
13664   // Two enumeration types are layout-compatible if they have the same
13665   // underlying type.
13666   return ED1->isComplete() && ED2->isComplete() &&
13667          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
13668 }
13669 
13670 /// Check if two fields are layout-compatible.
13671 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
13672                                FieldDecl *Field2) {
13673   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
13674     return false;
13675 
13676   if (Field1->isBitField() != Field2->isBitField())
13677     return false;
13678 
13679   if (Field1->isBitField()) {
13680     // Make sure that the bit-fields are the same length.
13681     unsigned Bits1 = Field1->getBitWidthValue(C);
13682     unsigned Bits2 = Field2->getBitWidthValue(C);
13683 
13684     if (Bits1 != Bits2)
13685       return false;
13686   }
13687 
13688   return true;
13689 }
13690 
13691 /// Check if two standard-layout structs are layout-compatible.
13692 /// (C++11 [class.mem] p17)
13693 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
13694                                      RecordDecl *RD2) {
13695   // If both records are C++ classes, check that base classes match.
13696   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
13697     // If one of records is a CXXRecordDecl we are in C++ mode,
13698     // thus the other one is a CXXRecordDecl, too.
13699     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
13700     // Check number of base classes.
13701     if (D1CXX->getNumBases() != D2CXX->getNumBases())
13702       return false;
13703 
13704     // Check the base classes.
13705     for (CXXRecordDecl::base_class_const_iterator
13706                Base1 = D1CXX->bases_begin(),
13707            BaseEnd1 = D1CXX->bases_end(),
13708               Base2 = D2CXX->bases_begin();
13709          Base1 != BaseEnd1;
13710          ++Base1, ++Base2) {
13711       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
13712         return false;
13713     }
13714   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
13715     // If only RD2 is a C++ class, it should have zero base classes.
13716     if (D2CXX->getNumBases() > 0)
13717       return false;
13718   }
13719 
13720   // Check the fields.
13721   RecordDecl::field_iterator Field2 = RD2->field_begin(),
13722                              Field2End = RD2->field_end(),
13723                              Field1 = RD1->field_begin(),
13724                              Field1End = RD1->field_end();
13725   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
13726     if (!isLayoutCompatible(C, *Field1, *Field2))
13727       return false;
13728   }
13729   if (Field1 != Field1End || Field2 != Field2End)
13730     return false;
13731 
13732   return true;
13733 }
13734 
13735 /// Check if two standard-layout unions are layout-compatible.
13736 /// (C++11 [class.mem] p18)
13737 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
13738                                     RecordDecl *RD2) {
13739   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
13740   for (auto *Field2 : RD2->fields())
13741     UnmatchedFields.insert(Field2);
13742 
13743   for (auto *Field1 : RD1->fields()) {
13744     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
13745         I = UnmatchedFields.begin(),
13746         E = UnmatchedFields.end();
13747 
13748     for ( ; I != E; ++I) {
13749       if (isLayoutCompatible(C, Field1, *I)) {
13750         bool Result = UnmatchedFields.erase(*I);
13751         (void) Result;
13752         assert(Result);
13753         break;
13754       }
13755     }
13756     if (I == E)
13757       return false;
13758   }
13759 
13760   return UnmatchedFields.empty();
13761 }
13762 
13763 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
13764                                RecordDecl *RD2) {
13765   if (RD1->isUnion() != RD2->isUnion())
13766     return false;
13767 
13768   if (RD1->isUnion())
13769     return isLayoutCompatibleUnion(C, RD1, RD2);
13770   else
13771     return isLayoutCompatibleStruct(C, RD1, RD2);
13772 }
13773 
13774 /// Check if two types are layout-compatible in C++11 sense.
13775 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
13776   if (T1.isNull() || T2.isNull())
13777     return false;
13778 
13779   // C++11 [basic.types] p11:
13780   // If two types T1 and T2 are the same type, then T1 and T2 are
13781   // layout-compatible types.
13782   if (C.hasSameType(T1, T2))
13783     return true;
13784 
13785   T1 = T1.getCanonicalType().getUnqualifiedType();
13786   T2 = T2.getCanonicalType().getUnqualifiedType();
13787 
13788   const Type::TypeClass TC1 = T1->getTypeClass();
13789   const Type::TypeClass TC2 = T2->getTypeClass();
13790 
13791   if (TC1 != TC2)
13792     return false;
13793 
13794   if (TC1 == Type::Enum) {
13795     return isLayoutCompatible(C,
13796                               cast<EnumType>(T1)->getDecl(),
13797                               cast<EnumType>(T2)->getDecl());
13798   } else if (TC1 == Type::Record) {
13799     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
13800       return false;
13801 
13802     return isLayoutCompatible(C,
13803                               cast<RecordType>(T1)->getDecl(),
13804                               cast<RecordType>(T2)->getDecl());
13805   }
13806 
13807   return false;
13808 }
13809 
13810 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
13811 
13812 /// Given a type tag expression find the type tag itself.
13813 ///
13814 /// \param TypeExpr Type tag expression, as it appears in user's code.
13815 ///
13816 /// \param VD Declaration of an identifier that appears in a type tag.
13817 ///
13818 /// \param MagicValue Type tag magic value.
13819 ///
13820 /// \param isConstantEvaluated wether the evalaution should be performed in
13821 
13822 /// constant context.
13823 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
13824                             const ValueDecl **VD, uint64_t *MagicValue,
13825                             bool isConstantEvaluated) {
13826   while(true) {
13827     if (!TypeExpr)
13828       return false;
13829 
13830     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
13831 
13832     switch (TypeExpr->getStmtClass()) {
13833     case Stmt::UnaryOperatorClass: {
13834       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
13835       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
13836         TypeExpr = UO->getSubExpr();
13837         continue;
13838       }
13839       return false;
13840     }
13841 
13842     case Stmt::DeclRefExprClass: {
13843       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
13844       *VD = DRE->getDecl();
13845       return true;
13846     }
13847 
13848     case Stmt::IntegerLiteralClass: {
13849       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
13850       llvm::APInt MagicValueAPInt = IL->getValue();
13851       if (MagicValueAPInt.getActiveBits() <= 64) {
13852         *MagicValue = MagicValueAPInt.getZExtValue();
13853         return true;
13854       } else
13855         return false;
13856     }
13857 
13858     case Stmt::BinaryConditionalOperatorClass:
13859     case Stmt::ConditionalOperatorClass: {
13860       const AbstractConditionalOperator *ACO =
13861           cast<AbstractConditionalOperator>(TypeExpr);
13862       bool Result;
13863       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
13864                                                      isConstantEvaluated)) {
13865         if (Result)
13866           TypeExpr = ACO->getTrueExpr();
13867         else
13868           TypeExpr = ACO->getFalseExpr();
13869         continue;
13870       }
13871       return false;
13872     }
13873 
13874     case Stmt::BinaryOperatorClass: {
13875       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
13876       if (BO->getOpcode() == BO_Comma) {
13877         TypeExpr = BO->getRHS();
13878         continue;
13879       }
13880       return false;
13881     }
13882 
13883     default:
13884       return false;
13885     }
13886   }
13887 }
13888 
13889 /// Retrieve the C type corresponding to type tag TypeExpr.
13890 ///
13891 /// \param TypeExpr Expression that specifies a type tag.
13892 ///
13893 /// \param MagicValues Registered magic values.
13894 ///
13895 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
13896 ///        kind.
13897 ///
13898 /// \param TypeInfo Information about the corresponding C type.
13899 ///
13900 /// \param isConstantEvaluated wether the evalaution should be performed in
13901 /// constant context.
13902 ///
13903 /// \returns true if the corresponding C type was found.
13904 static bool GetMatchingCType(
13905     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
13906     const ASTContext &Ctx,
13907     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
13908         *MagicValues,
13909     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
13910     bool isConstantEvaluated) {
13911   FoundWrongKind = false;
13912 
13913   // Variable declaration that has type_tag_for_datatype attribute.
13914   const ValueDecl *VD = nullptr;
13915 
13916   uint64_t MagicValue;
13917 
13918   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
13919     return false;
13920 
13921   if (VD) {
13922     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
13923       if (I->getArgumentKind() != ArgumentKind) {
13924         FoundWrongKind = true;
13925         return false;
13926       }
13927       TypeInfo.Type = I->getMatchingCType();
13928       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
13929       TypeInfo.MustBeNull = I->getMustBeNull();
13930       return true;
13931     }
13932     return false;
13933   }
13934 
13935   if (!MagicValues)
13936     return false;
13937 
13938   llvm::DenseMap<Sema::TypeTagMagicValue,
13939                  Sema::TypeTagData>::const_iterator I =
13940       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
13941   if (I == MagicValues->end())
13942     return false;
13943 
13944   TypeInfo = I->second;
13945   return true;
13946 }
13947 
13948 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
13949                                       uint64_t MagicValue, QualType Type,
13950                                       bool LayoutCompatible,
13951                                       bool MustBeNull) {
13952   if (!TypeTagForDatatypeMagicValues)
13953     TypeTagForDatatypeMagicValues.reset(
13954         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
13955 
13956   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
13957   (*TypeTagForDatatypeMagicValues)[Magic] =
13958       TypeTagData(Type, LayoutCompatible, MustBeNull);
13959 }
13960 
13961 static bool IsSameCharType(QualType T1, QualType T2) {
13962   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
13963   if (!BT1)
13964     return false;
13965 
13966   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
13967   if (!BT2)
13968     return false;
13969 
13970   BuiltinType::Kind T1Kind = BT1->getKind();
13971   BuiltinType::Kind T2Kind = BT2->getKind();
13972 
13973   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
13974          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
13975          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
13976          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
13977 }
13978 
13979 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
13980                                     const ArrayRef<const Expr *> ExprArgs,
13981                                     SourceLocation CallSiteLoc) {
13982   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
13983   bool IsPointerAttr = Attr->getIsPointer();
13984 
13985   // Retrieve the argument representing the 'type_tag'.
13986   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
13987   if (TypeTagIdxAST >= ExprArgs.size()) {
13988     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
13989         << 0 << Attr->getTypeTagIdx().getSourceIndex();
13990     return;
13991   }
13992   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
13993   bool FoundWrongKind;
13994   TypeTagData TypeInfo;
13995   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
13996                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
13997                         TypeInfo, isConstantEvaluated())) {
13998     if (FoundWrongKind)
13999       Diag(TypeTagExpr->getExprLoc(),
14000            diag::warn_type_tag_for_datatype_wrong_kind)
14001         << TypeTagExpr->getSourceRange();
14002     return;
14003   }
14004 
14005   // Retrieve the argument representing the 'arg_idx'.
14006   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
14007   if (ArgumentIdxAST >= ExprArgs.size()) {
14008     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
14009         << 1 << Attr->getArgumentIdx().getSourceIndex();
14010     return;
14011   }
14012   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
14013   if (IsPointerAttr) {
14014     // Skip implicit cast of pointer to `void *' (as a function argument).
14015     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
14016       if (ICE->getType()->isVoidPointerType() &&
14017           ICE->getCastKind() == CK_BitCast)
14018         ArgumentExpr = ICE->getSubExpr();
14019   }
14020   QualType ArgumentType = ArgumentExpr->getType();
14021 
14022   // Passing a `void*' pointer shouldn't trigger a warning.
14023   if (IsPointerAttr && ArgumentType->isVoidPointerType())
14024     return;
14025 
14026   if (TypeInfo.MustBeNull) {
14027     // Type tag with matching void type requires a null pointer.
14028     if (!ArgumentExpr->isNullPointerConstant(Context,
14029                                              Expr::NPC_ValueDependentIsNotNull)) {
14030       Diag(ArgumentExpr->getExprLoc(),
14031            diag::warn_type_safety_null_pointer_required)
14032           << ArgumentKind->getName()
14033           << ArgumentExpr->getSourceRange()
14034           << TypeTagExpr->getSourceRange();
14035     }
14036     return;
14037   }
14038 
14039   QualType RequiredType = TypeInfo.Type;
14040   if (IsPointerAttr)
14041     RequiredType = Context.getPointerType(RequiredType);
14042 
14043   bool mismatch = false;
14044   if (!TypeInfo.LayoutCompatible) {
14045     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
14046 
14047     // C++11 [basic.fundamental] p1:
14048     // Plain char, signed char, and unsigned char are three distinct types.
14049     //
14050     // But we treat plain `char' as equivalent to `signed char' or `unsigned
14051     // char' depending on the current char signedness mode.
14052     if (mismatch)
14053       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
14054                                            RequiredType->getPointeeType())) ||
14055           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
14056         mismatch = false;
14057   } else
14058     if (IsPointerAttr)
14059       mismatch = !isLayoutCompatible(Context,
14060                                      ArgumentType->getPointeeType(),
14061                                      RequiredType->getPointeeType());
14062     else
14063       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
14064 
14065   if (mismatch)
14066     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
14067         << ArgumentType << ArgumentKind
14068         << TypeInfo.LayoutCompatible << RequiredType
14069         << ArgumentExpr->getSourceRange()
14070         << TypeTagExpr->getSourceRange();
14071 }
14072 
14073 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
14074                                          CharUnits Alignment) {
14075   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
14076 }
14077 
14078 void Sema::DiagnoseMisalignedMembers() {
14079   for (MisalignedMember &m : MisalignedMembers) {
14080     const NamedDecl *ND = m.RD;
14081     if (ND->getName().empty()) {
14082       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
14083         ND = TD;
14084     }
14085     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
14086         << m.MD << ND << m.E->getSourceRange();
14087   }
14088   MisalignedMembers.clear();
14089 }
14090 
14091 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
14092   E = E->IgnoreParens();
14093   if (!T->isPointerType() && !T->isIntegerType())
14094     return;
14095   if (isa<UnaryOperator>(E) &&
14096       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
14097     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
14098     if (isa<MemberExpr>(Op)) {
14099       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
14100       if (MA != MisalignedMembers.end() &&
14101           (T->isIntegerType() ||
14102            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
14103                                    Context.getTypeAlignInChars(
14104                                        T->getPointeeType()) <= MA->Alignment))))
14105         MisalignedMembers.erase(MA);
14106     }
14107   }
14108 }
14109 
14110 void Sema::RefersToMemberWithReducedAlignment(
14111     Expr *E,
14112     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
14113         Action) {
14114   const auto *ME = dyn_cast<MemberExpr>(E);
14115   if (!ME)
14116     return;
14117 
14118   // No need to check expressions with an __unaligned-qualified type.
14119   if (E->getType().getQualifiers().hasUnaligned())
14120     return;
14121 
14122   // For a chain of MemberExpr like "a.b.c.d" this list
14123   // will keep FieldDecl's like [d, c, b].
14124   SmallVector<FieldDecl *, 4> ReverseMemberChain;
14125   const MemberExpr *TopME = nullptr;
14126   bool AnyIsPacked = false;
14127   do {
14128     QualType BaseType = ME->getBase()->getType();
14129     if (BaseType->isDependentType())
14130       return;
14131     if (ME->isArrow())
14132       BaseType = BaseType->getPointeeType();
14133     RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
14134     if (RD->isInvalidDecl())
14135       return;
14136 
14137     ValueDecl *MD = ME->getMemberDecl();
14138     auto *FD = dyn_cast<FieldDecl>(MD);
14139     // We do not care about non-data members.
14140     if (!FD || FD->isInvalidDecl())
14141       return;
14142 
14143     AnyIsPacked =
14144         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
14145     ReverseMemberChain.push_back(FD);
14146 
14147     TopME = ME;
14148     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
14149   } while (ME);
14150   assert(TopME && "We did not compute a topmost MemberExpr!");
14151 
14152   // Not the scope of this diagnostic.
14153   if (!AnyIsPacked)
14154     return;
14155 
14156   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
14157   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
14158   // TODO: The innermost base of the member expression may be too complicated.
14159   // For now, just disregard these cases. This is left for future
14160   // improvement.
14161   if (!DRE && !isa<CXXThisExpr>(TopBase))
14162       return;
14163 
14164   // Alignment expected by the whole expression.
14165   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
14166 
14167   // No need to do anything else with this case.
14168   if (ExpectedAlignment.isOne())
14169     return;
14170 
14171   // Synthesize offset of the whole access.
14172   CharUnits Offset;
14173   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
14174        I++) {
14175     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
14176   }
14177 
14178   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
14179   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
14180       ReverseMemberChain.back()->getParent()->getTypeForDecl());
14181 
14182   // The base expression of the innermost MemberExpr may give
14183   // stronger guarantees than the class containing the member.
14184   if (DRE && !TopME->isArrow()) {
14185     const ValueDecl *VD = DRE->getDecl();
14186     if (!VD->getType()->isReferenceType())
14187       CompleteObjectAlignment =
14188           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
14189   }
14190 
14191   // Check if the synthesized offset fulfills the alignment.
14192   if (Offset % ExpectedAlignment != 0 ||
14193       // It may fulfill the offset it but the effective alignment may still be
14194       // lower than the expected expression alignment.
14195       CompleteObjectAlignment < ExpectedAlignment) {
14196     // If this happens, we want to determine a sensible culprit of this.
14197     // Intuitively, watching the chain of member expressions from right to
14198     // left, we start with the required alignment (as required by the field
14199     // type) but some packed attribute in that chain has reduced the alignment.
14200     // It may happen that another packed structure increases it again. But if
14201     // we are here such increase has not been enough. So pointing the first
14202     // FieldDecl that either is packed or else its RecordDecl is,
14203     // seems reasonable.
14204     FieldDecl *FD = nullptr;
14205     CharUnits Alignment;
14206     for (FieldDecl *FDI : ReverseMemberChain) {
14207       if (FDI->hasAttr<PackedAttr>() ||
14208           FDI->getParent()->hasAttr<PackedAttr>()) {
14209         FD = FDI;
14210         Alignment = std::min(
14211             Context.getTypeAlignInChars(FD->getType()),
14212             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
14213         break;
14214       }
14215     }
14216     assert(FD && "We did not find a packed FieldDecl!");
14217     Action(E, FD->getParent(), FD, Alignment);
14218   }
14219 }
14220 
14221 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
14222   using namespace std::placeholders;
14223 
14224   RefersToMemberWithReducedAlignment(
14225       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
14226                      _2, _3, _4));
14227 }
14228